问:
getting error widget on which setState() or markNeedsBuild() using FutureBuilder with provider
I am getting this error he widget on which setState() or markNeedsBuild() was called was: _

```<code>InheritedProviderScope<AuthProvider?>
    value: Instance of 'AuthProvider'
    listening to value
The widget which was currently being built when the offending call was made was: RegistrationScreen
    dirty
</code>```

This _InheritedProviderScope<AuthProvider?> widget cannot be marked as
needing to build because the framework is already in the process of
building widgets. A widget can be marked as needing to be built during
the build phase only if one of its ancestors is currently building.
This exception is allowed because the framework builds parent widgets
before children, which means a dirty descendant will always be built.
Otherwise, the framework might not visit this widget during this build
phase.

//Registration Screen handles the state and update the views

```<code>class RegistrationScreen extends StatefulWidget {
      const RegistrationScreen({super.key});

      @override
      State<RegistrationScreen> createState() => _RegistrationScreenState();
    }

    class _RegistrationScreenState extends State<RegistrationScreen> {
      @override
      Widget build(BuildContext context) {
        NavigationService service = NavigationService();
        final authProviders = Provider.of<AuthProvider>(context, listen: false);
        // final authService = AuthService();
        final firstNameController = TextEditingController();
        final lastNameController = TextEditingController();
        final phoneNumberController = TextEditingController();
        final emailController = TextEditingController();
        final passwordController = TextEditingController();

        Future<void> submitForm(BuildContext context) async {
          // final authProviders = Provider.of<AuthProvider>(context, listen: false);
          await authProviders.registration(
            email: emailController.text,
            password: passwordController.text,
            firstName: firstNameController.text,
            lastName: lastNameController.text,
            phoneNumber: phoneNumberController.text,
          );
          // service.navigateTo('/otp_screen', arguments: "");
        }

        return FutureBuilder(
            future: submitForm(context),
            builder: (context, AsyncSnapshot snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(
                  child: Platform.isIOS
                      ? const CupertinoActivityIndicator(
                          color: Colors.black,
                          radius: 30,
                        )
                      : const CircularProgressIndicator(),
                );
              } else if (snapshot.hasError) {
                Future.delayed(
                    Duration.zero,
                    () => showCupertinoDialog(
                          context: context,
                          builder: (BuildContext context) => CupertinoAlertDialog(
                            title: const Text("Error"),
                            content: Text(snapshot.error.toString()),
                            actions: [
                              CupertinoDialogAction(
                                onPressed: () {
                                  Navigator.of(context).pop();
                                },
                                isDefaultAction: true,
                                child: const Text("ok"),
                              ),
                            ],
                          ),
                        ));
              } else if (snapshot.connectionState == ConnectionState.done &&
                  snapshot.hasData) {
                service.navigateTo('/otp_screen', arguments: "");
              }
              return MainForm(
                firstNameController: firstNameController,
                lastNameController: lastNameController,
                phoneNumberController: phoneNumberController,
                emailController: emailController,
                passwordController: passwordController,
                authProvider: authProviders,
                onSubmit: () => submitForm(context),
              );
            });
      }
    }

//MainForm is a form to register
class MainForm extends StatelessWidget {
  const MainForm({
    Key? key,
    required this.firstNameController,
    required this.lastNameController,
    required this.phoneNumberController,
    required this.emailController,
    required this.passwordController,
    required this.authProvider,
    required this.onSubmit,
  }) : super(key: key);

  final TextEditingController firstNameController;
  final TextEditingController lastNameController;
  final TextEditingController phoneNumberController;
  final TextEditingController emailController;
  final TextEditingController passwordController;
  final AuthProvider authProvider;
  final VoidCallback onSubmit;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Text(
          "Trend Spotter ",
          style: TextStyle(fontSize: 35),
        ),
        const SizedBox(
          height: 10,
        ),
        const Text(
          "Register ",
          style: TextStyle(fontSize: 35),
        ),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
          textToDisplay: "First Name",
          fontSize: Constants.loginButtonFontSize,
          textFieldPadding: Constants.loginTextFieldOutLinePadding,
          obscureText: false,
          controller: firstNameController,
          type: TextInputType.name,
        ),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
          textToDisplay: "Last Name",
          fontSize: Constants.loginButtonFontSize,
          textFieldPadding: Constants.loginTextFieldOutLinePadding,
          obscureText: false,
          controller: lastNameController,
          type: TextInputType.name,
        ),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
            textToDisplay: "Phone Number",
            fontSize: Constants.loginButtonFontSize,
            textFieldPadding: Constants.loginTextFieldOutLinePadding,
            obscureText: false,
            controller: phoneNumberController,
            type: TextInputType.phone),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
          textToDisplay: "Email",
          fontSize: Constants.loginButtonFontSize,
          textFieldPadding: Constants.loginTextFieldOutLinePadding,
          obscureText: false,
          controller: emailController,
          type: TextInputType.emailAddress,
        ),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
          textToDisplay: Constants.loginTextfieldPassword,
          fontSize: Constants.loginButtonFontSize,
          textFieldPadding: Constants.loginTextFieldOutLinePadding,
          obscureText: true,
          controller: passwordController,
          type: TextInputType.visiblePassword,
        ),
        const SizedBox(
          height: 10,
        ),
        ElevatedButton(
          style: ElevatedButton.styleFrom(
            fixedSize: const Size(
                Constants.loginButtonWidth, Constants.loginButtonHeight),
          ),
          onPressed: () => onSubmit,
          child: const Text("Sign up"),
        )
      ],
    ));
  }
}
</code>```

Body:
I am getting this error he widget on which setState() or markNeedsBuild() was called was: _

InheritedProviderScope<AuthProvider?>
    value: Instance of 'AuthProvider'
    listening to value
The widget which was currently being built when the offending call was made was: RegistrationScreen
    dirty

This _InheritedProviderScope<AuthProvider?> widget cannot be marked as
needing to build because the framework is already in the process of
building widgets. A widget can be marked as needing to be built during
the build phase only if one of its ancestors is currently building.
This exception is allowed because the framework builds parent widgets
before children, which means a dirty descendant will always be built.
Otherwise, the framework might not visit this widget during this build
phase.

//Registration Screen handles the state and update the views

class RegistrationScreen extends StatefulWidget {
      const RegistrationScreen({super.key});

      @override
      State<RegistrationScreen> createState() => _RegistrationScreenState();
    }

    class _RegistrationScreenState extends State<RegistrationScreen> {
      @override
      Widget build(BuildContext context) {
        NavigationService service = NavigationService();
        final authProviders = Provider.of<AuthProvider>(context, listen: false);
        // final authService = AuthService();
        final firstNameController = TextEditingController();
        final lastNameController = TextEditingController();
        final phoneNumberController = TextEditingController();
        final emailController = TextEditingController();
        final passwordController = TextEditingController();

        Future<void> submitForm(BuildContext context) async {
          // final authProviders = Provider.of<AuthProvider>(context, listen: false);
          await authProviders.registration(
            email: emailController.text,
            password: passwordController.text,
            firstName: firstNameController.text,
            lastName: lastNameController.text,
            phoneNumber: phoneNumberController.text,
          );
          // service.navigateTo('/otp_screen', arguments: "");
        }

        return FutureBuilder(
            future: submitForm(context),
            builder: (context, AsyncSnapshot snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(
                  child: Platform.isIOS
                      ? const CupertinoActivityIndicator(
                          color: Colors.black,
                          radius: 30,
                        )
                      : const CircularProgressIndicator(),
                );
              } else if (snapshot.hasError) {
                Future.delayed(
                    Duration.zero,
                    () => showCupertinoDialog(
                          context: context,
                          builder: (BuildContext context) => CupertinoAlertDialog(
                            title: const Text("Error"),
                            content: Text(snapshot.error.toString()),
                            actions: [
                              CupertinoDialogAction(
                                onPressed: () {
                                  Navigator.of(context).pop();
                                },
                                isDefaultAction: true,
                                child: const Text("ok"),
                              ),
                            ],
                          ),
                        ));
              } else if (snapshot.connectionState == ConnectionState.done &&
                  snapshot.hasData) {
                service.navigateTo('/otp_screen', arguments: "");
              }
              return MainForm(
                firstNameController: firstNameController,
                lastNameController: lastNameController,
                phoneNumberController: phoneNumberController,
                emailController: emailController,
                passwordController: passwordController,
                authProvider: authProviders,
                onSubmit: () => submitForm(context),
              );
            });
      }
    }

//MainForm is a form to register
class MainForm extends StatelessWidget {
  const MainForm({
    Key? key,
    required this.firstNameController,
    required this.lastNameController,
    required this.phoneNumberController,
    required this.emailController,
    required this.passwordController,
    required this.authProvider,
    required this.onSubmit,
  }) : super(key: key);

