问:
How to disable HTTP traffic on Squid proxy
I have configured a Squid proxy, the idea is to allow only HTTPS traffic through. The fact is that it works halfway for me, because it allows HTTPS traffic to pass through, but also HTTP traffic, which I don't want to be allowed.

I don't understand why, because I disabled port 80 which is the http port.

I share with you  the configuration of the squid.conf file:

```<code>#
# Recommended minimum configuration:
#

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 0.0.0.1-0.255.255.255  # RFC 1122 "this" network (LAN)
acl localnet src 10.0.0.0/8             # RFC 1918 local private network (LAN)
acl localnet src 100.64.0.0/10          # RFC 6598 shared address space (CGN)
acl localnet src 169.254.0.0/16         # RFC 3927 link-local (directly plugged) machines
acl localnet src 172.16.0.0/12          # RFC 1918 local private network (LAN)
acl localnet src 192.168.0.0/16         # RFC 1918 local private network (LAN)
acl localnet src fc00::/7               # RFC 4193 local private network range
acl localnet src fe80::/10              # RFC 4291 link-local (directly plugged) machines

acl SSL_ports port 443
#acl Safe_ports port 80         # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http

# add acl to block port 80, later on will be blocked

acl port80 port 80
##################################################

acl CONNECT method CONNECT

# Add whitelist
acl whitelist dstdomain '/etc/squid/whitelist'

http_access deny !whitelist

http_access allow whitelist

#
# Recommended minimum Access Permission configuration:
#
# Deny requests to certain unsafe ports
http_access deny !Safe_ports

# deny access to port 80 HTTP traffic
http_access deny port80
#######################

# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# Only allow cachemgr access from localhost
http_access allow localhost manager
http_access deny manager

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost

# Squid normally listens to port 3128
http_port 3128

# Uncomment and adjust the following to add a disk cache directory.
#cache_dir ufs /var/spool/squid 100 16 256

####### PROXY AUTHENTICATION CONFIGURATION

auth_param basic program /usr/lib64/squid/basic_ncsa_auth /etc/squid/passwd
auth_param basic children 5
auth_param basic realm Proxy Squid Basic Authentication
auth_param basic credentialsttl 2 hours

acl auth_users proxy_auth REQUIRED

# And finally deny all other access to this proxy

http_access deny !auth_users

http_access allow auth_users

http_access deny all

###############  END  PROXY AUTHENTICATION CONFIGURATION

# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid

#
# Add any of your own refresh_pattern entries above these.
#
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320

</code>```

Those are test I made

```<code>curl -x http://XX.XXX.XXX.XXX:3128 --proxy-user user:password -I  https://updates.jenkins.io
    * HTTP/1.1 200 Connection established *
    * HTTP/2 200 *
    date: Sun, 04 Dec 2022 13:25:17 GMT
    server: Apache

 curl -x http://XX.XXX.XXX.XXX:3128 --proxy-user user:password -I  http://updates.jenkins.io
    *HTTP/1.1 200 OK *
    Date: Sun, 04 Dec 2022 13:27:48 GMT
    Server: Apache

</code>```

Could be tha the only possibility to perform this is to block the http protocol in the firewall with a rich rule, like:

```<code>firewall-cmd --add-rich-rule='rule protocol value=http reject'
</code>```

Many thanks in advance

Body:
I have configured a Squid proxy, the idea is to allow only HTTPS traffic through. The fact is that it works halfway for me, because it allows HTTPS traffic to pass through, but also HTTP traffic, which I don't want to be allowed.

I don't understand why, because I disabled port 80 which is the http port.

I share with you  the configuration of the squid.conf file:

#
# Recommended minimum configuration:
#

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 0.0.0.1-0.255.255.255  # RFC 1122 "this" network (LAN)
acl localnet src 10.0.0.0/8             # RFC 1918 local private network (LAN)
acl localnet src 100.64.0.0/10          # RFC 6598 shared address space (CGN)
acl localnet src 169.254.0.0/16         # RFC 3927 link-local (directly plugged) machines
acl localnet src 172.16.0.0/12          # RFC 1918 local private network (LAN)
acl localnet src 192.168.0.0/16         # RFC 1918 local private network (LAN)
acl localnet src fc00::/7               # RFC 4193 local private network range
acl localnet src fe80::/10              # RFC 4291 link-local (directly plugged) machines

acl SSL_ports port 443
#acl Safe_ports port 80         # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http

# add acl to block port 80, later on will be blocked

acl port80 port 80
##################################################

acl CONNECT method CONNECT

# Add whitelist
acl whitelist dstdomain '/etc/squid/whitelist'

http_access deny !whitelist

http_access allow whitelist

#
# Recommended minimum Access Permission configuration:
#
# Deny requests to certain unsafe ports
http_access deny !Safe_ports

# deny access to port 80 HTTP traffic
http_access deny port80
#######################

# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# Only allow cachemgr access from localhost
http_access allow localhost manager
http_access deny manager

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost

# Squid normally listens to port 3128
http_port 3128

# Uncomment and adjust the following to add a disk cache directory.
#cache_dir ufs /var/spool/squid 100 16 256

####### PROXY AUTHENTICATION CONFIGURATION

auth_param basic program /usr/lib64/squid/basic_ncsa_auth /etc/squid/passwd
auth_param basic children 5
auth_param basic realm Proxy Squid Basic Authentication
auth_param basic credentialsttl 2 hours

acl auth_users proxy_auth REQUIRED

# And finally deny all other access to this proxy

http_access deny !auth_users

http_access allow auth_users

http_access deny all

###############  END  PROXY AUTHENTICATION CONFIGURATION

# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid

#
# Add any of your own refresh_pattern entries above these.
#
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320

Those are test I made

curl -x http://XX.XXX.XXX.XXX:3128 --proxy-user user:password -I  https://updates.jenkins.io
    * HTTP/1.1 200 Connection established *
    * HTTP/2 200 *
    date: Sun, 04 Dec 2022 13:25:17 GMT
    server: Apache

 curl -x http://XX.XXX.XXX.XXX:3128 --proxy-user user:password -I  http://updates.jenkins.io
    *HTTP/1.1 200 OK *
    Date: Sun, 04 Dec 2022 13:27:48 GMT
    Server: Apache

Could be tha the only possibility to perform this is to block the http protocol in the firewall with a rich rule, like:

firewall-cmd --add-rich-rule='rule protocol value=http reject'

Many thanks in advance


来源: stackexchange

问:
Is there a way to define a custom attribute withou input value for a directive in angularJS?
The title could probably be wrong.
What i want to do is insert inside an html directive an attribute, binded inside angularJS, but
instead of make it equals to a value/entity or something else, i want to leave it blank, like this code:

```<code><custom-directive custom-attribute></custom-directive>
</code>```

And, if it's present inside the html directive, i can see it in the controller and use the fact that it was inserted to modify something .

Is that possible?

ContentLicense: CC BY-SA 4.0

Body:
The title could probably be wrong.
What i want to do is insert inside an html directive an attribute, binded inside angularJS, but
instead of make it equals to a value/entity or something else, i want to leave it blank, like this code:

<custom-directive custom-attribute></custom-directive>

And, if it's present inside the html directive, i can see it in the controller and use the fact that it was inserted to modify something .

Is that possible?


问:
compiling .pyx with cython without `Microsoft Visual C++ 14.0`?
I want to speed up my apps in work which calculates data based on data from large files and after implementing multiprocessing i want to use cython but here is a problem.
Cython need to MS visual C++ and it's not free for professional use. Is it possible to compile .pyx files for free in professional use on windows?

My software build:
Python 3.8, Windows 10, Visual Studio Code

I found no answer for my question using google.


问:
Cmake find_package directory path missing
I'm pretty new to linux and cmake and I'm studying this book https://github.com/gaoxiang12/slambook2 and running into a library linkage problem when compiling the code snippet under ch3/visualgeometry which use Pagolin.

After find_package(Pagonlin REQUIRED), I try to print the file path in CMakeLists, it's empty, but the lib names are there, which confuses me. See attached code:

CMakeLists.txt

```<code>cmake_minimum_required( VERSION 3.0 )
project( visualizeGeometry )

set(CMAKE_CXX_FLAGS "-std=c++17")

include_directories( "/usr/include/eigen3" )

find_package( Pangolin REQUIRED )
message("Pangolin include dir: ${Pangolin_INCLUDE_DIRS}")
message("Pangolin libs: ${Pangolin_LIBRARIES}")
include_directories( ${Pangolin_INCLUDE_DIRS} )

add_executable( visualizeGeometry visualizeGeometry.cpp )
target_link_libraries( visualizeGeometry ${Pangolin_LIBRARIES} )
</code>```

compile and run

```<code>linyz0100@linyz0100-QEMU-VM:~/Desktop/slambook2/ch3/visualizeGeometry/build$ cmake ..
Pangolin include dir:
Pangolin libs: pango_core;pango_display;pango_geometry;pango_glgeometry;pango_image;pango_opengl;pango_packetstream;pango_plot;pango_python;pango_scene;pango_tools;pango_vars;pango_video;pango_windowing;tinyobj
-- Configuring done
-- Generating done
-- Build files have been written to: /home/linyz0100/Desktop/slambook2/ch3/visualizeGeometry/build
linyz0100@linyz0100-QEMU-VM:~/Desktop/slambook2/ch3/visualizeGeometry/build$ make
Consolidate compiler generated dependencies of target visualizeGeometry
[100%] Built target visualizeGeometry
linyz0100@linyz0100-QEMU-VM:~/Desktop/slambook2/ch3/visualizeGeometry/build$ ./visualizeGeometry
./visualizeGeometry: error while loading shared libraries: libpango_windowing.so: cannot open shared object file: No such file or directory

</code>```

I suspect that cmake does not find the directory path? It compiles successfully, but the executable can't locate the the library. I think Pagolin is correctly installed, as you can see the .so files under usr/local/lib

shared libs

```<code>linyz0100@linyz0100-QEMU-VM:/usr/local/lib$ ls
cmake                   libpango_opengl.so        libpango_vars.so
libpango_core.so        libpango_packetstream.so  libpango_video.so
libpango_display.so     libpango_plot.so          libpango_windowing.so
libpango_geometry.so    libpango_python.so        libtinyobj.so
libpango_glgeometry.so  libpango_scene.so         python3.10
libpango_image.so       libpango_tools.so
</code>```

Can someone explain this process to me? What is missing?
Thanks!

