问:
Running .NET 6 project in Docker throws Globalization.CultureNotFoundException
I have upgraded API project from .NET 5 to .NET 6 successfully and running fine when executed locally (without Docker).

I have also updated the version in Dockerfile from "5.0-alpine3.13" to "6.0-alpine3.14" as below (only change I made).

```<code>ARG VERSION=6.0-alpine3.14

#Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
EXPOSE 8080
ENV DOTNET_RUNNING_IN_CONTAINER=true \
  ASPNETCORE_URLS=http://+:8080

#Build stage
FROM mcr.microsoft.com/dotnet/sdk:$VERSION AS build
WORKDIR /src
COPY ["/src/RM.Api/RM.Api.csproj", "/src/RM.Api/"]
RUN dotnet restore "/src/RM.Api/RM.Api.csproj"
COPY . .
WORKDIR "/src/src/RM.Api"

#Publish dotnet project
FROM build AS publish
ARG BUILDCONFIG=RELEASE
RUN dotnet publish "RM.Api.csproj" -c $BUILDCONFIG -o /app/publish

#Create local user, change ownership, and copy artifacts
FROM base AS final
WORKDIR /app
RUN adduser \
  --disabled-password \
  --home /app \
  --gecos '' app \
  && chown -R app /app
USER app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RM.Api.dll"]
</code>```

But when I run this .NET 6 project in Docker it throws the below Azure.Storage exception in the Startup.cs file.

Full stack trace is here.

```<code>Microsoft.Azure.Storage.StorageException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
---> System.Globalization.CultureNotFoundException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
at Microsoft.Azure.Storage.Core.Util.AuthenticationUtility.AppendCanonicalizedCustomHeaders(CanonicalizedString canonicalizedString, HttpRequestMessage request)
at Microsoft.Azure.Storage.Core.Auth.SharedKeyCanonicalizer.CanonicalizeHttpRequest(HttpRequestMessage request, String accountName)
at Microsoft.Azure.Storage.Auth.Protocol.StorageAuthenticationHttpHandler.GetSharedKeyAuthenticationTask(StorageRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.Storage.Auth.Protocol.StorageAuthenticationHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<>n__0(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext, CancellationToken token)
--- End of inner exception stack trace ---
at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext, CancellationToken token)
at Microsoft.Azure.Storage.Blob.CloudBlobContainer.CreateAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
at Microsoft.Azure.Storage.Blob.CloudBlobContainer.CreateIfNotExistsAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
at RM.Api.Startup.ConfigureServices(IServiceCollection services) in /src/src/RM.Api/Startup.cs:line 91
</code>```

I have updated the Dockerfile as below but it did not work.
Can any one help here?

```<code>ARG VERSION=6.0-alpine3.14

#Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
EXPOSE 8080
ENV DOTNET_RUNNING_IN_CONTAINER=true \
  ASPNETCORE_URLS=http://+:8080

#Build stage
FROM mcr.microsoft.com/dotnet/sdk:$VERSION AS build
WORKDIR /src
COPY ["/src/RM.Api/RM.Api.csproj", "/src/RM.Api/"]
RUN dotnet restore "/src/RM.Api/RM.Api.csproj"
COPY . .
WORKDIR "/src/src/RM.Api"

RUN apk add --no-cache icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib

ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true

#Publish dotnet project
FROM build AS publish
ARG BUILDCONFIG=RELEASE
RUN dotnet publish "RM.Api.csproj" -c $BUILDCONFIG -o /app/publish

#Create local user, change ownership, and copy artifacts
FROM base AS final
WORKDIR /app
RUN adduser \
  --disabled-password \
  --home /app \
  --gecos '' app \
  && chown -R app /app
USER app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RM.Api.dll"]
</code>```

答:
You've put the ENV statement in the 'build' part of the Dockerfile which means that it doesn't get placed in the final image. Either put it in the 'base' part or the 'final' part.

I'd put it in the 'base' section with the other ENV statements.

You might also want to move the apk add to the base or final sections of the file, if you want the software installed in the final image.

Body:
I have upgraded API project from .NET 5 to .NET 6 successfully and running fine when executed locally (without Docker).

I have also updated the version in Dockerfile from "5.0-alpine3.13" to "6.0-alpine3.14" as below (only change I made).

ARG VERSION=6.0-alpine3.14

#Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
EXPOSE 8080
ENV DOTNET_RUNNING_IN_CONTAINER=true \
  ASPNETCORE_URLS=http://+:8080

#Build stage
FROM mcr.microsoft.com/dotnet/sdk:$VERSION AS build
WORKDIR /src
COPY ["/src/RM.Api/RM.Api.csproj", "/src/RM.Api/"]
RUN dotnet restore "/src/RM.Api/RM.Api.csproj"
COPY . .
WORKDIR "/src/src/RM.Api"

#Publish dotnet project
FROM build AS publish
ARG BUILDCONFIG=RELEASE
RUN dotnet publish "RM.Api.csproj" -c $BUILDCONFIG -o /app/publish

#Create local user, change ownership, and copy artifacts
FROM base AS final
WORKDIR /app
RUN adduser \
  --disabled-password \
  --home /app \
  --gecos '' app \
  && chown -R app /app
USER app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RM.Api.dll"]

But when I run this .NET 6 project in Docker it throws the below Azure.Storage exception in the Startup.cs file.

Full stack trace is here.

Microsoft.Azure.Storage.StorageException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
---> System.Globalization.CultureNotFoundException: Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
en-US is an invalid culture identifier.
at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
at Microsoft.Azure.Storage.Core.Util.AuthenticationUtility.AppendCanonicalizedCustomHeaders(CanonicalizedString canonicalizedString, HttpRequestMessage request)
at Microsoft.Azure.Storage.Core.Auth.SharedKeyCanonicalizer.CanonicalizeHttpRequest(HttpRequestMessage request, String accountName)
at Microsoft.Azure.Storage.Auth.Protocol.StorageAuthenticationHttpHandler.GetSharedKeyAuthenticationTask(StorageRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.Storage.Auth.Protocol.StorageAuthenticationHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<>n__0(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext, CancellationToken token)
--- End of inner exception stack trace ---
at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext, CancellationToken token)
at Microsoft.Azure.Storage.Blob.CloudBlobContainer.CreateAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
at Microsoft.Azure.Storage.Blob.CloudBlobContainer.CreateIfNotExistsAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
at RM.Api.Startup.ConfigureServices(IServiceCollection services) in /src/src/RM.Api/Startup.cs:line 91

I have updated the Dockerfile as below but it did not work.
Can any one help here?

ARG VERSION=6.0-alpine3.14

#Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:$VERSION AS base
EXPOSE 8080
ENV DOTNET_RUNNING_IN_CONTAINER=true \
  ASPNETCORE_URLS=http://+:8080

#Build stage
FROM mcr.microsoft.com/dotnet/sdk:$VERSION AS build
WORKDIR /src
COPY ["/src/RM.Api/RM.Api.csproj", "/src/RM.Api/"]
RUN dotnet restore "/src/RM.Api/RM.Api.csproj"
COPY . .
WORKDIR "/src/src/RM.Api"

RUN apk add --no-cache icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib

ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true

#Publish dotnet project
FROM build AS publish
ARG BUILDCONFIG=RELEASE
RUN dotnet publish "RM.Api.csproj" -c $BUILDCONFIG -o /app/publish

#Create local user, change ownership, and copy artifacts
FROM base AS final
WORKDIR /app
RUN adduser \
  --disabled-password \
  --home /app \
  --gecos '' app \
  && chown -R app /app
USER app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "RM.Api.dll"]


来源: stackexchange

问:
android problem:Read file problem res/raw/img/img123.jpg
I'm beginner of android.
And I get a problem.
Can I get the file under the folder I create in res/raw?

For example: res/raw/img/img123.jpg

Can I get the id or use the file img123.jpg?

if yes,how can i do that?

答:
Please read this:
http://developer.android.com/guide/topics/resources/drawable-resource.html

Instead of accessing it as a raw resource, try creating a res/drawable/img123.jpg to easily access it using

```<code>getResources().getDrawable(R.drawable.img123);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please read this:
http://developer.android.com/guide/topics/resources/drawable-resource.html

Instead of accessing it as a raw resource, try creating a res/drawable/img123.jpg to easily access it using

getResources().getDrawable(R.drawable.img123);


问:
What is RouterView in Vue.js?
When I do the Vue quickstart and it creates a HelloWorld application, I see that App.vue line 20 contains this line:

```<code><RouterView />
</code>```

I can't find any documentation for RouterView. It seems odd that a quickstart / tutorial would include an undocumented tag. I do see router-view, is that the same thing?

答:
From Vue docs for Component Registration > Name Casing:

When defining a component with PascalCase, you can use either case when referencing its custom element. That means both <my-component-name> and <MyComponentName> are acceptable. Note, however, that only kebab-case names are valid directly in the DOM (i.e. non-string templates).

So <RouterView /> is the same as <router-view />.

ContentLicense: CC BY-SA 4.0

Title: What is RouterView in Vue.js?

Body:
When I do the Vue quickstart and it creates a HelloWorld application, I see that App.vue line 20 contains this line:

<RouterView />

I can't find any documentation for RouterView. It seems odd that a quickstart / tutorial would include an undocumented tag. I do see router-view, is that the same thing?


问:
Clang errors about instructions when rebuilding human readable .ll files
I converted some binary bitcode files into human readable form using llvm-dis. When I tried to rebuild those .ll files into the main binary, I will see errors such as

```<code>clang -cc1 version 13.0.0 (clang-1300.0.29.30) default target x86_64-apple-darwin20.6.0
arm64_6B51A8D2-17A7-4252-8C72-2D1877B77E09.ll:240:175: error: expected metadata after comma
  %24 = atomicrmw add i64* bitcast (i8* getelementptr inbounds (%"__ir_hidden#224_", %"__ir_hidden#224_"* @"\01__hidden#199_", i64 0, i32 0, i64 24) to i64*), i64 1 acquire, align 8, !dbg !139, !noalias !150