  final TextEditingController firstNameController;
  final TextEditingController lastNameController;
  final TextEditingController phoneNumberController;
  final TextEditingController emailController;
  final TextEditingController passwordController;
  final AuthProvider authProvider;
  final VoidCallback onSubmit;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Text(
          "Trend Spotter ",
          style: TextStyle(fontSize: 35),
        ),
        const SizedBox(
          height: 10,
        ),
        const Text(
          "Register ",
          style: TextStyle(fontSize: 35),
        ),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
          textToDisplay: "First Name",
          fontSize: Constants.loginButtonFontSize,
          textFieldPadding: Constants.loginTextFieldOutLinePadding,
          obscureText: false,
          controller: firstNameController,
          type: TextInputType.name,
        ),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
          textToDisplay: "Last Name",
          fontSize: Constants.loginButtonFontSize,
          textFieldPadding: Constants.loginTextFieldOutLinePadding,
          obscureText: false,
          controller: lastNameController,
          type: TextInputType.name,
        ),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
            textToDisplay: "Phone Number",
            fontSize: Constants.loginButtonFontSize,
            textFieldPadding: Constants.loginTextFieldOutLinePadding,
            obscureText: false,
            controller: phoneNumberController,
            type: TextInputType.phone),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
          textToDisplay: "Email",
          fontSize: Constants.loginButtonFontSize,
          textFieldPadding: Constants.loginTextFieldOutLinePadding,
          obscureText: false,
          controller: emailController,
          type: TextInputType.emailAddress,
        ),
        const SizedBox(
          height: 10,
        ),
        CustomTextField(
          textToDisplay: Constants.loginTextfieldPassword,
          fontSize: Constants.loginButtonFontSize,
          textFieldPadding: Constants.loginTextFieldOutLinePadding,
          obscureText: true,
          controller: passwordController,
          type: TextInputType.visiblePassword,
        ),
        const SizedBox(
          height: 10,
        ),
        ElevatedButton(
          style: ElevatedButton.styleFrom(
            fixedSize: const Size(
                Constants.loginButtonWidth, Constants.loginButtonHeight),
          ),
          onPressed: () => onSubmit,
          child: const Text("Sign up"),
        )
      ],
    ));
  }
}


来源: stackexchange

问:
Profiling cache coherence latency
Is there a tool that makes it possible to monitor the time spent on managing cache coherence by MESIF protocol on Skylake servers or its successors for Linux OS? I am also interested in programmatic ways in C if possible.</p>

ContentLicense: CC BY-SA 4.0

Title: Profiling cache coherence latency


问:
Can't install Python 2.7.x using pyenv
I am trying to use pyenv to install Python2.7.  It fails, it seems, due to inabilities to download a compatible version of pip.  I have already downgraded to pip version 20.3.4, but can't figure out how to tell pyenv this:

```<code>pyenv install 2.7.7
Installing openssl-1.0.2k...
Installed openssl-1.0.2k to /Users/username/.pyenv/versions/2.7.7

python-build: use readline from homebrew
Installing Python-2.7.7...
patching file ./Lib/site.py
patching file ./Lib/ssl.py
patching file ./Modules/_ssl.c
python-build: use tcl-tk from homebrew
python-build: use readline from homebrew
python-build: use zlib from xcode sdk
WARNING: The Python sqlite3 extension was not compiled. Missing the SQLite3 lib?
Installing pip from https://bootstrap.pypa.io/pip/2.7/get-pip.py...
error: failed to install pip via get-pip.py

BUILD FAILED (OS X 12.6.2 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/xl/3b9jpy1x5sq6gr7b_qzw1pkm0000gn/T/python-build.20221225200507.60628
Results logged to /var/folders/xl/3b9jpy1x5sq6gr7b_qzw1pkm0000gn/T/python-build.20221225200507.60628.log

Last 10 log lines:
WARNING: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Aug 27 18:45:09 2023 GMT', 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org')), 'subject': ((('commonName', u'www.python.org'),),)}
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/pip/
/var/folders/xl/3b9jpy1x5sq6gr7b_qzw1pkm0000gn/T/tmpiEoxv0/pip.zip/pip/_vendor/urllib3/util/ssl_.py:164: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
WARNING: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Aug 27 18:45:09 2023 GMT', 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org')), 'subject': ((('commonName', u'www.python.org'),),)}
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/pip/
/var/folders/xl/3b9jpy1x5sq6gr7b_qzw1pkm0000gn/T/tmpiEoxv0/pip.zip/pip/_vendor/urllib3/util/ssl_.py:164: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
WARNING: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Aug 27 18:45:09 2023 GMT', 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org')), 'subject': ((('commonName', u'www.python.org'),),)}
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)) - skipping
ERROR: Could not find a version that satisfies the requirement pip<21.0 (from versions: none)
ERROR: No matching distribution found for pip<21.0
</code>```

I'm on Mac 12.6

Title: Can't install Python 2.7.x using pyenv

Body:
I am trying to use pyenv to install Python2.7.  It fails, it seems, due to inabilities to download a compatible version of pip.  I have already downgraded to pip version 20.3.4, but can't figure out how to tell pyenv this:

pyenv install 2.7.7
Installing openssl-1.0.2k...
Installed openssl-1.0.2k to /Users/username/.pyenv/versions/2.7.7

python-build: use readline from homebrew
Installing Python-2.7.7...
patching file ./Lib/site.py
patching file ./Lib/ssl.py
patching file ./Modules/_ssl.c
python-build: use tcl-tk from homebrew
python-build: use readline from homebrew
python-build: use zlib from xcode sdk
WARNING: The Python sqlite3 extension was not compiled. Missing the SQLite3 lib?
Installing pip from https://bootstrap.pypa.io/pip/2.7/get-pip.py...
error: failed to install pip via get-pip.py

BUILD FAILED (OS X 12.6.2 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/xl/3b9jpy1x5sq6gr7b_qzw1pkm0000gn/T/python-build.20221225200507.60628
Results logged to /var/folders/xl/3b9jpy1x5sq6gr7b_qzw1pkm0000gn/T/python-build.20221225200507.60628.log

Last 10 log lines:
WARNING: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Aug 27 18:45:09 2023 GMT', 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org')), 'subject': ((('commonName', u'www.python.org'),),)}
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/pip/
/var/folders/xl/3b9jpy1x5sq6gr7b_qzw1pkm0000gn/T/tmpiEoxv0/pip.zip/pip/_vendor/urllib3/util/ssl_.py:164: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
WARNING: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Aug 27 18:45:09 2023 GMT', 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org')), 'subject': ((('commonName', u'www.python.org'),),)}
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/pip/
/var/folders/xl/3b9jpy1x5sq6gr7b_qzw1pkm0000gn/T/tmpiEoxv0/pip.zip/pip/_vendor/urllib3/util/ssl_.py:164: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
WARNING: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Aug 27 18:45:09 2023 GMT', 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org')), 'subject': ((('commonName', u'www.python.org'),),)}
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)) - skipping
ERROR: Could not find a version that satisfies the requirement pip<21.0 (from versions: none)
ERROR: No matching distribution found for pip<21.0

I'm on Mac 12.6


问:
Laravel 9 with breeze & react, Auth::check() always returning false
I installed Laravel 9 with breeze and react.

In the react page, I call this api and it needs to check the user is logged in.

Wishbox.jsx

```<code>axios
    .post("/api/add/wishlist", {
      prd_no: event.target.getAttribute("productno"),
      mem_id: 1,
    })
</code>```

At first, I tried to add middleware in the routes/api.php like this.

```<code>Route::post('/add/wishlist', [App\Http\Controllers\UserController::class, 'addWishlist'])->middleware('auth');
</code>```

Unfortunately, it didn't work at all and couldn't find out why.

It just kept giving me the error 401 Unauthenticated.

So I removed the middleware part from the route, then decided to check in the controller side, like this.

UserController.php

```<code>public function addWishlist(Request $request) {
        dd(Auth::guard('web')->check());
...
</code>```

but it just keep returning false, even though I already logged in. Without the guard('web') part, the result is same.

And If I go back to / (Home) route for just checking I am logged in, it looks like I didn't log in. But I just logged in! Right before I press the button to go previous page in the browser. So I refreshed the page, then it says I am logged in.

I really don't understand why it works like this.

Please anyone guide me to understand what's happening here and what did I miss or wrong here.

Body:
I installed Laravel 9 with breeze and react.

In the react page, I call this api and it needs to check the user is logged in.

Wishbox.jsx

axios
    .post("/api/add/wishlist", {
      prd_no: event.target.getAttribute("productno"),
      mem_id: 1,
    })

At first, I tried to add middleware in the routes/api.php like this.

Route::post('/add/wishlist', [App\Http\Controllers\UserController::class, 'addWishlist'])->middleware('auth');

Unfortunately, it didn't work at all and couldn't find out why.

It just kept giving me the error 401 Unauthenticated.

So I removed the middleware part from the route, then decided to check in the controller side, like this.

UserController.php

public function addWishlist(Request $request) {
        dd(Auth::guard('web')->check());
...

but it just keep returning false, even though I already logged in. Without the guard('web') part, the result is same.

And If I go back to / (Home) route for just checking I am logged in, it looks like I didn't log in. But I just logged in! Right before I press the button to go previous page in the browser. So I refreshed the page, then it says I am logged in.

I really don't understand why it works like this.

Please anyone guide me to understand what's happening here and what did I miss or wrong here.


问:
Python Manchine Learning for content based Recommendation system using cosine similarities
I am building content based recommendation system. I have done count vectorization, the vectors are

```<code>from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=5000,stop_words='english')
newdata = newdata.dropna(subset=['tags'])
movievector = cv.fit_transform(newdata['tags']).toarray()
movievector

 -----------The array from moviecector are:  array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=int64)

movievector.shape

-----------and the shape is (4806, 5000)
</code>```

I am not using any libraries for calculating cosine similarity. And according to the rule of my project, I cannot use the library in this part. I need to use pure python code.

I am not able to take any two random vectors to calculate the cosine similarities to recommend the movies.
Help me to pass two random vectors in the plain python code so that cosine similarities can be calculated and I can recommend the movie.

```<code>import requests
from math import sqrt

def cosine_similarity(item1, item2):
    dot_product = 0
    norm1 = 0
    norm2 = 0

    for key in item1:
        if key in item2:
            dot_product += item1[key] * item2[key]

    for key in item1:
        norm1 += item1[key] ** 2
    for key in item2:
        norm2 += item2[key] ** 2

    return dot_product / (sqrt(norm1) * sqrt(norm2))

def generate_recommendations(item_id):
    response = requests.get('/api/items')
    items = response.json()

    selected_item = next(item for item in items if item['id'] == item_id)

    similarities = [{'item': item, 'similarity': cosine_similarity(selected_item, item)} for item in items]

    sorted_similarities = sorted(similarities, key=lambda x: x['similarity'], reverse=True)

    recommendations = sorted_similarities[:5]

    return recommendations

</code>```

I tried different ways but failed to solve this problem.

Body:
I am building content based recommendation system. I have done count vectorization, the vectors are

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=5000,stop_words='english')
newdata = newdata.dropna(subset=['tags'])
movievector = cv.fit_transform(newdata['tags']).toarray()
movievector

 -----------The array from moviecector are:  array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=int64)