Body:
I'm pretty new to linux and cmake and I'm studying this book https://github.com/gaoxiang12/slambook2 and running into a library linkage problem when compiling the code snippet under ch3/visualgeometry which use Pagolin.

After find_package(Pagonlin REQUIRED), I try to print the file path in CMakeLists, it's empty, but the lib names are there, which confuses me. See attached code:

CMakeLists.txt

cmake_minimum_required( VERSION 3.0 )
project( visualizeGeometry )

set(CMAKE_CXX_FLAGS "-std=c++17")

include_directories( "/usr/include/eigen3" )

find_package( Pangolin REQUIRED )
message("Pangolin include dir: ${Pangolin_INCLUDE_DIRS}")
message("Pangolin libs: ${Pangolin_LIBRARIES}")
include_directories( ${Pangolin_INCLUDE_DIRS} )

add_executable( visualizeGeometry visualizeGeometry.cpp )
target_link_libraries( visualizeGeometry ${Pangolin_LIBRARIES} )

compile and run

linyz0100@linyz0100-QEMU-VM:~/Desktop/slambook2/ch3/visualizeGeometry/build$ cmake ..
Pangolin include dir:
Pangolin libs: pango_core;pango_display;pango_geometry;pango_glgeometry;pango_image;pango_opengl;pango_packetstream;pango_plot;pango_python;pango_scene;pango_tools;pango_vars;pango_video;pango_windowing;tinyobj
-- Configuring done
-- Generating done
-- Build files have been written to: /home/linyz0100/Desktop/slambook2/ch3/visualizeGeometry/build
linyz0100@linyz0100-QEMU-VM:~/Desktop/slambook2/ch3/visualizeGeometry/build$ make
Consolidate compiler generated dependencies of target visualizeGeometry
[100%] Built target visualizeGeometry
linyz0100@linyz0100-QEMU-VM:~/Desktop/slambook2/ch3/visualizeGeometry/build$ ./visualizeGeometry
./visualizeGeometry: error while loading shared libraries: libpango_windowing.so: cannot open shared object file: No such file or directory

I suspect that cmake does not find the directory path? It compiles successfully, but the executable can't locate the the library. I think Pagolin is correctly installed, as you can see the .so files under usr/local/lib

shared libs

linyz0100@linyz0100-QEMU-VM:/usr/local/lib$ ls
cmake                   libpango_opengl.so        libpango_vars.so
libpango_core.so        libpango_packetstream.so  libpango_video.so
libpango_display.so     libpango_plot.so          libpango_windowing.so
libpango_geometry.so    libpango_python.so        libtinyobj.so
libpango_glgeometry.so  libpango_scene.so         python3.10
libpango_image.so       libpango_tools.so

Can someone explain this process to me? What is missing?
Thanks!


问:
how to calculate elapsed time between dates from a table? in pho
I want to know how to calculate the difference between timestamps presented in a table, for example, if in the first field I have "2022-07-23 13:10:11" and in the second field I have "2022-07-23 13:15: 11" I would like to know the time elapsed between those times, for example it would only be 5 min but in the third field I have "2022-07-24 13:15:11", the difference between 2 and 3 would be 1 day, for that time data elapsed would be a new column, but I want to know if it could be done, I have investigated and there is the date_diff function but I do not understand how to use it to do it in a table since a for would be used</p>


问:
API call seemed successful but returned invalid response [ASP.NET API and .NET MAUI]
I have an ASP.NET Core API -- running on .NET 7 -- and I make POST a call to this API from a .NET MAUI app -- also running on .NET 7.

The call is working and I see the record created in the database but the call ends up in the catch block with this error, which I've never seen before:

"API call seemed successful but returned invalid response. URL:
/myapi/endpoint/create"

I make a lot of other calls to this API from the same .NET MAUI app and they all seem to be working fine.

Google search returns nothing for this error and so far I don't see anything unusual with my code.

BTW, I use Postman to make this API call and it works and I receive a status code 200.

Has anyone experienced this error before? Any idea what maybe causing this?


问:
Rerun VBA Formula triggered by font color change
i wrote a simple VBA script that sums cells with a choosen font color but when i manually change a cell font color excel doesn't recalculate the formula automatically. Is there any way to do that?</p>


问:
Subfunction returning choropleth map
I have two functions, one part of another:
One returns values lat, lon, df, zoom, geojson based on input
This function works fine
Another function is supposed to return a choropleth map based on inputs that are outputs for the first function, i .e. inputs here are lat,lon,df,zoom,geojson

Let's suppose that these are outputs for the first function:

```<code>lat=39.90341108652551
lon=-76.12312247933444
zoom=10
df=df2
geojson=geo_lower
</code>```

geo_lower is a json file from:

```<code>geo_lower='https://www.redistricting.state.pa.us/Resources/GISData/Districts/Legislative/House/2021-Final/JSON/2022%20LRC-House-Final.json'
with urlopen(geo_lower) as response:
    geo_lower = json.load(response)
</code>```

df2 looks like one-row dataframe:

District
Total Popultation
...

2
234,678
...

The second function looks like this:

```<code>fig=px.choropleth_mapbox(df,
                         geojson=geojson,
                         locations='District',
                         mapbox_style="carto-positron",
                         zoom=zoom,
                         center={'lat':lat, 'lon':lon},
                         opacity=0.3)
</code>```

The result is:

However, if i input values manually, the function returns intended outcome:

```<code>fig = px.choropleth_mapbox(df2,
                           geojson=geo_lower,
                           locations='District',
                           mapbox_style="carto-positron",
                           zoom=10,
                           center={'lat':39.90341108652551,'lon':-76.12312247933444},
                           opacity=0.3
                           )
fig.show()
</code>```

I believe the problem is with the second function's center, because when i print(fig), its center is not the same as the input center:

How can I solve the issue?

Title: Subfunction returning choropleth map

Body:
I have two functions, one part of another:
One returns values lat, lon, df, zoom, geojson based on input
This function works fine
Another function is supposed to return a choropleth map based on inputs that are outputs for the first function, i .e. inputs here are lat,lon,df,zoom,geojson

Let's suppose that these are outputs for the first function:

lat=39.90341108652551
lon=-76.12312247933444
zoom=10
df=df2
geojson=geo_lower

geo_lower is a json file from:

geo_lower='https://www.redistricting.state.pa.us/Resources/GISData/Districts/Legislative/House/2021-Final/JSON/2022%20LRC-House-Final.json'
with urlopen(geo_lower) as response:
    geo_lower = json.load(response)

df2 looks like one-row dataframe:

District
Total Popultation
...

2
234,678
...

The second function looks like this:

fig=px.choropleth_mapbox(df,
                         geojson=geojson,
                         locations='District',
                         mapbox_style="carto-positron",
                         zoom=zoom,
                         center={'lat':lat, 'lon':lon},
                         opacity=0.3)

The result is:

However, if i input values manually, the function returns intended outcome:

fig = px.choropleth_mapbox(df2,
                           geojson=geo_lower,
                           locations='District',
                           mapbox_style="carto-positron",
                           zoom=10,
                           center={'lat':39.90341108652551,'lon':-76.12312247933444},
                           opacity=0.3
                           )
fig.show()

I believe the problem is with the second function's center, because when i print(fig), its center is not the same as the input center:

How can I solve the issue?


问:
Apple pay can't complete when using square_in_app_payment flutter plugin
I already integrated Apple pay on the project and double-checked the whole configuration steps.
The Apple payment sheet launches successfully, but I couldn't complete the payment transaction.
Here is how i requested nonce for Apple Pay.

```<code>await InAppPayments.requestApplePayNonce(
    price: '1.00',//formatMoney(cart.total),
    summaryLabel: 'Cart items',
    countryCode: 'US',
    currencyCode: 'USD',
    paymentType: ApplePayPaymentType.finalPayment,
    onApplePayNonceRequestSuccess: (CardDetails cardDetails) async {
      await InAppPayments.completeApplePayAuthorization(isSuccess: true);
      completer.complete(cardDetails);
    },
    onApplePayNonceRequestFailure: (errorDetails) async {
      print('RequestFailure: ' + errorDetails.toString());
      await InAppPayments.completeApplePayAuthorization(
          isSuccess: false,
          errorMessage: errorDetails.message);
      completer.completeError(ApplePayNonceRequestException(errorInfo: errorDetails));
    },
    onApplePayComplete: () {}
);
</code>```

I've got this error log after inputing payment pin code.

```<code>flutter: RequestFailure: ErrorInfo {
  code=usageError,
  message=Something went wrong. Please contact the developer of this application and provide them with this error code: unexpected,
  debugCode=apple_pay_nonce_request_unexpected,
  debugMessage=Square In-App Payments SDK encountered an unexpected error. Please contact Square developer support via https://squareup.com/help/contact,
}
</code>```

Hope I can get any helpful suggestions. Thanks in advance.

I tried with both sandbox account and production one, but got same result.

Body:
I already integrated Apple pay on the project and double-checked the whole configuration steps.
The Apple payment sheet launches successfully, but I couldn't complete the payment transaction.
Here is how i requested nonce for Apple Pay.

await InAppPayments.requestApplePayNonce(
    price: '1.00',//formatMoney(cart.total),
    summaryLabel: 'Cart items',
    countryCode: 'US',
    currencyCode: 'USD',
    paymentType: ApplePayPaymentType.finalPayment,
    onApplePayNonceRequestSuccess: (CardDetails cardDetails) async {
      await InAppPayments.completeApplePayAuthorization(isSuccess: true);
      completer.complete(cardDetails);
    },
    onApplePayNonceRequestFailure: (errorDetails) async {
      print('RequestFailure: ' + errorDetails.toString());
      await InAppPayments.completeApplePayAuthorization(
          isSuccess: false,
          errorMessage: errorDetails.message);
      completer.completeError(ApplePayNonceRequestException(errorInfo: errorDetails));
    },
    onApplePayComplete: () {}
);

I've got this error log after inputing payment pin code.

flutter: RequestFailure: ErrorInfo {
  code=usageError,
  message=Something went wrong. Please contact the developer of this application and provide them with this error code: unexpected,
  debugCode=apple_pay_nonce_request_unexpected,
  debugMessage=Square In-App Payments SDK encountered an unexpected error. Please contact Square developer support via https://squareup.com/help/contact,
}

Hope I can get any helpful suggestions. Thanks in advance.

I tried with both sandbox account and production one, but got same result.