</code>```

It seems that clang encountered a problem trying to parse the instructions translated by llvm-dis?

EDIT 9 Feb 2022

I did not make any changes to the .ll files. This was what I did

```<code>#!/bin/bash

for bitcodefile in $(ls | grep -i ^arm64)
do
    echo $bitcodefile
    llvm-dis $bitcodefile -o ./readable2/$bitcodefile.ll
done
</code>```

Then I tried to rebuild the .ll files into the final binary

```<code>/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch arm64 -mios-version-min=12.2.0 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.2.sdk -dead_strip -v -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/ -L/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/lib/swift/ -fembed-bitcode *.ll -o 64bit_executable -F /path/to/Frameworks
</code>```

答: It seems you are using Apple-provided clang to compile LLVM IR produced by mainline LLVM. This in general might not work, you need to use "matching" IR producers / consumers (e.g. mainline clang of the same version).</p>

Body:
I converted some binary bitcode files into human readable form using llvm-dis. When I tried to rebuild those .ll files into the main binary, I will see errors such as

clang -cc1 version 13.0.0 (clang-1300.0.29.30) default target x86_64-apple-darwin20.6.0
arm64_6B51A8D2-17A7-4252-8C72-2D1877B77E09.ll:240:175: error: expected metadata after comma
  %24 = atomicrmw add i64* bitcast (i8* getelementptr inbounds (%"__ir_hidden#224_", %"__ir_hidden#224_"* @"\01__hidden#199_", i64 0, i32 0, i64 24) to i64*), i64 1 acquire, align 8, !dbg !139, !noalias !150

It seems that clang encountered a problem trying to parse the instructions translated by llvm-dis?

EDIT 9 Feb 2022

I did not make any changes to the .ll files. This was what I did

#!/bin/bash

for bitcodefile in $(ls | grep -i ^arm64)
do
    echo $bitcodefile
    llvm-dis $bitcodefile -o ./readable2/$bitcodefile.ll
done

Then I tried to rebuild the .ll files into the final binary

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch arm64 -mios-version-min=12.2.0 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.2.sdk -dead_strip -v -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/ -L/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/lib/swift/ -fembed-bitcode *.ll -o 64bit_executable -F /path/to/Frameworks


问:
How can I implement incremental training for xgboost?
The problem is that my train data could not be placed into RAM due to train data size. So I need a method which first builds one tree on whole train data set, calculate residuals build another tree and so on (like gradient boosted tree do). Obviously if I call model = xgb.train(param, batch_dtrain, 2) in some loop - it will not help, because in such case it just rebuilds whole model for each batch.

答:
One possible solution that I have not tested is to used a dask dataframe which  should act the same as a pandas dataframe but (I assume) utilize disk and reads in and out of RAM. here are some helpful links.
this link mentions how to use it with xgboost also see
also see.
further there is an experimental options from XGBoost as well here but it is "not ready for production"</p>


问:
How to find the *smallest* number in the list that is close to a given number in Python?
I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.

Foe e.x.

```<code>my_list=[1,10,15,20,45,56]
my_no=9
</code>```

Output should be equal to 1
Explanation: since 9 comes between 1 and 10 and I want the smaller number, i.e. 1.

Similarly if my_no=3, output is equal to 1

I am new to python, so any help will be much appreciated. Thanks!

答:
You can reduce from functools:

```<code>from functools import reduce

i = reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
print(i)

# Output
1
</code>```

Test

```<code># my_no = 18
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
15

# my_no = 59
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
56
</code>```

Note: this code doesn't work if my_no < my_list[0]. You have to check it before.

Body:
I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.

Foe e.x.

my_list=[1,10,15,20,45,56]
my_no=9

Output should be equal to 1
Explanation: since 9 comes between 1 and 10 and I want the smaller number, i.e. 1.

Similarly if my_no=3, output is equal to 1

I am new to python, so any help will be much appreciated. Thanks!

Body:
You can reduce from functools:

from functools import reduce

i = reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
print(i)

# Output
1

Test

# my_no = 18
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
15

# my_no = 59
>>> reduce(lambda l, r: l if l <= my_no <= r else r, my_list)
56

Note: this code doesn't work if my_no < my_list[0]. You have to check it before.


问:
Library Database Design
Hi i've trying to design a library database.
Entities are

Book

Magazine

DVD

Member

Librarian

...

Media types can be borrowed by members.Should i create 3 different

loan tables for all media types or just one loan table.

if we think media as object , (book,magazine and dvd inherits

media ) how can they expressed in E&R diagram.

If all copies of a book are borrowed,the book can be    reservable.I
can control it programatically(using select count(*) from books)

but    i wonder if there is an efficient way to do this.

答:
You can use one loan table which includes a ref to other tables.

This link http://www.csc.liv.ac.uk/~valli/Comp507/slides23.pdf will
    be helpful for you.There is a sample.

You can create book table which has a column named total_quantity ,
    and another table book_copies.If a book is borrowed, you can
update
    book.total_quatity--. When lending you can control whether
    book.total_quantity is zero or not

Title: Library Database Design


问:
How to convert csv to xlsx with openpyxl to any column?
I am creating code for converting csv to xlsx but my code has a problem, it can convert the values only to A1 column. How to make code to be can writing values from csv to any selected column?</p>
```<code>import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('text.csv') as f:
    reader = csv.reader(f, delimiter=':')
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')
</code>```

答:
Why do you use open()?

You can use pandas to open and save files:

```<code>pd.read_csv('text.csv').to_excel('file.xlsx')
</code>```

Body:
I am creating code for converting csv to xlsx but my code has a problem, it can convert the values only to A1 column. How to make code to be can writing values from csv to any selected column?

import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('text.csv') as f:
    reader = csv.reader(f, delimiter=':')
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')

Body:
Why do you use open()?

You can use pandas to open and save files:

pd.read_csv('text.csv').to_excel('file.xlsx')


问:
Flutter with direct dart firebase initialization still gets error on real device: Could not locate configuration file: 'GoogleService-Info.plist'
Flutter 2.8.1 using flutterfire - according to docs, should not need use the GoogleService-Info.plist file. This version states that it support direct dart initialization. Works fine on simulator, but when running on real iOS device - from Android Studio or XCode, I get the error about the plist file. flutterfire configure creates a valid firebase_options.dart file and main looks like this:

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  runApp(const MyApp());
}
</code>```

Output of flutter doctor:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.8.1, on macOS 12.0.1 21A559 darwin-x64, locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] VS Code (version 1.63.2)
[✓] Connected device (3 available)
</code>```

答:
Do you have add the GoogleServices-info.plist file in XCode?

I mean do you have drag and drop it from Finder to Android Studio or XCode.

You need to drag and drop it to XCode.

Body:
Flutter 2.8.1 using flutterfire - according to docs, should not need use the GoogleService-Info.plist file. This version states that it support direct dart initialization. Works fine on simulator, but when running on real iOS device - from Android Studio or XCode, I get the error about the plist file. flutterfire configure creates a valid firebase_options.dart file and main looks like this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  runApp(const MyApp());
}

Output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.8.1, on macOS 12.0.1 21A559 darwin-x64, locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] VS Code (version 1.63.2)
[✓] Connected device (3 available)


问:
React updating array state
I'm trying to update an array state, ok it updates the state correctly if I checked the state in the react dev tool, but the logged message is the state without the last update.
If I use array.push to update the state, it logs the updated state

My Code

答:
setGoalsArray will not update the variable for the current scope but only for the next render.

Therefore you will need to create an effect which triggers once goalsArray is changed e.g.:

```<code>  useEffect(() => console.log(goalsArray), [goalsArray])
</code>```

See https://reactjs.org/docs/hooks-effect.html

Title: React updating array state

Body:
setGoalsArray will not update the variable for the current scope but only for the next render.

Therefore you will need to create an effect which triggers once goalsArray is changed e.g.:

  useEffect(() => console.log(goalsArray), [goalsArray])

See https://reactjs.org/docs/hooks-effect.html


问:
How do I make .gitlab-ci.yml execute different ansible playbooks in different folders/subfolders?
I just started learning about NetDevOps.

All the examples containing demos of GitLAb + Ansible show how to execute "deploy.yml" from Ansible from the .gitlab-ci.yml.

However, when I see a general network equipment based Ansible tutorial the author executes different Ansible cookbook .yml files, for example sites.yml from the root, deploy.yml from another subfolder, interfaces.yml from another subfolder.

Can someone give me an example of how I would execute the different Ansible playbook .yml files on demand?

I.e. - When it detects changes in .yml in a folder, run that .yml file under that folder?

答:
lets say you have an ansible repo and a .gitlab-ci.yml in the root of it.

```<code>.gitlab-ci.yml
ansible/cookbook1
ansible/cookbook2
</code>```

For each cookbook you could create a Gitlab job

```<code>execute_cookbook1:
 script:
  - ...ANSIBLE COMMANDS...
 ...
 only:
     changes:
       - ansible/cookbook1/**/*.yml

execute_cookbook2:
 script:
  - ...ANSIBLE COMMANDS...
 ...
 only:
     changes:
       - ansible/cookbook2/**/*.yml