movievector.shape

-----------and the shape is (4806, 5000)

I am not using any libraries for calculating cosine similarity. And according to the rule of my project, I cannot use the library in this part. I need to use pure python code.

I am not able to take any two random vectors to calculate the cosine similarities to recommend the movies.
Help me to pass two random vectors in the plain python code so that cosine similarities can be calculated and I can recommend the movie.

import requests
from math import sqrt

def cosine_similarity(item1, item2):
    dot_product = 0
    norm1 = 0
    norm2 = 0

    for key in item1:
        if key in item2:
            dot_product += item1[key] * item2[key]

    for key in item1:
        norm1 += item1[key] ** 2
    for key in item2:
        norm2 += item2[key] ** 2

    return dot_product / (sqrt(norm1) * sqrt(norm2))

def generate_recommendations(item_id):
    response = requests.get('/api/items')
    items = response.json()

    selected_item = next(item for item in items if item['id'] == item_id)

    similarities = [{'item': item, 'similarity': cosine_similarity(selected_item, item)} for item in items]

    sorted_similarities = sorted(similarities, key=lambda x: x['similarity'], reverse=True)

    recommendations = sorted_similarities[:5]

    return recommendations

I tried different ways but failed to solve this problem.


问:
Overflow on CSS
I can't figure out how to remove the overflow of these links placed in the navbar.

I wish they were shown as in this photo:

Screenshot1 (Here they have been inserted as buttons)

But instead they come out like this:

Screenshot2 (Here they have been inserted as links [a tags])

HTML:

```<code><header>
    <a href="index.html" target="_self"><img src="../media/logo.png" alt="Logo Teatro Amatoriale" title="Logo Teatro Amatoriale" id="logo_img"></a>
    <nav>
        <a href="#" class="bottone_attivo nav_button" target="_self">Home</a>
        <a href="about.html" class="bottone_inattivo nav_button" target="_self">Chi Siamo</a>
        <a href="contacts.html" class="bottone_inattivo nav_button" target="_self">Contatti</a>
        <a href="booking.html" class="bottone_inattivo nav_button" target="_self">Prenota</a>
        <a href="findus.html" class="bottone_inattivo nav_button" target="_self">Come Trovarci</a>
        <a href="news.html" class="bottone_inattivo nav_button" target="_self">News</a>
    </nav>
</header>
</code>```

CSS:

```<code>.bottone_inattivo
{
    background-color: #1B6845;
    border-radius: 15px;
    border: none;
    color: white;
    padding: 12px 28px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}

.bottone_attivo
{
    background-color: #37b47a;
    border-radius: 15px;
    border: none;
    color: black;
    padding: 12px 28px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    pointer-events: none;
    font-weight: bold;
}

@media screen and (min-width: 160px) and (max-width: 649px) /* Media query per schermi piccoli in verticale*/
{
    .nav_button
    {
        width: 100%;
        margin-top: 1%;
        margin-bottom: 1%;
        outline: 1px solid red;

    }

    nav
    {
        background-color: grey;
        outline: 1px solid red;
    }
}
</code>```

Can you help me out? Thanks! :)

Title: Overflow on CSS

Body:
I can't figure out how to remove the overflow of these links placed in the navbar.

I wish they were shown as in this photo:

Screenshot1 (Here they have been inserted as buttons)

But instead they come out like this:

Screenshot2 (Here they have been inserted as links [a tags])

HTML:

        Home
        Chi Siamo
        Contatti
        Prenota
        Come Trovarci
        News

CSS:

.bottone_inattivo
{
    background-color: #1B6845;
    border-radius: 15px;
    border: none;
    color: white;
    padding: 12px 28px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}

.bottone_attivo
{
    background-color: #37b47a;
    border-radius: 15px;
    border: none;
    color: black;
    padding: 12px 28px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    pointer-events: none;
    font-weight: bold;
}

@media screen and (min-width: 160px) and (max-width: 649px) /* Media query per schermi piccoli in verticale*/
{
    .nav_button
    {
        width: 100%;
        margin-top: 1%;
        margin-bottom: 1%;
        outline: 1px solid red;

    }

    nav
    {
        background-color: grey;
        outline: 1px solid red;
    }
}

Can you help me out? Thanks! :)


问:
How can I apply conditional formatting in C++ MFC?
https://learn.microsoft.com/en-us/previous-versions/office/developer/office-2007/bb404903(v=office.12)?redirectedfrom=MSDN

Microsoft provides example codes in C# and Visual Basic.

For example C# code as follows.

```<code>ApplicationClass excelApplication = null;
Workbook newWorkbook = null;
Worksheet targetSheet = null;
ColorScale cfColorScale = null;
IconSetCondition cfIconSet = null;
string paramWorkbookPath = @"C:\Temp\Test.xlsx";
object paramMissing = Type.Missing;
excelApplication = new ApplicationClass();
newWorkbook = excelApplication.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
targetSheet = (Worksheet)(newWorkbook.Worksheets[1]);
targetSheet.Name = "Conditional Formatting";

// Fill cells A1:A10 with sample data.
targetSheet.get_Range("A1", paramMissing).set_Value(XlRangeValueDataType.xlRangeValueDefault, 1);
targetSheet.get_Range("A2", paramMissing).set_Value(XlRangeValueDataType.xlRangeValueDefault, 2);
targetSheet.get_Range("A1:A2",
paramMissing).AutoFill(targetSheet.get_Range("A1:A10", paramMissing), XlAutoFillType.xlFillSeries);

// Create a two-color ColorScale object for the created sample data
// range.
cfColorScale = (ColorScale)(targetSheet.get_Range("A1:A10",
Type.Missing).FormatConditions.AddColorScale(2));

// Set the minimum threshold to red (0x000000FF) and maximum threshold
// to blue (0x00FF0000).
cfColorScale.ColorScaleCriteria[1].FormatColor.Color = 0x000000FF;
cfColorScale.ColorScaleCriteria[2].FormatColor.Color = 0x00FF0000;
</code>```

How can we apply conditional formatting in C++ MFC?

```<code>range = ws.get_Range(COleVariant(_T("A1"), COleVariant(_T("A10")));
CFormatCondition fc;

fc = range.get_FormatConditions();

</code>```

Body:
https://learn.microsoft.com/en-us/previous-versions/office/developer/office-2007/bb404903(v=office.12)?redirectedfrom=MSDN

Microsoft provides example codes in C# and Visual Basic.

For example C# code as follows.

ApplicationClass excelApplication = null;
Workbook newWorkbook = null;
Worksheet targetSheet = null;
ColorScale cfColorScale = null;
IconSetCondition cfIconSet = null;
string paramWorkbookPath = @"C:\Temp\Test.xlsx";
object paramMissing = Type.Missing;
excelApplication = new ApplicationClass();
newWorkbook = excelApplication.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
targetSheet = (Worksheet)(newWorkbook.Worksheets[1]);
targetSheet.Name = "Conditional Formatting";

// Fill cells A1:A10 with sample data.
targetSheet.get_Range("A1", paramMissing).set_Value(XlRangeValueDataType.xlRangeValueDefault, 1);
targetSheet.get_Range("A2", paramMissing).set_Value(XlRangeValueDataType.xlRangeValueDefault, 2);
targetSheet.get_Range("A1:A2",
paramMissing).AutoFill(targetSheet.get_Range("A1:A10", paramMissing), XlAutoFillType.xlFillSeries);

// Create a two-color ColorScale object for the created sample data
// range.
cfColorScale = (ColorScale)(targetSheet.get_Range("A1:A10",
Type.Missing).FormatConditions.AddColorScale(2));

// Set the minimum threshold to red (0x000000FF) and maximum threshold
// to blue (0x00FF0000).
cfColorScale.ColorScaleCriteria[1].FormatColor.Color = 0x000000FF;
cfColorScale.ColorScaleCriteria[2].FormatColor.Color = 0x00FF0000;

How can we apply conditional formatting in C++ MFC?

