问:
S3 presigned url: 403 error when reading a file but OK when downloading
I am working with a s3 presigned url.
OK: links works well to download.
NOT OK: using the presigned url to read a file in the bucket

I am getting the following error in console:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AuthorizationQueryParametersError</Code><Message>Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.</Message>
</code>```

and here is how generate the url with boto3

```<code>    s3_client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'), region_name='eu-west-3')
    bucket_name = config("AWS_STORAGE_BUCKET_NAME")

    file_name = '{}/{}/{}/{}'.format(user, 'projects', building.building_id, file.file)

    ifc_url = s3_client.generate_presigned_url(
        'get_object',
        Params={
            'Bucket': bucket_name,
            'Key': file_name,
        },
        ExpiresIn=1799
    )

</code>```

I am using IFC.js which allows to load ifc formated models from their urls . Basically the url of the bucket acts as the path to the file. Accessing files in a public bucket has been working well however it won't work with private buckets.

Something to note as well is that using the presigned url copied from clipboard from the aws s3 interface works.
it looks like this:

```<code>"https://bucket.s3.eu-west-3.amazonaws.com/om1/projects/1/v1.ifc?response-content-disposition=inline&X-Amz-Security-Token=qqqqzdfffrA%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230105T224241Z&X-Amz-SignedHeaders=host&X-Amz-Expires=60&X-Amz-Credential=5%2Feu-west-3%2Fs3%2Faws4_request&X-Amz-Signature=c470c72b3abfb99"
</code>```

the one I obtain with boto3 is the following:

```<code>"https://bucket.s3.amazonaws.com/om1/projects/1/v1.ifc?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKI230105%2Feu-west-3%2Fs3%2Faws4_request&X-Amz-Date=20230105T223404Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=1b4f277b85639b408a9ee16e"
</code>```

I am fairly new to use s3 buckets so I am not sure what is wrong here, and searching around on SO and online has not been very helpful so far. Could anyone point me in the right direction?

Body:
I am working with a s3 presigned url.
OK: links works well to download.
NOT OK: using the presigned url to read a file in the bucket

I am getting the following error in console:

<?xml version="1.0" encoding="UTF-8"?>
<Error>AuthorizationQueryParametersError<Message>Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.</Message>

and here is how generate the url with boto3

    s3_client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'), region_name='eu-west-3')
    bucket_name = config("AWS_STORAGE_BUCKET_NAME")

    file_name = '{}/{}/{}/{}'.format(user, 'projects', building.building_id, file.file)

    ifc_url = s3_client.generate_presigned_url(
        'get_object',
        Params={
            'Bucket': bucket_name,
            'Key': file_name,
        },
        ExpiresIn=1799
    )

I am using IFC.js which allows to load ifc formated models from their urls . Basically the url of the bucket acts as the path to the file. Accessing files in a public bucket has been working well however it won't work with private buckets.

Something to note as well is that using the presigned url copied from clipboard from the aws s3 interface works.
it looks like this:

"https://bucket.s3.eu-west-3.amazonaws.com/om1/projects/1/v1.ifc?response-content-disposition=inline&X-Amz-Security-Token=qqqqzdfffrA%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230105T224241Z&X-Amz-SignedHeaders=host&X-Amz-Expires=60&X-Amz-Credential=5%2Feu-west-3%2Fs3%2Faws4_request&X-Amz-Signature=c470c72b3abfb99"

the one I obtain with boto3 is the following:

"https://bucket.s3.amazonaws.com/om1/projects/1/v1.ifc?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKI230105%2Feu-west-3%2Fs3%2Faws4_request&X-Amz-Date=20230105T223404Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=1b4f277b85639b408a9ee16e"

I am fairly new to use s3 buckets so I am not sure what is wrong here, and searching around on SO and online has not been very helpful so far. Could anyone point me in the right direction?


来源: stackexchange

问:
Nrwl NX enforce-module-boundaries - rule if lib does NOT have source tag?
We are trying to setup a lib in NX with a scope:example tag, such that it can only be imported by other libs with a scope:example tag.

We were hoping to set it up like this:

```<code>{
   "sourceTag": "scope:example",
   "onlyDependOnLibsWithTags": ["scope:example"]
},
{
  "sourceTag": "*",
  "notDependOnLibsWithTags": ["scope:example"]
}
</code>```

This doesn't work, because the 2nd rule applies even to the scope:example libs, preventing them from importing other scope:example libs.

We could fix this by adding a new tag to all of our existing libs, so we can replace the * in the second rule with that new tag.

This is not ideal, because if other devs make libs, the rule will not be enforced unless they manually add the new tag to it.

What would be ideal is something like:

```<code>{
   "sourceTag": "scope:example",
   "onlyDependOnLibsWithTags": ["scope:example"]
},
{
  "libsNotContainingSourceTag": "scope:example",
  "notDependOnLibsWithTags": ["scope:example"]
}
</code>```

Any help on any means to achieve the desired lint rule? Thanks in advance!

ContentLicense: CC BY-SA 4.0

Body:
We are trying to setup a lib in NX with a scope:example tag, such that it can only be imported by other libs with a scope:example tag.

We were hoping to set it up like this:

{
   "sourceTag": "scope:example",
   "onlyDependOnLibsWithTags": ["scope:example"]
},
{
  "sourceTag": "*",
  "notDependOnLibsWithTags": ["scope:example"]
}

This doesn't work, because the 2nd rule applies even to the scope:example libs, preventing them from importing other scope:example libs.

We could fix this by adding a new tag to all of our existing libs, so we can replace the * in the second rule with that new tag.

This is not ideal, because if other devs make libs, the rule will not be enforced unless they manually add the new tag to it.

What would be ideal is something like:

{
   "sourceTag": "scope:example",
   "onlyDependOnLibsWithTags": ["scope:example"]
},
{
  "libsNotContainingSourceTag": "scope:example",
  "notDependOnLibsWithTags": ["scope:example"]
}

Any help on any means to achieve the desired lint rule? Thanks in advance!


问:
How can I create a new user in Firebase without sign in automatically?
Using React js and Firebase.

I am new to firebase and generally programming. In a new project, a admin user should be able to create new users centrally.

```<code>createUserWithEmailAndPassword(auth, email, password1)
</code>```

By using this method, I am able to create new users. Nevertheless, I get logged in in this new users automatically. Is there any solution to avoid the automatic log in?

I already found some stack overflow questions from 2016 and 2018 and the common question is, that I need to run the Firebase Admin SDK on a server. Is this the only solution?
I would prefer to practice a little bit more my new ReactJS and Firebase knowledge before starting with these server side topics.

Body:
Using React js and Firebase.

I am new to firebase and generally programming. In a new project, a admin user should be able to create new users centrally.

createUserWithEmailAndPassword(auth, email, password1)

By using this method, I am able to create new users. Nevertheless, I get logged in in this new users automatically. Is there any solution to avoid the automatic log in?

I already found some stack overflow questions from 2016 and 2018 and the common question is, that I need to run the Firebase Admin SDK on a server. Is this the only solution?
I would prefer to practice a little bit more my new ReactJS and Firebase knowledge before starting with these server side topics.


问:
Quantization aware training in tensorflow makes my model predict allways the same class
I'm using tensorflow_model_optimization..quantization.keras.quantize_model on a VGG16 model pretrained on imagenet, to test transfer learning over cifar10. When trained normally for 5 epochs, accuracy reaches 60%, but when quantized it directly drops to 10% (random guessing), as it always predicts the same class. I also noticed that both evaluation and training are significantly lower with the quantized model.
This is the code:

```<code>import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.datasets import cifar10
from keras.applications.vgg16 import VGG16
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout, GlobalAveragePooling2D
from keras.models import Model
import tensorflow_model_optimization as tfmot

# Load the CIFAR10 data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()

# Input image dimensions and classes
input_shape = x_train.shape[1:]
num_classes = 10

# Target one-hot vectorization
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# Normalize data
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

# Import pre-trained layers and freeze them
base_model = keras.applications.vgg16.VGG16(include_top=False, input_shape=(32,32,3), weights="imagenet")
for layer in base_model.layers:
    layer.trainable = False

# Establish new fully connected block
x = base_model.output
x = Flatten()(x)  # flatten from convolution tensor output
x = Dense(4096, activation='relu')(x) # number of layers and units are hyperparameters, as usual
x = Dense(4096, activation='relu')(x)
x = Dropout(0.5)(x)
predictions = Dense(num_classes, activation='softmax')(x) # should match # of classes predicted

# This is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(optimizer="adam", loss='categorical_crossentropy', metrics=['accuracy', 'Precision', 'Recall'])

model.fit(x_train, y_train, batch_size=32, epochs = 5, verbose = 1, validation_data = (x_test, y_test))

# Quantize the model
model_quant = tfmot.quantization.keras.quantize_model(model)
model_quant.compile(optimizer="adam", loss="categorical_crossentropy", metrics=['accuracy', 'Precision', 'Recall'])