</code>```

This way when you push your code to ansible repo, Gitlab will detect which cookbook changed. And run the according job

Body:
lets say you have an ansible repo and a .gitlab-ci.yml in the root of it.

.gitlab-ci.yml
ansible/cookbook1
ansible/cookbook2

For each cookbook you could create a Gitlab job

execute_cookbook1:
 script:
  - ...ANSIBLE COMMANDS...
 ...
 only:
     changes:
       - ansible/cookbook1/**/*.yml

execute_cookbook2:
 script:
  - ...ANSIBLE COMMANDS...
 ...
 only:
     changes:
       - ansible/cookbook2/**/*.yml

This way when you push your code to ansible repo, Gitlab will detect which cookbook changed. And run the according job


问:
Covert SQL to Laravel Query Builder
I'm a beginner regarding Laravel Query Builder, can you guys help me convert this SQL to Query Builder

```<code>public function check_available_room(Request $request, $checkin_date)
{
    $available_rooms = DB::SELECT("SELECT * FROM rooms WHERE id NOT IN (SELECT room_id FROM bookings WHERE '$checkin_date' BETWEEN checkin_date AND checkout_date)");

}
</code>```

Book model

function rooms() {
   return $this->belongsTo(Room::class, 'room_id');
}
```
<p><strong>Room model</strong></p>
<pre class="lang-php prettyprint-override"><code>public function bookings() {
    return $this->hasMany(Booking::class);
}
</code>```

Thank you so much

答:
```<code>$unavailable_room_ids = Booking::where('checkin_date', '<', $checkin_date)
    ->where('checkout_date', '>=', $checkin_date)
    ->pluck('room_id')->get();

$available_rooms = Room::whereNotIn('id', $unavailable_room_ids)->get();
</code>```

Title: Covert SQL to Laravel Query Builder

Body:
I'm a beginner regarding Laravel Query Builder, can you guys help me convert this SQL to Query Builder

public function check_available_room(Request $request, $checkin_date)
{
    $available_rooms = DB::SELECT("SELECT * FROM rooms WHERE id NOT IN (SELECT room_id FROM bookings WHERE '$checkin_date' BETWEEN checkin_date AND checkout_date)");

}

Book model

function rooms() {
   return $this->belongsTo(Room::class, 'room_id');
}

Room model

public function bookings() {
    return $this->hasMany(Booking::class);
}

Thank you so much


问:
moved to left and right after click?
My code does not work. What I want is to move my pagination to the left and to the right after #prev_pag and #next_pag are clicked on. I don't know why this code isn't working?

EXAMPLE: http://jsfiddle.net/szVKD/

JS code:

```<code>$('#next_pag').click(function() {
        $('#pagination').animate({
            marginLeft: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            marginLeft: '+=100px'
        },
        500);
    });
});
</code>```

答:
Try to animate not 'marginLeft' but 'left';
EXAMPLE:
http://www3.montonfashion.com/js/slider/carouselPP.js
http://www3.montonfashion.com/et/waistcoat-willy.html

Title: moved to left and right after click?

Body:
My code does not work. What I want is to move my pagination to the left and to the right after #prev_pag and #next_pag are clicked on. I don't know why this code isn't working?

EXAMPLE: http://jsfiddle.net/szVKD/

JS code:

$('#next_pag').click(function() {
        $('#pagination').animate({
            marginLeft: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            marginLeft: '+=100px'
        },
        500);
    });
});


问:
Azure Pipeline maven release:perform fails with "The git-clone command failed."
currently, I try to build a spring boot application and make releases with Azure Pipelines and maven-release-plugin.

My Azure Pipeline YAML Looks like this:

```<code>- stage: BuildRelease
  condition: true
  displayName: Building a Release with Maven
  jobs:
    - job: BuildReleaseJob
      displayName: Create a Maven release with version $(releaseVersion)
      steps:
      - checkout: self
        persistCredentials: true

      - task: MavenAuthenticate@0
        displayName: 'Authenticate to Maven'
        inputs:
          artifactsFeeds: 'ciam'

      - task: Bash@3
        displayName: Set Git Credentials
        inputs:
          targetType: 'inline'
          script: |
            git config --global user.email "you@example.com"
            git config --global user.name "Azure Pipeline Release"
            git checkout develop

       - task: Bash@3
         displayName: Maven Clean & Prepare Release
         inputs:
           targetType: 'inline'
           script: |
             mvn --batch-mode release:clean release:prepare -DscmCommentPrefix=***NO_CI***

      - task: Bash@3
        displayName: Maven  Perform Release
        inputs:
          targetType: 'inline'
          script: |
            mvn --batch-mode release:perform -DscmCommentPrefix=***NO_CI***
</code>```

I also added Allow Contriubte, Create branch, Create tag, and Read permission to Project Collection Build Service (MyCompany) in Azure Dev Ops Project Settings -> Repositories ->  -> Secuirty

Therefore everything works fine until the last task, which is executing release:perform
The shown Error is:

```<code>[INFO] Executing: /bin/sh -c cd /home/vsts/work/1/s/target && git clone --branch projectName-0.0.36 https:********@dev.azure.com/MyCompany/Project/_git/projectName-service /home/vsts/work/1/s/target/checkout
[INFO] Working directory: /home/vsts/work/1/s/target
[ERROR] The git-clone command failed.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.136 s
[INFO] Finished at: 2022-02-01T14:18:31Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.5.3:perform (default-cli) on project projectName-service: Unable to checkout from SCM
[ERROR] Provider message:
[ERROR] The git-clone command failed.
[ERROR] Command output:
[ERROR] Cloning into '/home/vsts/work/1/s/target/checkout'...
[ERROR] fatal: could not read Password for 'https://mycompany@dev.azure.com': terminal prompts disabled
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

Could anyone point me to somewhere what I did wrong?

After that, the git tag is built and committed in SCM

UPDATE
I tried to do in batch inline script what maven tries to do in release perform and it kind of worked. Now I am more confused.

```<code>    - task: Bash@3
      displayName: TestClone
      inputs:
        targetType: inline
        script: |
          ls -laf /home/vsts/work/1/s/target/checkout
          /bin/sh -c cd '/home/vsts/work/1/s/target' && 'git' 'clone' '--depth' '1' '--branch' 'myaccount-service-0.0.43' 'https://$(System.AccessToken)@dev.azure.com/kiongroup/CxP/_git/myaccount-service' 'checkout'
          cd /home/vsts/work/1/s/target/checkout
          ls
</code>```

Output is:

```<code>ls: cannot access '/home/vsts/work/1/s/target/checkout': No such file or directory
Cloning into 'checkout'...
Note: switching to '1653266b5f151fd6137b7b579044eef1867d8d5b'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

/home/vsts/work/_temp/358629de-4b6b-4548-942e-f9a05281c5a5.sh: line 3: cd: /home/vsts/work/1/s/target/checkout: No such file or directory
Dockerfile
README.md
azure-pipelines.yml
checkout
docker
mvnw
mvnw.cmd
pom.xml
pom.xml.releaseBackup
postman
release.properties
src
target
</code>```

答:
Ok, I found a solution for me that involves using the Azure DevOps Git SSH URL and not the HTTPS.

First of all, I created a SSH Key according to this Use SSH key authentication or choose your Git providers tutorial.

Once you have your SSH private and public key, you need to install the SSH Key into your YAML pipeline. See Install SSH Key task.

```<code>    - task: InstallSSHKey@0
      inputs:
        knownHostsEntry: ssh.dev.azure.com ssh-rsa <YOUR KNOWN HOST KEY>
        sshKeySecureFile: <NameOfSecureFileKey>
        sshPassphrase: <PassphraseIfUsed>
</code>```

Here are the steps summarized

Create a KeyPair in your .ssh folder with a private key azurePipeline and a public one azurePipeline.pub (enter passphrase if desired)

ssh-keygen -f ~.ssh/azurePipeline -t rsa

Get the known host entry e.g. ssh.dev.azure.com ssh-rsa AAAAB3Nz.... with

ssh-keyscan ssh.dev.azure.com

Go to Azure DevOps and add the content of public key as described in Use SSH key authentication

Add the private key as a secure file as described in Install SSH Key task

Change the SCM Urlin pom.xml to:

a

```<code><scm>
    <developerConnection>scm:git:git@ssh.dev.azure.com:v3/kiongroup/CxP/myaccount-service</developerConnection>
    <tag>HEAD</tag>
</scm>
</code>```

Hope this helps someone out there :)

Body:
currently, I try to build a spring boot application and make releases with Azure Pipelines and maven-release-plugin.

My Azure Pipeline YAML Looks like this:

- stage: BuildRelease
  condition: true
  displayName: Building a Release with Maven
  jobs:
    - job: BuildReleaseJob
      displayName: Create a Maven release with version $(releaseVersion)
      steps:
      - checkout: self
        persistCredentials: true

      - task: MavenAuthenticate@0
        displayName: 'Authenticate to Maven'
        inputs:
          artifactsFeeds: 'ciam'

      - task: Bash@3
        displayName: Set Git Credentials
        inputs:
          targetType: 'inline'
          script: |
            git config --global user.email "you@example.com"
            git config --global user.name "Azure Pipeline Release"
            git checkout develop

       - task: Bash@3
         displayName: Maven Clean & Prepare Release
         inputs:
           targetType: 'inline'
           script: |
             mvn --batch-mode release:clean release:prepare -DscmCommentPrefix=***NO_CI***

      - task: Bash@3
        displayName: Maven  Perform Release
        inputs:
          targetType: 'inline'
          script: |
            mvn --batch-mode release:perform -DscmCommentPrefix=***NO_CI***

I also added Allow Contriubte, Create branch, Create tag, and Read permission to Project Collection Build Service (MyCompany) in Azure Dev Ops Project Settings -> Repositories ->  -> Secuirty

Therefore everything works fine until the last task, which is executing release:perform
The shown Error is:

[INFO] Executing: /bin/sh -c cd /home/vsts/work/1/s/target && git clone --branch projectName-0.0.36 https:********@dev.azure.com/MyCompany/Project/_git/projectName-service /home/vsts/work/1/s/target/checkout
[INFO] Working directory: /home/vsts/work/1/s/target
[ERROR] The git-clone command failed.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.136 s
[INFO] Finished at: 2022-02-01T14:18:31Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.5.3:perform (default-cli) on project projectName-service: Unable to checkout from SCM
[ERROR] Provider message:
[ERROR] The git-clone command failed.
[ERROR] Command output:
[ERROR] Cloning into '/home/vsts/work/1/s/target/checkout'...
[ERROR] fatal: could not read Password for 'https://mycompany@dev.azure.com': terminal prompts disabled
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Could anyone point me to somewhere what I did wrong?

After that, the git tag is built and committed in SCM