问:
VsCode debugging, testing and launching full-stack (NextJS, Python) app
I'm developing a full-stack app using NextJS as frontend and Python FastAPI as backend, I'm investigating on the best way of launching, debugging and testing frontend and backend together.
The aim is to avoid having to launch frontend and backend separately from command line.

My code is structured in this way:

```<code>backend/
  server.py

frontend/
  package.json
  node_modules
  app

.vscode/
  launch.json
  settings.json
</code>```

I thought that the best ways to launch backend and frontend together were using .vscode settings or package.json scripts.

I opted for using the .vscode to integrate also debugging and tests launching with VsCode but I'm not sure this is the best way to do it, also because it's IDE-related, is there a way to do it in some IDE-agnostic way?
Do you have any suggestions?

These are my launch.json and settings.json configurations:

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Open App",
      "request": "launch",
      "type": "chrome",
      "url": "http://localhost:3000"
    },
    {
      "name": "Next.js: debug server-side",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev",
      "cwd": "${workspaceFolder}/frontend"
    },
    {
      "name": "Python: FastAPI backend",
      "type": "python",
      "request": "launch",
      "module": "uvicorn",
      "args": ["server:app", "--reload"],
      "jinja": true,
      "justMyCode": true,
      "cwd": "${workspaceFolder}/backend"
    },

  ],
  "compounds": [
    {
        "name": "Server/Client debug",
        "configurations": ["Next.js: debug server-side", "Python: FastAPI backend", "Open App"],
        "stopAll": true,
    }
  ]
}

```
<p>settings.json</p>
<pre class="lang-json prettyprint-override"><code>{
  "python.testing.unittestArgs": [
    "-v",
    "-s",
    "./backend",
    "-p",
    "*_test.py"
  ],
  "python.testing.cwd": "${workspaceFolder}/",
  "python.testing.pytestEnabled": false,
  "python.testing.unittestEnabled": true
}
</code>```

Is there something I can do better? Are there some useful tools I can use for debug and deploy my code?

Body:
I'm developing a full-stack app using NextJS as frontend and Python FastAPI as backend, I'm investigating on the best way of launching, debugging and testing frontend and backend together.
The aim is to avoid having to launch frontend and backend separately from command line.

My code is structured in this way:

backend/
  server.py

frontend/
  package.json
  node_modules
  app

.vscode/
  launch.json
  settings.json

I thought that the best ways to launch backend and frontend together were using .vscode settings or package.json scripts.

I opted for using the .vscode to integrate also debugging and tests launching with VsCode but I'm not sure this is the best way to do it, also because it's IDE-related, is there a way to do it in some IDE-agnostic way?
Do you have any suggestions?

These are my launch.json and settings.json configurations:

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Open App",
      "request": "launch",
      "type": "chrome",
      "url": "http://localhost:3000"
    },
    {
      "name": "Next.js: debug server-side",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev",
      "cwd": "${workspaceFolder}/frontend"
    },
    {
      "name": "Python: FastAPI backend",
      "type": "python",
      "request": "launch",
      "module": "uvicorn",
      "args": ["server:app", "--reload"],
      "jinja": true,
      "justMyCode": true,
      "cwd": "${workspaceFolder}/backend"
    },

  ],
  "compounds": [
    {
        "name": "Server/Client debug",
        "configurations": ["Next.js: debug server-side", "Python: FastAPI backend", "Open App"],
        "stopAll": true,
    }
  ]
}

settings.json

{
  "python.testing.unittestArgs": [
    "-v",
    "-s",
    "./backend",
    "-p",
    "*_test.py"
  ],
  "python.testing.cwd": "${workspaceFolder}/",
  "python.testing.pytestEnabled": false,
  "python.testing.unittestEnabled": true
}

Is there something I can do better? Are there some useful tools I can use for debug and deploy my code?


问:
How can I remove weekends in matplotlib for data of variable frequency in python?
I looked for an answer to the below, but they're never quite right.

Say we have data of variable frequency in pandas:

```<code>import pandas as pd
testDf = pd.DataFrame(
    {'ImpliedVolatility': {
        pd.Timestamp('2022-11-30 16:20:00+0100'): 19.1269013106775,
        pd.Timestamp('2022-11-30 16:30:00+0100'): 19.0800712368193,
        pd.Timestamp('2022-12-01 15:20:00+0100'): 19.5300982613676,
        pd.Timestamp('2022-12-02 09:00:00+0100'): 18.8579952967423,
        pd.Timestamp('2022-12-02 09:20:00+0100'): 18.6791915364582,
        pd.Timestamp('2022-12-02 15:10:00+0100'): 18.5538057657658,
        pd.Timestamp('2022-12-02 15:20:00+0100'): 18.6965706501837,
        pd.Timestamp('2022-12-02 15:50:00+0100'): 17.5678872272944,
        pd.Timestamp('2022-12-05 09:00:00+0100'): 18.2304285690717}})
</code>```

It's simple to get a sensible graph out:

```<code>import matplotlib.pyplot as plt
fig1, ax1 = plt.subplots()
fig1.autofmt_xdate()
ax1.plot(testDf.ImpliedVolatility, 'o-')
plt.show()
</code>```

However, I would like to get rid of weekend gaps in this graph. To be precise: Fridays at midnight to Sundays at midnight.

Solutions online have several issues, the most common one is that it resets ticker frequencies to regular intervals:

```<code>import numpy as np
fig, axes = plt.subplots(ncols=1)

# write a custom formatter
N = len(testDf)
ind = np.arange(N)  # the evenly spaced plot indices

def format_date(x, pos=None):
    thisind = np.clip(int(x + 0.5), 0, N - 1)
    return testDf.index[thisind].strftime('%Y-%m-%d %Hh')

ax = axes
ax.plot(ind, testDf.ImpliedVolatility, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()

plt.show()
</code>```

But that is inadequate here since we have data of variable frequency.

N.B.: the best would be a graph that removes all non-trading-hours, but that's difficult since it is different for each exchange. Here I'm interested in the EUREX Exchange for Options.

I tried several solutions given online - including StackOverflow. Solutions online have several issues, the most common one is that it resets x-ticker frequencies to regular intervals.

Body:
I looked for an answer to the below, but they're never quite right.

Say we have data of variable frequency in pandas:

import pandas as pd
testDf = pd.DataFrame(
    {'ImpliedVolatility': {
        pd.Timestamp('2022-11-30 16:20:00+0100'): 19.1269013106775,
        pd.Timestamp('2022-11-30 16:30:00+0100'): 19.0800712368193,
        pd.Timestamp('2022-12-01 15:20:00+0100'): 19.5300982613676,
        pd.Timestamp('2022-12-02 09:00:00+0100'): 18.8579952967423,
        pd.Timestamp('2022-12-02 09:20:00+0100'): 18.6791915364582,
        pd.Timestamp('2022-12-02 15:10:00+0100'): 18.5538057657658,
        pd.Timestamp('2022-12-02 15:20:00+0100'): 18.6965706501837,
        pd.Timestamp('2022-12-02 15:50:00+0100'): 17.5678872272944,
        pd.Timestamp('2022-12-05 09:00:00+0100'): 18.2304285690717}})

It's simple to get a sensible graph out:

import matplotlib.pyplot as plt
fig1, ax1 = plt.subplots()
fig1.autofmt_xdate()
ax1.plot(testDf.ImpliedVolatility, 'o-')
plt.show()

However, I would like to get rid of weekend gaps in this graph. To be precise: Fridays at midnight to Sundays at midnight.

Solutions online have several issues, the most common one is that it resets ticker frequencies to regular intervals:

import numpy as np
fig, axes = plt.subplots(ncols=1)

# write a custom formatter
N = len(testDf)
ind = np.arange(N)  # the evenly spaced plot indices

def format_date(x, pos=None):
    thisind = np.clip(int(x + 0.5), 0, N - 1)
    return testDf.index[thisind].strftime('%Y-%m-%d %Hh')

ax = axes
ax.plot(ind, testDf.ImpliedVolatility, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()

plt.show()

But that is inadequate here since we have data of variable frequency.

N.B.: the best would be a graph that removes all non-trading-hours, but that's difficult since it is different for each exchange. Here I'm interested in the EUREX Exchange for Options.

I tried several solutions given online - including StackOverflow. Solutions online have several issues, the most common one is that it resets x-ticker frequencies to regular intervals.


问:
monaco-editor-webpack-plugin loads all features
I'm using react-app-rewired in my React app, I added the plugin for Monaco Editor, and I'm trying to reduce the amount of features.
I tried multiple steps, but nothing worked.

This is the configuration I added for testing:

```<code>new MonacoWebpackPlugin({
  languages: ['json'],
  features: ['rename'],
})
</code>```

This should only compile the rename feature, but after running analyzer on the build folder I get that all the features were loaded:
The analyzed bundle for MonacoEditor

I tried other stuff too, the bundle size remained the same no matter what I did, am I missing something?

Body:
I'm using react-app-rewired in my React app, I added the plugin for Monaco Editor, and I'm trying to reduce the amount of features.
I tried multiple steps, but nothing worked.

This is the configuration I added for testing:

new MonacoWebpackPlugin({
  languages: ['json'],
  features: ['rename'],
})

This should only compile the rename feature, but after running analyzer on the build folder I get that all the features were loaded:
The analyzed bundle for MonacoEditor

I tried other stuff too, the bundle size remained the same no matter what I did, am I missing something?


问:
Passing an object rather than a single file using React?
I have a simple web app that uploads a selected file to an S3 bucket. I need the file name in the sending to the post request. I try passing an object but I get a at XMLHttpRequest.handleError

When I pass only the file everything works perfectly. I want the data sent to the back end to have both the file and the name. When I pass only the file, I can't extract the original file name.

Here is the code I am getting the error with:

`

```<code>import './App.css';
import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  state = {
    selectedFile: null,
    fileUploadedSuccessfully: false
  }

  onFileChange = event => {
    this.setState({selectedFile: event.target.files[0]})
  };

  onFileUpload = () => {
    const formData = new FormData();
    formData.append(
      "demo file",
      this.state.selectedFile,
      this.state.selectedFile.name
    )
    var upload = document.getElementById('upload');
    var file = upload.files[0];

    const file_datails = {
      File: file,
      FileName: file.name
    }

    axios.post("https://qblcuaql1h.execute-api.us-east-1.amazonaws.com/upload", file_datails).then(() => {
    this.setState({selectedFile: null});
    this.setState({fileUploadedSuccessfully: true});
  })

  }

  fileData = () => {
    if (this.state.selectedFile) {
      return (
      <div>
        <h2>File Details:</h2>
        <p>File Name: {this.state.selectedFile.name}</p>
        <p>File Type: {this.state.selectedFile.type}</p>
        <p>Last Modified: {""}
          {this.state.selectedFile.lastModifiedDate.toDateString()}
        </p>
      </div>
      );
    } else if (this.state.fileUploadedSuccessfully) {
      return (
        <div>
          <br />
          <h4>Your file has been successfully uploaded</h4>
        </div>
      );
    } else {
      return (
        <div>
        <br />
        <h4>Choose a file and select upload</h4>
        </div>
      )
    }
  }

render() {
  return (
    <div className="container">
      <h2>CETO New Logo Upload</h2>
      <h3>Please Upload File and Input Brand Id:</h3>
      <div>
       <input type='file' id="upload" onChange={this.onFileChange} />
       <button onClick={this.onFileUpload}>
         Upload
       </button>
      </div>
      {this.fileData()}
    </div>
  )
}
}
export default App;