# Evaluate both models
print(model.evaluate(x_test, y_test))
print(model_quant.evaluate(x_test, y_test))
</code>```

This is the result:

```<code>313/313 [==============================] - 4s 12ms/step - loss: 1.1593 - accuracy: 0.6008 - precision: 0.7149 - recall: 0.4872
[1.1592937707901, 0.6007999777793884, 0.714893639087677, 0.487199991941452]
313/313 [==============================] - 16s 48ms/step - loss: 6.6550 - accuracy: 0.1000 - precision: 0.1000 - recall: 0.1000
[6.654963493347168, 0.10000000149011612, 0.10000000149011612, 0.10000000149011612]
</code>```

As you see, evaluation is x4 slower and doesn't work at all. When trying to see the predictions with model_quant.predict(x_test), the output is:

```<code>[[0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 ...
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]]
</code>```

Training the quantized model doesn't seem to improve accuracy, and each epoch lasts like 5 minutes when in previosly lasted less than 30 seconds.

I have based my code on the official page, but I fail to find what is going wrong in here.

Body:
I'm using tensorflow_model_optimization..quantization.keras.quantize_model on a VGG16 model pretrained on imagenet, to test transfer learning over cifar10. When trained normally for 5 epochs, accuracy reaches 60%, but when quantized it directly drops to 10% (random guessing), as it always predicts the same class. I also noticed that both evaluation and training are significantly lower with the quantized model.
This is the code:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.datasets import cifar10
from keras.applications.vgg16 import VGG16
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout, GlobalAveragePooling2D
from keras.models import Model
import tensorflow_model_optimization as tfmot

# Load the CIFAR10 data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()

# Input image dimensions and classes
input_shape = x_train.shape[1:]
num_classes = 10

# Target one-hot vectorization
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# Normalize data
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

# Import pre-trained layers and freeze them
base_model = keras.applications.vgg16.VGG16(include_top=False, input_shape=(32,32,3), weights="imagenet")
for layer in base_model.layers:
    layer.trainable = False

# Establish new fully connected block
x = base_model.output
x = Flatten()(x)  # flatten from convolution tensor output
x = Dense(4096, activation='relu')(x) # number of layers and units are hyperparameters, as usual
x = Dense(4096, activation='relu')(x)
x = Dropout(0.5)(x)
predictions = Dense(num_classes, activation='softmax')(x) # should match # of classes predicted

# This is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(optimizer="adam", loss='categorical_crossentropy', metrics=['accuracy', 'Precision', 'Recall'])

model.fit(x_train, y_train, batch_size=32, epochs = 5, verbose = 1, validation_data = (x_test, y_test))

# Quantize the model
model_quant = tfmot.quantization.keras.quantize_model(model)
model_quant.compile(optimizer="adam", loss="categorical_crossentropy", metrics=['accuracy', 'Precision', 'Recall'])

# Evaluate both models
print(model.evaluate(x_test, y_test))
print(model_quant.evaluate(x_test, y_test))

This is the result:

313/313 [==============================] - 4s 12ms/step - loss: 1.1593 - accuracy: 0.6008 - precision: 0.7149 - recall: 0.4872
[1.1592937707901, 0.6007999777793884, 0.714893639087677, 0.487199991941452]
313/313 [==============================] - 16s 48ms/step - loss: 6.6550 - accuracy: 0.1000 - precision: 0.1000 - recall: 0.1000
[6.654963493347168, 0.10000000149011612, 0.10000000149011612, 0.10000000149011612]

As you see, evaluation is x4 slower and doesn't work at all. When trying to see the predictions with model_quant.predict(x_test), the output is:

[[0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 ...
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]]

Training the quantized model doesn't seem to improve accuracy, and each epoch lasts like 5 minutes when in previosly lasted less than 30 seconds.

I have based my code on the official page, but I fail to find what is going wrong in here.


问:
Zend OPcache file cache
first of all I'm new here so I apologize if I'm posting something wrong.

I'm using php 8.0.26 on a Wordpress based website and Zend OPcache is installed and running on my server, but I noticed that the file cache feature is turned off, I wanted to activate it but I couldn't succeed in any way, the documentation I found on the internet contained too many techniques for me, I couldn't.

First of all I'm going to use this feature for the first time and I think it will improve my website speed, if I'm wrong please tell me I'm "wrong" so I won't waste any more time on this.

Some information that I think will be useful to you.

enter image description here

I want to learn from experts and improve myself

Title: Zend OPcache file cache


问:
bootstrap 4, narrow viewport, navigation escapes to the right - desperate novice needs advice
Please forgive my ignorance. I'm not really a coder. I'm a laid off graphic designer desperately trying to get my portfolio a little more polished than the wordpress site I had.

I've rebuilt from what Dreamweaver puts in when you start a new page with bootstrap 4. I've managed to get a lot customized with some help on here.

But I've broken something in the process, because it was working well until recently.

When I narrow the page, at some point in between the most narrow and a normal desktop size, the navigation exceed the container. When I view the site on my phone in landscape this is the default. I've taken a screenshot (further below) but I also have linked the site directly below.

Is this a media-query thing? I just don't even know where to look for this issue to resolve it.

My site, such as it is

Also!

Not as crucial but I'd love to fix.

a. How can I make the black band under the navbar stretch to the entire screen when it is at it's most narrow?

b. Is there a way (that I can manage without screwing things up) to make the container holding my banner and the navigation be black all across at it's most broad?

Thanks in advance!
Clare

Misbehaving Navbar when narrowed

1.5cm of padding I don't like when at the most narrow


问:
I have imported a csv file from my desktop and I cannot import csv file to postgresql
Want to import this csv file to new table
unicorn.csv

Created a Table "unicorns" through this syntax

```<code>CREATE TABLE IF NOT EXISTS unicorns (
company char,
url char,
last_valuation numeric,
date_joined char,
year_joined numeric,
city char,
country char,
industry char
);
</code>```

Then I imported the file to 'unicorn' table but when I view the process, it displays no rows found.

I want to know the reason behind this problem so that I can address this in the future.

Body:
Want to import this csv file to new table
unicorn.csv

Created a Table "unicorns" through this syntax

CREATE TABLE IF NOT EXISTS unicorns (
company char,
url char,
last_valuation numeric,
date_joined char,
year_joined numeric,
city char,
country char,
industry char
);

Then I imported the file to 'unicorn' table but when I view the process, it displays no rows found.

I want to know the reason behind this problem so that I can address this in the future.


问:
MSVCP90.DLL is missing
I installed Microsoft Visual Studio 9.0 and created a simple command line C++ project (.EXE file). When I'm trying to execute it an error modal windows is saying: "The program can't start because MSVCP90.DLL is missing from your computer".

The file exists on the machine at c:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\msvcp90.dll.

What am I doing wrong?

ContentLicense: CC BY-SA 3.0

Title: MSVCP90.DLL is missing


问:
How to download files in WebView Flutter
I'm trying to download a file through webview_flutter, but the file won't download.
I've already got permissions to read and write to disk, but file download is nowhere to be found.

I expected the file to be downloaded to android. Can't find anything on downloading files in webview_flutter docs. I have tried alternate packages, but their solutions are messy or deprecated.

What is the standard way to download files from WebView in Flutter?

main.dart:

```<code>import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WebViewController controller = WebViewController()
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..setBackgroundColor(const Color(0x00000000))
  ..setNavigationDelegate(
    NavigationDelegate(
      onProgress: (int progress) {
        // Update loading bar.
      },
      onPageStarted: (String url) {},
      onPageFinished: (String url) {},
      onWebResourceError: (WebResourceError error) {}
    ),
  )
  ..loadRequest(Uri.parse('https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/'));

  @override
  Widget build(BuildContext context) {
    Permission.storage.request();
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
    appBar: AppBar(title: const Text('Flutter Simple Example')),
    body: WebViewWidget(controller: controller),
  );
  }
}
</code>```

Body:
I'm trying to download a file through webview_flutter, but the file won't download.
I've already got permissions to read and write to disk, but file download is nowhere to be found.

I expected the file to be downloaded to android. Can't find anything on downloading files in webview_flutter docs. I have tried alternate packages, but their solutions are messy or deprecated.

What is the standard way to download files from WebView in Flutter?

main.dart:

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WebViewController controller = WebViewController()
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..setBackgroundColor(const Color(0x00000000))
  ..setNavigationDelegate(
    NavigationDelegate(
      onProgress: (int progress) {
        // Update loading bar.
      },
      onPageStarted: (String url) {},
      onPageFinished: (String url) {},
      onWebResourceError: (WebResourceError error) {}
    ),
  )
  ..loadRequest(Uri.parse('https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/'));

  @override
  Widget build(BuildContext context) {
    Permission.storage.request();
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
    appBar: AppBar(title: const Text('Flutter Simple Example')),
    body: WebViewWidget(controller: controller),
  );
  }
}


问:
Base-n integer representations library in Isabelle/HOL?
Context: I am trying to translate math contest problems into Isabelle/HOL. A lot of these contest problems involve questions like "what are the last two digits of this number when written in base 7"?

Isabelle/HOL has a rudimentary treatment of base-10 integer representations in the ThreeDivides theory. It also has a far more elaborate theory for binary numeral representations. And arguably the fundamental nat datatype is a base-one representation. But so far I have been unable to find any theory file that deals with base-n representations in general. Am I missing anything?

I'd like it to include basic theorems like the existence and uniqueness of the representation (which ThreeDivides actually does not show for its decimal representations), an easy way to write things down (e.g., "[4, 3]⇘base 5⇙ = 23"), and basic rules for manipulation. I can create such a theory file myself of course, but I'd rather not waste the time if it already exists.

Is there a standard theory in Isabelle/HOL for stating and proving facts about the digits of integers in arbitrary natural number bases?


问:
angular routing not working when using url in browser
```<code> <span class="menu-link"[routerLink]="['/']">Home</span>
   <button mat-button [matMenuTriggerFor]="menu" *ngIf="isUserAdmin">Admin</button>
  <mat-menu #menu="matMenu">
    <button mat-menu-item [routerLink]="['./admin/nomination-list']">Nomination(s) View</button>
  </mat-menu>
  <button mat-button [matMenuTriggerFor]="menu1"  *ngIf="this.Enable">Points</button>
  <mat-menu #menu1="matMenu">
    <button mat-menu-item [routerLink]="['./points/recognitionactivity']">Recognition Activity</button>
  </mat-menu>
</code>```

above is my code for navigation page

when i navigate from navmenu link, all the url's are working fine but when i just use the url in the browser it is not working, even if refresh the page, page is not rendering. I notice some errors in console page but couldnt make much of it.

after refersh shows like this

getting below errors in console page

App routing module

```<code>export const appRoutes: Routes = [
{
  path: '',
  redirectTo: '/home',
  pathMatch: 'full',
  canActivate: ['authGuard'],
  canActivateChild: ['authGuard']
},
{
  path: 'nav-menu',
  component: NavMenuComponent,
  canActivate: ['authGuard'],
  canActivateChild: ['authGuard']
},
{
  path: 'home',
  component: HomeComponent,
  canActivate: ['authGuard'],
  canActivateChild: ['authGuard']
 },
{
  path: 'admin/nomination-list',
  component: NominationListAdminComponent,
  pathMatch: 'full',
  canActivate: ['authGuardAdmin'],
  canActivateChild: ['authGuardAdmin']
},
{
  path: 'points/recognitionactivity',
  component: RecognitionsActivityComponent,
  pathMatch: 'full',
  canActivate: ['authGuardAdmin'],
  canActivateChild: ['authGuardAdmin']
},
{ path: 'silentauth', component: SilentAuthComponent, canActivate: [ 'authGuard' ] },

{path: '**', redirectTo: '', pathMatch: 'full'}
 ];

 @NgModule({
 imports: [RouterModule.forRoot(appRoutes, { useHash: false, enableTracing: false })],
 exports: [RouterModule]
 })
 export class AppRoutingModule {
 }