UPDATE
I tried to do in batch inline script what maven tries to do in release perform and it kind of worked. Now I am more confused.

    - task: Bash@3
      displayName: TestClone
      inputs:
        targetType: inline
        script: |
          ls -laf /home/vsts/work/1/s/target/checkout
          /bin/sh -c cd '/home/vsts/work/1/s/target' && 'git' 'clone' '--depth' '1' '--branch' 'myaccount-service-0.0.43' 'https://$(System.AccessToken)@dev.azure.com/kiongroup/CxP/_git/myaccount-service' 'checkout'
          cd /home/vsts/work/1/s/target/checkout
          ls

Output is:

ls: cannot access '/home/vsts/work/1/s/target/checkout': No such file or directory
Cloning into 'checkout'...
Note: switching to '1653266b5f151fd6137b7b579044eef1867d8d5b'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

/home/vsts/work/_temp/358629de-4b6b-4548-942e-f9a05281c5a5.sh: line 3: cd: /home/vsts/work/1/s/target/checkout: No such file or directory
Dockerfile
README.md
azure-pipelines.yml
checkout
docker
mvnw
mvnw.cmd
pom.xml
pom.xml.releaseBackup
postman
release.properties
src
target

Body:
Ok, I found a solution for me that involves using the Azure DevOps Git SSH URL and not the HTTPS.

First of all, I created a SSH Key according to this Use SSH key authentication or choose your Git providers tutorial.

Once you have your SSH private and public key, you need to install the SSH Key into your YAML pipeline. See Install SSH Key task.

    - task: InstallSSHKey@0
      inputs:
        knownHostsEntry: ssh.dev.azure.com ssh-rsa <YOUR KNOWN HOST KEY>
        sshKeySecureFile: <NameOfSecureFileKey>
        sshPassphrase: <PassphraseIfUsed>

Here are the steps summarized

Create a KeyPair in your .ssh folder with a private key azurePipeline and a public one azurePipeline.pub (enter passphrase if desired)

ssh-keygen -f ~.ssh/azurePipeline -t rsa

Get the known host entry e.g. ssh.dev.azure.com ssh-rsa AAAAB3Nz.... with

ssh-keyscan ssh.dev.azure.com

Go to Azure DevOps and add the content of public key as described in Use SSH key authentication

Add the private key as a secure file as described in Install SSH Key task

Change the SCM Urlin pom.xml to:

a

<scm>
    <developerConnection>scm:git:git@ssh.dev.azure.com:v3/kiongroup/CxP/myaccount-service</developerConnection>
    <tag>HEAD</tag>
</scm>

Hope this helps someone out there :)


问:
How to restart VScode after editing extension's config?
VScode notifies you when you open a config of an extension:

remember to Restart VScode

But it says nothing about how. They use capital letter for the restart word, so normally it should mean something if you emphasize an appellation. Is there some hidden restart button or a key shortcut?

How do I restart the IDE?

答:
Method1

VIEW->COMMAND PALETTE->RELOAD WINDOW

Method2

cntrl+Shift+p
Then Type: Reload window (Method1 same but using shortcut)

Method3

cntrl+R

NB:if Method3 did'nt work try this approach https://stackoverflow.com/a/71046140/7706354


问:
How to move the terminal as a column next to the side bar?
After today 4.02.22 VSCode introduced the "Side panel" in update 1.64.0
It should give more flexibility and such, but in my case, it actually breaks my layout and takes the option that I was using out.

I have my layout - | Code | Terminal | Side bar |
Each in a column.
Now I cannot move the terminal anywhere but left as a column (before the code vide) and bottom.

Does anyone know how to revert this, or achieve my old layout?
Thanks

答: I have another workaround to this:

Body: I have another workaround to this:


问:
Elastic Search filter query for null values

I am trying to write a query where it searches in elastic that if fields is null then filter it out. In my case if both battery temperature and temperature value is null then remove it from the bucket, if one value is null then no need to filter.

Above query is used and in some cases both temperature and battery values are coming null which I need to remove from the buckets.

GET ts-history*/_search/?pretty
{
  "aggs": {
    "timestamp": {
      "date_histogram": {
        "field": "timestamp",
        "interval": "1s",
        "time_zone": "America/New_York",
        "min_doc_count": 1
      },
      "aggs": {
        "temperature75cea6bd-21bb-4794-8314-0291a7c9ad71": {
          "avg": {
            "field": "temperature"
          }
        },
        "heater_temperature75cea6bd-21bb-4794-8314-0291a7c9ad71": {
          "avg": {
            "field": "battery_temperature"
          }
        }
      }
    }
  },
  "size": 0,
  "_source": {
    "excludes": []
  },
  "stored_fields": ["*"],
  "script_fields": {},
  "docvalue_fields": [
    {
      "field": "@timestamp",
      "format": "date_time"
    },
    {
      "field": "timestamp",
      "format": "date_time"
    }
  ],
  "query": {
    "bool": {
      "must": [
        {
          "match_all": {}
        },
        {
          "range": {
            "timestamp": {
              "gte": 1644225612000,
              "lte": 1644315612000
            }
          }
        },
        {
          "match_phrase": {
            "asset_id.keyword": {
              "query": "75cea6bd-21bb-4794-8314-0291a7c9ad71"
            }
          }
        }
      ],
      "filter": [],
      "should": [],
      "must_not": []
    }
  }
}
```
<p>query should get asset 1 and 3 but in my case i am getting asset 2 which i need to filter.</p>
```AssetId Timestamp                       temperature   battery_temperature
1      2022-02-07T06:31:37.000-05:00   10             null
2      2022-02-07T06:35:37.000-05:00   null           null
3      2022-02-07T06:40:37.000-05:00   null           20
```

答:
As you need to get document if atleast one field available then you can use should clause with exists query.

Below is query for your requirement:

{
  "query": {
    "bool": {
      "should": [
        {
          "exists": {
            "field": "temperature"
          }
        },
        {
          "exists": {
            "field": "battery_temperature"
          }
        }
      ]
    }
  }
}
```
<p>Sample document which is in index:</p>
<pre class="lang-json prettyprint-override"><code>{
"hits" : [
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "w9V43X4BGC8jFmD-T06n",
        "_score" : 1.0,
        "_source" : {
          "temperature" : 10,
          "battery_temperature" : 10
        }
      },
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "xNV43X4BGC8jFmD-Z06W",
        "_score" : 1.0,
        "_source" : {
          "temperature" : null,
          "battery_temperature" : 10
        }
      },
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "xdV43X4BGC8jFmD-hk4n",
        "_score" : 1.0,
        "_source" : {
          "temperature" : null,
          "battery_temperature" : null
        }
      }
    ]
}
</code>```

Response for above query:

{
"hits" : [
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "w9V43X4BGC8jFmD-T06n",
        "_score" : 2.0,
        "_source" : {
          "temperature" : 10,
          "battery_temperature" : 10
        }
      },
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "xNV43X4BGC8jFmD-Z06W",
        "_score" : 1.0,
        "_source" : {
          "temperature" : null,
          "battery_temperature" : 10
        }
      }
    ]
}
```

Body:
I am trying to write a query where it searches in elastic that if fields is null then filter it out. In my case if both battery temperature and temperature value is null then remove it from the bucket, if one value is null then no need to filter.

Above query is used and in some cases both temperature and battery values are coming null which I need to remove from the buckets.

GET ts-history*/_search/?pretty
{
  "aggs": {
    "timestamp": {
      "date_histogram": {
        "field": "timestamp",
        "interval": "1s",
        "time_zone": "America/New_York",
        "min_doc_count": 1
      },
      "aggs": {
        "temperature75cea6bd-21bb-4794-8314-0291a7c9ad71": {
          "avg": {
            "field": "temperature"
          }
        },
        "heater_temperature75cea6bd-21bb-4794-8314-0291a7c9ad71": {
          "avg": {
            "field": "battery_temperature"
          }
        }
      }
    }
  },
  "size": 0,
  "_source": {
    "excludes": []
  },
  "stored_fields": ["*"],
  "script_fields": {},
  "docvalue_fields": [
    {
      "field": "@timestamp",
      "format": "date_time"
    },
    {
      "field": "timestamp",
      "format": "date_time"
    }
  ],
  "query": {
    "bool": {
      "must": [
        {
          "match_all": {}
        },
        {
          "range": {
            "timestamp": {
              "gte": 1644225612000,
              "lte": 1644315612000
            }
          }
        },
        {
          "match_phrase": {
            "asset_id.keyword": {
              "query": "75cea6bd-21bb-4794-8314-0291a7c9ad71"
            }
          }
        }
      ],
      "filter": [],
      "should": [],
      "must_not": []
    }
  }
}

query should get asset 1 and 3 but in my case i am getting asset 2 which i need to filter.

AssetId Timestamp                       temperature   battery_temperature
1      2022-02-07T06:31:37.000-05:00   10             null
2      2022-02-07T06:35:37.000-05:00   null           null
3      2022-02-07T06:40:37.000-05:00   null           20

Body:
As you need to get document if atleast one field available then you can use should clause with exists query.

Below is query for your requirement:

{
  "query": {
    "bool": {
      "should": [
        {
          "exists": {
            "field": "temperature"
          }
        },
        {
          "exists": {
            "field": "battery_temperature"
          }
        }
      ]
    }
  }
}

Sample document which is in index:

{
"hits" : [
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "w9V43X4BGC8jFmD-T06n",
        "_score" : 1.0,
        "_source" : {
          "temperature" : 10,
          "battery_temperature" : 10
        }
      },
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "xNV43X4BGC8jFmD-Z06W",
        "_score" : 1.0,
        "_source" : {
          "temperature" : null,
          "battery_temperature" : 10
        }
      },
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "xdV43X4BGC8jFmD-hk4n",
        "_score" : 1.0,
        "_source" : {
          "temperature" : null,
          "battery_temperature" : null
        }
      }
    ]
}

Response for above query:

{
"hits" : [
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "w9V43X4BGC8jFmD-T06n",
        "_score" : 2.0,
        "_source" : {
          "temperature" : 10,
          "battery_temperature" : 10
        }
      },
      {
        "_index" : "nullcheck",
        "_type" : "_doc",
        "_id" : "xNV43X4BGC8jFmD-Z06W",
        "_score" : 1.0,
        "_source" : {
          "temperature" : null,
          "battery_temperature" : 10
        }
      }
    ]
}


问:
Dynamic change of the class of an HTML element not working effectively
I've written an HTML page that contains a form. The form is checked by a PHP page by having at the beginning of the HTML page :

```<code><script type="text/javascript" src="js/mootools/core.js"></script>
<script type="text/javascript" src="js/mootools/more.js"></script>
<script type="text/javascript" src="js/formcheck/lang/fr.js"> </script>
<script type="text/javascript" src="js/formcheck/formcheck.js"> </script>

<script type="text/javascript">
    window.addEvent('domready', function(){
       new FormCheck('form');
});
</script>
</code>```

The problem is that I add dynamically a class to an HTML element after the page is loaded under some conditions.

The following code sample of the HTML page is a radio button to know if the visitor of the page has a car. If she/he puts yes then the class 'validate['required']' is added to select element number of cars meaning the user must choose a value (number of cars). Otherwise the user has no car and then doesn't have to choose and the default empty string is accepted and transmitted.

```<code><input type="radio" name="cars" value="yes" onclick="document.getElementById('number_of_cars').setAttribute('class','validate[\'required\']');">oui
<input type="radio" name="cars" value="no" checked="checked">no

<label>How many cars do you have ? :</label>
<select name="number_of_cars" id="number_of_cars">
<option value="">-</option>
<option value="01" >01</option>
<option value="02" >02</option>
<option value="03" >03</option>
</select>
</code>```

The problem I have is that when I check with Firebug the HTML element has the class 'validate['required']' when needed (radio button yes) but the PHP page doesn't seem to work because the form is transmitted even if the user hasn't choosed a number of cars.

My guess is that the event "domready" on the Javascript part of my HTML page is not appropriate but I don't know what to do.

Edit: I've changed the javascript element to onChange but it doesn't work neither.

答:
The window.addEvent('domready') is part of the MooTools library, it is not part of Javascript itself. It seems to me that you are not using that, so you should either add the MooTools script to your html, or use the onLoad event.

MooTools is used

Edit

Either that, or the value you send with the FormCheck object is wrong. FormCheck needs an id and not a tagname, so you should at least have somewhere:

```<code><form id="myForm">

new FormCheck('myForm');
</code>```

Edit 2

If you're already using MooTools, it's best to use the built-in event handlers. Direct approaches like onClick and onLoad should be avoided because of cross-browser issues. MooTools takes care of that.

```<code><script type="text/javascript">
  window.addEvent('domready', function(){
    $('cars').addEvent('click', function() {
      $('number_of_cars').addClass("validate['required']");
    });

    new FormCheck('form');
  });
</script>
</code>```

MooTools needs id's for this to work, so:

```<code><input type="radio" name="cars" id="cars" value="yes">
</code>```

Edit 3

Also read the docs of FormCheck carefully. They contain lots of sample code: http://mootools.floor.ch/en/demos/formcheck/

Docs: http://mootools.floor.ch/docs/formcheck/files/formcheck-js.html

Hope this helps

Body:
I've written an HTML page that contains a form. The form is checked by a PHP page by having at the beginning of the HTML page :

The problem is that I add dynamically a class to an HTML element after the page is loaded under some conditions.

The following code sample of the HTML page is a radio button to know if the visitor of the page has a car. If she/he puts yes then the class 'validate['required']' is added to select element number of cars meaning the user must choose a value (number of cars). Otherwise the user has no car and then doesn't have to choose and the default empty string is accepted and transmitted.

<input type="radio" name="cars" value="yes" onclick="document.getElementById('number_of_cars').setAttribute('class','validate[\'required\']');">oui
<input type="radio" name="cars" value="no" checked="checked">no

How many cars do you have ? :
<select name="number_of_cars" id="number_of_cars">
<option value="">-</option>
<option value="01" >01</option>
<option value="02" >02</option>
<option value="03" >03</option>
</select>

The problem I have is that when I check with Firebug the HTML element has the class 'validate['required']' when needed (radio button yes) but the PHP page doesn't seem to work because the form is transmitted even if the user hasn't choosed a number of cars.

My guess is that the event "domready" on the Javascript part of my HTML page is not appropriate but I don't know what to do.

Edit: I've changed the javascript element to onChange but it doesn't work neither.

Body:
The window.addEvent('domready') is part of the MooTools library, it is not part of Javascript itself. It seems to me that you are not using that, so you should either add the MooTools script to your html, or use the onLoad event.

MooTools is used

Edit

Either that, or the value you send with the FormCheck object is wrong. FormCheck needs an id and not a tagname, so you should at least have somewhere:

<form id="myForm">

new FormCheck('myForm');

Edit 2

If you're already using MooTools, it's best to use the built-in event handlers. Direct approaches like onClick and onLoad should be avoided because of cross-browser issues. MooTools takes care of that.

<script type="text/javascript">
  window.addEvent('domready', function(){
    $('cars').addEvent('click', function() {
      $('number_of_cars').addClass("validate['required']");
    });

    new FormCheck('form');
  });
</script>

MooTools needs id's for this to work, so:

<input type="radio" name="cars" id="cars" value="yes">

Edit 3

Also read the docs of FormCheck carefully. They contain lots of sample code: http://mootools.floor.ch/en/demos/formcheck/

Docs: http://mootools.floor.ch/docs/formcheck/files/formcheck-js.html

Hope this helps


问:
Flink 1.12.x DataSet --> Flink 1.14.x DataStream
I am trying to migrate from Flink 1.12.x DataSet api to Flink 1.14.x DataStream api.  mapPartition is not available in Flink DataStream.

Our Code using Flink 1.12.x DataSet

```<code>dataset
    .<few operations>
    .mapPartition(new SomeMapParitionFn())
    .<few more operations>

public static class SomeMapPartitionFn extends RichMapPartitionFunction<InputModel, OutputModel> {

    @Override
    public void mapPartition(Iterable<InputModel> records, Collector<OutputModel> out) throws Exception {
        for (InputModel record : records) {
            /*
            do some operation
             */
            if (/* some condition based on processing *MULTIPLE* records */) {
                out.collect(...); // Conditional collect                ---> (1)
            }
        }

        // At the end of the data, collect
        out.collect(...);   // Collect processed data                   ---> (2)
    }
}
</code>```

(1) - Collector.collect invoked based on some condition after processing few records

(2) - Collector.collect invoked at the end of data

Initially we thought of using flatMap instead of mapPartition, but collector not available in close function.

https://issues.apache.org/jira/browse/FLINK-14709 - Only available in case of chained drivers

How to implement this in Flink 1.14.x DataStream?  Please advise...

Note: Our application works with only finite set of data (Batch Mode)

答:
In Flink's DataSet API, a MapPartitionFunction has two parameters. An iterator for the input and a collector for the result of the function. A MapPartitionFunction in a Flink DataStream program would never return from the first function call, because the iterator would iterate over an endless stream of records. However, Flink's internal stream processing model requires that user functions return in order to checkpoint function state. Therefore, the DataStream API does not offer a mapPartition transformation.

In order to implement similar function, you need to define a window over the stream. Windows discretize streams which is somewhat similar to mini batches but windows offer way more flexibility

Body:
I am trying to migrate from Flink 1.12.x DataSet api to Flink 1.14.x DataStream api.  mapPartition is not available in Flink DataStream.

Our Code using Flink 1.12.x DataSet

dataset
    .<few operations>
    .mapPartition(new SomeMapParitionFn())
    .<few more operations>

public static class SomeMapPartitionFn extends RichMapPartitionFunction<InputModel, OutputModel> {

    @Override
    public void mapPartition(Iterable<InputModel> records, Collector<OutputModel> out) throws Exception {
        for (InputModel record : records) {
            /*
            do some operation
             */
            if (/* some condition based on processing *MULTIPLE* records */) {
                out.collect(...); // Conditional collect                ---> (1)
            }
        }

        // At the end of the data, collect
        out.collect(...);   // Collect processed data                   ---> (2)
    }
}

(1) - Collector.collect invoked based on some condition after processing few records

(2) - Collector.collect invoked at the end of data

Initially we thought of using flatMap instead of mapPartition, but collector not available in close function.

https://issues.apache.org/jira/browse/FLINK-14709 - Only available in case of chained drivers

How to implement this in Flink 1.14.x DataStream?  Please advise...

Note: Our application works with only finite set of data (Batch Mode)


问:
Discord.js ban duration
I have been struggling with this issue for quite some time

I wanna see what options I have for a ban duration. However

the official discord documentation is barebones on this subject

```<code>guildMember.ban({ days: 7, reason: 'They deserved it' })
  .then(console.log)
  .catch(console.error);
</code>```

This code bans a guildmember for 7 days

But aside from days are there minutes ? Hours ? Etc ?

答:
Days is not the duration. Days specifies the days to delete messages in. Its like when you try to ban someone on discord, it gives you the option to select for how long you want to delete past messages. To implement a temp ban, you have to manually write code that unbans them.

Reference: https://discord.js.org/#/docs/main/stable/typedef/BanOptions

Title: Discord.js ban duration

Body:
I have been struggling with this issue for quite some time

I wanna see what options I have for a ban duration. However

the official discord documentation is barebones on this subject

guildMember.ban({ days: 7, reason: 'They deserved it' })
  .then(console.log)
  .catch(console.error);

This code bans a guildmember for 7 days

But aside from days are there minutes ? Hours ? Etc ?


问:
Raise Header's Z-Index Over Material UI Modal Backdrop
I'm building a mobile version of a web app using Material UI and having trouble matching designs. I'm using MUI App-Bar together with MUI Modal to create something similar to the mockups shown below.