</code>```

`

Body:
I have a simple web app that uploads a selected file to an S3 bucket. I need the file name in the sending to the post request. I try passing an object but I get a at XMLHttpRequest.handleError

When I pass only the file everything works perfectly. I want the data sent to the back end to have both the file and the name. When I pass only the file, I can't extract the original file name.

Here is the code I am getting the error with:

`

import './App.css';
import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
  state = {
    selectedFile: null,
    fileUploadedSuccessfully: false
  }

  onFileChange = event => {
    this.setState({selectedFile: event.target.files[0]})
  };

  onFileUpload = () => {
    const formData = new FormData();
    formData.append(
      "demo file",
      this.state.selectedFile,
      this.state.selectedFile.name
    )
    var upload = document.getElementById('upload');
    var file = upload.files[0];

    const file_datails = {
      File: file,
      FileName: file.name
    }

    axios.post("https://qblcuaql1h.execute-api.us-east-1.amazonaws.com/upload", file_datails).then(() => {
    this.setState({selectedFile: null});
    this.setState({fileUploadedSuccessfully: true});
  })

  }

  fileData = () => {
    if (this.state.selectedFile) {
      return (

File Details:

File Name: {this.state.selectedFile.name}

File Type: {this.state.selectedFile.type}

Last Modified: {""}
          {this.state.selectedFile.lastModifiedDate.toDateString()}

      );
    } else if (this.state.fileUploadedSuccessfully) {
      return (

Your file has been successfully uploaded

      );
    } else {
      return (

Choose a file and select upload

      )
    }
  }

render() {
  return (

CETO New Logo Upload

Please Upload File and Input Brand Id:

       <input type='file' id="upload" onChange={this.onFileChange} />
       <button onClick={this.onFileUpload}>
         Upload
       </button>

      {this.fileData()}

  )
}
}
export default App;

`


问:
I want to convert 28*28 pixel to 32*32 pixel of image
I have Mnist dataset. This dataset has 70,000 row and 785 column which one of column is class.
For example, how to convert 2828 pixel values to 3232 pixels using first row pixel variable ?

my csv file


问:
Is there any way to get UK Working Days in Python?
I am aware of

```<code>from pandas.tseries.offsets import BDay
</code>```

That gives me business days but my understanding is this only accounts for American holidays? How would I go about getting holidays for England?

Body:
I am aware of

from pandas.tseries.offsets import BDay

That gives me business days but my understanding is this only accounts for American holidays? How would I go about getting holidays for England?


问:
How can I make long tuple list of URLs separate into JSON objects?
I have a long tuple list of URLs that I would like to convert to JSON format in a specific way that allows each tuple item to be in their own nested object.

Kinda puzzled at how to manage to do that.
I'm trying to convert the tuple into JSON so that it looks as such...

```<code>        "links": [
            {
                "src": tuple-item-1
            },
            {
                "src": tuple-item-2
            },
            {
                "src": tuple-item-3
            }
            ...
        ]
</code>```

Thanks in advance :)

Body:
I have a long tuple list of URLs that I would like to convert to JSON format in a specific way that allows each tuple item to be in their own nested object.

Kinda puzzled at how to manage to do that.
I'm trying to convert the tuple into JSON so that it looks as such...

        "links": [
            {
                "src": tuple-item-1
            },
            {
                "src": tuple-item-2
            },
            {
                "src": tuple-item-3
            }
            ...
        ]

Thanks in advance :)


问:
I am trying to use the excel filter function to pull in data from a file on sharepoint but this is not working
I am trying to use the excel filter function to pull in data from an excel file on sharepoint, but the filter function is not working. Does anyone have a good way to locate the correct URL so that this will work?

I am able to pull the data in when performing this action from another workbook in the same file, but filter function does not find results when from a sharepoint location.
What I need to do is to use one cell reference to bring in the data from all the columns associated with this value.