range = ws.get_Range(COleVariant(_T("A1"), COleVariant(_T("A10")));
CFormatCondition fc;

fc = range.get_FormatConditions();


问:
How can I programmatically show a ShareLink sheet with SwiftUI (4.0)
This is how to implement in a view:

```<code>ShareLink(url) {
    Label("Share", systemImage: "square.and.arrow.up")
}
</code>```

How could I make this a programmatic experience?

Ex. Tap a button, do an async task, then show sharelink sheet when task is finished.

Body:
This is how to implement in a view:

ShareLink(url) {
    Label("Share", systemImage: "square.and.arrow.up")
}

How could I make this a programmatic experience?

Ex. Tap a button, do an async task, then show sharelink sheet when task is finished.


问:
Snowflake where clause not functioning properly fetching the incorrect answer
One of the query

```<code>select *
from "ANALYTICS_DEV"."DBT_schema"."WF3_M3_REGRESSION_MODEL"
where "quantile"= 0.8
</code>```

is fetching no records but there are records that would satisfy the condition.
The where clause is not working fine in snowflake. WF3_M3_REGRESSION_MODEL is a model in dbt that make use of the python in snowpark to do a regression model.

I tried using multiple equality operators in snowflake and its not helping.

Body:
One of the query

select *
from "ANALYTICS_DEV"."DBT_schema"."WF3_M3_REGRESSION_MODEL"
where "quantile"= 0.8

is fetching no records but there are records that would satisfy the condition.
The where clause is not working fine in snowflake. WF3_M3_REGRESSION_MODEL is a model in dbt that make use of the python in snowpark to do a regression model.

I tried using multiple equality operators in snowflake and its not helping.


问:
React rest call map result to selectbox with avatar and label per option
Hi here is rest response:

```<code>[
  {
    "self": "https://your-domain.atlassian.net/rest/api/3/project/EX",
    "id": "10000",
    "key": "EX",
    "name": "Example",
    "avatarUrls": {
      "48x48": "https://your-domain.atlassian.net/secure/projectavatar?size=large&pid=10000",
      "24x24": "https://your-domain.atlassian.net/secure/projectavatar?size=small&pid=10000",
      "16x16": "https://your-domain.atlassian.net/secure/projectavatar?size=xsmall&pid=10000",
      "32x32": "https://your-domain.atlassian.net/secure/projectavatar?size=medium&pid=10000"
    },
    "projectCategory": {
      "self": "https://your-domain.atlassian.net/rest/api/3/projectCategory/10000",
      "id": "10000",
      "name": "FIRST",
      "description": "First Project Category"
    },
    "simplified": false,
    "style": "classic",
    "insight": {
      "totalIssueCount": 100,
      "lastIssueUpdateTime": "2022-12-08T07:09:19.702+0000"
    }
  },
  {
    "self": "https://your-domain.atlassian.net/rest/api/3/project/ABC",
    "id": "10001",
    "key": "ABC",
    "name": "Alphabetical",
    "avatarUrls": {
      "48x48": "https://your-domain.atlassian.net/secure/projectavatar?size=large&pid=10001",
      "24x24": "https://your-domain.atlassian.net/secure/projectavatar?size=small&pid=10001",
      "16x16": "https://your-domain.atlassian.net/secure/projectavatar?size=xsmall&pid=10001",
      "32x32": "https://your-domain.atlassian.net/secure/projectavatar?size=medium&pid=10001"
    },
    "projectCategory": {
      "self": "https://your-domain.atlassian.net/rest/api/3/projectCategory/10000",
      "id": "10000",
      "name": "FIRST",
      "description": "First Project Category"
    },
    "simplified": false,
    "style": "classic",
    "insight": {
      "totalIssueCount": 100,
      "lastIssueUpdateTime": "2022-12-08T07:09:19.702+0000"
    }
  }
]
</code>```

I want to make select bobx having

```<code><option value={data.id}><Img {data.16x16}/>data.label</option>
</code>```

But result would be all projects if company has multiple projects so select box values have to map or loop into react

```<code><Select options="result">
</code>```

Im stuck as my code displays only label not any image there.
Another problem is that using data.avatarUrls.16x16 does not compile. VSCode says expecting "," and puts red underline to 16x16

Here is my code a lot is broken here because I have tested a lot ways but no luck

```<code>import React, { useState } from 'react';
import Select from 'react-select'

import { components } from 'react-select';

//Kun selectbox
const handleChange = event => {
  //console.log(event.target.value);
  setSelected(event.target.value);
};
//Palauttaa projectit json taulukon

const getProjects = async () => {
  //Matti tähän sitten atlasion cmpany projection haku
  const response = await api.asUser().requestJira(route`/rest/api/3/project`, {
    headers: {
      'Accept': 'application/json'
    }
  });
  const data = await response.json();
  //Mapataa hausta tarvittavat tiedot
  const result = data.map(function (item, i) {
    console.log('test');
    return [
      {
        label: item.name,
        value: item.id,
        avatar: item.avatarUrls.16x16
      }
    ]
  })
  return result
}

function Projects() {
  //haetaan atlasiansita projectit array
  const p = getProjects
  //asetetaan state selectbox muutokselle
  const [selected, setSelected] = useState(p.id);

  return (
    <div className='projects'>
      <Select
        className='select-projects'
        options={p}
        onChange={handleChange}
      />
    </div>
  );
}

export default Projects
</code>```

Body:
Hi here is rest response:

[
  {
    "self": "https://your-domain.atlassian.net/rest/api/3/project/EX",
    "id": "10000",
    "key": "EX",
    "name": "Example",
    "avatarUrls": {
      "48x48": "https://your-domain.atlassian.net/secure/projectavatar?size=large&pid=10000",
      "24x24": "https://your-domain.atlassian.net/secure/projectavatar?size=small&pid=10000",
      "16x16": "https://your-domain.atlassian.net/secure/projectavatar?size=xsmall&pid=10000",
      "32x32": "https://your-domain.atlassian.net/secure/projectavatar?size=medium&pid=10000"
    },
    "projectCategory": {
      "self": "https://your-domain.atlassian.net/rest/api/3/projectCategory/10000",
      "id": "10000",
      "name": "FIRST",
      "description": "First Project Category"
    },
    "simplified": false,
    "style": "classic",
    "insight": {
      "totalIssueCount": 100,
      "lastIssueUpdateTime": "2022-12-08T07:09:19.702+0000"
    }
  },
  {
    "self": "https://your-domain.atlassian.net/rest/api/3/project/ABC",
    "id": "10001",
    "key": "ABC",
    "name": "Alphabetical",
    "avatarUrls": {
      "48x48": "https://your-domain.atlassian.net/secure/projectavatar?size=large&pid=10001",
      "24x24": "https://your-domain.atlassian.net/secure/projectavatar?size=small&pid=10001",
      "16x16": "https://your-domain.atlassian.net/secure/projectavatar?size=xsmall&pid=10001",
      "32x32": "https://your-domain.atlassian.net/secure/projectavatar?size=medium&pid=10001"
    },
    "projectCategory": {
      "self": "https://your-domain.atlassian.net/rest/api/3/projectCategory/10000",
      "id": "10000",
      "name": "FIRST",
      "description": "First Project Category"
    },
    "simplified": false,
    "style": "classic",
    "insight": {
      "totalIssueCount": 100,
      "lastIssueUpdateTime": "2022-12-08T07:09:19.702+0000"
    }
  }
]

I want to make select bobx having

<option value={data.id}>data.label</option>

But result would be all projects if company has multiple projects so select box values have to map or loop into react

<Select options="result">

Im stuck as my code displays only label not any image there.
Another problem is that using data.avatarUrls.16x16 does not compile. VSCode says expecting "," and puts red underline to 16x16

Here is my code a lot is broken here because I have tested a lot ways but no luck

import React, { useState } from 'react';
import Select from 'react-select'

import { components } from 'react-select';

//Kun selectbox
const handleChange = event => {
  //console.log(event.target.value);
  setSelected(event.target.value);
};
//Palauttaa projectit json taulukon

const getProjects = async () => {
  //Matti tähän sitten atlasion cmpany projection haku
  const response = await api.asUser().requestJira(route`/rest/api/3/project`, {
    headers: {
      'Accept': 'application/json'
    }
  });
  const data = await response.json();
  //Mapataa hausta tarvittavat tiedot
  const result = data.map(function (item, i) {
    console.log('test');
    return [
      {
        label: item.name,
        value: item.id,
        avatar: item.avatarUrls.16x16
      }
    ]
  })
  return result
}

function Projects() {
  //haetaan atlasiansita projectit array
  const p = getProjects
  //asetetaan state selectbox muutokselle
  const [selected, setSelected] = useState(p.id);

  return (

      <Select
        className='select-projects'
        options={p}
        onChange={handleChange}
      />

  );
}

export default Projects


问:
OS X Lion: NIB/XIB doesn't seem to get loaded if app is launched as a Startup Item
I have a problem which is driving me nuts.

Suppose you have an app with a window that is set to "Visible at Launch". When you launch the app, the window immediatly appears.
If you add this simple app to the login startup items list, when you log in, the app is automatically launched and you have the window just opened in front of you. This is what was happening in Snow Leopard.

If you repeat the same steps in Lion, as soon as you log-in, the app is launched but the window does not appear.. It seems that the NIB doesn't get loaded.
To make it appear you have to click on the app icon in the dock (even if the app is already launched).

This happens even if you specify [NSApp disableRelaunchOnLogin] according to Apple documentation here.

Things become worst if your app has NSUIElement = 0 and therefore it doesn't have neither an icon in the Dock, nor a Menubar. In this case there's no way to make the window to appear.

Is there a way to obtain the expected behavior of Snow Leopard? Am I missing something?

ContentLicense: CC BY-SA 3.0


问:
How to detect WORDS regardless of character set, using a JS regex
This /[a-z]/i.test(s) is a JS regex that checks the string s for the presence of at least one alphabetic character.

That's great for English or Simplified English but I'd like to broaden it to match "letters" from all languages. What I'm actually trying to do is detect strings with words in them. Obviously things like Chinese aren't going to match [a-z].

Is there a reliable pan-language method to do this?

The question How can I use Unicode-aware regular expressions in JavaScript? mentions the \w symbol but the accepted response totally ignores this aspect and only covers how to enable Unicode support. It does not address the question of how to detect words.


问:
Connect react native with my dialogflow account
I am creating this application currently following this tutorial

When I send a message in the chatbot, the onSend function works, however, I get an error with my chatbot's response and I am given this error in the console.

Received response:

```<code>{
   "error":{
      "code":401,
      "message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie, or another valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
      "status":"UNAUTHENTICATED"
   }
}
</code>```

Can anyone help?

I have tried to see if my Google cloud APIs and services status is active and checked if my credentials have been revoked in IAM & Admin, still, the same error is returned in my console

Body:
I am creating this application currently following this tutorial

When I send a message in the chatbot, the onSend function works, however, I get an error with my chatbot's response and I am given this error in the console.

Received response:

{
   "error":{
      "code":401,
      "message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie, or another valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
      "status":"UNAUTHENTICATED"
   }
}

Can anyone help?

I have tried to see if my Google cloud APIs and services status is active and checked if my credentials have been revoked in IAM & Admin, still, the same error is returned in my console


问:
comparator and conditional in Thymeleaf in one expression
trying to compare object to Enum and then to display proper result. I have Enum:

```<code>public enum GameStatus {

    NOTPLAYED("notPlayedGame"),
    PLAYED("playedGame");

    private final String gameStatus;

     GameStatus(String gameStatus) {
        this.gameStatus = gameStatus;
    }
    public String toString() {
        return gameStatus;
    }
}
</code>```

and trying like that:

```<code><td th:text="(${g.getGameStatus()} == 'notPlayedGame')? '-' : ${g.hostScore}"></td>

</code>```

but always got displayed g.hostScore result. even when adding one line earlier:

```<code><td th:text="${g.getGameStatus()}"></td>
</code>```

to compare and where the result is right one- "notPlayedGame".
so pls help me to find my oversight. how it should correctly look like???

Body:
trying to compare object to Enum and then to display proper result. I have Enum:

public enum GameStatus {

    NOTPLAYED("notPlayedGame"),
    PLAYED("playedGame");

    private final String gameStatus;

     GameStatus(String gameStatus) {
        this.gameStatus = gameStatus;
    }
    public String toString() {
        return gameStatus;
    }
}

and trying like that:

but always got displayed g.hostScore result. even when adding one line earlier:

to compare and where the result is right one- "notPlayedGame".
so pls help me to find my oversight. how it should correctly look like???


问:
I need advice on aggregating data in a spreadsheet to be analyzed with Python
I want to input the past couple of years of my high school soccer team's stat books into a spreadsheet so I can run my own analysis on it using Python in Google Colab or a Jupyter Notebook. The problem I have right now is that I don't know what the best way of aggregating it in Excel is. I have a record of basic stats such as lineups, shots, saves, goals, assists, etc. for each individual game (standard box score stuff you'd expect from a high school team who uses a JV player to keep stats). But what would be the best way to input all of this in a way that will make it easy for me to analyze? Obviously I can't make a separate Excel tab for each individual game (there are hundreds of games), and I don't think logging them all into the same tab would be the best thing to do either, but I don't what I should do in order to solve this problem. This seems like a simple problem, and I'm probably missing a really obvious solution, but if anyone could give me some advice, I'd be very grateful. Does anyone have any experience doing anything similar? Thanks for taking the time to help.

I haven't tried anything yet because I wanted to figure out a good method before I put a bunch of time into this.


问:
Translation missing only for link's title
I'm using I18n and it works fine but I noticed that it shows a translation missing in the link's title:

```<code><li><%= link_to t("menu.admin.publishers"), admin_publishers_path %></li>
</code>```

I have this in the en.yml:

```<code>en:
  menu:
    admin:
      publishers: "Publishers"
</code>```

But it is generating:

```<code><li><a href="/admin/publishers"><span class="translation_missing" title="translation missing: en.menu.admin.publishers">Publishers</span></a></li>
</code>```

So in the content of the span tag is translating correctly but in title it is generating a translation missing error. I understood that it is adding twice the language prefix.

I'm using rails 3.0.7 and the locale config is the default one.

I followed the documentation on http://guides.rubyonrails.org/i18n.html but with no success.

Anyone knows how to solve this? or have seen this before?

Body:
I'm using I18n and it works fine but I noticed that it shows a translation missing in the link's title:

<%= link_to t("menu.admin.publishers"), admin_publishers_path %>

I have this in the en.yml:

en:
  menu:
    admin:
      publishers: "Publishers"

But it is generating:

Publishers

So in the content of the span tag is translating correctly but in title it is generating a translation missing error. I understood that it is adding twice the language prefix.

I'm using rails 3.0.7 and the locale config is the default one.

I followed the documentation on http://guides.rubyonrails.org/i18n.html but with no success.

Anyone knows how to solve this? or have seen this before?


问:
Developing on Unity -> Steam VR -> Oculus Link -> Quest2: Laggy
Anybody that has experience with developing for VR: do you know if testing your game/scene this way is even possible?
Right now it is very laggy. When I play normal games through SteamVR on the Quest everything works as expected.
Maybe I should build/test on the Oculus without going through SteamVR?</p>


问:
Android - Get ID of item at specific index in string-array resource
So I have a string-array I have defined in an XML file that is comprised of about 20 or so different string items that are defined outside the string-array container in the xml file. Each string item has it's own uniquely defined name (and also ID if my understanding is correct). I want to get the ID of the item at index 17 of the string-array, how would I do this?</p>


问:
Validation of request data defined by OpenApi specification in TypeScript
I have OpenApi/nswag specification json file, which contains validation/format metadata (only important part is shown):

```<code>{
  "x-generator": "NSwag v13.18.2.0 (NJsonSchema v10.8.0.0 (Newtonsoft.Json v10.0.0.0))",
  "swagger": "2.0",
  "paths": {
    "/api/Public/Register": {
      "post": {
        "operationId": "Public_Register",
        "parameters": [
          {
            "type": "string",
            "name": "email",
            "in": "query",
            "format": "email",
            "x-nullable": true
          },
          {
            "type": "string",
            "name": "password",
            "in": "query",
            "maxLength": 100,
            "minLength": 12,
            "x-nullable": true
          }
        ],
        "responses": {
          "200": {}
        }
      }
    }
  }
}
</code>```

Also I have generated typescript proxy class using nswag:

```<code>    register(email: string | null | undefined, password: string | null | undefined): Promise<void> {
        let url_ = this.baseUrl + "/api/Public/Register?";
        if (email !== undefined && email !== null)
            url_ += "email=" + encodeURIComponent("" + email) + "&";
        if (password !== undefined && password !== null)
            url_ += "password=" + encodeURIComponent("" + password) + "&";
        url_ = url_.replace(/[?&]$/, "");

        let options_: RequestInit = {
            method: "POST",
            headers: {
            }
        };

        return this.transformOptions(options_).then(transformedOptions_ => {
            return this.http.fetch(url_, transformedOptions_);
        }).then((_response: Response) => {
            return this.transformResult(url_, _response, (_response: Response) => this.processRegister(_response));
        });
    }
</code>```

And it does not contain any validation code. How can I add it?
May be I can use any other tools to load JSON specification and just execute validation using transformOptions ? Do we have any validation SDKs which supports openAPI/swagger?

Body:
I have OpenApi/nswag specification json file, which contains validation/format metadata (only important part is shown):

{
  "x-generator": "NSwag v13.18.2.0 (NJsonSchema v10.8.0.0 (Newtonsoft.Json v10.0.0.0))",
  "swagger": "2.0",
  "paths": {
    "/api/Public/Register": {
      "post": {
        "operationId": "Public_Register",
        "parameters": [
          {
            "type": "string",
            "name": "email",
            "in": "query",
            "format": "email",
            "x-nullable": true
          },
          {
            "type": "string",
            "name": "password",
            "in": "query",
            "maxLength": 100,
            "minLength": 12,
            "x-nullable": true
          }
        ],
        "responses": {
          "200": {}
        }
      }
    }
  }
}

Also I have generated typescript proxy class using nswag:

    register(email: string | null | undefined, password: string | null | undefined): Promise<void> {
        let url_ = this.baseUrl + "/api/Public/Register?";
        if (email !== undefined && email !== null)
            url_ += "email=" + encodeURIComponent("" + email) + "&";
        if (password !== undefined && password !== null)
            url_ += "password=" + encodeURIComponent("" + password) + "&";
        url_ = url_.replace(/[?&]$/, "");

        let options_: RequestInit = {
            method: "POST",
            headers: {
            }
        };

        return this.transformOptions(options_).then(transformedOptions_ => {
            return this.http.fetch(url_, transformedOptions_);
        }).then((_response: Response) => {
            return this.transformResult(url_, _response, (_response: Response) => this.processRegister(_response));
        });
    }

And it does not contain any validation code. How can I add it?
May be I can use any other tools to load JSON specification and just execute validation using transformOptions ? Do we have any validation SDKs which supports openAPI/swagger?


问:
TypeError: Cannot read properties of undefined (reading 'GUILDS')
I have looked over all over and I know there are similar threads here but I can't seam to figure it out. I have made a discord bot but it has problem with guilds and get the error in name.

const { Client, GatewayIntentBits, Collection, MessageEmbed } = require('discord.js');
const { getVoiceConnection } = require("@discordjs/voice");

const client = new Client(clientSettingsObject());

client.deploySlash = {
  enabled: true,
  guild: false,
}
client.config = require("./config/config.json");

client.commands = new Collection();
client.slashCommands = new Collection();
client.queues = new Collection();

require("./util/musicUtils.js")(client);

require("./util/handler.js")(client);

client.login(client.config.token);

function clientSettingsObject() {
  return {
    shards: "auto",
    allowedMentions: {
      parse: ["roles", "users", "everyone" ],
      repliedUser: false,
    },
    failIfNotExists: false,
    partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
    GatewayIntentBits: [
        GatewayIntentBits.FLAGS.GUILDS,
        GatewayIntentBits.FLAGS.GUILD_MESSAGES,
        GatewayIntentBits.FLAGS.GUILD_VOICE_STATES
        ]
    }
}

```

I would expect it to work but have no clue, sorry for inconvenience but I am new to programing and is trying to learn, would be much appreciated

Body:
I have looked over all over and I know there are similar threads here but I can't seam to figure it out. I have made a discord bot but it has problem with guilds and get the error in name.

const { Client, GatewayIntentBits, Collection, MessageEmbed } = require('discord.js');
const { getVoiceConnection } = require("@discordjs/voice");

const client = new Client(clientSettingsObject());

client.deploySlash = {
  enabled: true,
  guild: false,
}
client.config = require("./config/config.json");

client.commands = new Collection();
client.slashCommands = new Collection();
client.queues = new Collection();

require("./util/musicUtils.js")(client);

require("./util/handler.js")(client);

client.login(client.config.token);

function clientSettingsObject() {
  return {
    shards: "auto",
    allowedMentions: {
      parse: ["roles", "users", "everyone" ],
      repliedUser: false,
    },
    failIfNotExists: false,
    partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
    GatewayIntentBits: [
        GatewayIntentBits.FLAGS.GUILDS,
        GatewayIntentBits.FLAGS.GUILD_MESSAGES,
        GatewayIntentBits.FLAGS.GUILD_VOICE_STATES
        ]
    }
}

I would expect it to work but have no clue, sorry for inconvenience but I am new to programing and is trying to learn, would be much appreciated


问:
Stored procedures with two input dates - is there any way to load before query - BigQuery SQL
I am being asked to run a query everyday and would like to have it automated but the stored procedure requires me to update the start and end dates.

Format is yyyymmdd (example: '20221220', '20221221')

```<code>call A.procedure ('startdate', 'enddate');
</code>```

I've tried declaring or setting date values - with no success.

Body:
I am being asked to run a query everyday and would like to have it automated but the stored procedure requires me to update the start and end dates.

Format is yyyymmdd (example: '20221220', '20221221')

call A.procedure ('startdate', 'enddate');

I've tried declaring or setting date values - with no success.


问:
When using listview to display millions of data, the spacing will become larger and smaller
When using listview to display millions of data, the spacing will become larger and smaller.

```<code>import QtQuick 2.0

import QtGraphicalEffects 1.0

Item
{
    width: 1000
    height: 1000
    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            testListView.positionViewAtEnd()
        }
    }
    ListView
    {
        id:testListView
        width: 500
        height: 600
        model: 1000000
        delegate: listViewDelegate
    }
    Component
    {
        id:listViewDelegate
        Rectangle
        {
            width: 500
            height: 100
            color: "red"
            Text
            {
                text: index
                anchors.centerIn: parent
            }
        }
    }
}
</code>```

There is a problem when running the above code, how should I solve this problem.

Body:
When using listview to display millions of data, the spacing will become larger and smaller.

import QtQuick 2.0

import QtGraphicalEffects 1.0

Item
{
    width: 1000
    height: 1000
    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            testListView.positionViewAtEnd()
        }
    }
    ListView
    {
        id:testListView
        width: 500
        height: 600
        model: 1000000
        delegate: listViewDelegate
    }
    Component
    {
        id:listViewDelegate
        Rectangle
        {
            width: 500
            height: 100
            color: "red"
            Text
            {
                text: index
                anchors.centerIn: parent
            }
        }
    }
}

There is a problem when running the above code, how should I solve this problem.


问:
How could I invoke Microsoft Password Provider's LogonPasswordReset in my custom credential provider?
I have a custom credential provider to do 2fa authentication and I want to use self service password reset of windows. I found LogonPasswordReset in the registry:

```<code>HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{8841d728-1a76-4682-bb6f-a9ea53b4b3ba}porint to keymgr.dll
</code>```

and LogonPasswordReset under the password provider:

```<code>\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\{60b78e88-ead8-445c-9cfd-0b87f74ea6cd}\LogonPasswordReset
</code>```

Is there any way to invoke this LogonPasswordReset ?

Or Is there any Windows API to get the security questions list of passwords and how to pass them to reset the password of windows?

Body:
I have a custom credential provider to do 2fa authentication and I want to use self service password reset of windows. I found LogonPasswordReset in the registry:

HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{8841d728-1a76-4682-bb6f-a9ea53b4b3ba}porint to keymgr.dll

and LogonPasswordReset under the password provider:

\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\{60b78e88-ead8-445c-9cfd-0b87f74ea6cd}\LogonPasswordReset

Is there any way to invoke this LogonPasswordReset ?

Or Is there any Windows API to get the security questions list of passwords and how to pass them to reset the password of windows?


问:
ValueError: Input 0 of layer conv1d_26 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: [167, 8]
This is my code:

def cnn_model(data):
    BATCH_SIZE, TIMESTEPS, FEATURES = 167, data.shape[0], data.shape[1]
    input_shape = (BATCH_SIZE, TIMESTEPS, FEATURES)
    #input_shape = (1,8)

    inp = keras.layers.Input(shape=input_shape)
    conv1 = keras.layers.Conv1D(filters=32, kernel_size=3, activation='relu', input_shape=input_shape[1:])(inp)
    conv2 = keras.layers.Conv1D(filters=64, kernel_size=3, strides=4, activation='relu')(conv1)

    #flat = keras.layers.Flatten()(conv2)
    d1 = keras.layers.Dense(units=16, activation='relu')(conv2)
    out = keras.layers.Dense(units=1, activation='sigmoid')(d1)

    model = keras.Model(inputs=inp, outputs=out, name='motion_classfier')
    print(model.summary())
    return model

model = cnn_model(x_train)
```
<p>Following is the dataset:</p>
```x_train: (324147, 8) | y_train: (324147, 1)
x_val: (259317, 8)   | y_val: (259317, 1)
x_test: (64830, 8)  | y_test: (64830, 1)
```
<p>Error:</p>
```WARNING:tensorflow:Model was constructed with shape (None, 167, 324147, 8) for input Tensor("input_13:0", shape=(None, 167, 324147, 8), dtype=float32), but it was called on an input with incompatible shape (167, 8).
```
```ValueError: Input 0 of layer conv1d_26 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: [167, 8]
```