</code>```

Body:
 Home
   <button mat-button [matMenuTriggerFor]="menu" *ngIf="isUserAdmin">Admin</button>
  <mat-menu #menu="matMenu">
    <button mat-menu-item [routerLink]="['./admin/nomination-list']">Nomination(s) View</button>
  </mat-menu>
  <button mat-button [matMenuTriggerFor]="menu1"  *ngIf="this.Enable">Points</button>
  <mat-menu #menu1="matMenu">
    <button mat-menu-item [routerLink]="['./points/recognitionactivity']">Recognition Activity</button>
  </mat-menu>

above is my code for navigation page

when i navigate from navmenu link, all the url's are working fine but when i just use the url in the browser it is not working, even if refresh the page, page is not rendering. I notice some errors in console page but couldnt make much of it.

after refersh shows like this

getting below errors in console page

App routing module

export const appRoutes: Routes = [
{
  path: '',
  redirectTo: '/home',
  pathMatch: 'full',
  canActivate: ['authGuard'],
  canActivateChild: ['authGuard']
},
{
  path: 'nav-menu',
  component: NavMenuComponent,
  canActivate: ['authGuard'],
  canActivateChild: ['authGuard']
},
{
  path: 'home',
  component: HomeComponent,
  canActivate: ['authGuard'],
  canActivateChild: ['authGuard']
 },
{
  path: 'admin/nomination-list',
  component: NominationListAdminComponent,
  pathMatch: 'full',
  canActivate: ['authGuardAdmin'],
  canActivateChild: ['authGuardAdmin']
},
{
  path: 'points/recognitionactivity',
  component: RecognitionsActivityComponent,
  pathMatch: 'full',
  canActivate: ['authGuardAdmin'],
  canActivateChild: ['authGuardAdmin']
},
{ path: 'silentauth', component: SilentAuthComponent, canActivate: [ 'authGuard' ] },

{path: '**', redirectTo: '', pathMatch: 'full'}
 ];

 @NgModule({
 imports: [RouterModule.forRoot(appRoutes, { useHash: false, enableTracing: false })],
 exports: [RouterModule]
 })
 export class AppRoutingModule {
 }


问:
How to deploy Kubeflow Components with cloud build?
I am using Containerized Python components to create the components in my pipeline which works well but I cannot deploy them using Google Cloud Platform Cloud Build.

```<code>steps:
  - name: gcr.io/cloud-builders/docker
    args: [ 'build', '-t', 'dcgp', '-f', 'cloudbuild/DockerfileDeploy', '.', '--network=cloudbuild']
    id: 'dcgp-build'
  - name: gcr.io/cloud-builders/docker
    args: [ 'run', '--network=cloudbuild', '-v', '/var/run/docker.sock:/var/run/docker.sock',
    'dcgp', 'kfp', 'component', 'build', 'stages/simple', '--no-push-image' ]
    id: 'stages-build'
  - name: gcr.io/cloud-builders/docker
    args: [ 'push', 'europe-west2-docker.pkg.dev/my-project/stages/simple:latest' ]
    waitFor: ['stages-build']
    id: 'stages-deploy'