The expected behavior is that the user selects the button in the top right of the header to open the modal, and has the option to use the top right button again to close the modal. The user should also be able to select My App logo in the header to navigate to the home page.

The actual behavior is that the header bar is covered by the modal's backdrop; I can add styling like marginTop: 150px to the backdrop to visually achieve the expected result, but the button and the logo are still not usable.

Is there a way to override the backdrop component so that the header will be usable?

```<code>const useStyles = makeStyles((theme: Theme) => ({
  card: {
    position: "absolute",
    top: "160px",
    width: "90vw",
    borderTopLeftRadius: "0px",
    borderTopRightRadius: "0px",
  },
  backDrop: {
    marginTop: "160px",
  },
}));

const Header = (props) => {
  const classes = useStyles();

  const [menuOpen, setMenuOpen] = React.useState(false);

  const handleOpenUserMenu = () => {
    setMenuOpen(true);
  };

  const handleCloseUserMenu = () => {
    setMenuOpen(false);
  };

  return (
    <AppBar
      position="static"
      style={{
        backgroundColor: "#FFFFFF",
        zIndex: -1,
      }}
    >
      <Container maxWidth="xl">
        <Toolbar>
          <Box sx={{ flexGrow: 1 }}>
            <Link to={"/home"}>
              <Logo className={classes.logo} />
            </Link>
          </Box>
          <Box sx={{ flexGrow: 0 }}>
            <IconButton onClick={handleOpenUserMenu}>
              <MenuIcon />
            </IconButton>
            <Modal
              open={menuOpen}
              onClose={onClose}
              BackdropProps={{ classes: { root: classes.backDrop } }}
            >
              <Card className={classes.card}>
                <CardContent>
                  <MenuItems menuOptions={menuOptions} />
                </CardContent>
              </Card>
            </Modal>
          </Box>
        </Toolbar>
      </Container>
    </AppBar>
  );
};
</code>```

答:
As stated in MUIModal documentation the modal component is supposed to behave like that I would try to use menu component instead

Quoting documentation:

If you are creating a modal dialog, you probably want to use the Dialog component rather than directly using Modal. Modal is a lower-level construct that is leveraged by the following components:

Dialog

Drawer

Menu  <--

Popover

Body:
I'm building a mobile version of a web app using Material UI and having trouble matching designs. I'm using MUI App-Bar together with MUI Modal to create something similar to the mockups shown below.

The expected behavior is that the user selects the button in the top right of the header to open the modal, and has the option to use the top right button again to close the modal. The user should also be able to select My App logo in the header to navigate to the home page.

The actual behavior is that the header bar is covered by the modal's backdrop; I can add styling like marginTop: 150px to the backdrop to visually achieve the expected result, but the button and the logo are still not usable.

Is there a way to override the backdrop component so that the header will be usable?

const useStyles = makeStyles((theme: Theme) => ({
  card: {
    position: "absolute",
    top: "160px",
    width: "90vw",
    borderTopLeftRadius: "0px",
    borderTopRightRadius: "0px",
  },
  backDrop: {
    marginTop: "160px",
  },
}));

const Header = (props) => {
  const classes = useStyles();

  const [menuOpen, setMenuOpen] = React.useState(false);

  const handleOpenUserMenu = () => {
    setMenuOpen(true);
  };

  const handleCloseUserMenu = () => {
    setMenuOpen(false);
  };

  return (
    <AppBar
      position="static"
      style={{
        backgroundColor: "#FFFFFF",
        zIndex: -1,
      }}
    >
      <Container maxWidth="xl">
        <Toolbar>
          <Box sx={{ flexGrow: 1 }}>
            <Link to={"/home"}>
              <Logo className={classes.logo} />
            </Link>
          </Box>
          <Box sx={{ flexGrow: 0 }}>
            <IconButton onClick={handleOpenUserMenu}>
              <MenuIcon />
            </IconButton>
            <Modal
              open={menuOpen}
              onClose={onClose}
              BackdropProps={{ classes: { root: classes.backDrop } }}
            >
              <Card className={classes.card}>
                <CardContent>
                  <MenuItems menuOptions={menuOptions} />
                </CardContent>
              </Card>
            </Modal>
          </Box>
        </Toolbar>
      </Container>
    </AppBar>
  );
};


答: It doesn't ban the member for 7 days. It just deletes 7 days of their messages. To actually ban them for ? days, ? minutes, ? hours, etc., you need to set a timer yourself (e.g. setTimeout, although the timer will be reset when you restart the bot).</p>

Title: Discord.js ban duration


问:
Why does eclipse SOMETIMES prompt me which device to launch my app on?
Why does eclipse SOMETIMES prompt me which device to launch my app on when there is only 1 phone connected to my machine? Sometimes, it stays like this for months.... how to fix?

It says my target phone is 2.3.4    and there is a small yellow exclamation warning next to it.

答:
Do Like this:
Right Click on Your Project Name -> Run As -> Run Configurations.. -> then select target And then select Automatic Mode.</p>


问:
SetTimout in react export function
What is the right way to add setTimeout in this function?
Next js WP headless CMS</p>
```<code>export async function getStaticProps() {
      const allPosts = await getAllPosts();
      return {
        props: {
          allPosts
        }
      };
    }
</code>```

答:
You can try something like

```<code>export async function getStaticProps() {
   return new Promise((res, rej) => {
      setTimeout(async () => {
        const allPosts = await getAllPosts();
        res({ props: { allPosts } })
       }, 2000)
   })
}
</code>```

Basically returning a promise that will be resolved after 2 seconds. This way you can use await getStaticProps() in other functions.

Title: SetTimout in react export function

Body:
What is the right way to add setTimeout in this function?
Next js WP headless CMS

export async function getStaticProps() {
      const allPosts = await getAllPosts();
      return {
        props: {
          allPosts
        }
      };
    }

Body:
You can try something like

export async function getStaticProps() {
   return new Promise((res, rej) => {
      setTimeout(async () => {
        const allPosts = await getAllPosts();
        res({ props: { allPosts } })
       }, 2000)
   })
}

Basically returning a promise that will be resolved after 2 seconds. This way you can use await getStaticProps() in other functions.


问:
Scrollview cannot scroll to bottom with keyboard in react native
Scrollview scrolls to the bottom normally but when I touch the TextInput and the keyboard pops up, it scrolls only a very short distance and I am not able to look at the content below.

Just focus on android as of now

android:windowSoftInputMode="adjustPan"

My code:

```<code>const Welcome = ({}) => {

  return (
    <View style={{flex:1}>
      <View style={{height: RFValue(33), backgroundColor: '#B1C59B'}} />
      <Main/>
    </View>
  );
};
</code>```

where the Main component contains the scrollView

```<code>      const Main = () => {

          return (
         <ScrollView
              keyboardShouldPersistTaps="always"
              contentContainerStyle={styles.container}>
          {CONTENT}
        </Scrollview>
        )
      }

     const styles = StyleSheet.create({
         container: {
         flexGrow: 1,
     },
</code>```

答:
Try adding flex:1 in your container style like

```<code>container:{
  flex: 1,
}
</code>```

Body:
Scrollview scrolls to the bottom normally but when I touch the TextInput and the keyboard pops up, it scrolls only a very short distance and I am not able to look at the content below.

Just focus on android as of now

android:windowSoftInputMode="adjustPan"

My code:

const Welcome = ({}) => {

  return (
    <View style={{flex:1}>
      <View style={{height: RFValue(33), backgroundColor: '#B1C59B'}} />

    </View>
  );
};

where the Main component contains the scrollView

      const Main = () => {

          return (
         <ScrollView
              keyboardShouldPersistTaps="always"
              contentContainerStyle={styles.container}>
          {CONTENT}
        </Scrollview>
        )
      }

     const styles = StyleSheet.create({
         container: {
         flexGrow: 1,
     },

Body:
Try adding flex:1 in your container style like

container:{
  flex: 1,
}


问:
I try to take the data from the list and do simple calculation but it errors; error said "can only concatenate str (not "int") to str"
```<code>class bus:

  def __init__(self, name):

       self.seat = []
       self.name = name
       self.color = color
       self.passenger = []

  def input(self):

            s = int(input("Enter the number of seat %s bus: "%(self.name)))
            self.seat.append(s)
            p = int(input("Enter the number of passenger in %s bus: "%(self.name)))
            self.passenger.append(p)
  def display(self):

        print (self.name, "bus color is ", self.color," and have", self.seat, "seats","and have",self.passenger,"passenger")
  def p(self, b=None):

    if b is None:
      self.seat = [int(i) for i in self.seat]
      b = str(self.seat)
      print(str(self.seat)+4)

name = input("Enter the name of bus driver:")

color = input("Enter the color of ther bus: ")

b1 = bus(name)

b1.input()

b1.display()

b1.p()
</code>```

答:
The error message is quite clear. You cannot concatenate a string ant an integer.

print(str(self.seat)+4)
should be:

print(str(self.seat)+str(4))

Additionally, please format your code, it's basically unreadable


问:
How to turn off AutoSave in word/PowerPoint/excel/OneNote, while we open it in browser using SharePoint online?
I am using SharePoint online. when I open document using browser option. Its using autosave. Is there any way we can change settings and turn off the autosave option when user open file in browser ?

答: As per my knowledge, it is impossible to disable auto-save in web client.</p>


问:
Loading PyTorch model and receiving error "AttributeError: Can't get attribute 'Model' on <module '__main__'>"
I'm using torch.load() to load a Pytorch model and am receiving the error "AttributeError: Can't get attribute 'Model' on <module 'main'>". Does anyone know what is causing this?

答:
The weights that have been saved must have a class. You should keep the same class and file architecture with the weights you load.

Because torch.load() uses pickle module implicitly.


问:
Flutter Http get coming Null
I started to learn work with APIs. I tried an api without authentication reqres.in and it worked for me . But now im trying to get datas from a api which is work with key, and this datas coming null. When i used my key like this on web browsers https://api.rawg.io/api/games?key=MY_API_KEY&page=1 its working ( i can see JSON data). But when i use this api key for my working code datas coming null and i couldn't understand why.

Here is my code

```<code>class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  Future<Welcome> apiCall() async {
    final response = await http.get(Uri.parse(
        'https://api.rawg.io/api/games?key=84e37baf...(mykey)&page=1'));

    return Welcome.fromJson(jsonDecode(response.body));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: FutureBuilder<Welcome>(
          future: apiCall(),
          builder: (context, snapshot) {
            var growableList = [];
            List<Result> data = snapshot.data!.results;
            growableList.add(data[0].name);
            return Text('${growableList}');
          },
        ),
      ),
    );
  }
}
</code>```

答: I fixed the problem. Problem was in dataclass, there  was some classes which has same names and variable problems like int or double, For exmaple When i tried to generate my code with looking example response i used int except double. But response in real getting double variables. Mistakes like this doesn't let me print it.</p>

Title: Flutter Http get coming Null

Body:
I started to learn work with APIs. I tried an api without authentication reqres.in and it worked for me . But now im trying to get datas from a api which is work with key, and this datas coming null. When i used my key like this on web browsers https://api.rawg.io/api/games?key=MY_API_KEY&page=1 its working ( i can see JSON data). But when i use this api key for my working code datas coming null and i couldn't understand why.

Here is my code

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  Future<Welcome> apiCall() async {
    final response = await http.get(Uri.parse(
        'https://api.rawg.io/api/games?key=84e37baf...(mykey)&page=1'));

    return Welcome.fromJson(jsonDecode(response.body));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: FutureBuilder<Welcome>(
          future: apiCall(),
          builder: (context, snapshot) {
            var growableList = [];
            List<Result> data = snapshot.data!.results;
            growableList.add(data[0].name);
            return Text('${growableList}');
          },
        ),
      ),
    );
  }
}