Example:
=FILTER('https://.sharepoint.com/sites//Shared Documents/Reports/[Historical_Repairs.xlsxQuery1'!$A$2":$Q$100000,'https://****.sharepoint.com/sites/********/Shared Documents/Reports/[Historical_Repairs.xlsxQuery1'!$Q$2":$Q$100000=C4,"No Data Found"


问:
NextJS Auth0 JWT API Authentication
I have Auth0 Bearer access token and I want to call an API in NextJS with that. But the problem is that https://www.npmjs.com/package/@auth0/nextjs-auth0 is session based and you can only authorize on the basis of session.

I am thinking of creating a temporary session using that Bearer Token but that sounds hacky way. What are the available options? and if I had to move forward with creating Temporary Session, what should I do?

I tried calling API on NextJS with Bearer Token but it failed. I was expecting it to authorize and deduce the user calling that API.

Title: NextJS Auth0 JWT API Authentication


问:
How to select a value from column (B, C or D) based on the value in Column A, into a new column D in R
I have a large dataset in R with c. 20 variables and 1000s of observations. I'm new to R and can't find a way to select 1 value from multiple columns into a new column based on a
I want to create a new column (F) that selects a value from columns B:E based on the value returned in column A.

Is that possible?

I have tried to use this code:

```<code>library("tidyverse")
library("dplyr")

df <- df %>%
  mutate(F = case_when(A == 1 ~ B,
                       A == 2 ~ C,
                       A == 3 ~ D,
                       A == 4 ~ E,
                       TRUE ~ NA))
</code>```

and received this error:

```<code>Error in `mutate()`:
! Problem while computing `F = case_when(...)`.
Caused by error in `case_when()`:
Run `rlang::last_error()` to see where the error occurred.
</code>```

Body:
I have a large dataset in R with c. 20 variables and 1000s of observations. I'm new to R and can't find a way to select 1 value from multiple columns into a new column based on a
I want to create a new column (F) that selects a value from columns B:E based on the value returned in column A.

Is that possible?

I have tried to use this code:

library("tidyverse")
library("dplyr")

df <- df %>%
  mutate(F = case_when(A == 1 ~ B,
                       A == 2 ~ C,
                       A == 3 ~ D,
                       A == 4 ~ E,
                       TRUE ~ NA))

and received this error:

Error in `mutate()`:
! Problem while computing `F = case_when(...)`.
Caused by error in `case_when()`:
Run `rlang::last_error()` to see where the error occurred.


问:
Entity Framework Reverse Engineering - Error on HasOne

It's the 1st time I do Reverse Engineering in an existing database to EF Core...this is part of my model and this is the generated code...

```<code>modelBuilder.Entity<CompaniesCountry>(entity =>
            {
                entity.HasKey(e => new { e.CountriesIso3166, e.CompaniesId })
                    .HasName("Companies_Country_pk");

                entity.ToTable("Companies_Country");

                entity.Property(e => e.CountriesIso3166)
                    .HasMaxLength(3)
                    .IsUnicode(false)
                    .HasColumnName("Countries_Iso3166")
                    .IsFixedLength();

                entity.Property(e => e.CompaniesId).HasColumnName("Companies_Id");

                entity.HasOne() // Error Here
                    .WithMany()
                    .HasForeignKey(d => d.CompaniesId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("Companies_Country_Companies");

                entity.HasOne() // Error Here
                    .WithMany()
                    .HasForeignKey(d => d.CountriesIso3166)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("Companies_Country_Countries");
            });
</code>```

The database has 25 tables...and everything was generated pretty well, but this code in particular is causing this error:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   CS0411  The type arguments for method 'EntityTypeBuilder<CompaniesCountry>.HasOne<TRelatedEntity>
(Expression<Func<CompaniesCountry, TRelatedEntity?>>?)' cannot be
inferred from the usage. Try specifying the type arguments explicitly.
MSSQL_DbContext.cs  110 Active

Severity    Code    Description Project File    Line    Suppression State
Error   CS0411  The type arguments for method 'EntityTypeBuilder<CompaniesCountry>.HasOne<TRelatedEntity>
(Expression<Func<CompaniesCountry, TRelatedEntity?>>?)' cannot be
inferred from the usage. Try specifying the type arguments explicitly.
MSSQL_DbContext.cs  116 Active
</code>```

Any idea ?

Body:
It's the 1st time I do Reverse Engineering in an existing database to EF Core...this is part of my model and this is the generated code...

modelBuilder.Entity<CompaniesCountry>(entity =>
            {
                entity.HasKey(e => new { e.CountriesIso3166, e.CompaniesId })
                    .HasName("Companies_Country_pk");

                entity.ToTable("Companies_Country");

                entity.Property(e => e.CountriesIso3166)
                    .HasMaxLength(3)
                    .IsUnicode(false)
                    .HasColumnName("Countries_Iso3166")
                    .IsFixedLength();

                entity.Property(e => e.CompaniesId).HasColumnName("Companies_Id");

                entity.HasOne() // Error Here
                    .WithMany()
                    .HasForeignKey(d => d.CompaniesId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("Companies_Country_Companies");

                entity.HasOne() // Error Here
                    .WithMany()
                    .HasForeignKey(d => d.CountriesIso3166)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("Companies_Country_Countries");
            });

The database has 25 tables...and everything was generated pretty well, but this code in particular is causing this error:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0411  The type arguments for method 'EntityTypeBuilder<CompaniesCountry>.HasOne<TRelatedEntity>
(Expression<Func<CompaniesCountry, TRelatedEntity?>>?)' cannot be
inferred from the usage. Try specifying the type arguments explicitly.
MSSQL_DbContext.cs  110 Active

Severity    Code    Description Project File    Line    Suppression State
Error   CS0411  The type arguments for method 'EntityTypeBuilder<CompaniesCountry>.HasOne<TRelatedEntity>
(Expression<Func<CompaniesCountry, TRelatedEntity?>>?)' cannot be
inferred from the usage. Try specifying the type arguments explicitly.
MSSQL_DbContext.cs  116 Active

Any idea ?


问:
How can I get VSCode + Flake8 to use tabs?
.vscode/settings.json

{
    ...
    "python.linting.enabled": true,
    "python.linting.flake8Enabled": true,
}
```
<p>I have the following config with linting with flake8. However, I see no options for flake8 to use tabs in my python project. I found flake8-tabs and attempted to configure it with VS Code to get it to work:</p>
```[flake8]
use-flake8-tabs = true
```

Body:
.vscode/settings.json

{
    ...
    "python.linting.enabled": true,
    "python.linting.flake8Enabled": true,
}

I have the following config with linting with flake8. However, I see no options for flake8 to use tabs in my python project. I found flake8-tabs and attempted to configure it with VS Code to get it to work:

[flake8]
use-flake8-tabs = true


问:
Javascript - Prevent window refresh when use focus
I have to implement the next requirement: From a specified page I have to open a new page (new browser tab, lets call it Live tab) and focus on it. Only one Live tab can be opened at a time

What I've tried is

```<code>const win = this.window.open(url, 'New tab');
win?.focus();
</code>```

This is working as expected but if the Live tab is already opened, the focus operation triggers a refresh of the Live tab every time.

Can we prevent this somehow ?

Body:
I have to implement the next requirement: From a specified page I have to open a new page (new browser tab, lets call it Live tab) and focus on it. Only one Live tab can be opened at a time

What I've tried is

const win = this.window.open(url, 'New tab');
win?.focus();

This is working as expected but if the Live tab is already opened, the focus operation triggers a refresh of the Live tab every time.

Can we prevent this somehow ?


问:
i couldn't step to the main in keil 5 during debugging
i write simple counter program and compiled successfully when I try to debug it, the debugger cursor is not stepping in to the main program[[enter image description here](https://i.stack.imgur.com/a5dxZ.png)](https://i.stack.imgur.com/rVPVr.png)

keil5 debugger doesn't enter to main


问:
JPA processing row by row with locking
I have a problem with JPA (Postgres db). Let's assume we have a table like:

```<code>id | data
 1 | aaa
 2 | bbb
 3 | ccc
 4 | ddd
</code>```

It is kind of a queue and I want to process it like a queue (please do not ask why). I have multiple applications that will 'consume' that data. And I would like to allow them to work concurrently.

What I need to do is to read the first row from the table (can be any, not necessarily the first one), process it and finally remove it from the table. Second application/pod should not access the row currently processed by the first one.

Also, when the first pod processes the row, I do not want to lock the entire table.

Let's assume I have two pods: P1 and P2:

P1 starts processing row number 1,

P2 wants to execute the same logic, but it shouldn't see the row number 1 (which is currently under processing by P1), it should retrieve and handle row number 2.

How to achieve that with JPA? I tried some JPA queries with @Lock(LockModeType.PESSIMISTIC_WRITE) but I am locking the entire table then (second app waits till I leave @Transactional block in the first one).

If there was a query to delete a row and return the deleted data - it would be the easiest approach with proper transaction level.

Any ideas?

Title: JPA processing row by row with locking

Body:
I have a problem with JPA (Postgres db). Let's assume we have a table like:

id | data
 1 | aaa
 2 | bbb
 3 | ccc
 4 | ddd

It is kind of a queue and I want to process it like a queue (please do not ask why). I have multiple applications that will 'consume' that data. And I would like to allow them to work concurrently.

What I need to do is to read the first row from the table (can be any, not necessarily the first one), process it and finally remove it from the table. Second application/pod should not access the row currently processed by the first one.

Also, when the first pod processes the row, I do not want to lock the entire table.

Let's assume I have two pods: P1 and P2:

P1 starts processing row number 1,

P2 wants to execute the same logic, but it shouldn't see the row number 1 (which is currently under processing by P1), it should retrieve and handle row number 2.

How to achieve that with JPA? I tried some JPA queries with @Lock(LockModeType.PESSIMISTIC_WRITE) but I am locking the entire table then (second app waits till I leave @Transactional block in the first one).

If there was a query to delete a row and return the deleted data - it would be the easiest approach with proper transaction level.

Any ideas?


问:
I tried to resize PersistentVolumeClaim with help of Kubectl patch pvc to increase storage from 10 Gi to 70 Gi but it’s giving error:
$ k patch pvc pv-volume -p '{"spec":{"resources":{"requests":{"storage":"70Mi"}}}}'
Error from server (Forbidden): persistentvolumeclaims "pv-volume" is forbidden: only dynamically provisioned pvc can be resized and the storageclass that provisions the pvc must support resize

Question: Create a pvc
name: pv-volume, class: csi-hostpath-sc, capacity:10Mi
Create a pod which mount the pvc as a volume.
name: web-server, image:nginx,mountpath: /usr/share/nginx/html
configure the new pod to have readWriteOnce
finally using kubectl edit ot kubectl patch pvc to a capacity of 70 Mi and record that change.

Please give me solution to patch pvc and record the change.

pv.yaml

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv
spec:
  capacity:
    storage: 70Mi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Recycle
  storageClassName: csi-hostpath-sc
  hostPath:
    path: /usr/share/nginx/html
</code>```
```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pv-volume
spec:
  accessModes:
    - ReadWriteOnce
  volumeMode: Filesystem
  resources:
    requests:
      storage: 10Mi
  storageClassName: csi-hostpath-sc
</code>```

pod.yaml

```<code>apiVersion: v1
kind: Pod
metadata:
  name: web-server
spec:
  containers:
    - name: web-server
      image: nginx
      volumeMounts:
      - mountPath: "/usr/share/nginx/html"
        name: mypd
  volumes:
    - name: mypd
      persistentVolumeClaim:
        claimName: pv-volume
</code>```

Body:
$ k patch pvc pv-volume -p '{"spec":{"resources":{"requests":{"storage":"70Mi"}}}}'
Error from server (Forbidden): persistentvolumeclaims "pv-volume" is forbidden: only dynamically provisioned pvc can be resized and the storageclass that provisions the pvc must support resize

Question: Create a pvc
name: pv-volume, class: csi-hostpath-sc, capacity:10Mi
Create a pod which mount the pvc as a volume.
name: web-server, image:nginx,mountpath: /usr/share/nginx/html
configure the new pod to have readWriteOnce
finally using kubectl edit ot kubectl patch pvc to a capacity of 70 Mi and record that change.

Please give me solution to patch pvc and record the change.

pv.yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv
spec:
  capacity:
    storage: 70Mi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Recycle
  storageClassName: csi-hostpath-sc
  hostPath:
    path: /usr/share/nginx/html

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pv-volume
spec:
  accessModes:
    - ReadWriteOnce
  volumeMode: Filesystem
  resources:
    requests:
      storage: 10Mi
  storageClassName: csi-hostpath-sc

pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: web-server
spec:
  containers:
    - name: web-server
      image: nginx
      volumeMounts:
      - mountPath: "/usr/share/nginx/html"
        name: mypd
  volumes:
    - name: mypd
      persistentVolumeClaim:
        claimName: pv-volume


问:
How to shrink aut-py-to-exe folders
When I use auto-py-to-exe to convert a py script to a folder with an executable, it creates a pretty large folder (over 1 GB) even when the script is pretty basic. Are there some dlls or folders that I can delete (or some that I should keep) in order to shrink the folder? I used spyder as my compiler, so alternatively should I disable certain libraries there?</p>

Title: How to shrink aut-py-to-exe folders


问:
rotateX hides half of icon on iOS
I have an icon that i animation like so:

```<code>.bonus-chevron-down {
    will-change: transform;
    transform-origin: center;
    backface-visibility: visible;
    animation-direction: reverse;
    transform: rotateX(-179.9deg);
    -webkit-transform:  rotateX(-179.9deg);
    transition: transform 0.6s ease-in-out;
  }
</code>```

But for some reason, safari on iOS makes the icon dissapear half

Title: rotateX hides half of icon on iOS

Body:
I have an icon that i animation like so:

.bonus-chevron-down {
    will-change: transform;
    transform-origin: center;
    backface-visibility: visible;
    animation-direction: reverse;
    transform: rotateX(-179.9deg);
    -webkit-transform:  rotateX(-179.9deg);
    transition: transform 0.6s ease-in-out;
  }

But for some reason, safari on iOS makes the icon dissapear half


问:
How to write rules that skip the job when any of the specified files doesn't exist?
Here I have rules for a job so that it's added to the pipeline if and only if do_job is set and skip_job is not set.

rules:
- if: $skip_job == "true"
  when: never
- if: $do_job != "false"
```
<p>How to add a rule that also skips the job when any of the two files is missing?</p>
<p>(the two files are <code>tasks.yml</code> and <code>inputs.yml</code>)</p>
<p>Something like that:</p>
<pre class="lang-yaml prettyprint-override"><code>rules:
- if: $skip_job == "true"
  when: never
- does_not_exist:
  - tasks.yml
  when: never
- does_not_exist:
  - inputs.yml
  when: never
- if: $do_job != "false"
</code>```

Body:
Here I have rules for a job so that it's added to the pipeline if and only if do_job is set and skip_job is not set.

rules:
- if: $skip_job == "true"
  when: never
- if: $do_job != "false"

How to add a rule that also skips the job when any of the two files is missing?

(the two files are tasks.yml and inputs.yml)

Something like that:

rules:
- if: $skip_job == "true"
  when: never
- does_not_exist:
  - tasks.yml
  when: never
- does_not_exist:
  - inputs.yml
  when: never
- if: $do_job != "false"


问:
How to calculate distance between two points for get nearest distance in Spring Boot (Custom Query)?
This error is showing when I run my custom query
Cannot invoke "antlr.collections.AST.getFirstChild()" because "e_AST" is null

I tried this

```<code>@Query("SELECT v FROM Vehicle v WHERE 10 <= SQRT(POW(69.1 * (v.currentLatitude::float -  12.3), 2) + POW(69.1 * (12.36 - v.currentLongitude::float) * COS(v.currentLatitude::float / 57.3), 2))")
</code>```

Body:
This error is showing when I run my custom query
Cannot invoke "antlr.collections.AST.getFirstChild()" because "e_AST" is null

I tried this

@Query("SELECT v FROM Vehicle v WHERE 10 <= SQRT(POW(69.1 * (v.currentLatitude::float -  12.3), 2) + POW(69.1 * (12.36 - v.currentLongitude::float) * COS(v.currentLatitude::float / 57.3), 2))")


问:
How to send some data from my Objective-C code to direct MongoDB
```<code>- (IBAction)outputPowerEditingDidEnd:(id)sender
{
    int value = [self outputPowerFromSliderValue:self.outputPowerSlider.value];
    self.resultsTextView.text = [self.resultsTextView.text stringByAppendingFormat:@"Output level changed to: %2d\n\n", value];
    [self updateReaderInventoryConfiguration];
}
</code>```

I want send the value of self.outputPowerSlider.value to MongoDB

Body:
- (IBAction)outputPowerEditingDidEnd:(id)sender
{
    int value = [self outputPowerFromSliderValue:self.outputPowerSlider.value];
    self.resultsTextView.text = [self.resultsTextView.text stringByAppendingFormat:@"Output level changed to: %2d\n\n", value];
    [self updateReaderInventoryConfiguration];
}

I want send the value of self.outputPowerSlider.value to MongoDB


问:
Docker compose ecs fails to deploy (fails when using docker compose up)
I am trying to determine why the cloudformation building of application fails when trying to create resources for BackgroundjobsService (Create failed in cloudformation). The only main differences from other services I have built is that it has no exposed ports and I am using ubuntu instead of php-apache image.

Dockerfile (I made it super simply (basically do nothing)

```<code># Pulling Ubuntu image
FROM ubuntu:20.04
</code>```

docker-compose.yml

```<code>services:
  background_jobs:
    image: 000.dkr.ecr.us-east-1.amazonaws.com/company/job-scheduler
    restart: always
    env_file: ../.env.${ENV}
    build:
      context: "."
</code>```

How I deploy (I verified the enf files exist in the parent directory of job-scheduler).

```<code>cd job-scheduler
ENV=dev docker --context default compose build
docker push 000.dkr.ecr.us-east-1.amazonaws.com/company/job-scheduler:latest
ENV=dev docker --context tcetra-dev compose up
</code>```

I don't know how to find any sort of error logs but the task defination gets created and all my env vars are in there.

Body:
I am trying to determine why the cloudformation building of application fails when trying to create resources for BackgroundjobsService (Create failed in cloudformation). The only main differences from other services I have built is that it has no exposed ports and I am using ubuntu instead of php-apache image.

Dockerfile (I made it super simply (basically do nothing)

# Pulling Ubuntu image
FROM ubuntu:20.04

docker-compose.yml

services:
  background_jobs:
    image: 000.dkr.ecr.us-east-1.amazonaws.com/company/job-scheduler
    restart: always
    env_file: ../.env.${ENV}
    build:
      context: "."

How I deploy (I verified the enf files exist in the parent directory of job-scheduler).

cd job-scheduler
ENV=dev docker --context default compose build
docker push 000.dkr.ecr.us-east-1.amazonaws.com/company/job-scheduler:latest
ENV=dev docker --context tcetra-dev compose up

I don't know how to find any sort of error logs but the task defination gets created and all my env vars are in there.


问:
Add css linear-gradient background image to canvas background
So I have a background gradient style

```<code>background-image: linear-gradient(to top, #1c1d22, #28292e, #34353a, #404247, #4d4f54);
</code>```

I also have a canvas element I wish too use that gradient as the background.

I know you can draw an image as a background on the canvas ::

```<code>var background = new Image();
background.src = "http://www.example.com/image.jpb";
</code>```

^ similar above, but I don't know how to set the linear-gradient style I have for my div background in css as the background for my canvas.

I've tried making the background of the canvas transparent and the div behind the style, but was unable too.

I tried Canvas background transparent and background div having the background.

Body:
So I have a background gradient style

background-image: linear-gradient(to top, #1c1d22, #28292e, #34353a, #404247, #4d4f54);

I also have a canvas element I wish too use that gradient as the background.

I know you can draw an image as a background on the canvas ::

var background = new Image();
background.src = "http://www.example.com/image.jpb";

^ similar above, but I don't know how to set the linear-gradient style I have for my div background in css as the background for my canvas.

I've tried making the background of the canvas transparent and the div behind the style, but was unable too.

I tried Canvas background transparent and background div having the background.


问:
TypeError: unhashable type: 'list' when trying to explode() dataframe
I've been looking around for a way to pd.exlode() my entire dataframe that contains lists in the fields to break out the lists out into rows of their own.

The typical way of achieving this seems to be doing something like this:

```<code>df.set_index('Column_Name').apply(pd.Series.explode).reset_index()
</code>```

Although when I try and do this to my dataframe I receive  this error

TypeError: unhashable type: 'list'

Would anyone know why I'd be receiving this error? My pandas version is 1.5.2

Body:
I've been looking around for a way to pd.exlode() my entire dataframe that contains lists in the fields to break out the lists out into rows of their own.

The typical way of achieving this seems to be doing something like this:

df.set_index('Column_Name').apply(pd.Series.explode).reset_index()

Although when I try and do this to my dataframe I receive  this error

TypeError: unhashable type: 'list'

Would anyone know why I'd be receiving this error? My pandas version is 1.5.2


问:
Scipy optimize curve fit issue using Timestamp X values
Just posting this in case others have a similar problem.  I was analyzing my weather station temperature data using scipy.optimize.curve_fit in a python jupyter notebook in vscode. fitting outdoor temp (ten minute intervals) against the UTC timestamp, which is of course a very large number (1.5X10e09 to 1.65x10e09).  This is a sinewave curve fit with a year period. optimize.curve_fit failed to actually make any progress and since it didn't improve the SofS it stopped with no change to the initial guesses.  Acting on a hunch that it was choking on the large magnitude of the UTC numbers I then divided them by 10e6 and changed my initial guesses of frequency (x10e6) and phase (/10e06).  I then got a solution. Here is the working code, including how to get full output from optimize.curve_fit as an infodict.  (Could not find any examples of that; turns out you have to all the arguments in front of the equal sign to get it working.)

from scipy import optimize
def test_func(t, a,b,c,d):
return a * np.sin(b * t + c) + d

print (test_func(t[0], guess[0], guess[1], guess[2], guess[3]) -data[0])

params, params_covariance, info, mesg, ier  = optimize.curve_fit(test_func, t, data,p0=guess,full_output=True)

print(params, guess)
print (params_covariance)
print (info)
print (mesg)
print(ier)

data_fit=params[0]*np.sin(params[1] * t + params[2]) + params[3]

plt.plot(t, data, '.')
plt.plot(t, test_func(t, guess[0],guess[1],guess[2],guess[3]), label='first guess')
plt.plot(t, test_func(t,params[0],params[1],params[2],params[3]), label='after fitting')
plt.legend()
plt.show()


问:
How to broadcast a list of data into dataframe (Or multiIndex )
I have a big dataframe its about 200k of rows and 3 columns (x, y, z). Some rows doesn't have y,z values and just have x value. I want to make a new column that first set of data with z value be 1,second one be 2,then 3, etc. Or make a multiIndex same format.

Following image shows what I mean

Like this image

I made a new column called "NO." and put zero as initial value. Then
I tried to record the index of where I want the new column get a new value. with following code

```<code>df = pd.read_fwf(path, header=None, names=['x','y','z'])
df['NO.']=0
index_NO_changed = df.index[df['z'].isnull()]
</code>```

Then I loop through it and change the number:

```<code>for i in range(len(index_NO_changed)-1):
    df['NO.'].iloc[index_NO_changed[i]:index_NO_changed[i+1]]=i+1

df['NO.'].iloc[index_NO_changed[-1]:]=len(index_NO_changed)
</code>```

But the problem is I get a warning that "

```<code>A value is trying to be set on a copy of a slice from a DataFrame
</code>```

I was wondering
Is there any better way? Is creating multiIndex instead of adding another column easier considering size of dataframe?

Body:
I have a big dataframe its about 200k of rows and 3 columns (x, y, z). Some rows doesn't have y,z values and just have x value. I want to make a new column that first set of data with z value be 1,second one be 2,then 3, etc. Or make a multiIndex same format.

Following image shows what I mean

Like this image

I made a new column called "NO." and put zero as initial value. Then
I tried to record the index of where I want the new column get a new value. with following code

df = pd.read_fwf(path, header=None, names=['x','y','z'])
df['NO.']=0
index_NO_changed = df.index[df['z'].isnull()]

Then I loop through it and change the number:

for i in range(len(index_NO_changed)-1):
    df['NO.'].iloc[index_NO_changed[i]:index_NO_changed[i+1]]=i+1

df['NO.'].iloc[index_NO_changed[-1]:]=len(index_NO_changed)

But the problem is I get a warning that "

A value is trying to be set on a copy of a slice from a DataFrame

I was wondering
Is there any better way? Is creating multiIndex instead of adding another column easier considering size of dataframe?


问:
What is the proper non ascii (UTF-8) email message text encoding in a multipart message
I would like to send an email message with attachments. So the message should be multipart.

The encoded message body looks like:

```<code>From: another@address
To: an@address
Subject: Unimportant message
Content-Type: multipart/mixed; boundary="----=_Part_0_1457006650.1670256299458"
 ...
------=_Part_0_1457006650.1670256299458
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Hello,

=E2=80=9ESomething here=E2=80=9C

------=_Part_0_1457006650.1670256299458
Content-Type: image/png; name=sample.png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=sample.png
Content-Description: sample.png

iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9
  ...
FElEQVQY02P8z8WABzAxMIxKYwIATTQBHSBDi6AAAAAASUVORK5CYII=
------=_Part_0_1457006650.1670256299458--
</code>```

Web MS Outlook and Gmail do not display non ASCII characters correctly showing a placeholder for each UTF-8 byte in the message body. For example:

I tried different Transfer-Message-Encoding values and different multipart layouts (multiple top-level sections, and nested as parts inside the root-multipart) but the result seem the same - it seems that Web Outlook does take into account the transfer encoding, but does not recognize the message text encoding as UTF-8.

Is this a problem with Outlook Web? Or the message should have some additional meta information or different multipart layout?

I probably could use an HTML encoding, but the message is generated from a template, so all non-ASCII symbols will have to be converted to entities automatically, if I understand correctly. We do not need any fancy formatting besides plain text message, so that option seems over-complicated.

Body:
I would like to send an email message with attachments. So the message should be multipart.

The encoded message body looks like:

From: another@address
To: an@address
Subject: Unimportant message
Content-Type: multipart/mixed; boundary="----=_Part_0_1457006650.1670256299458"
 ...
------=_Part_0_1457006650.1670256299458
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Hello,

=E2=80=9ESomething here=E2=80=9C

------=_Part_0_1457006650.1670256299458
Content-Type: image/png; name=sample.png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=sample.png
Content-Description: sample.png

iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9
  ...
FElEQVQY02P8z8WABzAxMIxKYwIATTQBHSBDi6AAAAAASUVORK5CYII=
------=_Part_0_1457006650.1670256299458--

Web MS Outlook and Gmail do not display non ASCII characters correctly showing a placeholder for each UTF-8 byte in the message body. For example:

I tried different Transfer-Message-Encoding values and different multipart layouts (multiple top-level sections, and nested as parts inside the root-multipart) but the result seem the same - it seems that Web Outlook does take into account the transfer encoding, but does not recognize the message text encoding as UTF-8.

Is this a problem with Outlook Web? Or the message should have some additional meta information or different multipart layout?

I probably could use an HTML encoding, but the message is generated from a template, so all non-ASCII symbols will have to be converted to entities automatically, if I understand correctly. We do not need any fancy formatting besides plain text message, so that option seems over-complicated.


问:
How can I limit the number of requests my Ktor Clientside can make to an endpoint?
I am using the Notion API and weirdly enough, i never recieve the error code for exceeding the rate limit, my request just get timeouted out, even with 3 retries spaced by 15 seconds each but I know I am exceeding the number of 3 request per seconds.

I found some thing in the documentation of ktor client side but I didn't understand how it works
Documentation

I didn't understand what I tried, it made requests slower but not enough to be below 333ms
I found some github things but it was made for Ktor server and I am using ktor client


问:
using Adobe Acrobat SDK in linux
Hi i'm trying to automate PDF to HTML conversion on my linux cloud using Adobe Acrobat SDK. I know there are a lot of PDF to HTML packages out there but nothing preserves the layout of my pdf as Adobe does. Is there a way to call Adobe Acrobat services from my python script on a linux machine? I'm ready to pay for the SDK.
Note: I tried to buy Adobe Acrobat but they explicitly stated that it's only for Mac and Windows.

I'm using Adobe Acrobat DC on my windows pc and is working flawlessly.

```<code>src = 'location to pdf file'
AvDoc = Dispatch("AcroExch.AVDoc")
if AvDoc.Open(src, ""):
    pdDoc = AvDoc.GetPDDoc()
    jsObject = pdDoc.GetJSObject()
    jsObject.SaveAs(filename+ ".html", "com.adobe.acrobat.html")
</code>```

i need the same on my Ubuntu machine. Is there a way to install Adobe Acrobat 2021 SDK on my ubuntu machine? or any other API services from adobe? Please help.

Title: using Adobe Acrobat SDK in linux

Body:
Hi i'm trying to automate PDF to HTML conversion on my linux cloud using Adobe Acrobat SDK. I know there are a lot of PDF to HTML packages out there but nothing preserves the layout of my pdf as Adobe does. Is there a way to call Adobe Acrobat services from my python script on a linux machine? I'm ready to pay for the SDK.
Note: I tried to buy Adobe Acrobat but they explicitly stated that it's only for Mac and Windows.

I'm using Adobe Acrobat DC on my windows pc and is working flawlessly.

src = 'location to pdf file'
AvDoc = Dispatch("AcroExch.AVDoc")
if AvDoc.Open(src, ""):
    pdDoc = AvDoc.GetPDDoc()
    jsObject = pdDoc.GetJSObject()
    jsObject.SaveAs(filename+ ".html", "com.adobe.acrobat.html")

i need the same on my Ubuntu machine. Is there a way to install Adobe Acrobat 2021 SDK on my ubuntu machine? or any other API services from adobe? Please help.


问:
Notify Mturk Workers via AWS CloudShell
I am trying to notify my mturk workers in AWS CloudShell using the following code:

aws mturk notify-workers --subject test --message-text test --worker-ids test

I received the following error message:

Could not connect to the endpoint URL: "https://mturk-requester.us-west-2.amazonaws.com/"

I have connected AWS to my Mturk account, configured AWS using my keys, and I have checked that my region is correct.

Any suggestions would be greatly appreciated.

Title: Notify Mturk Workers via AWS CloudShell


问:
Python SQLALCHEMY issue
I am in the beginner phase of learning Python/coding and I would love to get your input/help.

I am trying to build a website that will have a database to store some data (users, notes etc).

I am using FLASK and SQLALCHEMY for this project but I am not able to start/connect the database. Could you please help me and see what I am doing wrong?

Models.py file:

```<code>from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    last_name = db.Column(db.String(150))
    notes = db.relationship('Note')
</code>```

init.py file:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
from sqlalchemy import create_engine

db = SQLAlchemy()
DB_NAME = "database.db"

def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "dkaodkocmasoxmawowma"
    app.config["SQLALCHEMY_DATABASE_URI"] = f'sqlite:////{DB_NAME}'
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix="/")
    app.register_blueprint(auth, url_prefix="/")

    from .models import User, Note

    with app.app_context():
        db.create_all()

    return app

</code>```

The code runs but it seems like no DB is created. When I open the files I can't see any DB?

I have tried different approaches but I don't get it to work.

Title: Python SQLALCHEMY issue

Body:
I am in the beginner phase of learning Python/coding and I would love to get your input/help.

I am trying to build a website that will have a database to store some data (users, notes etc).

I am using FLASK and SQLALCHEMY for this project but I am not able to start/connect the database. Could you please help me and see what I am doing wrong?

Models.py file:

from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    last_name = db.Column(db.String(150))
    notes = db.relationship('Note')

init.py file:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
from sqlalchemy import create_engine

db = SQLAlchemy()
DB_NAME = "database.db"

def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "dkaodkocmasoxmawowma"
    app.config["SQLALCHEMY_DATABASE_URI"] = f'sqlite:////{DB_NAME}'
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix="/")
    app.register_blueprint(auth, url_prefix="/")

    from .models import User, Note

    with app.app_context():
        db.create_all()

    return app

The code runs but it seems like no DB is created. When I open the files I can't see any DB?

I have tried different approaches but I don't get it to work.


问:
How to create a wii option selector with devkitpro?
How to create a wii options selector like wii mod lite? (devkitpro + C) wii mod lite options selector

i searched and searched, but i didnt found anything


问:
migration with USING array[value] corrupt data
I am using typeorm and postgress in nestjs.
I've created migration script to change Table Column from enum to enum[] and set old value as first element in the array:

```<code>
export class MultiSpecialities implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE "visits" ALTER COLUMN "segmentTag"
        TYPE "public"."visits_segmenttag_enum"[] USING array[segmentTag]`);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
          //.....
    }

}
</code>```

the result is the column type changed but the previous data has corrupted, i.e it trimmed the value first & last letter.
,e.g:

suppose to be: gastroenterology , dental care

Body:
I am using typeorm and postgress in nestjs.
I've created migration script to change Table Column from enum to enum[] and set old value as first element in the array:

export class MultiSpecialities implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE "visits" ALTER COLUMN "segmentTag"
        TYPE "public"."visits_segmenttag_enum"[] USING array[segmentTag]`);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
          //.....
    }

}