</code>```

It fails when I try to push in the final step with

An image does not exist locally with the tag: europe-west2-docker.pkg.dev/my-project/stages/simple

I thought because I had mounted the docker daemon in my container in the second stage that it would function like building a pushing any other image like described in these google docs.

I want to know if there is a simpler and easier way to deploy kubeflow components using Cloud Build and building my images using the kubeflow CLI.

Body:
I am using Containerized Python components to create the components in my pipeline which works well but I cannot deploy them using Google Cloud Platform Cloud Build.

steps:
  - name: gcr.io/cloud-builders/docker
    args: [ 'build', '-t', 'dcgp', '-f', 'cloudbuild/DockerfileDeploy', '.', '--network=cloudbuild']
    id: 'dcgp-build'
  - name: gcr.io/cloud-builders/docker
    args: [ 'run', '--network=cloudbuild', '-v', '/var/run/docker.sock:/var/run/docker.sock',
    'dcgp', 'kfp', 'component', 'build', 'stages/simple', '--no-push-image' ]
    id: 'stages-build'
  - name: gcr.io/cloud-builders/docker
    args: [ 'push', 'europe-west2-docker.pkg.dev/my-project/stages/simple:latest' ]
    waitFor: ['stages-build']
    id: 'stages-deploy'

It fails when I try to push in the final step with

An image does not exist locally with the tag: europe-west2-docker.pkg.dev/my-project/stages/simple

I thought because I had mounted the docker daemon in my container in the second stage that it would function like building a pushing any other image like described in these google docs.

I want to know if there is a simpler and easier way to deploy kubeflow components using Cloud Build and building my images using the kubeflow CLI.


问:
Chrome extension to autofill additional form elements that appear after selection is made
I'm building a Chrome extension that auto-fills a form. The first field on the form triggers additional fields to appear after it is filled out. I'm able to successfully field out the first field, but am struggling to fill out the sub fields.

To fill out the first field I use this code:

```<code>document.getElementById('theElementID').focus()
document.execCommand('insertText', false, 'theTextToAutoFill)
</code>```

Here are a few things I've tried:

Use that same code (updated with the correct IDs) for additional form fields, but document.getElementById returns null because those fields don't exist when the page initially loads

Refresh the page after filling out the first form using reload(), but it's refreshing the entire page (not just the section after the first field). Is there a way to just reload a section of the page?

Add an event listener to the class the first field is in (which also contains the sub fields). Wait until that class has been clicked to attempt to fill the subfields. See code below.

```<code>document.getElementsByClassName('theClassContainingSubFormFields')[0].addEventListener("click", function() {
    document.execCommand('insertText', false, 'theTextToAutoFill)
    });
</code>```

Ideally, I'm looking for a solution that uses JavaScript.

Body:
I'm building a Chrome extension that auto-fills a form. The first field on the form triggers additional fields to appear after it is filled out. I'm able to successfully field out the first field, but am struggling to fill out the sub fields.

To fill out the first field I use this code:

document.getElementById('theElementID').focus()
document.execCommand('insertText', false, 'theTextToAutoFill)

Here are a few things I've tried:

Use that same code (updated with the correct IDs) for additional form fields, but document.getElementById returns null because those fields don't exist when the page initially loads

Refresh the page after filling out the first form using reload(), but it's refreshing the entire page (not just the section after the first field). Is there a way to just reload a section of the page?

Add an event listener to the class the first field is in (which also contains the sub fields). Wait until that class has been clicked to attempt to fill the subfields. See code below.

document.getElementsByClassName('theClassContainingSubFormFields')[0].addEventListener("click", function() {
    document.execCommand('insertText', false, 'theTextToAutoFill)
    });

Ideally, I'm looking for a solution that uses JavaScript.


问:
2FA of the Google Authenticator App with VBA
First of all I am not a native English speaker and new here. It is also not a question, but a possible solution.

I've been looking for a complete solution on how to implement the Google Authenticator App function in VBA. But all hmac and sha1 examples I found give wrong results.

Therefore, using other programming languages, I reproduced the logic. Sources that helped me from the community are given in the source code.

The code works for me, but I am an amateur in VBA. Maybe it is helpful and any optimization is welcome to me.

```<code>Private Type SYSTEMTIME
    wYear As Integer
    wMonth As Integer
    wDayOfWeek As Integer
    wDay As Integer
    wHour As Integer
    wMinute As Integer
    wSecond As Integer
    wMilliseconds As Integer
End Type
Private Declare Sub GetSystemTime Lib "Kernel32" (ByRef lpSystemTime As SYSTEMTIME)

Sub otp()
    Dim Key As String, Secret As String, Time As String, hmac As String, ch As String, p1 As String, p2 As String, otp As String
    Dim offset As Long, d As Long, i As Long, n As Long, j As Long, a As Long
    Secret = UCase("<replace with secret from QR>")
    If Len(Secret) >= 20 Then
        n = 0
        j = 0

        ' stackoverflow.com/questions/60327784/converting-from-base-32-to-decimal-without-vba
        ' Change: use base32 variant
        For i = 1 To Len(Secret)
            ch = Mid$(Secret, i, 1)
            If ch >= "A" And ch <= "Z" Then
                d = asc(ch) - asc("A")
            ElseIf ch >= "2" And ch <= "7" Then
                d = asc(ch) - asc("0") + 24
            End If
            ' www.idontplaydarts.com/2011/07/google-totp-two-factor-authentication-for-php/
            ' reproduced
            n = (ShiftLeft(n, 5)) + d
            j = j + 5
            If j >= 8 Then
                j = j - 8
                Key = Key & WorksheetFunction.Dec2Hex(ShiftRight((n And ShiftLeft(255, j)), j), 2)
            End If
        Next i
        Time = Right("0000000000000000" & Hex(WorksheetFunction.Floor(CurrentTimeMillis() / 1000 / 30, 1)), 16)
        hmac = HEX_HMACSHA1(Time, Key)
        offset = Hex2UInt(Right(hmac, 1))
        p2 = Hex2UInt("7fffffff")
        If offset = 0 Then
            p1 = Hex2UInt(Left(hmac, 8))
        Else
            p1 = Hex2UInt(Mid(hmac, offset * 2 + 1, 8))
        End If
        otp = Right(WorksheetFunction.Bitand(p1, p2), 6)
        Debug.Print otp
    End If

End Sub

' stackoverflow.com/questions/29772224/get-unix-time-milliseconds
Function CurrentTimeMillis() As Double
    ' Returns the milliseconds from 1970/01/01 00:00:00.0 to system UTC
    Dim st As SYSTEMTIME
    GetSystemTime st
    Dim t_Start, t_Now
    t_Start = DateSerial(1970, 1, 1) ' Starting time for Linux
    t_Now = DateSerial(st.wYear, st.wMonth, st.wDay) + _
        TimeSerial(st.wHour, st.wMinute, st.wSecond)
    CurrentTimeMillis = DateDiff("s", t_Start, t_Now) * 1000 + st.wMilliseconds
End Function

' stackoverflow.com/questions/40213758/convert-hex-string-to-unsigned-int-vba
Function Hex2UInt(h As String) As Double
    Dim dbl As Double: dbl = CDbl("&h" & h)

    If dbl < 0 Then
        dbl = CDbl("&h1" & h) - 4294967296#
    End If

    Hex2UInt = dbl
End Function

' mrexcel.com/board/threads/hmac-sha1-hash-hex-input-string.1137771/
' Change: use byte array with unsigned integer and return hex with leading zeros
Public Function HEX_HMACSHA1(ByVal sTextToHash As String, ByVal sSharedSecretKey As String) As String
    Dim asc                 As Object
    Dim enc                 As Object
    Dim TextToHash()        As Byte
    Dim SharedSecretKey()   As Byte
    Dim Bytes()             As Byte
    Dim sHexString          As String
    Dim i                   As Long

    Set asc = CreateObject("System.Text.UTF8Encoding")
    Set enc = CreateObject("System.Security.Cryptography.HMACSHA1")

    TextToHash = HexStringToByteArray(sTextToHash)
    SharedSecretKey = HexStringToByteArray(sSharedSecretKey)
    enc.Key = SharedSecretKey

    Bytes = enc.ComputeHash_2((TextToHash))
    HEX_HMACSHA1 = ByteArrayToHexStr(Bytes)
    Set asc = Nothing
    Set enc = Nothing
End Function

' stackoverflow.com/questions/44979363/excel-vba-regex-function-that-returns-multiple-matches-into-a-single-cell
' Change: create byte array with unsigned integer
Function HexStringToByteArray(strInput As String) As Byte()

Dim rMatch As Object
Dim s As String
Dim arrayMatches() As Byte
Dim i As Long

With New RegExp
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "([A-F0-9]{2})"
    If .Test(strInput) Then
        For Each rMatch In .Execute(strInput)
            ReDim Preserve arrayMatches(i)
            arrayMatches(i) = Hex2UInt(rMatch.Value)
            i = i + 1
        Next
    End If
End With

    HexStringToByteArray = arrayMatches
End Function

' https://www.vbforums.com/showthread.php?559398-Byte-array-to-hex-string
' Change: removed Spaces between Hex
Function ByteArrayToHexStr(b() As Byte) As String
   Dim n As Long, i As Long

   ByteArrayToHexStr = Space$(2 * (UBound(b) - LBound(b)) + 2)
   n = 1
   For i = LBound(b) To UBound(b)
      Mid$(ByteArrayToHexStr, n, 2) = Right$("00" & Hex$(b(i)), 2)
      n = n + 2
   Next
End Function

' xbeat.net/vbspeed/c_ShiftLeft.htm
Public Static Function ShiftLeft(ByVal Value As Long, ByVal ShiftCount As Long) As Long
' by Jost Schwider, jost@schwider.de, 20010928
  Dim Pow2(0 To 31) As Long
  Dim i As Long
  Dim mask As Long

  Select Case ShiftCount
  Case 1 To 31

    'Ggf. Initialisieren:
    If i = 0 Then
      Pow2(0) = 1
      For i = 1 To 30
        Pow2(i) = 2 * Pow2(i - 1)
      Next i
    End If

    'Los gehts:
    mask = Pow2(31 - ShiftCount)
    If Value And mask Then
      ShiftLeft = (Value And (mask - 1)) * Pow2(ShiftCount) Or &H80000000
    Else
      ShiftLeft = (Value And (mask - 1)) * Pow2(ShiftCount)
    End If

  Case 0

    ShiftLeft = Value

  End Select
End Function

' xbeat.net/vbspeed/c_ShiftRight.htm
Public Static Function ShiftRight(ByVal Value As Long, ByVal ShiftCount As Long) As Long
' by Donald, donald@xbeat.net, 20011009
  Dim lPow2(0 To 30) As Long
  Dim i As Long

  Select Case ShiftCount
  Case 0 To 30
    If i = 0 Then
      lPow2(0) = 1
      For i = 1 To 30
        lPow2(i) = 2 * lPow2(i - 1)
      Next
    End If
    If Value And &H80000000 Then
      ShiftRight = Int(Value / lPow2(ShiftCount))
    Else
      ShiftRight = Value \ lPow2(ShiftCount)
    End If
  Case 31
    If Value And &H80000000 Then
      ShiftRight = -1
    Else
      ShiftRight = 0
    End If
  End Select
End Function

</code>```

Body:
First of all I am not a native English speaker and new here. It is also not a question, but a possible solution.

I've been looking for a complete solution on how to implement the Google Authenticator App function in VBA. But all hmac and sha1 examples I found give wrong results.

Therefore, using other programming languages, I reproduced the logic. Sources that helped me from the community are given in the source code.

The code works for me, but I am an amateur in VBA. Maybe it is helpful and any optimization is welcome to me.

Private Type SYSTEMTIME
    wYear As Integer
    wMonth As Integer
    wDayOfWeek As Integer
    wDay As Integer
    wHour As Integer
    wMinute As Integer
    wSecond As Integer
    wMilliseconds As Integer
End Type
Private Declare Sub GetSystemTime Lib "Kernel32" (ByRef lpSystemTime As SYSTEMTIME)

Sub otp()
    Dim Key As String, Secret As String, Time As String, hmac As String, ch As String, p1 As String, p2 As String, otp As String
    Dim offset As Long, d As Long, i As Long, n As Long, j As Long, a As Long
    Secret = UCase("<replace with secret from QR>")
    If Len(Secret) >= 20 Then
        n = 0
        j = 0

        ' stackoverflow.com/questions/60327784/converting-from-base-32-to-decimal-without-vba
        ' Change: use base32 variant
        For i = 1 To Len(Secret)
            ch = Mid$(Secret, i, 1)
            If ch >= "A" And ch <= "Z" Then
                d = asc(ch) - asc("A")
            ElseIf ch >= "2" And ch <= "7" Then
                d = asc(ch) - asc("0") + 24
            End If
            ' www.idontplaydarts.com/2011/07/google-totp-two-factor-authentication-for-php/
            ' reproduced
            n = (ShiftLeft(n, 5)) + d
            j = j + 5
            If j >= 8 Then
                j = j - 8
                Key = Key & WorksheetFunction.Dec2Hex(ShiftRight((n And ShiftLeft(255, j)), j), 2)
            End If
        Next i
        Time = Right("0000000000000000" & Hex(WorksheetFunction.Floor(CurrentTimeMillis() / 1000 / 30, 1)), 16)
        hmac = HEX_HMACSHA1(Time, Key)
        offset = Hex2UInt(Right(hmac, 1))
        p2 = Hex2UInt("7fffffff")
        If offset = 0 Then
            p1 = Hex2UInt(Left(hmac, 8))
        Else
            p1 = Hex2UInt(Mid(hmac, offset * 2 + 1, 8))
        End If
        otp = Right(WorksheetFunction.Bitand(p1, p2), 6)
        Debug.Print otp
    End If

End Sub

' stackoverflow.com/questions/29772224/get-unix-time-milliseconds
Function CurrentTimeMillis() As Double
    ' Returns the milliseconds from 1970/01/01 00:00:00.0 to system UTC
    Dim st As SYSTEMTIME
    GetSystemTime st
    Dim t_Start, t_Now
    t_Start = DateSerial(1970, 1, 1) ' Starting time for Linux
    t_Now = DateSerial(st.wYear, st.wMonth, st.wDay) + _
        TimeSerial(st.wHour, st.wMinute, st.wSecond)
    CurrentTimeMillis = DateDiff("s", t_Start, t_Now) * 1000 + st.wMilliseconds
End Function

' stackoverflow.com/questions/40213758/convert-hex-string-to-unsigned-int-vba
Function Hex2UInt(h As String) As Double
    Dim dbl As Double: dbl = CDbl("&h" & h)

    If dbl < 0 Then
        dbl = CDbl("&h1" & h) - 4294967296#
    End If

    Hex2UInt = dbl
End Function

' mrexcel.com/board/threads/hmac-sha1-hash-hex-input-string.1137771/
' Change: use byte array with unsigned integer and return hex with leading zeros
Public Function HEX_HMACSHA1(ByVal sTextToHash As String, ByVal sSharedSecretKey As String) As String
    Dim asc                 As Object
    Dim enc                 As Object
    Dim TextToHash()        As Byte
    Dim SharedSecretKey()   As Byte
    Dim Bytes()             As Byte
    Dim sHexString          As String
    Dim i                   As Long

    Set asc = CreateObject("System.Text.UTF8Encoding")
    Set enc = CreateObject("System.Security.Cryptography.HMACSHA1")

    TextToHash = HexStringToByteArray(sTextToHash)
    SharedSecretKey = HexStringToByteArray(sSharedSecretKey)
    enc.Key = SharedSecretKey

    Bytes = enc.ComputeHash_2((TextToHash))
    HEX_HMACSHA1 = ByteArrayToHexStr(Bytes)
    Set asc = Nothing
    Set enc = Nothing
End Function

' stackoverflow.com/questions/44979363/excel-vba-regex-function-that-returns-multiple-matches-into-a-single-cell
' Change: create byte array with unsigned integer
Function HexStringToByteArray(strInput As String) As Byte()

Dim rMatch As Object
Dim s As String
Dim arrayMatches() As Byte
Dim i As Long

With New RegExp
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "([A-F0-9]{2})"
    If .Test(strInput) Then
        For Each rMatch In .Execute(strInput)
            ReDim Preserve arrayMatches(i)
            arrayMatches(i) = Hex2UInt(rMatch.Value)
            i = i + 1
        Next
    End If
End With

    HexStringToByteArray = arrayMatches
End Function

' https://www.vbforums.com/showthread.php?559398-Byte-array-to-hex-string
' Change: removed Spaces between Hex
Function ByteArrayToHexStr(b() As Byte) As String
   Dim n As Long, i As Long

   ByteArrayToHexStr = Space$(2 * (UBound(b) - LBound(b)) + 2)
   n = 1
   For i = LBound(b) To UBound(b)
      Mid$(ByteArrayToHexStr, n, 2) = Right$("00" & Hex$(b(i)), 2)
      n = n + 2
   Next
End Function

' xbeat.net/vbspeed/c_ShiftLeft.htm
Public Static Function ShiftLeft(ByVal Value As Long, ByVal ShiftCount As Long) As Long
' by Jost Schwider, jost@schwider.de, 20010928
  Dim Pow2(0 To 31) As Long
  Dim i As Long
  Dim mask As Long

  Select Case ShiftCount
  Case 1 To 31

    'Ggf. Initialisieren:
    If i = 0 Then
      Pow2(0) = 1
      For i = 1 To 30
        Pow2(i) = 2 * Pow2(i - 1)
      Next i
    End If

    'Los gehts:
    mask = Pow2(31 - ShiftCount)
    If Value And mask Then
      ShiftLeft = (Value And (mask - 1)) * Pow2(ShiftCount) Or &H80000000
    Else
      ShiftLeft = (Value And (mask - 1)) * Pow2(ShiftCount)
    End If

  Case 0

    ShiftLeft = Value

  End Select
End Function

' xbeat.net/vbspeed/c_ShiftRight.htm
Public Static Function ShiftRight(ByVal Value As Long, ByVal ShiftCount As Long) As Long
' by Donald, donald@xbeat.net, 20011009
  Dim lPow2(0 To 30) As Long
  Dim i As Long

  Select Case ShiftCount
  Case 0 To 30
    If i = 0 Then
      lPow2(0) = 1
      For i = 1 To 30
        lPow2(i) = 2 * lPow2(i - 1)
      Next
    End If
    If Value And &H80000000 Then
      ShiftRight = Int(Value / lPow2(ShiftCount))
    Else
      ShiftRight = Value \ lPow2(ShiftCount)
    End If
  Case 31
    If Value And &H80000000 Then
      ShiftRight = -1
    Else
      ShiftRight = 0
    End If
  End Select
End Function


问:
How can I see the result of what I save into the "MySQL" database?
I have the following function that works fine and saves the new user data into the database:

```<code>  static async create(req: Request, res: Response, next: NextFunction){
    await pool.execute<IUser & RowDataPacket[]>(
      "INSERT INTO users (email, password, admin) VALUES(?,?,?)",
      [req.body.email, req.body.password, req.body.admin])
      .then(() => {
        res.status(200).json(("user created successfully"));
      })
      .catch(err => { console.log(err); next(); });
  }
</code>```

But when I try to change the following line:

```<code>await pool.execute<IUser & RowDataPacket[]>(
</code>```

Like this:

```<code>const user = await pool.execute<IUser & RowDataPacket[]>(
</code>```

Or change this line:

```<code>.then(() => {
</code>```

To

```<code>.then((user) => { res.send(user);
</code>```

In none of the cases I can't read the value of user and it's undefined. Is there a simple way that after I save a user into the database, I get a response with the saved user information inside the database?

EDIT: The configuration for the database looks like thie below code:

```<code>import mysql from "mysql2";

const pool =  mysql.createPool(
  {
  host : (process.env.DB_HOST),
  user : (process.env.DB_USER),
  password:  (process.env.DB_PASSWORD ),
  database: (process.env.DB_NAME ),
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
  }).promise();
</code>```

Body:
I have the following function that works fine and saves the new user data into the database:

  static async create(req: Request, res: Response, next: NextFunction){
    await pool.execute<IUser & RowDataPacket[]>(
      "INSERT INTO users (email, password, admin) VALUES(?,?,?)",
      [req.body.email, req.body.password, req.body.admin])
      .then(() => {
        res.status(200).json(("user created successfully"));
      })
      .catch(err => { console.log(err); next(); });
  }

But when I try to change the following line:

await pool.execute<IUser & RowDataPacket[]>(

Like this:

const user = await pool.execute<IUser & RowDataPacket[]>(

Or change this line:

.then(() => {

To

.then((user) => { res.send(user);

In none of the cases I can't read the value of user and it's undefined. Is there a simple way that after I save a user into the database, I get a response with the saved user information inside the database?

EDIT: The configuration for the database looks like thie below code:

import mysql from "mysql2";

const pool =  mysql.createPool(
  {
  host : (process.env.DB_HOST),
  user : (process.env.DB_USER),
  password:  (process.env.DB_PASSWORD ),
  database: (process.env.DB_NAME ),
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
  }).promise();


问:
"ValueError too many values to unpack (expected 2)" (Machine Learning)
I'm coding a regression model and for some reason it gives me an error "ValueError too many values to unpack (expected 2)" when fitting.

However, my x_train, x_test, y_train, y_test are in the correct order and seem to receive the correct values.

```<code>from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline, Pipeline
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from sklearn.compose import make_column_transformer
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split

lst_object = []
for columns, content in df.items():
    if pd.api.types.is_object_dtype(content):
        lst_object.append(columns)

lst_numerical = []
for columns, content in df.items():
    if pd.api.types.is_numeric_dtype(content):
        lst_numerical.append(columns)

numerical_type = make_pipeline((SimpleImputer(missing_values=np.nan, strategy = 'median')),
                                   MinMaxScaler())

object_type = make_pipeline(SimpleImputer(missing_values=np.nan, strategy = 'most_frequent'),
                            OneHotEncoder(handle_unknown= 'ignore'),
                            MinMaxScaler())

transform = make_column_transformer((numerical_type, lst_numerical),
                                    (object_type, lst_object))

model = Pipeline(steps=[('transform', transform),
                          'model', RandomForestRegressor])

X = df.drop('SalePrice', axis = 1)
Y =df.SalePrice
x_train, x_test, y_train, y_test = train_test_split(X,Y, test_size=0.2, random_state = 0, shuffle=True)

model.fit(x_train, x_test)
</code>```

Body:
I'm coding a regression model and for some reason it gives me an error "ValueError too many values to unpack (expected 2)" when fitting.

However, my x_train, x_test, y_train, y_test are in the correct order and seem to receive the correct values.

from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline, Pipeline
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from sklearn.compose import make_column_transformer
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split

lst_object = []
for columns, content in df.items():
    if pd.api.types.is_object_dtype(content):
        lst_object.append(columns)

lst_numerical = []
for columns, content in df.items():
    if pd.api.types.is_numeric_dtype(content):
        lst_numerical.append(columns)

numerical_type = make_pipeline((SimpleImputer(missing_values=np.nan, strategy = 'median')),
                                   MinMaxScaler())

object_type = make_pipeline(SimpleImputer(missing_values=np.nan, strategy = 'most_frequent'),
                            OneHotEncoder(handle_unknown= 'ignore'),
                            MinMaxScaler())

transform = make_column_transformer((numerical_type, lst_numerical),
                                    (object_type, lst_object))

model = Pipeline(steps=[('transform', transform),
                          'model', RandomForestRegressor])

X = df.drop('SalePrice', axis = 1)
Y =df.SalePrice
x_train, x_test, y_train, y_test = train_test_split(X,Y, test_size=0.2, random_state = 0, shuffle=True)

model.fit(x_train, x_test)


问:
How can I publish to subscriber based on connection id via go library `graph-gophers`
I am using graph-gophers library to build graphql application on the server side. I have a lambda works as resolvers and websocket apigateway which works as transport layer. The lambda will take the request from apigateway then call graph-gophers library schema methods to trigger resolver. It works well for query and mutation. But I am not sure how to make it work for subscription.

The library graph-gophers requires the subscription resolver to return a go channels which it listens to. but in case of lambda which is a short lived application, it can't keep alive for a long time. That means I can't use channel for publishing data.

What I am doing is to save the socket connection id on a database, when there is a need to publish data, I will grab the connection id from db to find all the subscribers. But I don't know how to trigger the publish in this case. Anyone has any idea about how to do that?


问:
Quarto ignores ipython output
Consider the following quarto document:

```<code>---
title: "Untitled"
format: pdf
jupyter: r-reticulate
---

```{ipython}
print('hello1')
```

```{python}
print('hello2')
```
</code>```

The pdf document does not print hello1, but prints hello2. It seems that quarto ignores ipython output. Is that expected?

Title: Quarto ignores ipython output

Body:
Consider the following quarto document:

---
title: "Untitled"
format: pdf
jupyter: r-reticulate
---

```{ipython}
print('hello1')
```

```{python}
print('hello2')
```

The pdf document does not print hello1, but prints hello2. It seems that quarto ignores ipython output. Is that expected?


问:
Microsoft Azure Spatial anchors script problem
I haven't find so far any good and update script for manage the Microsoft Spatial Azure Anchors, could you please review this code and tell me more or less if i am in the right way or not ? Actually I am trying to minimize the code for having the pure functionality, but i am stack and i can't even find an understandable guideline
hope the code is readable and well documented.

thanks in advance.
Andrea

```<code>using Microsoft.Azure;
using Microsoft.Azure.SpatialAnchors;
using Microsoft.Azure.SpatialAnchors.Unity;
using Microsoft.MixedReality.OpenXR;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.XR.WSA;
using UnityEngine.XR.WSA.Input;

public class AnchorsManager : MonoBehaviour
{

    /// <summary>
    /// Input
    /// </summary>
    private GameObject localAnchor;

    /// <summary>
    /// AZURE settings AccountId
    /// </summary>
    private string AccountId = "00886172-b41a-....";

    /// <summary>
    /// AZURE settings AccountKey
    /// </summary>
    private string AccountKey = "09c3eddc-....";

    /// <summary>
    /// AZURE settings AccountDomain
    /// </summary>
    private string AccountDomain = "northeurope.mixedreality.azure.com";

    /// <summary>
    /// Azure session
    /// </summary>
    private CloudSpatialAnchorSession cloudSession;

    /// <summary>
    /// For Storing the object Ids
    /// </summary>
    private AnchorLocateCriteria criteria =  new AnchorLocateCriteria();
    protected List<string> anchorIdsToLocate = new List<string>();

    void Start()
    {
        InitializeSession();
    }

    /// <summary>
    /// Only when the user drag an object we can save the anchor with the latest position
    /// </summary>
    void onMouseObjectDown(GameObject prefab)
    {
        this.localAnchor = prefab;
        this.cloudSession.Start();
    }

    /// <summary>
    /// Inizialize the cloudSpatialAnchorSession.
    /// </summary>
    void InitializeSession()
    {

        try {
            this.cloudSession = new CloudSpatialAnchorSession();

            this.cloudSession.Configuration.AccountId = this.AccountId;
            this.cloudSession.Configuration.AccountKey = this.AccountKey;
            this.cloudSession.Configuration.AccountDomain = this.AccountDomain;

            this.cloudSession.SessionUpdated += (sender, args) =>
            {
                if (args.Status.RecommendedForCreateProgress != 0)
                {
                    this.CreateAnchor();
                }
            };

            //WATCHERS
            this.cloudSession.CreateWatcher(criteria);

            this.cloudSession.AnchorLocated += (object sender, AnchorLocatedEventArgs args) =>
            {
                switch (args.Status)
                {
                    case LocateAnchorStatus.Located:
                        CloudSpatialAnchor foundAnchor = args.Anchor;
                        Debug.Log("ASA Info: Anchor located! Identifier: " + args.Identifier);
                        break;
                    case LocateAnchorStatus.AlreadyTracked:
                        Debug.Log("This anchor has already been reported and is being tracked" + args.Identifier);
                        break;
                    case LocateAnchorStatus.NotLocated:
                        Debug.Log("ASA Info: Anchor not located. Identifier: " + args.Identifier);
                        break;
                    case LocateAnchorStatus.NotLocatedAnchorDoesNotExist:
                        Debug.LogError("ASA Error: Anchor not located does not exist. Identifier: " + args.Identifier);
                        break;
                }
            };

        }
        catch (Exception ex) {
            Debug.LogError("Error on initialize the session: " + ex.Message);
        }

    }

    /// <summary>
    /// CreateAnchor
    /// </summary>
    async void CreateAnchor()
    {

        // Create Anchor in local;
        localAnchor.AddComponent<CloudNativeAnchor>();
        CloudNativeAnchor cloudNativeAnchor = localAnchor.GetComponent<CloudNativeAnchor>();
        if (cloudNativeAnchor.CloudAnchor == null) { await cloudNativeAnchor.NativeToCloud(); }

        // Add Anchor property;
        CloudSpatialAnchor cloudAnchor = cloudNativeAnchor.CloudAnchor;
        cloudAnchor.AppProperties[@"room"] = @"bagno";
        cloudAnchor.AppProperties[@"product"] = @"saponetta";
        cloudAnchor.Expiration = DateTimeOffset.Now.AddDays(7);

        // Create Anchor
        await cloudSession.CreateAnchorAsync(cloudAnchor);
        Debug.Log("Cloud anchor created with ID = " + cloudAnchor.Identifier);

        // Save Anchor ID
        this.anchorIdsToLocate.Add(cloudAnchor.Identifier);
        this.criteria.Identifiers = anchorIdsToLocate.ToArray();
        Debug.Log("Anchor Id has been saved on the array");

    }

}
</code>```

Body:
I haven't find so far any good and update script for manage the Microsoft Spatial Azure Anchors, could you please review this code and tell me more or less if i am in the right way or not ? Actually I am trying to minimize the code for having the pure functionality, but i am stack and i can't even find an understandable guideline
hope the code is readable and well documented.

thanks in advance.
Andrea

using Microsoft.Azure;
using Microsoft.Azure.SpatialAnchors;
using Microsoft.Azure.SpatialAnchors.Unity;
using Microsoft.MixedReality.OpenXR;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.XR.WSA;
using UnityEngine.XR.WSA.Input;

public class AnchorsManager : MonoBehaviour
{

    ///
    /// Input
    ///
    private GameObject localAnchor;

    ///
    /// AZURE settings AccountId
    ///
    private string AccountId = "00886172-b41a-....";

    ///
    /// AZURE settings AccountKey
    ///
    private string AccountKey = "09c3eddc-....";

    ///
    /// AZURE settings AccountDomain
    ///
    private string AccountDomain = "northeurope.mixedreality.azure.com";

    ///
    /// Azure session
    ///
    private CloudSpatialAnchorSession cloudSession;

    ///
    /// For Storing the object Ids
    ///
    private AnchorLocateCriteria criteria =  new AnchorLocateCriteria();
    protected List<string> anchorIdsToLocate = new List<string>();

    void Start()
    {
        InitializeSession();
    }

    ///
    /// Only when the user drag an object we can save the anchor with the latest position
    ///
    void onMouseObjectDown(GameObject prefab)
    {
        this.localAnchor = prefab;
        this.cloudSession.Start();
    }

    ///
    /// Inizialize the cloudSpatialAnchorSession.
    ///
    void InitializeSession()
    {

        try {
            this.cloudSession = new CloudSpatialAnchorSession();

            this.cloudSession.Configuration.AccountId = this.AccountId;
            this.cloudSession.Configuration.AccountKey = this.AccountKey;
            this.cloudSession.Configuration.AccountDomain = this.AccountDomain;

            this.cloudSession.SessionUpdated += (sender, args) =>
            {
                if (args.Status.RecommendedForCreateProgress != 0)
                {
                    this.CreateAnchor();
                }
            };

            //WATCHERS
            this.cloudSession.CreateWatcher(criteria);

            this.cloudSession.AnchorLocated += (object sender, AnchorLocatedEventArgs args) =>
            {
                switch (args.Status)
                {
                    case LocateAnchorStatus.Located:
                        CloudSpatialAnchor foundAnchor = args.Anchor;
                        Debug.Log("ASA Info: Anchor located! Identifier: " + args.Identifier);
                        break;
                    case LocateAnchorStatus.AlreadyTracked:
                        Debug.Log("This anchor has already been reported and is being tracked" + args.Identifier);
                        break;
                    case LocateAnchorStatus.NotLocated:
                        Debug.Log("ASA Info: Anchor not located. Identifier: " + args.Identifier);
                        break;
                    case LocateAnchorStatus.NotLocatedAnchorDoesNotExist:
                        Debug.LogError("ASA Error: Anchor not located does not exist. Identifier: " + args.Identifier);
                        break;
                }
            };

        }
        catch (Exception ex) {
            Debug.LogError("Error on initialize the session: " + ex.Message);
        }

    }

    ///
    /// CreateAnchor
    ///
    async void CreateAnchor()
    {

        // Create Anchor in local;
        localAnchor.AddComponent<CloudNativeAnchor>();
        CloudNativeAnchor cloudNativeAnchor = localAnchor.GetComponent<CloudNativeAnchor>();
        if (cloudNativeAnchor.CloudAnchor == null) { await cloudNativeAnchor.NativeToCloud(); }

        // Add Anchor property;
        CloudSpatialAnchor cloudAnchor = cloudNativeAnchor.CloudAnchor;
        cloudAnchor.AppProperties[@"room"] = @"bagno";
        cloudAnchor.AppProperties[@"product"] = @"saponetta";
        cloudAnchor.Expiration = DateTimeOffset.Now.AddDays(7);

        // Create Anchor
        await cloudSession.CreateAnchorAsync(cloudAnchor);
        Debug.Log("Cloud anchor created with ID = " + cloudAnchor.Identifier);

        // Save Anchor ID
        this.anchorIdsToLocate.Add(cloudAnchor.Identifier);
        this.criteria.Identifiers = anchorIdsToLocate.ToArray();
        Debug.Log("Anchor Id has been saved on the array");

    }

}


问:
MS Chart. ¿How do you plot points in the middle of the range, defined by two tick marks?
How I do this with MS Chart?

Telerik have property PlotMode.


问:
How can I get status code in jest correctly?
```<code>import type { NextFunction, Response } from 'express';
import getAdminRedirect from './getAdminRedirect';

const adminRedirects = async (
  req: ServerRequestExpress,
  res: Response,
  next: NextFunction,
) => {
  try {
    const redirect = await getAdminRedirect(req);
    if (redirect) {
      const { code, target } = redirect;
      const codeInt = typeof code === 'string' ? parseInt(code) : code;
      return res
        .setHeader('x-admin-redirect', `${code},${target}`)
        .redirect(codeInt, target);
    }
    return next();
  } catch (error) {
    return res.setHeader('x-admin-redirect', 'error').redirect('/');
  }
};

export default adminRedirects;
</code>```

I have a middleware in nextjs like the above. I try to write unit tests for it.

This is my test file:

```<code>import { getMockReq, getMockRes } from '@jest-mock/express';
import getAdminRedirect from './getAdminRedirect';
import adminRedirects from './index';

jest.mock('./getAdminRedirect', () => jest.fn());

describe('adminRedirects', () => {
  const { res, next, clearMockRes } = getMockRes({
    setHeader: jest.fn().mockReturnThis(),
    redirect: jest.fn(),
  });
  const req = getMockReq();

  beforeEach(() => {
    clearMockRes();
  });

  it('sets x-admin-redirect header and redirects if redirect is returned from getAdminRedirect', async () => {
    (getAdminRedirect as jest.Mock).mockReturnValue({
      code: 301,
      target: '/new-target',
    });

    await adminRedirects(req, res, next);

    expect(res.setHeader).toHaveBeenCalledWith(
      'x-admin-redirect',
      '301,/new-target',
    );
    expect(res.redirect).toHaveBeenCalledWith(301, '/new-target');
    expect(next).not.toHaveBeenCalled();

    expect(res.statusCode).toBe(301);
  });
});
</code>```

I got an error for the last line:

```<code>Expected: 301
Received: 0
</code>```

I tried to fix like I added a status code into the first function:

```<code> return res
        .setHeader('x-admin-redirect', `${code},${target}`)
        .status(301)
        .redirect(codeInt, target);
</code>```

But I still get the same error.

Do you have any idea? What am I missing there?

Body:
import type { NextFunction, Response } from 'express';
import getAdminRedirect from './getAdminRedirect';

const adminRedirects = async (
  req: ServerRequestExpress,
  res: Response,
  next: NextFunction,
) => {
  try {
    const redirect = await getAdminRedirect(req);
    if (redirect) {
      const { code, target } = redirect;
      const codeInt = typeof code === 'string' ? parseInt(code) : code;
      return res
        .setHeader('x-admin-redirect', `${code},${target}`)
        .redirect(codeInt, target);
    }
    return next();
  } catch (error) {
    return res.setHeader('x-admin-redirect', 'error').redirect('/');
  }
};

export default adminRedirects;

I have a middleware in nextjs like the above. I try to write unit tests for it.

This is my test file:

import { getMockReq, getMockRes } from '@jest-mock/express';
import getAdminRedirect from './getAdminRedirect';
import adminRedirects from './index';

jest.mock('./getAdminRedirect', () => jest.fn());

describe('adminRedirects', () => {
  const { res, next, clearMockRes } = getMockRes({
    setHeader: jest.fn().mockReturnThis(),
    redirect: jest.fn(),
  });
  const req = getMockReq();

  beforeEach(() => {
    clearMockRes();
  });

  it('sets x-admin-redirect header and redirects if redirect is returned from getAdminRedirect', async () => {
    (getAdminRedirect as jest.Mock).mockReturnValue({
      code: 301,
      target: '/new-target',
    });

    await adminRedirects(req, res, next);

    expect(res.setHeader).toHaveBeenCalledWith(
      'x-admin-redirect',
      '301,/new-target',
    );
    expect(res.redirect).toHaveBeenCalledWith(301, '/new-target');
    expect(next).not.toHaveBeenCalled();

    expect(res.statusCode).toBe(301);
  });
});

I got an error for the last line:

Expected: 301
Received: 0

I tried to fix like I added a status code into the first function:

 return res
        .setHeader('x-admin-redirect', `${code},${target}`)
        .status(301)
        .redirect(codeInt, target);

But I still get the same error.

Do you have any idea? What am I missing there?


问:
How to fix matplotlib x axis showing January 1970 when setting format
I have a dataframe containing a grouped set of data with a month, year, and count. I'm trying to create a bar chart to show this. The bar chart displays properly when I run the code, but it shows the date as "(%m, %y)"

I'm trying to format the date to show as "%y-%m"

I tried to set ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%y')) but it makes all of the dates appear as January 1970. The bar chart is still correct except for the x axis labels. How can I format the x axis to show the correct date in the format %y-%m?

```<code>df['Time'] = pd.to_datetime(df['Time'], format = '%Y-%m-%d')

GB = df.groupby([df.Time.dt.month,
df.Time.dt.year]).agg({'Count':sum})

fig, ax = plt.subplots()

GB.plot.bar(ax=ax)
</code>```

I've already confirmed that the column is properly a datetime, and when I print GB, it shows the correct data:

```<code>Time Time   Count
2    2022    123
3    2022    267
4    2022    653
5    2022   5134
6    2022   7543
7    2022   1689
8    2022   2335
9    2022   9432
10   2022   9534
11   2022   1245
12   2022   9533
</code>```

I'm sure I'm making a silly mistake, and I'd really appreciate any help!

Body:
I have a dataframe containing a grouped set of data with a month, year, and count. I'm trying to create a bar chart to show this. The bar chart displays properly when I run the code, but it shows the date as "(%m, %y)"

I'm trying to format the date to show as "%y-%m"

I tried to set ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%y')) but it makes all of the dates appear as January 1970. The bar chart is still correct except for the x axis labels. How can I format the x axis to show the correct date in the format %y-%m?

df['Time'] = pd.to_datetime(df['Time'], format = '%Y-%m-%d')

GB = df.groupby([df.Time.dt.month,
df.Time.dt.year]).agg({'Count':sum})

fig, ax = plt.subplots()

GB.plot.bar(ax=ax)

I've already confirmed that the column is properly a datetime, and when I print GB, it shows the correct data:

Time Time   Count
2    2022    123
3    2022    267
4    2022    653
5    2022   5134
6    2022   7543
7    2022   1689
8    2022   2335
9    2022   9432
10   2022   9534
11   2022   1245
12   2022   9533

I'm sure I'm making a silly mistake, and I'd really appreciate any help!


问:
@WithMockUser make my tests work even when I don't pass the header
I am working on an API with an API Key authentication (X-API-KEY/VALUE) and its works fine. My issue is in the unit test. When I am using @WithMockUser on the Controller test slice I am testing with @WebMvcTest, the tests works fine even when I don't add the header in the mockMvc test.

I would like to know what is the best way to test it?

```<code>@Test
@WithMockUser
void givenController_whenFindingResult_thenReturnResultWithStatus_200() throws Exception {
    when(service.findResultDescriptionsByLanguage(anyString())).thenReturn(TestData.getSampleResultDescriptions());

    mockMvc.perform(get(TestData.API_V1_BASE_URL + "/descriptions/{language}", "en")
                .header(apiKeyProperties.getHeaderName(), apiKeyProperties.getApiKey())
                .contentType(MediaType.APPLICATION_JSON))
            .andExpectAll(
                status().isOk(),
                jsonPath("$.statusValue", is(HttpStatus.OK.value())),
                jsonPath("$.statusReasonPhrase", is(HttpStatus.OK.getReasonPhrase())),
                jsonPath("$.description", containsString("Descriptions found for en"))
        );
}
</code>```

Body:
I am working on an API with an API Key authentication (X-API-KEY/VALUE) and its works fine. My issue is in the unit test. When I am using @WithMockUser on the Controller test slice I am testing with @WebMvcTest, the tests works fine even when I don't add the header in the mockMvc test.

I would like to know what is the best way to test it?

@Test
@WithMockUser
void givenController_whenFindingResult_thenReturnResultWithStatus_200() throws Exception {
    when(service.findResultDescriptionsByLanguage(anyString())).thenReturn(TestData.getSampleResultDescriptions());

    mockMvc.perform(get(TestData.API_V1_BASE_URL + "/descriptions/{language}", "en")
                .header(apiKeyProperties.getHeaderName(), apiKeyProperties.getApiKey())
                .contentType(MediaType.APPLICATION_JSON))
            .andExpectAll(
                status().isOk(),
                jsonPath("$.statusValue", is(HttpStatus.OK.value())),
                jsonPath("$.statusReasonPhrase", is(HttpStatus.OK.getReasonPhrase())),
                jsonPath("$.description", containsString("Descriptions found for en"))
        );
}


问:
Python, split terminal to have a menu and some logs at the same time with multithreading
I am making a program which print some logs on my terminal from a thread, but i want to still be able to use the menu without it being overwrited by the logs.

```<code>import time
import os
import random
from threading import Thread, Barrier

# here is the function that is multi threaded
def getLogs():
    while True:
        print("here come the logs")
        time.sleep(5)

threads = []

# here is the menu i want to display
def menu():
    print("""Actions:\n
             1) Choice 1
             2) Choice 2
             3) Choice 3
             4) Choice 4
             5) Choice 5
             """)

    input(Fore.GREEN + "(Choice) >>>" + Fore.RESET)

# here is where I start the threads
def startThread():
    with open("./files" + str(setFile)) as f:
        for line in f:
            t = Thread(target=getLogs, )
            t.start()
            threads.append(t)

    # What main thread do ?
    menu()

if __name__ == '__main__':
    startThread()
</code>```

So the goal here is to split the terminal in order to have the menu on the left side and the logs spawning on the right side.

I tried a lot of things like Urwid and curses library but I didn't succeed with both this way, I think that I am doing things wrong...

Body:
I am making a program which print some logs on my terminal from a thread, but i want to still be able to use the menu without it being overwrited by the logs.

import time
import os
import random
from threading import Thread, Barrier

# here is the function that is multi threaded
def getLogs():
    while True:
        print("here come the logs")
        time.sleep(5)

threads = []

# here is the menu i want to display
def menu():
    print("""Actions:\n
             1) Choice 1
             2) Choice 2
             3) Choice 3
             4) Choice 4
             5) Choice 5
             """)

    input(Fore.GREEN + "(Choice) >>>" + Fore.RESET)

# here is where I start the threads
def startThread():
    with open("./files" + str(setFile)) as f:
        for line in f:
            t = Thread(target=getLogs, )
            t.start()
            threads.append(t)

    # What main thread do ?
    menu()

if __name__ == '__main__':
    startThread()

So the goal here is to split the terminal in order to have the menu on the left side and the logs spawning on the right side.

I tried a lot of things like Urwid and curses library but I didn't succeed with both this way, I think that I am doing things wrong...


问:
Ionic PWA get reload every time user opens another application ( android device)
I have an Ionic PWA with angular. Every packages are in latest versions. I am using @capacitor/browser to open other application in android device

My navigation function is

const openLink = async () => {
  await Browser.open({ url: myURL });
};```

Each time that user opes a link, the ionic PWA app get reload and return to the login screen which turns the application not usable for the users

is that a standard behaviour in ionic PWA? or do I miss a configuration in the application

appreciate your support

Body:
I have an Ionic PWA with angular. Every packages are in latest versions. I am using @capacitor/browser to open other application in android device

My navigation function is

const openLink = async () => {
  await Browser.open({ url: myURL });
};

Each time that user opes a link, the ionic PWA app get reload and return to the login screen which turns the application not usable for the users

is that a standard behaviour in ionic PWA? or do I miss a configuration in the application

appreciate your support


问:
How do I display data from one worksheet in Excel on another worksheet and display that data in different cell locations, not just a filtered table
My ability to Google effectively has left my body because I can't find a solution and I'm convinced it's going to be super simple.

I have a large database of information with let's say 20 columns and several hundred rows. I want to make a new worksheet I could use to present to someone the information in a much clearer way. Let's call the main database "Database" and the second sheet "Display Sheet".

I want to have a simple drop down menu that pulls from a name in column A from Database and then it displays the different bits of information from the same row in individual cells I choose on Display Sheet.

For example, on Display Sheet I have the dropdown list in cell A1 that is currently pulling information from Database cell A8. I want Display Sheet cell C2 to show Database cell G8 and Display Sheet cell C4 to show Database cell B8. Then if I change the dropdown in Display Sheet to be showing Database cell A20, cells C2 and C4 both update to show that row and so on.

I am essentially trying to create a form that simply displays information from Database in Display Sheet, but if I even touch the word "form" on Google searches its all about data entry forms and nothing I find is about just displaying data. I don't want anything fancy, I just want to be able to say that data from column XYZ goes in whichever cells I choose once a row is selected via the drop down. I vaguely recall that this was basically what Access did in a way, but I can't use that so need it all in the same workbook.

I tried to follow some guides and thought that the FILTER formula was what I was after, but it doesn't seem to work at all whether I refer to the table name or a defined data range name. I also tried to see if pivot tables would work for me and I just don't understand them well enough at all. Most of the guides I've found simply pull a filtered table across to wherever you want to show it, but I don't want my data in a table when showing it to others.


问:
Symfony Dependency Injection shows a weird behaviour
When i try to inject a service in my Symfony 4.4.25 Bundle (with Akeneo) i encounter a very strange behavior.
Defining a mapped variable in the Bundle Config without having the variable in __construct() throws a fail. Adding the variable throws another strange failure

If i define my service like this:

```<code>services:
    acme_category_builder.event_subscriber.category_builder:
        class: Acme\Bundle\CategoryBuilderBundle\AcmeCategoryBuilderBundle
        arguments:
            $productModelRepository: '@pim_catalog.repository.product_model'
        tags: ['kernel.event_subscriber']
</code>```

or like this:

```<code>services:
    acme_category_builder.event_subscriber.category_builder:
        class: Acme\Bundle\CategoryBuilderBundle\AcmeCategoryBuilderBundle
        arguments:
            - '@pim_catalog.repository.product_model'
        tags: ['kernel.event_subscriber']
</code>```

with this constructor:

```<code>public function __construct(){}
</code>```

i get with first the Error that my constructor is missing the $productModelRepository.

```<code>Invalid service "acme_category_builder.event_subscriber.category_builder": method "Acme\Bundle\CategoryBuilderBundle\AcmeCategoryBuilderBundle::__construct()" has no argument named "$productModelRepository". Check your service definition.
</code>```

and with second the PHP Fatal Error from below

If i add it like this in the constructor:

```<code>public function __construct($productModelRepository){}
</code>```

i get the failure, that nothing was passed as Argument

```<code>PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function
Acme\Bundle\CategoryBuilderBundle\AcmeCategoryBuilderBundle::__construct(),
0 passed in /home/Workspace/Akeneo/pim/src/Kernel.php on line 36 and exactly
1 expected in /home/Workspace/Akeneo/pim/vendor/acme/category-builder-bundle/src/AcmeCategoryBuilderBundle.php:39
</code>```

however if i add a type hint (which was my first guess that could be missing, i retrieve the same error.

```<code>use Akeneo\Pim\Enrichment\Component\Product\Repository\ProductModelRepositoryInterface;

public function __construct(ProductModelRepositoryInterface $productModelRepository){

}
</code>```

How can this be explained? first it wants to pass a argument but cant, then it has to pass a argument and wont?

pls Help :(

Body:
When i try to inject a service in my Symfony 4.4.25 Bundle (with Akeneo) i encounter a very strange behavior.
Defining a mapped variable in the Bundle Config without having the variable in __construct() throws a fail. Adding the variable throws another strange failure

If i define my service like this:

services:
    acme_category_builder.event_subscriber.category_builder:
        class: Acme\Bundle\CategoryBuilderBundle\AcmeCategoryBuilderBundle
        arguments:
            $productModelRepository: '@pim_catalog.repository.product_model'
        tags: ['kernel.event_subscriber']

or like this:

services:
    acme_category_builder.event_subscriber.category_builder:
        class: Acme\Bundle\CategoryBuilderBundle\AcmeCategoryBuilderBundle
        arguments:
            - '@pim_catalog.repository.product_model'
        tags: ['kernel.event_subscriber']

with this constructor:

public function __construct(){}

i get with first the Error that my constructor is missing the $productModelRepository.

Invalid service "acme_category_builder.event_subscriber.category_builder": method "Acme\Bundle\CategoryBuilderBundle\AcmeCategoryBuilderBundle::__construct()" has no argument named "$productModelRepository". Check your service definition.

and with second the PHP Fatal Error from below

If i add it like this in the constructor:

public function __construct($productModelRepository){}

i get the failure, that nothing was passed as Argument

PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function
Acme\Bundle\CategoryBuilderBundle\AcmeCategoryBuilderBundle::__construct(),
0 passed in /home/Workspace/Akeneo/pim/src/Kernel.php on line 36 and exactly
1 expected in /home/Workspace/Akeneo/pim/vendor/acme/category-builder-bundle/src/AcmeCategoryBuilderBundle.php:39

however if i add a type hint (which was my first guess that could be missing, i retrieve the same error.

use Akeneo\Pim\Enrichment\Component\Product\Repository\ProductModelRepositoryInterface;

public function __construct(ProductModelRepositoryInterface $productModelRepository){

}

How can this be explained? first it wants to pass a argument but cant, then it has to pass a argument and wont?

pls Help :(


问:
How to force Docker to recreate container
in docker-compose it is possible to run
docker compose up container --force-recreate.

Is there a way to do that with docker (i.e. without docker-compose)?
Would docker container_name restart have the same effect?


问:
Attempting to run Powershell on Remote Computer - Errors
I am wanting to access another windows device on my local network and run powershell commands.  In my mind, it would be similar to SSH into a linux box.  I would have an open window on my machine, but would be operating within the remote machine so that I can execute composer install or php artisan migrate type commands on the remote machine.

I have followed the instructions from:
https://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/

I am attempting to use

```<code>Enter-PSSession -ComputerName <RemoteComputerName> -Credential <RemoteUser>
</code>```

When I run the command, I get a popup with the username populated and asking for a password.  I have entered my MS password for the account.  (I have changed the password from within Windows to ensure they are synced)

And I get the following error:

```<code>Enter-PSSession : Connecting to remote server <REMOTECOMPUTER> failed with the following error message : The WinRM client
cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not
joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts
configuration setting. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not
be authenticated. You can get more information about that by running the following command: winrm help config. For
more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName <REMOTECOMPUTER> -Credential <USER>
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (<REMOTECOMPUTER>:String) [Enter-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed
</code>```

I can't seem to figure out how to do this.  And, maybe more importantly, is there a better way/utility to accomplish my goal?  The remote computer is hosting WAMP and I just want to be execute development commands remotely so I can move the RemoteComputer into the basement and not have to spin my chair around to type on it.

TIA

Body:
I am wanting to access another windows device on my local network and run powershell commands.  In my mind, it would be similar to SSH into a linux box.  I would have an open window on my machine, but would be operating within the remote machine so that I can execute composer install or php artisan migrate type commands on the remote machine.

I have followed the instructions from:
https://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/

I am attempting to use

Enter-PSSession -ComputerName <RemoteComputerName> -Credential <RemoteUser>

When I run the command, I get a popup with the username populated and asking for a password.  I have entered my MS password for the account.  (I have changed the password from within Windows to ensure they are synced)

And I get the following error:

Enter-PSSession : Connecting to remote server <REMOTECOMPUTER> failed with the following error message : The WinRM client
cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not
joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts
configuration setting. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not
be authenticated. You can get more information about that by running the following command: winrm help config. For
more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName <REMOTECOMPUTER> -Credential <USER>
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (<REMOTECOMPUTER>:String) [Enter-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

I can't seem to figure out how to do this.  And, maybe more importantly, is there a better way/utility to accomplish my goal?  The remote computer is hosting WAMP and I just want to be execute development commands remotely so I can move the RemoteComputer into the basement and not have to spin my chair around to type on it.

TIA


问:
how to apply different styles to react leaftlet map based on state
I want to apply these certain styles to my react leaflet map when the user clicks a button to signal that they want a dark themed map or a light themed one but I am not entirely sure how to go about setting up the styles object properly I have created a function to determine the state being light or dark to decide what styles to apply to the map and then the function but not sure if I should have a state for the styles or if I should just have separate style objects and I am also not entirely sure how to adjust the react leaflet map to apply a dark themed to it I have looked around but cannot seem to find any resources on how to

Map component:

```<code>import react from 'react';
import { useState, useEffect} from 'react';
import { MapContainer, TileLayer, Popup} from 'react-leaflet';
import MapComp from './MapComp';

function Map() {

    const [activities, setActivities] = useState([]);
    const [polylines, setPolylines] = useState(null); // as empty array value is still truthy
    const [isLoading, setIsLoading] = useState(true);
    const [mapMode, setMapMode] = useState('light');
    const [mapStyle, setMapStyle] = useState({});

/*

*/

    function changeMapStyle() {
        if(mapMode === 'light') {
            setMapMode('dark');

          }
        else {
            setMapMode('light');
        }
    }

    return (

        <>
        <button onClick={changeMapStyle}>Change Map style</button>
        <MapComp className={`${mapMode}`}  style={{ width: "100%", height: "calc(100vh - 4rem)" }}/>
        </>

    )

}

export default Map;
</code>```

unsure about this file as I do not think the styles apply correctly to the map. Styles where sourced at https://github.com/pkrasicki/issviewer/blob/master/public/css/dark-theme.css
these styles where applied to vanilla js so that is why I am unsure.

style file:

```<code>.dark {
    --background: rgb(40, 44, 54);
    --nav-background: rgba(0, 0, 0, 0.7);
    --text: rgba(255, 255, 255, 0.85);
    --link: rgb(122, 191, 255);
    --link-hover: rgb(143, 200, 253);
    --text-label-color: rgb(255, 95, 95);
    --location-input-bg: rgba(0, 0, 0, 0.2);
    --location-input-color: rgba(255, 255, 255, 0.9);
    --location-input-border: transparent;
    --map-background: #1f1f1f;
    --map-border: rgba(255, 255, 255, 0.1);
    --map-tiles-filter: brightness(0.6) invert(1) contrast(3) hue-rotate(200deg) saturate(0.3) brightness(0.7);
    --map-attribution-bg: rgba(0, 0, 0, 0.6);
    --map-attribution-color: rgb(161, 161, 161);
    --map-zoom-bg: rgb(26, 26, 26);
    --map-zoom-border-bottom: rgba(255, 255, 255, 0.3);
    --brightness-bar-full: var(--primary);
    --spinner-color: var(--primary);
    width: "100%";
    height: "calc(100vh - 4rem)"
}

.light {
    width: "100%";
    height: "calc(100vh - 4rem)"
}

@media(prefers-color-scheme: dark) {

    :root {
        --background: rgb(40, 44, 54);
        --nav-background: rgba(0, 0, 0, 0.7);
        --text: rgba(255, 255, 255, 0.85);
        --link: rgb(122, 191, 255);
        --link-hover: rgb(143, 200, 253);
        --text-label-color: rgb(255, 95, 95);
        --location-input-bg: rgba(0, 0, 0, 0.2);
        --location-input-color: rgba(255, 255, 255, 0.9);
        --location-input-border: transparent;
        --map-background: #1f1f1f;
        --map-border: rgba(255, 255, 255, 0.1);
        --map-tiles-filter: brightness(0.6) invert(1) contrast(3) hue-rotate(200deg) saturate(0.3) brightness(0.7);
        --map-attribution-bg: rgba(0, 0, 0, 0.6);
        --map-attribution-color: rgb(161, 161, 161);
        --map-zoom-bg: rgb(26, 26, 26);
        --map-zoom-border-bottom: rgba(255, 255, 255, 0.3);
        --brightness-bar-full: var(--primary);
        --spinner-color: var(--primary);
    }
}
</code>```

Body:
I want to apply these certain styles to my react leaflet map when the user clicks a button to signal that they want a dark themed map or a light themed one but I am not entirely sure how to go about setting up the styles object properly I have created a function to determine the state being light or dark to decide what styles to apply to the map and then the function but not sure if I should have a state for the styles or if I should just have separate style objects and I am also not entirely sure how to adjust the react leaflet map to apply a dark themed to it I have looked around but cannot seem to find any resources on how to

Map component:

import react from 'react';
import { useState, useEffect} from 'react';
import { MapContainer, TileLayer, Popup} from 'react-leaflet';
import MapComp from './MapComp';

function Map() {

    const [activities, setActivities] = useState([]);
    const [polylines, setPolylines] = useState(null); // as empty array value is still truthy
    const [isLoading, setIsLoading] = useState(true);
    const [mapMode, setMapMode] = useState('light');
    const [mapStyle, setMapStyle] = useState({});

/*

*/

    function changeMapStyle() {
        if(mapMode === 'light') {
            setMapMode('dark');

          }
        else {
            setMapMode('light');
        }
    }

    return (

        <>
        <button onClick={changeMapStyle}>Change Map style</button>
        <MapComp className={`${mapMode}`}  style={{ width: "100%", height: "calc(100vh - 4rem)" }}/>
        </>

    )

}

export default Map;

unsure about this file as I do not think the styles apply correctly to the map. Styles where sourced at https://github.com/pkrasicki/issviewer/blob/master/public/css/dark-theme.css
these styles where applied to vanilla js so that is why I am unsure.

style file:

.dark {
    --background: rgb(40, 44, 54);
    --nav-background: rgba(0, 0, 0, 0.7);
    --text: rgba(255, 255, 255, 0.85);
    --link: rgb(122, 191, 255);
    --link-hover: rgb(143, 200, 253);
    --text-label-color: rgb(255, 95, 95);
    --location-input-bg: rgba(0, 0, 0, 0.2);
    --location-input-color: rgba(255, 255, 255, 0.9);
    --location-input-border: transparent;
    --map-background: #1f1f1f;
    --map-border: rgba(255, 255, 255, 0.1);
    --map-tiles-filter: brightness(0.6) invert(1) contrast(3) hue-rotate(200deg) saturate(0.3) brightness(0.7);
    --map-attribution-bg: rgba(0, 0, 0, 0.6);
    --map-attribution-color: rgb(161, 161, 161);
    --map-zoom-bg: rgb(26, 26, 26);
    --map-zoom-border-bottom: rgba(255, 255, 255, 0.3);
    --brightness-bar-full: var(--primary);
    --spinner-color: var(--primary);
    width: "100%";
    height: "calc(100vh - 4rem)"
}

.light {
    width: "100%";
    height: "calc(100vh - 4rem)"
}

@media(prefers-color-scheme: dark) {

    :root {
        --background: rgb(40, 44, 54);
        --nav-background: rgba(0, 0, 0, 0.7);
        --text: rgba(255, 255, 255, 0.85);
        --link: rgb(122, 191, 255);
        --link-hover: rgb(143, 200, 253);
        --text-label-color: rgb(255, 95, 95);
        --location-input-bg: rgba(0, 0, 0, 0.2);
        --location-input-color: rgba(255, 255, 255, 0.9);
        --location-input-border: transparent;
        --map-background: #1f1f1f;
        --map-border: rgba(255, 255, 255, 0.1);
        --map-tiles-filter: brightness(0.6) invert(1) contrast(3) hue-rotate(200deg) saturate(0.3) brightness(0.7);
        --map-attribution-bg: rgba(0, 0, 0, 0.6);
        --map-attribution-color: rgb(161, 161, 161);
        --map-zoom-bg: rgb(26, 26, 26);
        --map-zoom-border-bottom: rgba(255, 255, 255, 0.3);
        --brightness-bar-full: var(--primary);
        --spinner-color: var(--primary);
    }
}