I am working with 1D convolutional NN to perform time-series classification.

Body:
This is my code:

def cnn_model(data):
    BATCH_SIZE, TIMESTEPS, FEATURES = 167, data.shape[0], data.shape[1]
    input_shape = (BATCH_SIZE, TIMESTEPS, FEATURES)
    #input_shape = (1,8)

    inp = keras.layers.Input(shape=input_shape)
    conv1 = keras.layers.Conv1D(filters=32, kernel_size=3, activation='relu', input_shape=input_shape[1:])(inp)
    conv2 = keras.layers.Conv1D(filters=64, kernel_size=3, strides=4, activation='relu')(conv1)

    #flat = keras.layers.Flatten()(conv2)
    d1 = keras.layers.Dense(units=16, activation='relu')(conv2)
    out = keras.layers.Dense(units=1, activation='sigmoid')(d1)

    model = keras.Model(inputs=inp, outputs=out, name='motion_classfier')
    print(model.summary())
    return model

model = cnn_model(x_train)

Following is the dataset:

x_train: (324147, 8) | y_train: (324147, 1)
x_val: (259317, 8)   | y_val: (259317, 1)
x_test: (64830, 8)  | y_test: (64830, 1)

Error:

WARNING:tensorflow:Model was constructed with shape (None, 167, 324147, 8) for input Tensor("input_13:0", shape=(None, 167, 324147, 8), dtype=float32), but it was called on an input with incompatible shape (167, 8).