the result is the column type changed but the previous data has corrupted, i.e it trimmed the value first & last letter.
,e.g:

suppose to be: gastroenterology , dental care


问:
DigitalOcean Kubernetes NFS mount timed out when accessing across nodes
I run NFS server in kubernetes:

apiVersion: v1
kind: Pod
metadata:
  ...
spec:
  containers:
  - image: k8s.gcr.io/volume-nfs:0.8
    imagePullPolicy: Always
    name: nfs-server
    ports:
    - containerPort: 2049
      name: nfs
      protocol: TCP
    - containerPort: 20048
      name: mountd
      protocol: TCP
    - containerPort: 111
      name: rpcbind
      protocol: TCP
    resources: {}
    securityContext:
      privileged: true
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /exports
      name: nfs-server
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-xlk4c
      readOnly: true
  dnsPolicy: ClusterFirst
  volumes:
  - name: nfs-server
    persistentVolumeClaim:
      claimName: nfs-server
  - name: kube-api-access-xlk4c
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          expirationSeconds: 3607
          path: token
      - configMap:
          items:
          - key: ca.crt
            path: ca.crt
          name: kube-root-ca.crt
      - downwardAPI:
          items:
          - fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
            path: namespace
```
<p>I mount it directly from the pod in the same namespace:</p>
<pre class="lang-yaml prettyprint-override"><code>spec:
  containers:
    volumeMounts:
    - mountPath: /mnt/files
      name: files
  volumes:
  - name: files
    nfs:
      path: /
      server: 10.245.16.93
</code>```