问:
How can I align this input button in the center of the table row?
I understand that this is a very basic question, but I've searched stackoverflow and I cannot find a question that helps me solve my own issue.  I am trying to center align the contents (an input with type="submit") of a table cell (td element).  I can center the contents in the cell, but the cell itself is not stretching the width of the table.  I cannot find any css attribute that helps me to spread this td element the width of the table.  How can I do this?

td {border: 1px solid black;}
th {border: 1px solid black;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-container">

<main id="registration">
<div class="form">
    <h1>Register For an Account</h1>
    <form action="#" method="post">
        <table>
            <tbody><tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" required="" id="id_username"></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" required="" id="id_first_name"></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" required="" id="id_last_name"></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" required="" id="id_email"></td></tr>
<tr><th><label for="id_birthdate">Birthdate:</label></th><td><input type="text" name="birthdate" required="" id="id_birthdate"></td></tr>
<tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" required="" id="id_password"></td></tr>
<tr><th><label for="id_confirm_password">Confirm password:</label></th><td><input type="password" name="confirm_password" required="" id="id_confirm_password"></td></tr>
            <tr>
                <!-- This is the issue -->
                <td align="center" style="border: 1px solid black; width: 100%; text-align: center; margin: auto; display: block; horizontal-align: middle;" colspan=2><input type="submit" value="Register"></td>
            </tr>
        </tbody></table>

    </form>
</div>
</main>
</div></code>```

答:
Add colspan="2" also remove other style

```<code><tr>
    <!-- This is the issue -->
    <td align="center" colspan="2" style="border: 1px solid black; horizontal-align: middle;" colspan=2><input type="submit" value="Register"></td>
</tr>
</code>```

td {border: 1px solid black;}
th {border: 1px solid black;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-container">

<main id="registration">
<div class="form">
    <h1>Register For an Account</h1>
    <form action="#" method="post">
        <table>
            <tbody><tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" required="" id="id_username"></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" required="" id="id_first_name"></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" required="" id="id_last_name"></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" required="" id="id_email"></td></tr>
<tr><th><label for="id_birthdate">Birthdate:</label></th><td><input type="text" name="birthdate" required="" id="id_birthdate"></td></tr>
<tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" required="" id="id_password"></td></tr>
<tr><th><label for="id_confirm_password">Confirm password:</label></th><td><input type="password" name="confirm_password" required="" id="id_confirm_password"></td></tr>
            <tr>
                <!-- This is the issue -->
                <td align="center" colspan="2" style="border: 1px solid black; horizontal-align: middle;" colspan=2><input type="submit" value="Register"></td>
            </tr>
        </tbody></table>

    </form>
</div>
</main>
</div></code>```

Body:
I understand that this is a very basic question, but I've searched stackoverflow and I cannot find a question that helps me solve my own issue.  I am trying to center align the contents (an input with type="submit") of a table cell (td element).  I can center the contents in the cell, but the cell itself is not stretching the width of the table.  I cannot find any css attribute that helps me to spread this td element the width of the table.  How can I do this?

td {border: 1px solid black;}
th {border: 1px solid black;}

Register For an Account

    <form action="#" method="post">

Username:	<input type="text" name="username" required="" id="id_username">

First name:	<input type="text" name="first_name" required="" id="id_first_name">

Last name:	<input type="text" name="last_name" required="" id="id_last_name">

Email:	<input type="email" name="email" required="" id="id_email">

Birthdate:	<input type="text" name="birthdate" required="" id="id_birthdate">

Password:	<input type="password" name="password" required="" id="id_password">

Confirm password:	<input type="password" name="confirm_password" required="" id="id_confirm_password">

                <input type="submit" value="Register">

    </form>

Body:
Add colspan="2" also remove other style

<tr>
    <!-- This is the issue -->
    <td align="center" colspan="2" style="border: 1px solid black; horizontal-align: middle;" colspan=2><input type="submit" value="Register"></td>
</tr>

td {border: 1px solid black;}
th {border: 1px solid black;}

<div class="content-container">

<main id="registration">
<div class="form">
    <h1>Register For an Account</h1>
    <form action="#" method="post">
        <table>
            <tbody><tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" required="" id="id_username"></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" required="" id="id_first_name"></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" required="" id="id_last_name"></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" required="" id="id_email"></td></tr>
<tr><th><label for="id_birthdate">Birthdate:</label></th><td><input type="text" name="birthdate" required="" id="id_birthdate"></td></tr>
<tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" required="" id="id_password"></td></tr>
<tr><th><label for="id_confirm_password">Confirm password:</label></th><td><input type="password" name="confirm_password" required="" id="id_confirm_password"></td></tr>
            <tr>
                <!-- This is the issue -->
                <td align="center" colspan="2" style="border: 1px solid black; horizontal-align: middle;" colspan=2><input type="submit" value="Register"></td>
            </tr>
        </tbody></table>

    </form>
</div>
</main>
</div>


问:
Can Kafka Connect be made rack aware so that my connector reads all partitions from one broker?
We have a Kafka cluster in Amazon MSK that has 3 brokers in different availability zones of the same region. I want to set up a Kafka Connect connector that backs up all data from our Kafka brokers to Amazon S3, and I'm trying to do it with MSK Connect.

I set up Confluent's S3 Sink Connector on MSK Connect and it works - everything is uploaded to S3 as expected. The problem is that it costs a fortune in data transfer charges - our AWS bills for MSK nearly double whenever the connector is running, with EU-DataTransfer-Regional-Bytes accounting for the entire increase.

It seems that the connector is pulling messages from all three of our brokers, i.e. from three different AZs, and so we're getting billed for inter-AZ data transfer. This makes sense because by default it will read a partition from that partition's leader, which could be any of the three brokers. But if we were creating a normal consumer, not a connector, it would be possible to restrict the consumer to read all partitions from a specific broker:

```<code>"client.rack" : "euw1-az3"
</code>```

☝ For a consumer in the euw1-az3 AZ, this setting makes the consumer read all partitions from the local broker, regardless of the partitions' leader - which avoids the need for inter-AZ data transfer and brings the bills down massively.

My question is, is it possible to do something similar for a Kafka Connector? What config setting do I have to pass to the connector, or the worker, to make it only read from one specific broker/AZ? Is this possible with MSK Connect?

答:
Maybe I am missing something about your question. I think you want to have a look at this:

https://docs.confluent.io/platform/current/tutorials/examples/multiregion/docs/multiregion.html

```<code>replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector
</code>```

I though it was general knowledge, it applies to any on-premises or cloud deployment.

Body:
We have a Kafka cluster in Amazon MSK that has 3 brokers in different availability zones of the same region. I want to set up a Kafka Connect connector that backs up all data from our Kafka brokers to Amazon S3, and I'm trying to do it with MSK Connect.

I set up Confluent's S3 Sink Connector on MSK Connect and it works - everything is uploaded to S3 as expected. The problem is that it costs a fortune in data transfer charges - our AWS bills for MSK nearly double whenever the connector is running, with EU-DataTransfer-Regional-Bytes accounting for the entire increase.

It seems that the connector is pulling messages from all three of our brokers, i.e. from three different AZs, and so we're getting billed for inter-AZ data transfer. This makes sense because by default it will read a partition from that partition's leader, which could be any of the three brokers. But if we were creating a normal consumer, not a connector, it would be possible to restrict the consumer to read all partitions from a specific broker:

"client.rack" : "euw1-az3"

☝ For a consumer in the euw1-az3 AZ, this setting makes the consumer read all partitions from the local broker, regardless of the partitions' leader - which avoids the need for inter-AZ data transfer and brings the bills down massively.

My question is, is it possible to do something similar for a Kafka Connector? What config setting do I have to pass to the connector, or the worker, to make it only read from one specific broker/AZ? Is this possible with MSK Connect?

Body:
Maybe I am missing something about your question. I think you want to have a look at this:

https://docs.confluent.io/platform/current/tutorials/examples/multiregion/docs/multiregion.html

replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector

I though it was general knowledge, it applies to any on-premises or cloud deployment.


问:
How to convert csv to xlsx with openpyxl to any column?
I am creating code for converting csv to xlsx but my code has a problem, it can convert the values only to A1 column. How to make code to be can writing values from csv to any selected column?</p>
```<code>import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('text.csv') as f:
    reader = csv.reader(f, delimiter=':')
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')
</code>```

答:
You need to use a comma (,) not : for delimiter.

I just tested this code and it made a perfect xlsx file with seperated columns.

```<code>import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('text.csv') as f:
    reader = csv.reader(f, delimiter=',') # changed to ,
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')
</code>```

text.csv

```<code>a,b
1,2
3,4
</code>```

file.xlsx

Body:
I am creating code for converting csv to xlsx but my code has a problem, it can convert the values only to A1 column. How to make code to be can writing values from csv to any selected column?

import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('text.csv') as f:
    reader = csv.reader(f, delimiter=':')
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')

Body:
You need to use a comma (,) not : for delimiter.

I just tested this code and it made a perfect xlsx file with seperated columns.

import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('text.csv') as f:
    reader = csv.reader(f, delimiter=',') # changed to ,
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')

text.csv

a,b
1,2
3,4

file.xlsx


问:
if ListBox Contains, don't add
I've got a Method:

```<code>FillListBox();
</code>```

I call this method from different places.. But sometimes it happens, that things were loaded twice!

Now I'm trying to do something like:

```<code>if (listBox.Items[1].ToString() == "hello")
{
   DO NOT FILL
}
else
{
   FILL
}
</code>```

THIS DONT WORKS! :(

```<code>Fault: InvalidArgument=Value of '1' is not valid for 'index'.
Parameter name: index
</code>```

And something like that:

```<code>if(listBox.Items.Contains("hello"))
{
   DONT FILL
}
</code>```

Dont works too :(

What can I do?

答: I solved the problem.. I just used myListBox.Items.Clear();</p>

Title: if ListBox Contains, don't add

Body:
I've got a Method:

FillListBox();

I call this method from different places.. But sometimes it happens, that things were loaded twice!

Now I'm trying to do something like:

if (listBox.Items[1].ToString() == "hello")
{
   DO NOT FILL
}
else
{
   FILL
}

THIS DONT WORKS! :(

Fault: InvalidArgument=Value of '1' is not valid for 'index'.
Parameter name: index

And something like that:

if(listBox.Items.Contains("hello"))
{
   DONT FILL
}

Dont works too :(

What can I do?


问:
Git manage a portion of code to another repo
I have the following situation:
My code base folder has two subfolders:

main_code

experiments

Right now, only the code inside main_code is tracked added and committed. There is also a remote ("origin") to a external repository.

What I want to do is to put all the code in experiments (that is not tracked now) in another external repository. How can I do that?

I was thinking of adding another remote (other than "origin"), say experiment_repo, but if I do that, how can I put only the code in experiments in said repo?

EDIT: Just to clarify:

main_code annd experiments are subfolders of base_folder and .git is in the base_folder .

答:
If your repository is in main_code (meaning there is a main_code/.git subfolder), and experiments is not yet in a repository, all you need to do is (since no part of experiments have been staged, tracked or committed):

cd base_folder
mv experiments ..
cd ../experiments
git init .
git add .
git commit -m "Import experiments code"
git remote add origin https://github.com/new/empty/repository
git push -u origin main
```

You could install and then use the gh CLI tool, and create your remote repository with gh repo create (after a gh auth login first).

Body:
If your repository is in main_code (meaning there is a main_code/.git subfolder), and experiments is not yet in a repository, all you need to do is (since no part of experiments have been staged, tracked or committed):

cd base_folder
mv experiments ..
cd ../experiments
git init .
git add .
git commit -m "Import experiments code"
git remote add origin https://github.com/new/empty/repository
git push -u origin main

You could install and then use the gh CLI tool, and create your remote repository with gh repo create (after a gh auth login first).


问:
Create a branch with its origin path on a different remote repository
Good morning/evening

I have two repos A and B.
I'm writing a hook for push events, in some cases I want to create a branch in B based on A.

example:

in A i'm working on main/release1.2/featureAAA/BugABC
when i push in A if the push is ok I want to create the branch in repo B BugABC but in the same path main/release1.2/featureAAA.

If the origin branches does not exists in B just exit with an error message

Thank you

答:
You have to be on branch A first:

```<code>git checkout A
</code>```

and then, you can make a new branch by:

```<code>git checkout -b B
</code>```

Body:
You have to be on branch A first:

git checkout A

and then, you can make a new branch by:

git checkout -b B


问:
flutter call a function after moving back to screen from another screen
How to call a function in flutter ,after moving back to a screen from another screen?

For Example:

Screen 1

```<code>function1(){
}
</code>```

Screen2

```<code>function2(){
//Go back to screen 1 and then call function1()
}
</code>```

答:
Imho the solutions provided here aren't valid solutions.
If you use a routes Future it may be called multiple times and will even be called in case of a forward navigation.

Instead use a NavigatorObserver:

```<code>class AppNavigationObserver extends NavigatorObserver {
  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    print("AppNavigationObserver: ${route.settings.name}");
    print("AppNavigationObserver: ${previousRoute?.settings.name}");
  }
}
</code>```

You can then use it for example like this:

```<code>  MaterialApp(
    navigatorObservers: [
      AppNavigationObserver()
    ],
    onGenerateRoute: (RouteSettings settings) {
      return PageRouteBuilder(
        maintainState: true,
        settings: settings,
        transitionDuration: const Duration(milliseconds: 300),
        pageBuilder: (context, animation, secondaryAnimation) {
          // Your route builder according to settings
        },
      );
    },
  )
</code>```

The important part is passing onGenerateRoute's settings paramter to the PageRouteBuilder settings. Otherwise settings.arguments and settings.name will be null in the didPop handler.

Body:
How to call a function in flutter ,after moving back to a screen from another screen?

For Example:

Screen 1

function1(){
}

Screen2

function2(){
//Go back to screen 1 and then call function1()
}

Body:
Imho the solutions provided here aren't valid solutions.
If you use a routes Future it may be called multiple times and will even be called in case of a forward navigation.

Instead use a NavigatorObserver:

class AppNavigationObserver extends NavigatorObserver {
  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    print("AppNavigationObserver: ${route.settings.name}");
    print("AppNavigationObserver: ${previousRoute?.settings.name}");
  }
}

You can then use it for example like this:

  MaterialApp(
    navigatorObservers: [
      AppNavigationObserver()
    ],
    onGenerateRoute: (RouteSettings settings) {
      return PageRouteBuilder(
        maintainState: true,
        settings: settings,
        transitionDuration: const Duration(milliseconds: 300),
        pageBuilder: (context, animation, secondaryAnimation) {
          // Your route builder according to settings
        },
      );
    },
  )

The important part is passing onGenerateRoute's settings paramter to the PageRouteBuilder settings. Otherwise settings.arguments and settings.name will be null in the didPop handler.


问:
How can ı remove ant design's space between dropdown and menu?
enter image description here

Hello, I want to delete the space between the menu and the button, so the button and the drop-down menu will be combined. I don't know how to do this can you help me?
I can not find how can ı remove it .

答: It would be a better way for us to help you if you share the code you wrote here.</p>


问:
How to poll email with hosted solutions? PHP or ASP
I have been looking for some time now but i cannot really find a good way to process an emial box using a hosted solution as justhost or asphost . Now my instinct tells me to write a service .. but i cant install it on either hosts.

Is there any other clever way to over come this problem using any thing from PHP to .NET?

答:
Assuming your webserver is running *nix, you should use crontab to create a cronjob that'll run automatically at your specified times.

If your server is running any form of Windows, you'll have to use Windows Task Scheduler.


问:
Is it possible to conditionally control isAmp through the server?
UPDATE:
I'll rephrase my question since it's not clear enough.
What I want to accomplish here is pass isAmp from getInitialProps to the component to control whether it'll be amp or a regular one.

Why I want to do that?
Because I want to make some client operations if the page is loading a deleted item; since amp is all done on the server, I can't use react hooks nor redirect the page after 10 seconds.
Hope this explains better.

I have an an amp page that I want to turn into a regular page when an item status(href="page/itemId") is deleted so I can use the client side to redirect the user after 10seconds.

To make a page amp, we just add this export at the top of the file

```<code>export const config = { amp: true };
</code>```

The mode I'm interested in is the 'hybrid' mode.
Is there a way to pass the isAmp value through the server and then to the client like this next hook does

```<code>const isAmp = useAmp();
</code>```

I want the value passed right to the first line of code above:

```<code>export const config = { amp: isAmp };
</code>```

I'm going through this process in order to make client side code work, like redirecting the page to another url. Which only works on non-amp pages.

答:
From the doc you are not allowed to do the dynamic / conditional page configuration.

this is not allowed:

```<code>const test= somecondition ? true : 'hybrid'

export const config = {
    amp: test
}
</code>```

see here:
https://nextjs.org/docs/messages/invalid-page-config

Body:
UPDATE:
I'll rephrase my question since it's not clear enough.
What I want to accomplish here is pass isAmp from getInitialProps to the component to control whether it'll be amp or a regular one.

Why I want to do that?
Because I want to make some client operations if the page is loading a deleted item; since amp is all done on the server, I can't use react hooks nor redirect the page after 10 seconds.
Hope this explains better.

I have an an amp page that I want to turn into a regular page when an item status(href="page/itemId") is deleted so I can use the client side to redirect the user after 10seconds.

To make a page amp, we just add this export at the top of the file

export const config = { amp: true };

The mode I'm interested in is the 'hybrid' mode.
Is there a way to pass the isAmp value through the server and then to the client like this next hook does

const isAmp = useAmp();

I want the value passed right to the first line of code above:

export const config = { amp: isAmp };

I'm going through this process in order to make client side code work, like redirecting the page to another url. Which only works on non-amp pages.

Body:
From the doc you are not allowed to do the dynamic / conditional page configuration.

this is not allowed:

const test= somecondition ? true : 'hybrid'

export const config = {
    amp: test
}

see here:
https://nextjs.org/docs/messages/invalid-page-config