ValueError: Input 0 of layer conv1d_26 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: [167, 8]

I am working with 1D convolutional NN to perform time-series classification.


问:
Append result of pymol iterate in a variable
I have the following code:

```<code>def grab(resi):
    s1 = f"resi {resi} & name P"
    s2 = f"resi {resi} & name C4'"
    s3 = f"resi {int(resi) + 1} & name P"
    s4 = f"resi {int(resi) +1 } & name C4'"

    try:
        dih = round(cmd.get_dihedral(s1,s2,s3,s4),2)
    except:
        dih = None

    return s1,s2,s3,s4,dih
</code>```
```<code>myspace = {"grab": grab}
cmd.iterate("(name P)","grab(resi)",space=myspace)
</code>```

This function basically grab some specific atoms and returns the dihaedral tuple. And that's exacly what I want.

The code return the following:

```<code>('resi 2 & name P',
 "resi 2 & name C4'",
 'resi 3 & name P',
 "resi 3 & name C4'",
 172.29)

('resi 3 & name P',
 "resi 3 & name C4'",
 'resi 4 & name P',
 "resi 4 & name C4'",
 -139.65)
...
</code>```

So, the code just print me the returned content of the function, I'd like to add this to a variable so that I can manipulate it.

In other words, I want a list of tuple connected to a variable:

```<code>my_final_list
> [('resi 2 & name P',
 "resi 2 & name C4'",
 'resi 3 & name P',
 "resi 3 & name C4'",
 172.29),('resi 3 & name P',
 "resi 3 & name C4'",
 'resi 4 & name P',
 "resi 4 & name C4'",
 -139.65) ..]
</code>```

Probably its easier than I think but I just can't arrive to the solution.

Body:
I have the following code:

def grab(resi):
    s1 = f"resi {resi} & name P"
    s2 = f"resi {resi} & name C4'"
    s3 = f"resi {int(resi) + 1} & name P"
    s4 = f"resi {int(resi) +1 } & name C4'"

    try:
        dih = round(cmd.get_dihedral(s1,s2,s3,s4),2)
    except:
        dih = None

    return s1,s2,s3,s4,dih

myspace = {"grab": grab}
cmd.iterate("(name P)","grab(resi)",space=myspace)

This function basically grab some specific atoms and returns the dihaedral tuple. And that's exacly what I want.

The code return the following:

('resi 2 & name P',
 "resi 2 & name C4'",
 'resi 3 & name P',
 "resi 3 & name C4'",
 172.29)

('resi 3 & name P',
 "resi 3 & name C4'",
 'resi 4 & name P',
 "resi 4 & name C4'",
 -139.65)
...

So, the code just print me the returned content of the function, I'd like to add this to a variable so that I can manipulate it.