Here 10.245.16.93 is a cluster IP of the NFS service:

```<code>NAMESPACE        NAME                                 TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)                      AGE
my-namespace   nfs-server                        ClusterIP      10.245.16.93     <none>           2049/TCP,20048/TCP,111/TCP   14m
</code>```

The NFS service:

```<code>Name:              nfs-server
Namespace:         my-namespace
Labels:            <none>
Annotations:       <none>
Selector:          name=nfs-server
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                10.245.16.93
IPs:               10.245.16.93
Port:              nfs  2049/TCP
TargetPort:        2049/TCP
Endpoints:         10.244.0.21:2049
Port:              mountd  20048/TCP
TargetPort:        20048/TCP
Endpoints:         10.244.0.21:20048
Port:              rpcbind  111/TCP
TargetPort:        111/TCP
Endpoints:         10.244.0.21:111
Session Affinity:  None
Events:            <none>
</code>```

It works fine if I create a single-node cluster in DOKS. However when it's a cluster with multiple nodes and NFS server pod and the pod where I mount the NFS volume from are on different nodes I get the following error:

```<code>  Warning  FailedMount       116s (x3 over 11m)     kubelet             Unable to attach or mount volumes: unmounted volumes=[files], unattached volumes=[files kube-api-access-w44kg]: timed out waiting for the condition
  Warning  FailedMount       57s (x4 over 10m)      kubelet             MountVolume.SetUp failed for volume "files" : mount failed: exit status 32
Mounting command: mount
Mounting arguments: -t nfs 10.245.16.93:/ /var/lib/kubelet/pods/0995510c-f6e9-403c-8ac5-dd0e9a1bf151/volumes/kubernetes.io~nfs/files
Output: mount.nfs: Connection timed out
</code>```

Body:
I run NFS server in kubernetes:

apiVersion: v1
kind: Pod
metadata:
  ...
spec:
  containers:
  - image: k8s.gcr.io/volume-nfs:0.8
    imagePullPolicy: Always
    name: nfs-server
    ports:
    - containerPort: 2049
      name: nfs
      protocol: TCP
    - containerPort: 20048
      name: mountd
      protocol: TCP
    - containerPort: 111
      name: rpcbind
      protocol: TCP
    resources: {}
    securityContext:
      privileged: true
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /exports
      name: nfs-server
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-xlk4c
      readOnly: true
  dnsPolicy: ClusterFirst
  volumes:
  - name: nfs-server
    persistentVolumeClaim:
      claimName: nfs-server
  - name: kube-api-access-xlk4c
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          expirationSeconds: 3607
          path: token
      - configMap:
          items:
          - key: ca.crt
            path: ca.crt
          name: kube-root-ca.crt
      - downwardAPI:
          items:
          - fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
            path: namespace

I mount it directly from the pod in the same namespace:

spec:
  containers:
    volumeMounts:
    - mountPath: /mnt/files
      name: files
  volumes:
  - name: files
    nfs:
      path: /
      server: 10.245.16.93

Here 10.245.16.93 is a cluster IP of the NFS service:

NAMESPACE        NAME                                 TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)                      AGE
my-namespace   nfs-server                        ClusterIP      10.245.16.93     <none>           2049/TCP,20048/TCP,111/TCP   14m

The NFS service:

Name:              nfs-server
Namespace:         my-namespace
Labels:            <none>
Annotations:       <none>
Selector:          name=nfs-server
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                10.245.16.93
IPs:               10.245.16.93
Port:              nfs  2049/TCP
TargetPort:        2049/TCP
Endpoints:         10.244.0.21:2049
Port:              mountd  20048/TCP
TargetPort:        20048/TCP
Endpoints:         10.244.0.21:20048
Port:              rpcbind  111/TCP
TargetPort:        111/TCP
Endpoints:         10.244.0.21:111
Session Affinity:  None
Events:            <none>

It works fine if I create a single-node cluster in DOKS. However when it's a cluster with multiple nodes and NFS server pod and the pod where I mount the NFS volume from are on different nodes I get the following error:

  Warning  FailedMount       116s (x3 over 11m)     kubelet             Unable to attach or mount volumes: unmounted volumes=[files], unattached volumes=[files kube-api-access-w44kg]: timed out waiting for the condition
  Warning  FailedMount       57s (x4 over 10m)      kubelet             MountVolume.SetUp failed for volume "files" : mount failed: exit status 32
Mounting command: mount
Mounting arguments: -t nfs 10.245.16.93:/ /var/lib/kubelet/pods/0995510c-f6e9-403c-8ac5-dd0e9a1bf151/volumes/kubernetes.io~nfs/files
Output: mount.nfs: Connection timed out


问:
filter to schedule meetings using DateTime in Genexus
I started programming a little while ago and started a project on genexus to schedule meetings for a company, which needs rules so as not to have appointments at the same times.
I made the rules using date and they were working, but when I switched to datetime they don't work anymore. I dont know Genexus syntax for that, if anyone can help with this I would appreciate it.</p>
```<code>do case
        case (LocacaoInicio <= &DTInicio and LocacaoFinal >= &DTInicio)
            or (LocacaoInicio <= &DTFinal and LocacaoFinal >= &DTFinal)
            &MensagemValidacao2 = 'Error'

        case (LocacaoInicio >= &DTInicio and LocacaoFinal <= &DTInicio)
            or (LocacaoInicio >= &DTInicio and LocacaoFinal <= &DTFinal)
            &MensagemValidacao2 = 'Error'

        case (LocacaoInicio < &DTFinal and LocacaoFinal < &DTFinal)
            or (LocacaoInicio > &DTInicio and LocacaoFinal > &DTInicio)
            &MensagemValidacao2 = 'ERROR'

        case (LocacaoInicio > &DTFinal and LocacaoFinal > &DTFinal)
            or (LocacaoInicio < &DTInicio and LocacaoFinal < &DTInicio)
            &MensagemValidacao2 = 'Error '
    endcase
</code>```
```<code>translation of attributes and variables
locacaoinicio = InicialDate
locacaofinal = FinalDate
&mensagemvalidacao2 = &validationMassege
&DTFinal = &DateTimeFinal
&DTInicio = &DateTimeInicio
</code>```

Body:
I started programming a little while ago and started a project on genexus to schedule meetings for a company, which needs rules so as not to have appointments at the same times.
I made the rules using date and they were working, but when I switched to datetime they don't work anymore. I dont know Genexus syntax for that, if anyone can help with this I would appreciate it.

do case
        case (LocacaoInicio <= &DTInicio and LocacaoFinal >= &DTInicio)
            or (LocacaoInicio <= &DTFinal and LocacaoFinal >= &DTFinal)
            &MensagemValidacao2 = 'Error'

        case (LocacaoInicio >= &DTInicio and LocacaoFinal <= &DTInicio)
            or (LocacaoInicio >= &DTInicio and LocacaoFinal <= &DTFinal)
            &MensagemValidacao2 = 'Error'

        case (LocacaoInicio < &DTFinal and LocacaoFinal < &DTFinal)
            or (LocacaoInicio > &DTInicio and LocacaoFinal > &DTInicio)
            &MensagemValidacao2 = 'ERROR'

        case (LocacaoInicio > &DTFinal and LocacaoFinal > &DTFinal)
            or (LocacaoInicio < &DTInicio and LocacaoFinal < &DTInicio)
            &MensagemValidacao2 = 'Error '
    endcase

translation of attributes and variables
locacaoinicio = InicialDate
locacaofinal = FinalDate
&mensagemvalidacao2 = &validationMassege
&DTFinal = &DateTimeFinal
&DTInicio = &DateTimeInicio


问:
table has found to column named
My issue is that when i submit my registration form to back it up, the page shows an operationalError and doesn't recognise the first item of my model which is the first name. I've tried makeMigrate after all modifications and rewriting all the items to make sure they match.
I've added the html and the view to make it more clear as to what im working with
i'm a beginner so any help is welcome !

```<code>def registration_view(request):
    if 'email' in request.GET:
        newUser = User(firstname=request.GET['firstname'],
                      lastname=request.GET['lastname'],
                      country=request.GET['country'],
                      email=request.GET['email'],
                      phone=request.GET['phone'],
                      password=request.GET['password'],
                      gender=request.GET['gender'])
        newUser.save()
        return redirect('/signin')
    else:
        response = render(request, 'registration.html')
    return response
</code>```
```<code>from django.db import models

class User(models.Model):
    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=50)
    country = models.CharField(max_length=50)
    email = models.EmailField(max_length=50)
    phone = models.CharField(max_length=30)
    password = models.CharField(max_length=128)
    GENDER_CHOICES = (
        ('M','Male'),
        ('F','Female'),
        ('X','X'),
        )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    friends = models.ManyToManyField('self')
    conjoint = models.OneToOneField('self', on_delete=models.CASCADE)
    def __str__(self):
        return self.firstname + ' ' + self.lastname

class WallMessage(models.Model):
    author = models.ForeignKey('User', on_delete=models.CASCADE)
    content = models.TextField()
    publication_date = models.DateField()
</code>```

<!DOCTYPE html>

     <title> Registration form </title>

    <form action="">

Registration

Please fill in this form to create an account

        First name
        <input type="text" placeholder="Enter first name" name="firstname" id="firstname" required>

        Last name
        <input type="text" placeholder="Enter last name" name="lastname" id="lastname" required>

        Email
        <input type="text" placeholder="Enter Email" name="email" id="email" required>

        Phone number
        <input type="text" placeholder="+32XXXXXXXXXXX" name="phone" id="phone" required>

        Gender
        <select name="gender" id="gender">
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
        </select>

        Country

            <input type="text" placeholder="Country" id="country" name="country">

        Password
        <input type="password" placeholder="Enter Password" name="password" id="password" required>

        Repeat Password
        <input type="password" placeholder="Confirm Password" name="confirmPassword" id="confirmPassword" required>

          <form>
          <input type="submit" name="" value="Submit">
          </form>

```

Title: table has found to column named

Body:
My issue is that when i submit my registration form to back it up, the page shows an operationalError and doesn't recognise the first item of my model which is the first name. I've tried makeMigrate after all modifications and rewriting all the items to make sure they match.
I've added the html and the view to make it more clear as to what im working with
i'm a beginner so any help is welcome !

def registration_view(request):
    if 'email' in request.GET:
        newUser = User(firstname=request.GET['firstname'],
                      lastname=request.GET['lastname'],
                      country=request.GET['country'],
                      email=request.GET['email'],
                      phone=request.GET['phone'],
                      password=request.GET['password'],
                      gender=request.GET['gender'])
        newUser.save()
        return redirect('/signin')
    else:
        response = render(request, 'registration.html')
    return response

from django.db import models

class User(models.Model):
    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=50)
    country = models.CharField(max_length=50)
    email = models.EmailField(max_length=50)
    phone = models.CharField(max_length=30)
    password = models.CharField(max_length=128)
    GENDER_CHOICES = (
        ('M','Male'),
        ('F','Female'),
        ('X','X'),
        )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    friends = models.ManyToManyField('self')
    conjoint = models.OneToOneField('self', on_delete=models.CASCADE)
    def __str__(self):
        return self.firstname + ' ' + self.lastname

class WallMessage(models.Model):
    author = models.ForeignKey('User', on_delete=models.CASCADE)
    content = models.TextField()
    publication_date = models.DateField()

<!DOCTYPE html>

     <title> Registration form </title>

    <form action="">

Registration

Please fill in this form to create an account

        First name
        <input type="text" placeholder="Enter first name" name="firstname" id="firstname" required>

        Last name
        <input type="text" placeholder="Enter last name" name="lastname" id="lastname" required>

        Email
        <input type="text" placeholder="Enter Email" name="email" id="email" required>

        Phone number
        <input type="text" placeholder="+32XXXXXXXXXXX" name="phone" id="phone" required>

        Gender
        <select name="gender" id="gender">
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
        </select>

        Country

            <input type="text" placeholder="Country" id="country" name="country">

        Password
        <input type="password" placeholder="Enter Password" name="password" id="password" required>

        Repeat Password
        <input type="password" placeholder="Confirm Password" name="confirmPassword" id="confirmPassword" required>

          <form>
          <input type="submit" name="" value="Submit">
          </form>