In other words, I want a list of tuple connected to a variable:

my_final_list
> [('resi 2 & name P',
 "resi 2 & name C4'",
 'resi 3 & name P',
 "resi 3 & name C4'",
 172.29),('resi 3 & name P',
 "resi 3 & name C4'",
 'resi 4 & name P',
 "resi 4 & name C4'",
 -139.65) ..]

Probably its easier than I think but I just can't arrive to the solution.


问:
what's the difference of optionalDependencies and peerDependenciesMeta's optional?
both of them are marking dependency as optional, so what's the use-case of each?

Is peerDependenciesMeta for npm package and the optionalDependencies for project?

I have a npm package, some modules in it need dependency foo, but if you don't import it, the relative peerDependency is able to not install


问:
Firefox: Error fetching cached project bundle for preview
Using stackblitz in firefox i get the following error. in firefox browser can't use stackblitz?

other projects i can but this angular project i can't.

If you know the solution can you please teach me.

The project that I want to open in firefox

・the url that comes out error in stackblitz.io

・the project i want to open in firefox

error message

Error fetching cached project bundle for preview.

※in google chrome I don't even get an error, I can open normally.


问:
Add a copy of object to a list<object> in java
I have a Object listA which has a list b inside it.
I need to save this modified object inside ArrayList
once I add the object to the arraylist and delete or update the old listA
java is deleting the copied list.</p>
```<code>public void test(ListA listA) {
ArrayList<ListA> tempListA = new ArrayList<>();
List<ListB> tempListB = new ArrayList<>(listA.getListB());
tempListB.forEach(loopList -> {
    listA.getListB().clear();
    listA.getListB().add(loopList);
    tempListA.add(listA);
    listA.remove(0);
});
}
</code>```

Body:
I have a Object listA which has a list b inside it.
I need to save this modified object inside ArrayList
once I add the object to the arraylist and delete or update the old listA
java is deleting the copied list.

public void test(ListA listA) {
ArrayList<ListA> tempListA = new ArrayList<>();
List<ListB> tempListB = new ArrayList<>(listA.getListB());
tempListB.forEach(loopList -> {
    listA.getListB().clear();
    listA.getListB().add(loopList);
    tempListA.add(listA);
    listA.remove(0);
});
}


问:
How would I pull and append each iteration of the href when I create a data frame from the webpage, and create its own column in the dataframe?
I am going through all the NBA players that have ever existed and making a dataframe with pertinent information, in order to do so I have to go through alphabetized webpages (alphabetized by last name) and extract the name and URL for each player from the table along with other details like school, position, and so forth. Below is an example of a table class with one player on one of the URLs:

```<code><tr data-row="0">
  <th scope="row" class="left " data-append-csv="abdelal01" data-stat="player">
   <a href="/players/a/abdelal01.html">Alaa Abdelnaby</a> #I want to get this URL when pulling the data frame
  </th>
 <td class="right " data-stat="year_min">1991</td>
 <td class="right " data-stat="year_max">1995</td>
 <td class="center " data-stat="pos">F-C</td>
 <td class="right " data-stat="height" csk="82.0">6-10</td>
 <td class="right " data-stat="weight">240</td>
 <td class="left " data-stat="birth_date" csk="19680624">
  <a href="/friv/birthdays.cgi?month=6&day=24">June 24, 1968</a>
 </td>
 <td class="left " data-stat="colleges">
  <a href="/friv/colleges.fcgi?college=duke">Duke</a></td>
</tr>
</code>```

I'm hoping to get a dataframe with the columns similar to below:

Name/Year_min/Year-max/PosHeight/Weight/Birthdate/College/PlayerURL

The PlayerURL will be the first a href

That said, I did perfectly fine extracting each row for the dataframe with the following Python code:

```<code>letters = list(string.ascii_lowercase)
playerlist_2023 = []
for letter in letters:
    playerlist = pd.read_html("https://www.basketball-reference.com/players/{}".format(letter))[0]
    time.sleep(4)

    playerlist_2023.append(playerlist)
</code>```

How can I also include the URL as a string in its own column as well?

Body:
I am going through all the NBA players that have ever existed and making a dataframe with pertinent information, in order to do so I have to go through alphabetized webpages (alphabetized by last name) and extract the name and URL for each player from the table along with other details like school, position, and so forth. Below is an example of a table class with one player on one of the URLs:

   Alaa Abdelnaby #I want to get this URL when pulling the data frame

 1991
 1995
 F-C
 6-10
 240

  June 24, 1968

  Duke

I'm hoping to get a dataframe with the columns similar to below:

Name/Year_min/Year-max/PosHeight/Weight/Birthdate/College/PlayerURL

The PlayerURL will be the first a href

That said, I did perfectly fine extracting each row for the dataframe with the following Python code:

letters = list(string.ascii_lowercase)
playerlist_2023 = []
for letter in letters:
    playerlist = pd.read_html("https://www.basketball-reference.com/players/{}".format(letter))[0]
    time.sleep(4)

    playerlist_2023.append(playerlist)

How can I also include the URL as a string in its own column as well?


问:
Azure Data Factory run New Job Cluster Mode Databricks Python Wheel
We are trying to install the external libraries via Azure data factory. After that we are planning to execute our notebook. Inside the notebook we will be using many different libraries to achieve the business logic.

In the Azure data factory, there is the Append Libraries option from where is possible to install new runtime libraries to the job cluster.

Our linked service connects always to a NEW JOB CLUSTER but we are getting below error while execute the ADF pipelines.

Run result unavailable: job failed with error message  Library
installation failed for library due to user error for whl:

"dbfs:/FileStore/jars/ephem-4.1.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl"

. Error messages: Library installation attempted on the driver node of
cluster 1226-023738-9cm6lm7d and failed. Please refer to the following
error message to fix the library or contact Databricks support.

Error Code: DRIVER_LIBRARY_INSTALLATION_FAILURE.

Error Message:
java.util.concurrent.ExecutionException:

java.io.FileNotFoundException:

dbfs:/FileStore/jars/ephem-4.1.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl


问:
How to change the following printer properties, SpoolEnabled & KeepPrintedJobs, using C#?
I'm trying to change the printer properties, SpoolEnabled & KeepPrintedJobs, using C#. I tried using the win32_printer but the SpoolEnabled value didn't change. I'm using .NET windows forms (4.6) & Windows 10.

```<code>ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Printer Where Default = True");
ManagementObjectCollection printerCollection = new ManagementObjectSearcher(query).Get();
if (printerCollection.Count > 0)
{
            foreach (ManagementObject printer in printerCollection)
            {
                PropertyDataCollection printerProperties = printer.Properties;
                if ((bool)printerProperties["Default"].Value)
                {
                    printerProperties["SpoolEnabled"].Value = true;
                    printer.Put();

                }
            }
}
</code>```

Also, I tried using the following code with no success:

```<code>    ManagementPath mPath = new ManagementPath("//./root/cimv2");
    mPath.RelativePath = "Win32_Printer.DeviceID=\"" + PrinterName + "\"";
    ManagementObject Printer = new ManagementObject(mPath);
    string oldname = Printer.Properties["SpoolEnabled"].Value.ToString();
    Printer.Properties["SpoolEnabled"].Value = true;
    Printer.Put();
</code>```

What library should I use, using c#, to change the SpoolEnabled & KeepPrintedJobs properties?

Body:
I'm trying to change the printer properties, SpoolEnabled & KeepPrintedJobs, using C#. I tried using the win32_printer but the SpoolEnabled value didn't change. I'm using .NET windows forms (4.6) & Windows 10.

ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Printer Where Default = True");
ManagementObjectCollection printerCollection = new ManagementObjectSearcher(query).Get();
if (printerCollection.Count > 0)
{
            foreach (ManagementObject printer in printerCollection)
            {
                PropertyDataCollection printerProperties = printer.Properties;
                if ((bool)printerProperties["Default"].Value)
                {
                    printerProperties["SpoolEnabled"].Value = true;
                    printer.Put();

                }
            }
}

Also, I tried using the following code with no success:

    ManagementPath mPath = new ManagementPath("//./root/cimv2");
    mPath.RelativePath = "Win32_Printer.DeviceID=\"" + PrinterName + "\"";
    ManagementObject Printer = new ManagementObject(mPath);
    string oldname = Printer.Properties["SpoolEnabled"].Value.ToString();
    Printer.Properties["SpoolEnabled"].Value = true;
    Printer.Put();

What library should I use, using c#, to change the SpoolEnabled & KeepPrintedJobs properties?


问:
SSH from local Ubuntu laptop to Windows host usinng Remote-SSH VScode
Can someone help me with the steps to connect my Ubuntu local laptop to a remote Windows 10 host with WSL using Remote -SSH extension vscode?

I tried to find a tutorial but couldn't.


问:
Something like vertex_id for Metal fragment shader, to identify fragment?
Vertex shaders in Metal can use a [[vertex_id]] attribute on an integer argument, and  that argument will get values between 0 and the number of vertexes. Is there a similar thing for fragment shaders?

I want to write some debug info to a buffer, within the fragment shader, as shown below. Then in the CPU code, I would print the contents of the buffer, as a way to debug what is going on in the fragment shader.

```<code>struct VertexIn {
    float4 position [[attribute(0)]];
};

struct VertexOut {
    float4 position [[position]];
};

vertex VertexOut vertex_main(const VertexIn vertex_in [[stage_in]]) {
    VertexOut out;
    out.position = vertex_in.position;
    return out;
}

fragment float4
fragment_main(VertexOut vo [[stage_in]],
              uint fragment_id [[fragment_id]],   // <-- Hypothetical, doesn't actually work.
              device float4 *debug_out [[buffer(0)]],
              device uint *debug_out2 [[buffer(1)]])
{
    debug_out[fragment_id] = vo.position;
    debug_out2[fragment_id] = ...
    return float4(0, 1, clamp(vo.position.x/1000, 0.0, 1.0), 1);
}
</code>```

Body:
Vertex shaders in Metal can use a [[vertex_id]] attribute on an integer argument, and  that argument will get values between 0 and the number of vertexes. Is there a similar thing for fragment shaders?

I want to write some debug info to a buffer, within the fragment shader, as shown below. Then in the CPU code, I would print the contents of the buffer, as a way to debug what is going on in the fragment shader.

struct VertexIn {
    float4 position [[attribute(0)]];
};

struct VertexOut {
    float4 position [[position]];
};

vertex VertexOut vertex_main(const VertexIn vertex_in [[stage_in]]) {
    VertexOut out;
    out.position = vertex_in.position;
    return out;
}

fragment float4
fragment_main(VertexOut vo [[stage_in]],
              uint fragment_id [[fragment_id]],   // <-- Hypothetical, doesn't actually work.
              device float4 *debug_out [[buffer(0)]],
              device uint *debug_out2 [[buffer(1)]])
{
    debug_out[fragment_id] = vo.position;
    debug_out2[fragment_id] = ...
    return float4(0, 1, clamp(vo.position.x/1000, 0.0, 1.0), 1);
}


问:
Color similarity for multiple colored images
I am trying to compare color between multiple images. My target is to find similar colored images sorted by the highest similarity score.

For example:

The input image is:

Current output:

I have tried different methods. I have cropped the image in the center and resized it to 10x10, and used cosine or euclidean distance to compare the image.

I have also used Kmeans clustering to find the dominating color and sort using the dominating color distances. I have also convolved the image down to a 12x12 image and compared it.

It works only for single-colored images. But none of methods works for multiple colored images.
If you see the example, I want the 2nd and 3rd images on the top because those clothes are a similar color to the input.

What would be the correct method to achieve it?


问:
Flutter go_router Match error found during build
I'm receiving this error every time I try to open the dynamic link

But the error is only on IOS, in Android everything works perfectly.
This is how it navigates to needed page from the dynamic link:

```<code>Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => FlashcardDetailedPage(
                    flashcard: flashcard,
                    deck: deck,
                    toDownload: true,
                  )),
  );
</code>```

How to fix this?

Body:
I'm receiving this error every time I try to open the dynamic link

But the error is only on IOS, in Android everything works perfectly.
This is how it navigates to needed page from the dynamic link:

Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => FlashcardDetailedPage(
                    flashcard: flashcard,
                    deck: deck,
                    toDownload: true,
                  )),
  );

How to fix this?


问:
Error code 18 AuthenticationFailed when add Secondary in replica set MongoDB
I received the error below:

```<code>{"t":{"$date":"2022-12-24T11:00:54.895+00:00"},"s":"I",  "c":"NETWORK",  "id":4712102, "ctx":"ReplicaSetMonitor-TaskExecutor","msg":"Host failed in replica set","attr":{"replicaSet":"{Replset_name}","host":"{VPS_IP}:27019","error":{"code":18,"codeName":"AuthenticationFailed","errmsg":"Authentication failed."},"action":{"dropConnections":false,"requestImmediateCheck
</code>```

That error is shown in mongod.log when I add Secondary in the existing replica set MongoDB between different docker containers in 2 server machines.

My replica set structure includes the following:

Primary on VPS1_DO:container1 (actived) (same overlay-network)

Secondary1 on VPS1_DO:container2 (actived) (same overlay-network)

Secondary2 on VPS2_Azure:container1 (error)

Details in rs.status()

```<code>"members" : [
                {
                        "_id" : 0,
                        "name" : "10.5.0.11(staticIP-container1):27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 258904,
                        "optime" : {
                                "ts" : Timestamp(1672026076, 1),
                                "t" : NumberLong(67)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1672026076, 1),
                                "t" : NumberLong(67)
                        },
                        "optimeDate" : ISODate("2022-12-26T03:41:16Z"),
                        "optimeDurableDate" : ISODate("2022-12-26T03:41:16Z"),
                        "lastAppliedWallTime" : ISODate("2022-12-26T03:41:16.739Z"),
                        "lastDurableWallTime" : ISODate("2022-12-26T03:41:16.739Z"),
                        "lastHeartbeat" : ISODate("2022-12-26T03:41:17.962Z"),
                        "lastHeartbeatRecv" : ISODate("2022-12-26T03:41:18.521Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "syncSourceHost" : "10.5.0.12:27017",
                        "syncSourceId" : 1,
                        "infoMessage" : "",
                        "configVersion" : 17,
                        "configTerm" : 67
                },
                {
                        "_id" : 1,
                        "name" : "10.5.0.12(staticIP-container2):27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 589529,
                        "optime" : {
                                "ts" : Timestamp(1672026076, 1),
                                "t" : NumberLong(67)
                        },
                        "optimeDate" : ISODate("2022-12-26T03:41:16Z"),
                        "lastAppliedWallTime" : ISODate("2022-12-26T03:41:16.739Z"),
                        "lastDurableWallTime" : ISODate("2022-12-26T03:41:16.739Z"),
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1671767185, 1),
                        "electionDate" : ISODate("2022-12-23T03:46:25Z"),
                        "configVersion" : 17,
                        "configTerm" : 67,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                },
                {
                        "_id" : 2,
                        "name" : "178.128.xx.xxx(IP-VPS):27019",
                        "health" : 0,
                        "state" : 6,
                        "stateStr" : "(not reachable/healthy)",
                        "uptime" : 0,
                        "optime" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastAppliedWallTime" : ISODate("1970-01-01T00:00:00Z"),
                        "lastDurableWallTime" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2022-12-26T03:41:17.427Z"),
                        "lastHeartbeatRecv" : ISODate("1970-01-01T00:00:00Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "authenticated" : false,
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : -1,
                        "configTerm" : -1
                }
        ],
</code>```

And I ensure that I follow some rules:

Same MongoDB version (5.0.6)

Same mongod.conf file (same replSet name)

Same keyFile and chmod 400 (read-only)

Can ping each order (open port ICMP inbound)

Many thanks !!

Body:
I received the error below:

{"t":{"$date":"2022-12-24T11:00:54.895+00:00"},"s":"I",  "c":"NETWORK",  "id":4712102, "ctx":"ReplicaSetMonitor-TaskExecutor","msg":"Host failed in replica set","attr":{"replicaSet":"{Replset_name}","host":"{VPS_IP}:27019","error":{"code":18,"codeName":"AuthenticationFailed","errmsg":"Authentication failed."},"action":{"dropConnections":false,"requestImmediateCheck

That error is shown in mongod.log when I add Secondary in the existing replica set MongoDB between different docker containers in 2 server machines.

My replica set structure includes the following:

Primary on VPS1_DO:container1 (actived) (same overlay-network)

Secondary1 on VPS1_DO:container2 (actived) (same overlay-network)

Secondary2 on VPS2_Azure:container1 (error)

Details in rs.status()

"members" : [
                {
                        "_id" : 0,
                        "name" : "10.5.0.11(staticIP-container1):27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 258904,
                        "optime" : {
                                "ts" : Timestamp(1672026076, 1),
                                "t" : NumberLong(67)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1672026076, 1),
                                "t" : NumberLong(67)
                        },
                        "optimeDate" : ISODate("2022-12-26T03:41:16Z"),
                        "optimeDurableDate" : ISODate("2022-12-26T03:41:16Z"),
                        "lastAppliedWallTime" : ISODate("2022-12-26T03:41:16.739Z"),
                        "lastDurableWallTime" : ISODate("2022-12-26T03:41:16.739Z"),
                        "lastHeartbeat" : ISODate("2022-12-26T03:41:17.962Z"),
                        "lastHeartbeatRecv" : ISODate("2022-12-26T03:41:18.521Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "syncSourceHost" : "10.5.0.12:27017",
                        "syncSourceId" : 1,
                        "infoMessage" : "",
                        "configVersion" : 17,
                        "configTerm" : 67
                },
                {
                        "_id" : 1,
                        "name" : "10.5.0.12(staticIP-container2):27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 589529,
                        "optime" : {
                                "ts" : Timestamp(1672026076, 1),
                                "t" : NumberLong(67)
                        },
                        "optimeDate" : ISODate("2022-12-26T03:41:16Z"),
                        "lastAppliedWallTime" : ISODate("2022-12-26T03:41:16.739Z"),
                        "lastDurableWallTime" : ISODate("2022-12-26T03:41:16.739Z"),
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1671767185, 1),
                        "electionDate" : ISODate("2022-12-23T03:46:25Z"),
                        "configVersion" : 17,
                        "configTerm" : 67,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                },
                {
                        "_id" : 2,
                        "name" : "178.128.xx.xxx(IP-VPS):27019",
                        "health" : 0,
                        "state" : 6,
                        "stateStr" : "(not reachable/healthy)",
                        "uptime" : 0,
                        "optime" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("1970-01-01T00:00:00Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastAppliedWallTime" : ISODate("1970-01-01T00:00:00Z"),
                        "lastDurableWallTime" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2022-12-26T03:41:17.427Z"),
                        "lastHeartbeatRecv" : ISODate("1970-01-01T00:00:00Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "authenticated" : false,
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : -1,
                        "configTerm" : -1
                }
        ],

And I ensure that I follow some rules:

Same MongoDB version (5.0.6)

Same mongod.conf file (same replSet name)

Same keyFile and chmod 400 (read-only)

Can ping each order (open port ICMP inbound)

Many thanks !!


问:
Sveltekit How do I run code when server exits
How do I run code when my Sveltekit application is exiting?

I have a hooks.server.ts file that initializes a DB connection when the app starts. If my server shuts off, how do I close the connection?

Thanks