问:
How do I edit variables and update content of a view component using a button within the same component?
Summary: I have a view component with buttons which need to be able to change the details displayed in the rest of the component on click, but i can't figure out how to update the components content and data using an element within the component.

I am using asp.net razor pages to make a simple UI which displays various info grabbed from a JSON file, no database connection or POST functionality necessary.

I want the block of html that displays the data to be a reusable component, so i don't have to rewrite it every time i want to show a different entry in the file. From my research, there are a few options: HTML components, tag helpers, razor components, partial views, and view components. I chose to use a view component since the other options all seemed either outdated or not capable enough to achieve what i wanted. That is, with the exception of razor components, which require blazor to function fully which would also require me to learn a whole new framework and retrofit my program to work for it.

My view component functions to the point where i can invoke it from Index.cs and the component shows all the data from the first log in the list, as desired.

My intention: the default entryNo value is 0, so the component shows the title and date from the first log entry. When a user clicks the "Next" button (inside the component), entryNo becomes 1, and the component shows the title and date of the second entry in the log file.

ViewComponent.cshtml:

```<code>@model FullLog

@{ int entryIndLocal = 0; }

<div>
    <div>@Model[entryNo].Title</div>
    <div>@Model[entryNo].Date</div>
    <button onclick={entryNo++}>Next</button>
</div>
</code>```

What i've tried:

Setting the entryNo value in the view's .cs file and including a function to increment that value when called. I couldn't figure out how to call the function from the cshtml.

Initialising the entryNo variable from within the cshtml file, with the intention of the adding onclick={@entryNo++}. This didn't work either.

Body:
Summary: I have a view component with buttons which need to be able to change the details displayed in the rest of the component on click, but i can't figure out how to update the components content and data using an element within the component.

I am using asp.net razor pages to make a simple UI which displays various info grabbed from a JSON file, no database connection or POST functionality necessary.

I want the block of html that displays the data to be a reusable component, so i don't have to rewrite it every time i want to show a different entry in the file. From my research, there are a few options: HTML components, tag helpers, razor components, partial views, and view components. I chose to use a view component since the other options all seemed either outdated or not capable enough to achieve what i wanted. That is, with the exception of razor components, which require blazor to function fully which would also require me to learn a whole new framework and retrofit my program to work for it.

My view component functions to the point where i can invoke it from Index.cs and the component shows all the data from the first log in the list, as desired.

My intention: the default entryNo value is 0, so the component shows the title and date from the first log entry. When a user clicks the "Next" button (inside the component), entryNo becomes 1, and the component shows the title and date of the second entry in the log file.

ViewComponent.cshtml:

@model FullLog

@{ int entryIndLocal = 0; }

@Model[entryNo].Title

@Model[entryNo].Date

    <button onclick={entryNo++}>Next</button>

What i've tried:

Setting the entryNo value in the view's .cs file and including a function to increment that value when called. I couldn't figure out how to call the function from the cshtml.

Initialising the entryNo variable from within the cshtml file, with the intention of the adding onclick={@entryNo++}. This didn't work either.


来源: stackexchange

问:
What is the Python equivalent to R's bkde function
I have the following line of code in R.

library(KernSmooth)
bkde(x = x, gridsize = 512L, range.x(min(x), max(x)))
```

What would be the Python equivalent?

Here is the documentation for bkde

ContentLicense: CC BY-SA 4.0

Body:
I have the following line of code in R.

library(KernSmooth)
bkde(x = x, gridsize = 512L, range.x(min(x), max(x)))

What would be the Python equivalent?

Here is the documentation for bkde


问:
How to make border responsive?
I finally got my first webpage finished, and got it to look good on both desktop and mobile. But on medium-screens like tablets, it does not look quite right.
I've tried fiddling with the @Media Queries, men I dont quite get it.

The border does not fill the part of the screen I want. What am I missing here?

Thanks!

Code:

https://codepen.io/Ludvigx86/pen/bGjpBmK

body {
  background-image: url(/Images/polkabkg.png);
  background-size: cover;
  border: 2ew solid aliceblue;
  font-family: Geneva, Tahoma, sans-serif;
  letter-spacing: 5px;
  margin: 60px 250px 100px 250px;
}

.navbar {
  display: flex;
  justify-content: center;
  list-style-type: none;
  margin: 10px;
}

.navbar a {
  color: aliceblue;
  display: flex;
  font-size: larger;
  padding: 15px;
  text-decoration: none;
}

.navbar a:hover {
  color: rgb(200, 0, 150);
  transition: 0.3s;
}

.house img {
  width: 30px;
}
.house {
  margin-left: 211px;
  margin-top: 44px;
  position: absolute;
}
.bord img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  padding-bottom: 30px;
  padding-top: 50px;
  width: 70%;
}
.hvem p {
  font-size: large;
  line-height: 40px;
  text-align: center;
}
.container ul {
  color: aliceblue;
  display: flex;
  list-style: none;
  text-align: center;
}

li {
  padding: 30px;
}

ul .kontakt a {
  color: gold;
}

.logo {
  display: flex;
  margin-bottom: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 50vh;
}

.band {
  display: flex;
  margin-bottom: 50px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 40px;
  width: 80%;
}
.mail {
  display: none;
  justify-content: center;
  border: solid 1px gold;
  border-width: 2px;
  border-radius: 10px;
  padding: 10px;
  margin-left: 40px;
  margin-right: 40px;
}
.mail a {
  text-decoration: none;
  color: gold;
}
h3 {
  color: aliceblue;
  text-align: center;
}
.private {
  border: dotted;
  border-color: aliceblue;
  margin-left: 250px;
  margin-right: 250px;
  margin-top: 100px;
}

h2 {
  color: aliceblue;
  font-style: italic;
  margin: 50px;
  text-align: center;
}

.konsert p {
  color: #f0f8ff;
  margin: 300px;
  text-align: center;
}
.sitat p {
  padding-right: 175px;
  text-align: right;
}
p {
  text-align: center;
  color: #f0f8ff;
}
hr {
  border-width: 2px;
}

footer {
  padding: 0px;
  color: #f0f8ff;
}
.container {
  display: flex;
  justify-content: center;
  padding-bottom: 0px;
}
footer img {
  display: flex;
  justify-content: center;
  padding: 15px;
  width: 30px;
}
.header {
  text-align: center;
}

.burger {
  position: absolute;
  top: 0.75rem;
  right: 1rem;
  display: none;
  flex-direction: column;
  justify-content: space-between;
  width: 31px;
  height: 21px;
}
.burger .bar {
  height: 3px;
  width: 100%;
  background-color: aliceblue;
  border-radius: 10px;
}

/* MEDIA QUERIES */

@media screen and (max-width: 768px) {
  body {
    background-image: url(/Images/polkabkg.png);
    background-size: cover;
    font-family: Geneva, Tahoma, sans-serif;
    letter-spacing: 5px;
  }

  .house {
    position: absolute;
    margin: 0px;
  }
  .house {
    position: absolute;
    margin-top: 28px;
    margin-left: 18px;
  }
  .house img {
    width: 15px;
  }
  .navbar {
    display: flex;
    list-style-type: none;
    margin: 0px;
    padding-top: 5px;
  }

  .navbar a {
    color: aliceblue;
    display: flex;
    font-size: smaller;

    text-decoration: none;
  }
  .kontakt {
    display: none;
  }

  ul .navbar {
    padding: 0px;
  }
  li {
    padding: 10px;
    margin-bottom: 15px;
  }

  .logo {
    width: 180px;
    margin-top: 10px;
  }

  body > div:nth-child(3) > h2 {
    margin: 0px;
    font-size: small;
  }
  .sitat p {
    padding-right: 15px;
    text-align: right;
  }

  body {
    border: 0px;
    margin: 0px;
  }
  .navbar {
    display: flex;
  }
  .mail {
    display: flex;
    justify-content: center;
    border: solid 1px gold;
    border-width: 2px;
    border-radius: 10px;
    padding: 10px;
    margin-left: 40px;
    margin-right: 40px;
  }

  .bord img {
    width: 400px;
    margin-top: 0px;
  }
  .hvem p {
    font-size: smaller;
    margin-left: 15px;
  }

  .container ul {
    color: aliceblue;
    display: block;
  }

  .private {
    display: flex;
    border: dotted;
    border-color: aliceblue;
    margin-top: 50px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
  }
  .konsert p {
    display: flex;
    margin: 80px;
  }
}

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  body {
    background-image: url(/Images/polkabkg.png);
    background-size: cover;
    border: 2px solid aliceblue;
    font-family: Geneva, Tahoma, sans-serif;
    letter-spacing: 5px;
    margin: 60px 250px 100px 250px;
  }

  .house {
    position: absolute;
    margin: 0px;
  }
  .house {
    position: absolute;
    margin-top: 28px;
    margin-left: 18px;
  }
  .house img {
    width: 15px;
  }
  .navbar {
    display: flex;
    list-style-type: none;
    margin: 0px;
    padding-top: 5px;
  }

  .navbar a {
    color: aliceblue;
    display: flex;
    font-size: smaller;

    text-decoration: none;
  }
  .kontakt {
    display: none;
  }

  ul .navbar {
    padding: 0px;
  }
  li {
    padding: 10px;
    margin-bottom: 15px;
  }

  .logo {
    width: 180px;
    margin-top: 10px;
  }

  body > div:nth-child(3) > h2 {
    margin: 0px;
    font-size: small;
  }
  .sitat p {
    padding-right: 15px;
    text-align: right;
  }

  body {
    border: 0px;
    margin: 0px;
  }
  .navbar {
    display: flex;
  }
  .mail {
    display: flex;
    justify-content: center;
    border: solid 1px gold;
    border-width: 2px;
    border-radius: 10px;
    padding: 10px;
    margin-left: 40px;
    margin-right: 40px;
  }

  .bord img {
    width: 400px;
    margin-top: 0px;
  }
  .hvem p {
    font-size: smaller;
    margin-left: 15px;
  }

  .container ul {
    color: aliceblue;
    display: block;
  }

  .private {
    display: flex;
    border: dotted;
    border-color: aliceblue;
    margin-top: 50px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
  }
  .konsert p {
    display: flex;
    margin: 80px;
  }
}
```

I've tried fiddling with the @Media Queries, men I dont quite get it.

The border should surround both the content and the navbar.

Title: How to make border responsive?

Body:
I finally got my first webpage finished, and got it to look good on both desktop and mobile. But on medium-screens like tablets, it does not look quite right.
I've tried fiddling with the @Media Queries, men I dont quite get it.

The border does not fill the part of the screen I want. What am I missing here?

Thanks!

Code:

https://codepen.io/Ludvigx86/pen/bGjpBmK

body {
  background-image: url(/Images/polkabkg.png);
  background-size: cover;
  border: 2ew solid aliceblue;
  font-family: Geneva, Tahoma, sans-serif;
  letter-spacing: 5px;
  margin: 60px 250px 100px 250px;
}

.navbar {
  display: flex;
  justify-content: center;
  list-style-type: none;
  margin: 10px;
}

.navbar a {
  color: aliceblue;
  display: flex;
  font-size: larger;
  padding: 15px;
  text-decoration: none;
}

.navbar a:hover {
  color: rgb(200, 0, 150);
  transition: 0.3s;
}

.house img {
  width: 30px;
}
.house {
  margin-left: 211px;
  margin-top: 44px;
  position: absolute;
}
.bord img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  padding-bottom: 30px;
  padding-top: 50px;
  width: 70%;
}
.hvem p {
  font-size: large;
  line-height: 40px;
  text-align: center;
}
.container ul {
  color: aliceblue;
  display: flex;
  list-style: none;
  text-align: center;
}

li {
  padding: 30px;
}

ul .kontakt a {
  color: gold;
}

.logo {
  display: flex;
  margin-bottom: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 50vh;
}

.band {
  display: flex;
  margin-bottom: 50px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 40px;
  width: 80%;
}
.mail {
  display: none;
  justify-content: center;
  border: solid 1px gold;
  border-width: 2px;
  border-radius: 10px;
  padding: 10px;
  margin-left: 40px;
  margin-right: 40px;
}
.mail a {
  text-decoration: none;
  color: gold;
}
h3 {
  color: aliceblue;
  text-align: center;
}
.private {
  border: dotted;
  border-color: aliceblue;
  margin-left: 250px;
  margin-right: 250px;
  margin-top: 100px;
}

h2 {
  color: aliceblue;
  font-style: italic;
  margin: 50px;
  text-align: center;
}

.konsert p {
  color: #f0f8ff;
  margin: 300px;
  text-align: center;
}
.sitat p {
  padding-right: 175px;
  text-align: right;
}
p {
  text-align: center;
  color: #f0f8ff;
}
hr {
  border-width: 2px;
}

footer {
  padding: 0px;
  color: #f0f8ff;
}
.container {
  display: flex;
  justify-content: center;
  padding-bottom: 0px;
}
footer img {
  display: flex;
  justify-content: center;
  padding: 15px;
  width: 30px;
}
.header {
  text-align: center;
}

.burger {
  position: absolute;
  top: 0.75rem;
  right: 1rem;
  display: none;
  flex-direction: column;
  justify-content: space-between;
  width: 31px;
  height: 21px;
}
.burger .bar {
  height: 3px;
  width: 100%;
  background-color: aliceblue;
  border-radius: 10px;
}

/* MEDIA QUERIES */

@media screen and (max-width: 768px) {
  body {
    background-image: url(/Images/polkabkg.png);
    background-size: cover;
    font-family: Geneva, Tahoma, sans-serif;
    letter-spacing: 5px;
  }

  .house {
    position: absolute;
    margin: 0px;
  }
  .house {
    position: absolute;
    margin-top: 28px;
    margin-left: 18px;
  }
  .house img {
    width: 15px;
  }
  .navbar {
    display: flex;
    list-style-type: none;
    margin: 0px;
    padding-top: 5px;
  }

  .navbar a {
    color: aliceblue;
    display: flex;
    font-size: smaller;

    text-decoration: none;
  }
  .kontakt {
    display: none;
  }

  ul .navbar {
    padding: 0px;
  }
  li {
    padding: 10px;
    margin-bottom: 15px;
  }

  .logo {
    width: 180px;
    margin-top: 10px;
  }

  body > div:nth-child(3) > h2 {
    margin: 0px;
    font-size: small;
  }
  .sitat p {
    padding-right: 15px;
    text-align: right;
  }

  body {
    border: 0px;
    margin: 0px;
  }
  .navbar {
    display: flex;
  }
  .mail {
    display: flex;
    justify-content: center;
    border: solid 1px gold;
    border-width: 2px;
    border-radius: 10px;
    padding: 10px;
    margin-left: 40px;
    margin-right: 40px;
  }

  .bord img {
    width: 400px;
    margin-top: 0px;
  }
  .hvem p {
    font-size: smaller;
    margin-left: 15px;
  }

  .container ul {
    color: aliceblue;
    display: block;
  }

  .private {
    display: flex;
    border: dotted;
    border-color: aliceblue;
    margin-top: 50px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
  }
  .konsert p {
    display: flex;
    margin: 80px;
  }
}

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  body {
    background-image: url(/Images/polkabkg.png);
    background-size: cover;
    border: 2px solid aliceblue;
    font-family: Geneva, Tahoma, sans-serif;
    letter-spacing: 5px;
    margin: 60px 250px 100px 250px;
  }

  .house {
    position: absolute;
    margin: 0px;
  }
  .house {
    position: absolute;
    margin-top: 28px;
    margin-left: 18px;
  }
  .house img {
    width: 15px;
  }
  .navbar {
    display: flex;
    list-style-type: none;
    margin: 0px;
    padding-top: 5px;
  }

  .navbar a {
    color: aliceblue;
    display: flex;
    font-size: smaller;

    text-decoration: none;
  }
  .kontakt {
    display: none;
  }

  ul .navbar {
    padding: 0px;
  }
  li {
    padding: 10px;
    margin-bottom: 15px;
  }

  .logo {
    width: 180px;
    margin-top: 10px;
  }

  body > div:nth-child(3) > h2 {
    margin: 0px;
    font-size: small;
  }
  .sitat p {
    padding-right: 15px;
    text-align: right;
  }

  body {
    border: 0px;
    margin: 0px;
  }
  .navbar {
    display: flex;
  }
  .mail {
    display: flex;
    justify-content: center;
    border: solid 1px gold;
    border-width: 2px;
    border-radius: 10px;
    padding: 10px;
    margin-left: 40px;
    margin-right: 40px;
  }

  .bord img {
    width: 400px;
    margin-top: 0px;
  }
  .hvem p {
    font-size: smaller;
    margin-left: 15px;
  }

  .container ul {
    color: aliceblue;
    display: block;
  }

  .private {
    display: flex;
    border: dotted;
    border-color: aliceblue;
    margin-top: 50px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
  }
  .konsert p {
    display: flex;
    margin: 80px;
  }
}

I've tried fiddling with the @Media Queries, men I dont quite get it.

The border should surround both the content and the navbar.


问:
Polar visualization for non-360 deg data with interpolation
I am trying (hard) to find an efficient way to visualize range-bearing data in a fan-shaped image.

So far I have come up with the method shown below using OpenCV's cv2.linearPolar function. However, since my data is only for a sensor opening angle of 120 deg, and not a full circle, it requires some hacks that are not very efficient in order to get the correct results from cv2.linearPolar. I.e. I need to insert empty blocks of data to represent a 360 deg image, in order to transform it, and then crop it afterwards to obtain only the region I am interested in.

Calculating the direct coordinates and mapping from A-->B results in non-interpolated, empty value between each "bearing-line" and does not look visually nice.

Since this need to run in real-time from a fast sensor, I would be interested in learning about another way to achieve this. Perhaps using OpenGL or something else.

Current ineffective method that obtains the wanted result:

```<code>import numpy as np
import cv2
import matplotlib.pyplot as plt

image = np.random.randint(256, size=(256,1000),dtype=np.uint8)
n_beams, n_ranges = image.shape[:2]

opening_angle_deg = 120
angle_res_deg = opening_angle_deg/n_beams

start_v = np.zeros((int(opening_angle_deg/angle_res_deg),n_ranges),dtype=np.uint8)
end_v = np.zeros((int((360-opening_angle_deg*2)/angle_res_deg),n_ranges),dtype=np.uint8)

polar = cv2.vconcat([start_v,image])
polar = cv2.vconcat([polar,end_v])

center = (n_ranges,polar.shape[0]/2)

if n_beams > n_ranges:

    dst = cv2.linearPolar(polar,(center),polar.shape[1]/2,cv2.INTER_LINEAR+cv2.WARP_INVERSE_MAP + cv2.WARP_FILL_OUTLIERS)

    x_max = np.ceil(np.sin(np.deg2rad(opening_angle_deg/2))*polar.shape[1]/2)*2

    dst      = dst     [int(center[1]-x_max/2):int(center[1]+x_max/2),int(dst.shape[1]-polar.shape[1]/2):]
else:
    dst = cv2.linearPolar(polar,(center),polar.shape[0]/2,cv2.INTER_LINEAR+cv2.WARP_INVERSE_MAP + cv2.WARP_FILL_OUTLIERS)

    x_max = np.ceil(np.sin(np.deg2rad(opening_angle_deg/2))*polar.shape[0]/2)*2

    dst      = dst     [int(center[1]-x_max/2):int(center[1]+x_max/2),int(dst.shape[1]-polar.shape[0]/2):]

dst = cv2.transpose(dst)

plt.imshow(dst)
</code>```

Body:
I am trying (hard) to find an efficient way to visualize range-bearing data in a fan-shaped image.

So far I have come up with the method shown below using OpenCV's cv2.linearPolar function. However, since my data is only for a sensor opening angle of 120 deg, and not a full circle, it requires some hacks that are not very efficient in order to get the correct results from cv2.linearPolar. I.e. I need to insert empty blocks of data to represent a 360 deg image, in order to transform it, and then crop it afterwards to obtain only the region I am interested in.

Calculating the direct coordinates and mapping from A-->B results in non-interpolated, empty value between each "bearing-line" and does not look visually nice.

Since this need to run in real-time from a fast sensor, I would be interested in learning about another way to achieve this. Perhaps using OpenGL or something else.

Current ineffective method that obtains the wanted result:

import numpy as np
import cv2
import matplotlib.pyplot as plt

image = np.random.randint(256, size=(256,1000),dtype=np.uint8)
n_beams, n_ranges = image.shape[:2]

opening_angle_deg = 120
angle_res_deg = opening_angle_deg/n_beams

start_v = np.zeros((int(opening_angle_deg/angle_res_deg),n_ranges),dtype=np.uint8)
end_v = np.zeros((int((360-opening_angle_deg*2)/angle_res_deg),n_ranges),dtype=np.uint8)

polar = cv2.vconcat([start_v,image])
polar = cv2.vconcat([polar,end_v])

center = (n_ranges,polar.shape[0]/2)

if n_beams > n_ranges:

    dst = cv2.linearPolar(polar,(center),polar.shape[1]/2,cv2.INTER_LINEAR+cv2.WARP_INVERSE_MAP + cv2.WARP_FILL_OUTLIERS)

    x_max = np.ceil(np.sin(np.deg2rad(opening_angle_deg/2))*polar.shape[1]/2)*2

    dst      = dst     [int(center[1]-x_max/2):int(center[1]+x_max/2),int(dst.shape[1]-polar.shape[1]/2):]
else:
    dst = cv2.linearPolar(polar,(center),polar.shape[0]/2,cv2.INTER_LINEAR+cv2.WARP_INVERSE_MAP + cv2.WARP_FILL_OUTLIERS)

    x_max = np.ceil(np.sin(np.deg2rad(opening_angle_deg/2))*polar.shape[0]/2)*2

    dst      = dst     [int(center[1]-x_max/2):int(center[1]+x_max/2),int(dst.shape[1]-polar.shape[0]/2):]

dst = cv2.transpose(dst)

plt.imshow(dst)


问:
Python File Doesn't Run When Windows Starts
I have a problem. There are two Python files in the startup file. One of them runs seamlessly when Windows starts up, but the other one does not run automatically even though the code is correct. But interestingly, it works when I open it manually.

Code:

from playsound import playsound
from gtts import gTTS
import os

def playSound(path):
    voiceMessage.save(path)
    playsound(path)
    os.remove(path)

vmessage = "Hello World!"
voiceMessage = gTTS(text=vmessage, lang="en", slow=False)

playSound("voicemessage.mp4")
```

In a nutshell>> I want run xxx.pyw file automatically to run the file named voicemessage.mp4. when the Windows starts up.

Body:
I have a problem. There are two Python files in the startup file. One of them runs seamlessly when Windows starts up, but the other one does not run automatically even though the code is correct. But interestingly, it works when I open it manually.

Code:

from playsound import playsound
from gtts import gTTS
import os

def playSound(path):
    voiceMessage.save(path)
    playsound(path)
    os.remove(path)

vmessage = "Hello World!"
voiceMessage = gTTS(text=vmessage, lang="en", slow=False)

playSound("voicemessage.mp4")

In a nutshell>> I want run xxx.pyw file automatically to run the file named voicemessage.mp4. when the Windows starts up.


问:
Django generate thumbnail with MoviePy, problem with Path
How to get the absolute path to a video, that works in development (Windows) and production (Ubuntu), ive tried almost everything, here is the closest I've gotten to a solution, I am trying to generate a thumbnail for a video when its posted.
`

```<code>from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent

def generate_thumbnail(instance):
    filename = Path.joinpath(BASE_DIR, 'media/video_files')
    print(filename)
    thumbnail = VideoFileClip(str(filename)+instance.video.url)
    name = instance.video.url + '.png'
    time = random.randrange(60)
    thumbnail.save_frame('media/uploads/thumbnail' + name, t=time, withmask=True)
    instance.thumbnail = name
</code>```

It never gives me a good path, its ether with '/' or with \ .

```<code>MoviePy error: the file C:\Users\User 1\Desktop\django\lumen\media\video_files/media/uploads/video_files/22/29/Elvis_-_If_I_Can_Dream_Official_Live_Performance_fcw0WKp.mp4 could not be found!
Please check that you entered the correct path.
</code>```

Body:
How to get the absolute path to a video, that works in development (Windows) and production (Ubuntu), ive tried almost everything, here is the closest I've gotten to a solution, I am trying to generate a thumbnail for a video when its posted.
`

from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent

def generate_thumbnail(instance):
    filename = Path.joinpath(BASE_DIR, 'media/video_files')
    print(filename)
    thumbnail = VideoFileClip(str(filename)+instance.video.url)
    name = instance.video.url + '.png'
    time = random.randrange(60)
    thumbnail.save_frame('media/uploads/thumbnail' + name, t=time, withmask=True)
    instance.thumbnail = name

It never gives me a good path, its ether with '/' or with \ .

MoviePy error: the file C:\Users\User 1\Desktop\django\lumen\media\video_files/media/uploads/video_files/22/29/Elvis_-_If_I_Can_Dream_Official_Live_Performance_fcw0WKp.mp4 could not be found!
Please check that you entered the correct path.


问:
influxdb2 / grafana - top x of timeserie values
I search a way to get the top X of value from timeseries influxdb:

the granularity is one minute.
Csv imported:

```<code>#datatype measurement,tag,tag,double,double,double,dateTime:number
HDD,server,hdd_id,Read_IOPS,Write_IOPS,Read_ms,time
HDD,srv1,hdd1,35,33,1,1671233940
HDD,srv1,hdd1,24,69,1,1671234000
HDD,srv1,hdd1,97,57,2,1671234060
HDD,srv1,hdd1,30,78,2,1671234120
HDD,srv1,hdd1,53,83,2,1671234180
HDD,srv1,hdd1,56,85,2,1671234240
HDD,srv1,hdd1,32,25,22,1671234300
HDD,srv1,hdd1,29,89,6,1671234360
HDD,srv1,hdd1,33,41,1,1671234420
HDD,srv1,hdd1,22,15,8,1671234480
HDD,srv1,hdd1,24,95,4,1671234540
…
HDD,srv1,hdd2,35,33,1,1671233940
HDD,srv1,hdd2,24,69,1,1671234000
HDD,srv1,hdd2,97,57,2,1671234060
HDD,srv1,hdd2,30,78,2,1671234120
HDD,srv1,hdd2,53,83,2,1671234180
HDD,srv1,hdd2,56,85,2,1671234240
HDD,srv1,hdd2,32,25,22,1671234300
HDD,srv1,hdd2,29,89,6,1671234360
HDD,srv1,hdd2,33,41,1,1671234420
HDD,srv1,hdd2,22,15,8,1671234480
HDD,srv1,hdd2,24,95,4,1671234540
…
HDD,srv1,hdd3,35,33,1,1671233940
HDD,srv1,hdd3,24,69,1,1671234000
HDD,srv1,hdd3,97,57,2,1671234060
HDD,srv1,hdd3,30,78,2,1671234120
HDD,srv1,hdd3,53,83,2,1671234180
HDD,srv1,hdd3,56,85,2,1671234240
HDD,srv1,hdd3,32,25,22,1671234300
HDD,srv1,hdd3,29,89,6,1671234360
HDD,srv1,hdd3,33,41,1,1671234420
HDD,srv1,hdd3,22,15,8,1671234480
HDD,srv1,hdd3,24,95,4,1671234540
…
</code>```

I try with this query (flux influxdb2), but only 2 point are displayed on the grafana dashboard:

-> I would like to display for example the top 2 of hdd more busiest for Read_IOPS

```<code>import "strings"

|> from(bucket: v.bucket)
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r._measurement == “HDD”)
|> drop(columns: [“server”])
|> filter(fn: (r) => r._field == “HDD_Read_IOPS”)
|> map(fn: (r) => ({r with newhddid: strings.substring(v: r.hdd_id, start: 0, end: 4)}))
|> group(columns: [“newhddid”])
|> highestMax(n: 2, groupColumns: [“newhddid”])
|> aggregateWindow(column: “_value”, every: v.windowPeriod, fn: mean)
</code>```

Many thanks for any help.

Body:
I search a way to get the top X of value from timeseries influxdb:

the granularity is one minute.
Csv imported:

#datatype measurement,tag,tag,double,double,double,dateTime:number
HDD,server,hdd_id,Read_IOPS,Write_IOPS,Read_ms,time
HDD,srv1,hdd1,35,33,1,1671233940
HDD,srv1,hdd1,24,69,1,1671234000
HDD,srv1,hdd1,97,57,2,1671234060
HDD,srv1,hdd1,30,78,2,1671234120
HDD,srv1,hdd1,53,83,2,1671234180
HDD,srv1,hdd1,56,85,2,1671234240
HDD,srv1,hdd1,32,25,22,1671234300
HDD,srv1,hdd1,29,89,6,1671234360
HDD,srv1,hdd1,33,41,1,1671234420
HDD,srv1,hdd1,22,15,8,1671234480
HDD,srv1,hdd1,24,95,4,1671234540
…
HDD,srv1,hdd2,35,33,1,1671233940
HDD,srv1,hdd2,24,69,1,1671234000
HDD,srv1,hdd2,97,57,2,1671234060
HDD,srv1,hdd2,30,78,2,1671234120
HDD,srv1,hdd2,53,83,2,1671234180
HDD,srv1,hdd2,56,85,2,1671234240
HDD,srv1,hdd2,32,25,22,1671234300
HDD,srv1,hdd2,29,89,6,1671234360
HDD,srv1,hdd2,33,41,1,1671234420
HDD,srv1,hdd2,22,15,8,1671234480
HDD,srv1,hdd2,24,95,4,1671234540
…
HDD,srv1,hdd3,35,33,1,1671233940
HDD,srv1,hdd3,24,69,1,1671234000
HDD,srv1,hdd3,97,57,2,1671234060
HDD,srv1,hdd3,30,78,2,1671234120
HDD,srv1,hdd3,53,83,2,1671234180
HDD,srv1,hdd3,56,85,2,1671234240
HDD,srv1,hdd3,32,25,22,1671234300
HDD,srv1,hdd3,29,89,6,1671234360
HDD,srv1,hdd3,33,41,1,1671234420
HDD,srv1,hdd3,22,15,8,1671234480
HDD,srv1,hdd3,24,95,4,1671234540
…

I try with this query (flux influxdb2), but only 2 point are displayed on the grafana dashboard:

-> I would like to display for example the top 2 of hdd more busiest for Read_IOPS

import "strings"

|> from(bucket: v.bucket)
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r._measurement == “HDD”)
|> drop(columns: [“server”])
|> filter(fn: (r) => r._field == “HDD_Read_IOPS”)
|> map(fn: (r) => ({r with newhddid: strings.substring(v: r.hdd_id, start: 0, end: 4)}))
|> group(columns: [“newhddid”])
|> highestMax(n: 2, groupColumns: [“newhddid”])
|> aggregateWindow(column: “_value”, every: v.windowPeriod, fn: mean)

Many thanks for any help.


问:
Kafka replicator topic renaming
I'm wondering if it's possible to replicate multiple topics at once and rename them on a topic by topic basis.

I'm looking to use confluent replicator.

I know I can use ${topic}.whatever

But if my topics are named
Example.cluster1.topic and example.cluster1.topic1

How would I rename these to
Example.cluster2.topic
Example.cluster2.topic1

Thanks

I have tried following the documentation here - https://docs.confluent.io/platform/current/multi-dc-deployments/replicator/index.html#architecture but have been unable to achieve the desired outcome.

Title: Kafka replicator topic renaming


问:
File won't copy to Docker file?
I run this file (partial) under "root" account on my Synology.
but it won't start, in my error log I got this message:

[FATAL tini (9)] exec /home/qgis/cmd.sh failed: No such file or directory

Can someone help me please...

This is the part where cmd.sh is added:

```<code>ENV TINI_VERSION v0.19.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini
RUN chmod +x /tini

ENV QGIS_PREFIX_PATH /usr
ENV QGIS_SERVER_LOG_STDERR 1
ENV QGIS_SERVER_LOG_LEVEL 2

COPY cmd.sh /home/qgis/cmd.sh
RUN chmod -R 777 /home/qgis/cmd.sh
RUN chown qgis:qgis /home/qgis/cmd.sh

USER qgis
WORKDIR /home/qgis

ENTRYPOINT ["/tini", "--"]

CMD ["/home/qgis/cmd.sh"]
create a file cmd.sh with this content:
</code>```

This is the cmd.sh file:

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

[[ $DEBUG == "1" ]] && env

exec /usr/bin/xvfb-run --auto-servernum --server-num=1 /usr/bin/spawn-fcgi -p 5555 -n -d /home/qgis -- /usr/lib/cgi-bin/qgis_mapserv.fcgi
</code>```

Title: File won't copy to Docker file?

Body:
I run this file (partial) under "root" account on my Synology.
but it won't start, in my error log I got this message:

[FATAL tini (9)] exec /home/qgis/cmd.sh failed: No such file or directory

Can someone help me please...

This is the part where cmd.sh is added:

ENV TINI_VERSION v0.19.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini
RUN chmod +x /tini

ENV QGIS_PREFIX_PATH /usr
ENV QGIS_SERVER_LOG_STDERR 1
ENV QGIS_SERVER_LOG_LEVEL 2

COPY cmd.sh /home/qgis/cmd.sh
RUN chmod -R 777 /home/qgis/cmd.sh
RUN chown qgis:qgis /home/qgis/cmd.sh

USER qgis
WORKDIR /home/qgis

ENTRYPOINT ["/tini", "--"]

CMD ["/home/qgis/cmd.sh"]
create a file cmd.sh with this content:

This is the cmd.sh file:

#!/bin/bash

[[ $DEBUG == "1" ]] && env

exec /usr/bin/xvfb-run --auto-servernum --server-num=1 /usr/bin/spawn-fcgi -p 5555 -n -d /home/qgis -- /usr/lib/cgi-bin/qgis_mapserv.fcgi


问:
Efficient file format to store nested objects
I am working on a python project where I have nested objects. I know the structure of each entity. I am looking for a way to save it.

Here is a very simple example:

A User always have:

an id (int)

a name: (string)

a list of items (0, 1 or many)

An item always have:

a name (str)

a price (int)

```<code>to_save_data = [
    { 'id': 8, 'name': 'Alice', 'items': [ { 'name': 'Sword', 'price': 10 } ] },
    { 'id': 23, 'name': 'Bob', 'items': [ { 'name': 'Axe', 'price': 4 }, { 'name': 'Shield', 'price': 33 } ] },
    { 'id': 57, 'name': 'Charlie', 'items': [] },
]
</code>```

I need to store the data with following constrainst:

All in one file, one line should correspond to one user

I can read / write line by line. I can add a line at the end of file (without reading all and rewriting all)

values are not encoded (like a csv file for instance but not like a pickle file)

efficient in terms of space.

I started with JSON but it is not efficient in terms of space because the name of each field is repated and written for each line.
In this example, words "id", "name" and "items" are written 3 times (if I had 1B users, it would be written 1B times, same problem for items).

I am looking for something that would look like this for instance:

A header on the first line that describes the data-structure. then:

```<code>8, 'Alice', [ ('Sword', 10) ]
23, 'Bob', [ ('Axe', 4), ('Shield', 33) ]
57, 'Charlie', []
</code>```

I could implement it but it would take time and I feel I would reinvent the wheel.

Is there an existing file-format and python module to handle that ?

Body:
I am working on a python project where I have nested objects. I know the structure of each entity. I am looking for a way to save it.

Here is a very simple example:

A User always have:

an id (int)

a name: (string)

a list of items (0, 1 or many)

An item always have:

a name (str)

a price (int)

to_save_data = [
    { 'id': 8, 'name': 'Alice', 'items': [ { 'name': 'Sword', 'price': 10 } ] },
    { 'id': 23, 'name': 'Bob', 'items': [ { 'name': 'Axe', 'price': 4 }, { 'name': 'Shield', 'price': 33 } ] },
    { 'id': 57, 'name': 'Charlie', 'items': [] },
]

I need to store the data with following constrainst:

All in one file, one line should correspond to one user

I can read / write line by line. I can add a line at the end of file (without reading all and rewriting all)

values are not encoded (like a csv file for instance but not like a pickle file)

efficient in terms of space.

I started with JSON but it is not efficient in terms of space because the name of each field is repated and written for each line.
In this example, words "id", "name" and "items" are written 3 times (if I had 1B users, it would be written 1B times, same problem for items).

I am looking for something that would look like this for instance:

A header on the first line that describes the data-structure. then:

8, 'Alice', [ ('Sword', 10) ]
23, 'Bob', [ ('Axe', 4), ('Shield', 33) ]
57, 'Charlie', []

I could implement it but it would take time and I feel I would reinvent the wheel.

Is there an existing file-format and python module to handle that ?


问:
Evaluating probability that a hash function is uniform
I inserted M items into a hash table with N buckets, and found that the largest bucket has K items. How can I compute the p-value corresponding to the null hypothesis that my hash function is uniform?

I know that one can derive various with-high-probability asymptotic bounds on K as a function of M and N. But it's not obvious how to utilize those asymptotic bounds to get a concrete p-value.

My practical use-case is that I want my application to automatically report a warning if it detects poor hash-balancing. Something this theoretically grounded is probably overkill, but why not use something sound if possible.


问:
Powershell - Export CSV file correctly
I am trying to export inbox rules for users via powershell.  But , I can not get correctly export as CSV file.

```<code>Get-Mailbox "user@contoso.com" |Get-InboxRule | select name,Identity,ForwardTo,ForwardAsAttachmentTo, RedirectTo, DeleteMessage , Description
</code>```

Output :

```<code>Name                  : [forward apply]
Identity              : contoso.local/IT/USERS/User\3315794656083574785
ForwardTo             :
ForwardAsAttachmentTo :
RedirectTo            : {"user1@gmail.com" [SMTP:user1@gmail.com]}
DeleteMessage         : False
Description           : Take the following actions:
                            redirect the message to 'user1@gmail.com'
                            and stop processing more rules on this message
</code>```

After  I want to export it. But, I am not getting to export as correctly for attributes such as Description and RedirectTo attribute.

```<code>Get-Mailbox "user@contoso.com" |Get-InboxRule | select name,Identity,ForwardTo,ForwardAsAttachmentTo, RedirectTo, DeleteMessage,Description | Export-csv "C:\temp\inbox_ruleexport.csv" -NoTypeInformation -encoding UTF8
</code>```

Output :

```<code>"Name","Identity","ForwardTo","ForwardAsAttachmentTo","RedirectTo","DeleteMessage","Description"
"[forward apply]","contoso.local/IT/USERS/User\3315794656083574785",,,"Microsoft.Exchange.Data.Storage.Management.ADRecipientOrAddress[]","False","Take the following actions:
    redirect the message to 'user1@gmail.com'
    and stop processing more rules on this message
"
</code>```

Title: Powershell - Export CSV file correctly

Body:
I am trying to export inbox rules for users via powershell.  But , I can not get correctly export as CSV file.

Get-Mailbox "user@contoso.com" |Get-InboxRule | select name,Identity,ForwardTo,ForwardAsAttachmentTo, RedirectTo, DeleteMessage , Description

Output :

Name                  : [forward apply]
Identity              : contoso.local/IT/USERS/User\3315794656083574785
ForwardTo             :
ForwardAsAttachmentTo :
RedirectTo            : {"user1@gmail.com" [SMTP:user1@gmail.com]}
DeleteMessage         : False
Description           : Take the following actions:
                            redirect the message to 'user1@gmail.com'
                            and stop processing more rules on this message

After  I want to export it. But, I am not getting to export as correctly for attributes such as Description and RedirectTo attribute.

Get-Mailbox "user@contoso.com" |Get-InboxRule | select name,Identity,ForwardTo,ForwardAsAttachmentTo, RedirectTo, DeleteMessage,Description | Export-csv "C:\temp\inbox_ruleexport.csv" -NoTypeInformation -encoding UTF8

Output :

"Name","Identity","ForwardTo","ForwardAsAttachmentTo","RedirectTo","DeleteMessage","Description"
"[forward apply]","contoso.local/IT/USERS/User\3315794656083574785",,,"Microsoft.Exchange.Data.Storage.Management.ADRecipientOrAddress[]","False","Take the following actions:
    redirect the message to 'user1@gmail.com'
    and stop processing more rules on this message
"


问:
Making UI Test Wait For The App To Load Before Performing Other Action - UI Testing In Android
In my app, I am getting some data from firebase after the user logs in.

While writing the test for the app

```<code>@Test
    public void loginAndLogoutTest() {
        //...after inputing the login details
        ViewInteraction materialButton = onView(
                allOf(withId(R.id.buttonLogin), withText("Login"), isDisplayed()));
        materialButton.perform(click());

        //...The app starts loading to get some data from the database

        //...

        //...The test fails and it does not wait for the app to load before trying to press the logout

        ViewInteraction materialTextView = onView(
                allOf(withId(R.id.textViewNavLogout), withText("Logout"), isDisplayed()));
        materialTextView.perform(click());

        //...
    }

</code>```

Is it possible to make the test wait till the app fetches the data from the database and then performs the logout click after?

Body:
In my app, I am getting some data from firebase after the user logs in.

While writing the test for the app

@Test
    public void loginAndLogoutTest() {
        //...after inputing the login details
        ViewInteraction materialButton = onView(
                allOf(withId(R.id.buttonLogin), withText("Login"), isDisplayed()));
        materialButton.perform(click());

        //...The app starts loading to get some data from the database

        //...

        //...The test fails and it does not wait for the app to load before trying to press the logout

        ViewInteraction materialTextView = onView(
                allOf(withId(R.id.textViewNavLogout), withText("Logout"), isDisplayed()));
        materialTextView.perform(click());

        //...
    }

Is it possible to make the test wait till the app fetches the data from the database and then performs the logout click after?


问:
Opening a PuTTY console with CreateProcess leaves one TCP connection open (but it should've ended)
I'm working on a server-client apllication which provides a CLI, I need two instances of this application working first instance acts as server and second instance acts as backup server; both servers are connected through a TCP sockets. In certain situations the role of server and backup server can swap, this can happen writting a swap instruction on the CLI.

I'm connecting to the CLI using PuTTY. The PuTTY instance is opened inside the application with a call to CreateProcess:

```<code>STARTUPINFO si = { sizeof(STARTUPINFO) };

// ...

process_information = PROCESS_INFORMATION();

BOOL success = CreateProcess
(
    NULL,
    command, // putty.exe param1 param2
    NULL,
    NULL,
    TRUE,
    DETACHED_PROCESS,
    NULL,
    static_cast<LPCWSTR>(workingDirectory),
    &si,
    &process_information
);
</code>```

But I have a problem with this approach: for some unknown reason if the PuTTY console is open when the server becomes backup server it maintains the TCP listener open and after swapping again it creates a new listener on the same port:

Then the backup server connects to the previous TCP listener which is not managed by the application anymore so my application acts as if no connection were made.

Here is the catch:

If I close the PuTTY console the zombie TCP listener closes and then the connection is stablished with the correct listener.

If I open the PuTTY console manually (instead of calling CreateProcess from inside my application) the TCP listener closes propperly and swapping server roles works perfectly.

Why opening PuTTY from my application (using CreateProcess) prevents the connection to close properly? Is there a way to avoid this?

Any help is appreciated, thanks for your time.

Body:
I'm working on a server-client apllication which provides a CLI, I need two instances of this application working first instance acts as server and second instance acts as backup server; both servers are connected through a TCP sockets. In certain situations the role of server and backup server can swap, this can happen writting a swap instruction on the CLI.

I'm connecting to the CLI using PuTTY. The PuTTY instance is opened inside the application with a call to CreateProcess:

STARTUPINFO si = { sizeof(STARTUPINFO) };

// ...

process_information = PROCESS_INFORMATION();

BOOL success = CreateProcess
(
    NULL,
    command, // putty.exe param1 param2
    NULL,
    NULL,
    TRUE,
    DETACHED_PROCESS,
    NULL,
    static_cast<LPCWSTR>(workingDirectory),
    &si,
    &process_information
);

But I have a problem with this approach: for some unknown reason if the PuTTY console is open when the server becomes backup server it maintains the TCP listener open and after swapping again it creates a new listener on the same port:

Then the backup server connects to the previous TCP listener which is not managed by the application anymore so my application acts as if no connection were made.

Here is the catch:

If I close the PuTTY console the zombie TCP listener closes and then the connection is stablished with the correct listener.

If I open the PuTTY console manually (instead of calling CreateProcess from inside my application) the TCP listener closes propperly and swapping server roles works perfectly.

Why opening PuTTY from my application (using CreateProcess) prevents the connection to close properly? Is there a way to avoid this?

Any help is appreciated, thanks for your time.


问:
Something Selenium related is eating up a whole bunch of SSD space, can I delete it?
I use Selenium here and there, and I noticed that there's a giant chunk of my ssd being taken up by something related to it.

In %USERPROFILE%\AppData\Local\Temp\rust_mozprofile\...

I also see something about it here:

https://github.com/SeleniumHQ/selenium/issues/4844

but I am unsure if it's some sort of cache or if it's being loaded when I run a script.

This is how I am loading selenium; I used to use geckodriver.exe but it appears that Selenium handles that now.

```<code>pp = r'C:\Users\userprofile\Documents\pyenvs\jupyterlab\projects\SimphonyEmployeeReportOptimization\FirefoxProfiles\r5963zu4.EV_YAY'
options=Options()
options.set_preference('profile', pp)
options.set_preference('browser.download.folderList', 2) #
options.set_preference('browser.download.dir', dl_dir)
options.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/csv+x')
driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), options=options)
</code>```

Body:
I use Selenium here and there, and I noticed that there's a giant chunk of my ssd being taken up by something related to it.

In %USERPROFILE%\AppData\Local\Temp\rust_mozprofile\...

I also see something about it here:

https://github.com/SeleniumHQ/selenium/issues/4844

but I am unsure if it's some sort of cache or if it's being loaded when I run a script.

This is how I am loading selenium; I used to use geckodriver.exe but it appears that Selenium handles that now.

pp = r'C:\Users\userprofile\Documents\pyenvs\jupyterlab\projects\SimphonyEmployeeReportOptimization\FirefoxProfiles\r5963zu4.EV_YAY'
options=Options()
options.set_preference('profile', pp)
options.set_preference('browser.download.folderList', 2) #
options.set_preference('browser.download.dir', dl_dir)
options.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/csv+x')
driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), options=options)


问:
Error trying to Input a BehaviorSubject into a library component
I created a library for my components and that components have an Input that contain data and settings to the component.
That object is inside a BehaviorSubject so I can change the data from anywhere and subscribe it to detect changes.
The library is separated from the project so it have its own node modules.
I create the BehaviorSubject in the Father (Project component) and input the variable into the Child(Library component).
The problem is that I cant Input the variable because the import of the BehaviorSubject is diferent in the components.

Error:

```<code>Type 'import("C:......../Libraries/node_modules/rxjs/dist/types/internal/BehaviorSubject").BehaviorSubject<import("C:/......../Libraries/projects/lib/src/lib/table/table").TableDatasource>' is not assignable to type 'import("C:/......../Libraries/projects/lib/node_modules/rxjs/dist/types/internal/BehaviorSubject").BehaviorSubject<import("C:/......../Libraries/projects/lib/src/lib/table/table").TableDatasource>'.
</code>```

I have been trying to export the rxjs from the library in the public api and use that but didnt work. What I expect is that I can use the sabe rxjs in the library and the project so I can share data between them.

Body:
I created a library for my components and that components have an Input that contain data and settings to the component.
That object is inside a BehaviorSubject so I can change the data from anywhere and subscribe it to detect changes.
The library is separated from the project so it have its own node modules.
I create the BehaviorSubject in the Father (Project component) and input the variable into the Child(Library component).
The problem is that I cant Input the variable because the import of the BehaviorSubject is diferent in the components.

Error:

Type 'import("C:......../Libraries/node_modules/rxjs/dist/types/internal/BehaviorSubject").BehaviorSubject<import("C:/......../Libraries/projects/lib/src/lib/table/table").TableDatasource>' is not assignable to type 'import("C:/......../Libraries/projects/lib/node_modules/rxjs/dist/types/internal/BehaviorSubject").BehaviorSubject<import("C:/......../Libraries/projects/lib/src/lib/table/table").TableDatasource>'.

I have been trying to export the rxjs from the library in the public api and use that but didnt work. What I expect is that I can use the sabe rxjs in the library and the project so I can share data between them.


问:
Django celery beat does seems to get triggered when on my EC2 instance
so this task runs completely fine when locally :

```<code>@shared_task
def test():
    print('test')

app.conf.beat_schedule = {
    'my-task-every-1-minutes': {
        'task': 'statistic_status.tasks.test',
        'schedule': crontab(minute='*/1'),
    },
}
</code>```

when on my EC2 and i start the worker it shows my tasks correctly
but when starting the beat the server looks like running fine but
it does no get triggered.

Locally everything works fine and on EC2 the only way I could triggered my tasks is
from the python shell.

Any help here ??

Body:
so this task runs completely fine when locally :

@shared_task
def test():
    print('test')

app.conf.beat_schedule = {
    'my-task-every-1-minutes': {
        'task': 'statistic_status.tasks.test',
        'schedule': crontab(minute='*/1'),
    },
}

when on my EC2 and i start the worker it shows my tasks correctly
but when starting the beat the server looks like running fine but
it does no get triggered.

Locally everything works fine and on EC2 the only way I could triggered my tasks is
from the python shell.

Any help here ??


问:
Ragged rank for TensorFlow ragged constant and ragged stack not retrieving shape information and instead is returning none for known shape
I am trying to create an input to check my graph convolutional model which should receive a shape of (n,2,2,none,none) with n being the batch size and 2,2 being a pair of a pair of none,none shape matrices since the matrices will have different lengths and widths. In my model the first pair level gets split and the 2 goes through 2 parallel layers so p1, p2 = tf.split with both p1 and p2 shape (n,2,none,none), this is where the problem starts since I think the tensors need to be ragged due to different matrix sizes however when passed into tf.ragged.constant , the 2,2 turns into none,none even with ragged_rank changed from 0 to 5 with all but 4 returning errors and the working value not changing the shape to correct one(also tried (n,4,none,none) and didn’t work).

```<code>print('shape prev',np.array(reshp_try_nre).shape)
raggyt = tf.ragged.constant(reshp_try_nre, ragged_rank=4)
print(raggyt.shape)
</code>```
```<code>C:\Users\Bib\AppData\Local\Temp\ipykernel_14596\2739577654.py:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  print('shape prev',np.array(reshp_try_nre).shape)
shape prev (135, 2, 2)
(135, None, None, None, None)
</code>```

Then tried putting in (4n,none,none) being split by n and then using stack (ragged and not) to try and get (n,4,none,none) to see if this works however it returned (n,none,none,none) even though all of the list of tensors returned (4,none,none) for shape. Sometihng similar was tried with expanded dimension and concatenate but also returned none shape.

```<code>print('shape prev',np.array(reshp_try4).shape)
raggyt = tf.ragged.constant(reshp_try4)
print(raggyt.shape)
</code>```
```<code>C:\Users\Bib\AppData\Local\Temp\ipykernel_14596\3895657277.py:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  print('shape prev',np.array(reshp_try4).shape)
shape prev (540,)
(540, None, None)
</code>```
```<code>print('1',raggyt.shape)
sliced = tf.split(raggyt,num_or_size_splits=135, axis=0)
print('2:',len(sliced))
print('3',sliced[0].shape)
for x in sliced:
    if x.shape != (4,None,None):
        print('problem')
    #print(x.shape)
    #if x.shape == (4,None,None):
    #    print('check')
comb = tf.ragged.stack(sliced)
print('4',comb.shape)
</code>```
```<code>1 (540, None, None)
2: 135
3 (4, None, None)
4 (135, None, None, None)
</code>```

So do you guys know of a resource that provides examples on dealing with ragged rank since all the other resources I have seen don't seem to help dealing with None shape other than ensure_shape which didn't seem to work (returns 'raggedtensors have no length' error) and there doesn't seem to be any resources for trying it on ragged tensors.

Body:
I am trying to create an input to check my graph convolutional model which should receive a shape of (n,2,2,none,none) with n being the batch size and 2,2 being a pair of a pair of none,none shape matrices since the matrices will have different lengths and widths. In my model the first pair level gets split and the 2 goes through 2 parallel layers so p1, p2 = tf.split with both p1 and p2 shape (n,2,none,none), this is where the problem starts since I think the tensors need to be ragged due to different matrix sizes however when passed into tf.ragged.constant , the 2,2 turns into none,none even with ragged_rank changed from 0 to 5 with all but 4 returning errors and the working value not changing the shape to correct one(also tried (n,4,none,none) and didn’t work).

print('shape prev',np.array(reshp_try_nre).shape)
raggyt = tf.ragged.constant(reshp_try_nre, ragged_rank=4)
print(raggyt.shape)

C:\Users\Bib\AppData\Local\Temp\ipykernel_14596\2739577654.py:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  print('shape prev',np.array(reshp_try_nre).shape)
shape prev (135, 2, 2)
(135, None, None, None, None)

Then tried putting in (4n,none,none) being split by n and then using stack (ragged and not) to try and get (n,4,none,none) to see if this works however it returned (n,none,none,none) even though all of the list of tensors returned (4,none,none) for shape. Sometihng similar was tried with expanded dimension and concatenate but also returned none shape.

print('shape prev',np.array(reshp_try4).shape)
raggyt = tf.ragged.constant(reshp_try4)
print(raggyt.shape)

C:\Users\Bib\AppData\Local\Temp\ipykernel_14596\3895657277.py:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  print('shape prev',np.array(reshp_try4).shape)
shape prev (540,)
(540, None, None)

print('1',raggyt.shape)
sliced = tf.split(raggyt,num_or_size_splits=135, axis=0)
print('2:',len(sliced))
print('3',sliced[0].shape)
for x in sliced:
    if x.shape != (4,None,None):
        print('problem')
    #print(x.shape)
    #if x.shape == (4,None,None):
    #    print('check')
comb = tf.ragged.stack(sliced)
print('4',comb.shape)

1 (540, None, None)
2: 135
3 (4, None, None)
4 (135, None, None, None)

So do you guys know of a resource that provides examples on dealing with ragged rank since all the other resources I have seen don't seem to help dealing with None shape other than ensure_shape which didn't seem to work (returns 'raggedtensors have no length' error) and there doesn't seem to be any resources for trying it on ragged tensors.


问:
Best approach for Laravel Cashier "top up" purchase flow
I'm building a web application where users can purchase "SMS credits". Each credit can be used to send an SMS. So users will need to purchase credits which are then stored as a CreditTransaction entry with a delta column in my database, this way, each transaction can have a negative or positive delta value and the sum of all of these is the user's credit balance.

My initial approach here, is to have a Laravel job called ProcessCreditTransaction which is triggered on the checkout, I believe this is fine for customers that enter my try block, but for customers that enter the catch, and where additional payment action is required, how can I only trigger my Job if successful?

Right now, for example, if the $e->payment->requiresPaymentMethod() block is triggered, then so is my job to add credits to their account, but if they didn't complete the purchase, then they've now got a positive amount of credits in their account?

How's best to handle this, here's my current checkout purchase flow:

The TODO comments are the parts I need some advice on.

// attempt to charge
try {
    $productPrice = Cashier::stripe()->prices->retrieve($productOption->stripe_id);

    // get user
    $user = Auth::user();

    // get customer
    if (Cashier::findBillable($user->stripe_id)) {
        $user->invoicePrice($productOption->stripe_id);
    } else {
        $user->createOrGetStripeCustomer();
        $user->updateDefaultPaymentMethod($request->input('token'));
        $user->invoicePrice($productOption->stripe_id);
    }

    // update region of API key
    if (!$apiKey->region_code) {
        $apiKey->region_code = $request->input('region');
        $apiKey->save();
    }

    // apply balance
    ProcessCreditTransaction::dispatch(
        Carbon::now(), $user->id, $apiKey->uuid, $productOption->quantity
    )->onQueue('on-demand-runs-now');

    return response()->json([
        'complete' => true,
        'message' => "You've successfully topped-up credits for this API key. You'll soon be able to download the invoice for this item. You can now start sending messages using this API key to the SMS region you specified.",
        'redirectTo' => "$frontendUrl/account/billing/checkout/result/?success=true&id=".$productOption->id,
    ], 200);

} catch (IncompletePayment $e) {

    // if we require some action, perform it here
    if ($e->payment->requiresAction()) {

        // update region of API key
        if (!$apiKey->region_code) {
            $apiKey->region_code = $request->input('region');
            $apiKey->save();
        }

        // apply balance
        // TODO: we may need to move this part to an event
        ProcessCreditTransaction::dispatch(
            Carbon::now(), $user->id, $apiKey->uuid, $productOption->quantity
        )->onQueue('on-demand-runs-now');

        return response()->json([
            'message' => 'We require some payment action from you to complete this purchase, this usually means you need to open your banking app to approve this subscription.',
            'requiresAction' => true,
            'redirectTo' => route('cashier.payment', [
                $e->payment->id,
                'redirect' => "$frontendUrl/account/billing/checkout/result/?id=".$productOption->id,
            ]),
        ], 400);
    } elseif ($e->payment->requiresPaymentMethod()) {

        // update region of API key
        if (!$apiKey->region_code) {
            $apiKey->region_code = $request->input('region');
            $apiKey->save();
        }

        // apply balance
        // TODO: we may need to move this part to an event
        ProcessCreditTransaction::dispatch(
            Carbon::now(), $user->id, $apiKey->uuid, $productOption->quantity
        )->onQueue('on-demand-runs-now');

        return response()->json([
            'message' => "The payment method currently set up is invalid or has sufficient funds, we're going to redirect you to complete this transaction, please wait.",
            'requiresAction' => true,
            'redirectTo' => route('cashier.payment', [
                $e->payment->id,
                'redirect' => "$frontendUrl/account/billing/checkout/result/?id=".$productOption->id,
            ]),
        ], 400);
    } elseif ($e->payment->requiresConfirmation()) {

        // update region of API key
        if (!$apiKey->region_code) {
            $apiKey->region_code = $request->input('region');
            $apiKey->save();
        }

        // apply balance
        // TODO: we may need to move this part to an event
        ProcessCreditTransaction::dispatch(
            Carbon::now(), $user->id, $apiKey->uuid, $productOption->quantity
        )->onQueue('on-demand-runs-now');

        return response()->json([
            'message' => 'We jsut need you to confirm this payment.',
            'requiresAction' => true,
            'redirectTo' => route('cashier.payment', [
                $e->payment->id,
                'redirect' => "$frontendUrl/account/billing/checkout/result/?id=".$productOption->id,
            ]),
        ], 400);
    }

    // generic error
    return response()->json([
        'message' => "We wasn't able to complete this purchase. You haven't been charged. Please try again soon.",
        'requiresAction' => true,
        'redirectTo' => "$frontendUrl/account/billing/checkout/result/?success=false",
    ], 400);
}
```


问:
PLS-00428: INTO clause is expected in this SELECT statement
I,ve got this error executing a statement to create an materialized view

PLS-00428: INTO clause is expected in this SELECT statement
ORA-06550: line 18, column 1:

```<code>CREATE MATERIALIZED VIEW TABLE_ADM.MVW_SUBSCRIBED_REPORT
USING INDEX
TABLESPACE TSDBDSUBSD01
PCTFREE 10
INITRANS 2
STORAGE
(
  INITIAL 524288000
  NEXT 10485760
  MINEXTENTS 1
  MAXEXTENTS UNLIMITED
  PCTINCREASE 0
  BUFFER_POOL DEFAULT
)
REFRESH FORCE ON DEMAND
WITH PRIMARY KEY
USING DEFAULT LOCAL ROLLBACK SEGMENT
DISABLE QUERY REWRITE AS
 SELECT TRUNC(ISS.DAT_INSCRIPTION) DAT_INSCRIPTION, INS.IDT_INSCRIPTION IDT_INSCRIPTION FROM
    INSCRIPTION INS JOIN INSCRIPTION_SALES ISS ON INS.IDT_INSCRIPTION = ISS.IDT_INSCRIPTION
    AND INS.COD_OFFER IN (2000,3001);
-- create synonym and grants
 CREATE PUBLIC SYNONYM MVW_SUBSCRIBED_REPORT FOR TABLE_ADM.MVW_SUBSCRIBED_REPORT;
 grant select on MVW_SUBSCRIBED_REPORT TO manut;
 grant select on MVW_SUBSCRIBED_REPORT TO SERVICE_JOB;

PROCEDURE DBMS_REFRESH.MAKE(
     name => '"TABLE_ADM"."RFGRP_MVW_SUBSCRIBED_REPORT"',
     list => 'MVW_SUBSCRIBED_REPORT',
     next_date => NULL,
     interval => '(TRUNC(sysdate) + 1) + 4/24',
     implicit_destroy => FALSE,
     lax => FALSE,
     job => 0,
     rollback_seg => NULL,
     push_deferred_rpc => TRUE,
     refresh_after_errors => FALSE,
     purge_option => NULL,
     parallelism => NULL,
     heap_size => NULL);
</code>```

Body:
I,ve got this error executing a statement to create an materialized view

PLS-00428: INTO clause is expected in this SELECT statement
ORA-06550: line 18, column 1:

CREATE MATERIALIZED VIEW TABLE_ADM.MVW_SUBSCRIBED_REPORT
USING INDEX
TABLESPACE TSDBDSUBSD01
PCTFREE 10
INITRANS 2
STORAGE
(
  INITIAL 524288000
  NEXT 10485760
  MINEXTENTS 1
  MAXEXTENTS UNLIMITED
  PCTINCREASE 0
  BUFFER_POOL DEFAULT
)
REFRESH FORCE ON DEMAND
WITH PRIMARY KEY
USING DEFAULT LOCAL ROLLBACK SEGMENT
DISABLE QUERY REWRITE AS
 SELECT TRUNC(ISS.DAT_INSCRIPTION) DAT_INSCRIPTION, INS.IDT_INSCRIPTION IDT_INSCRIPTION FROM
    INSCRIPTION INS JOIN INSCRIPTION_SALES ISS ON INS.IDT_INSCRIPTION = ISS.IDT_INSCRIPTION
    AND INS.COD_OFFER IN (2000,3001);
-- create synonym and grants
 CREATE PUBLIC SYNONYM MVW_SUBSCRIBED_REPORT FOR TABLE_ADM.MVW_SUBSCRIBED_REPORT;
 grant select on MVW_SUBSCRIBED_REPORT TO manut;
 grant select on MVW_SUBSCRIBED_REPORT TO SERVICE_JOB;

PROCEDURE DBMS_REFRESH.MAKE(
     name => '"TABLE_ADM"."RFGRP_MVW_SUBSCRIBED_REPORT"',
     list => 'MVW_SUBSCRIBED_REPORT',
     next_date => NULL,
     interval => '(TRUNC(sysdate) + 1) + 4/24',
     implicit_destroy => FALSE,
     lax => FALSE,
     job => 0,
     rollback_seg => NULL,
     push_deferred_rpc => TRUE,
     refresh_after_errors => FALSE,
     purge_option => NULL,
     parallelism => NULL,
     heap_size => NULL);


问:
Using RSelenium to download a file embedded into a frame
I am working into a project where I have a web page that I need to click to get a pdf file. The file appears in a new window inside same page (I think is an iframe). Then I need to click on a button to download the file. The code I am using is next:

```<code>library(wdman)
library(RSelenium)
library(xml2)
library(selectr)
library(httr)
library(jsonlite)
#Code
#start RSelenium
# using RSelenium to start firefox on the selenium server
remDr <- rsDriver(
  port = 4445L,
  browser = "firefox"
)
#remDr$open()
remDr <- remoteDriver(port = 4445L,browser = "firefox")
# open a new Tab on Chrome
remDr$open()
#navigate to your page
remDr$navigate("https://www.southtechhosting.com/SanJoseCity/CampaignDocsWebRetrieval/Search/SearchByElection.aspx")
Sys.sleep(2)
webElem <- remDr$findElement(using = "xpath", '//*[@id="ctl00_DefaultContent_ASPxRoundPanel1_btnFindFilers_CD"]')
webElem$clickElement()
Sys.sleep(1)
webElem2 <- remDr$findElement(using = "xpath", '//*[@id="ctl00_GridContent_gridFilers_DXCBtn0"]')
webElem2$clickElement()
Sys.sleep(1)
webElem3 <- remDr$findElement(using = "xpath", '//*[@id="ctl00_DefaultContent_gridFilingForms_DXCBtn0Img"]')
webElem3$clickElement()
Sys.sleep(1)
#Move
myframe <- remDr$findElement("xpath", '//*[@id="ctl00_GenericPopupSizeable_InnerPopupControl_CIF-1"]')
remDr$switchToFrame(myframe)
</code>```

I think at this point everything works well but then I get the issue. I do not know if I am not able to move to the iframe (despite my code last lines worked), because this is what I get:

Now, I need to do click on the download button, but when I inspect that element, I am getting this:

I have searched and it tells that the element is hidden. Is there any way to make Rselenium do click on download?

I am asking about this because in a similar project, I am getting a window in same style but at the moment of inspecting I got this:

The button appears and I can copy the xpath, but I read in the description of element that is hidden in some way, so I think that is why my code can not find the element even after moving to iframe.

Any help would be very appreciated, I think if somebody can help me with the first example, I could solve my issue related to the second example explained at the end many thanks.

Body:
I am working into a project where I have a web page that I need to click to get a pdf file. The file appears in a new window inside same page (I think is an iframe). Then I need to click on a button to download the file. The code I am using is next:

library(wdman)
library(RSelenium)
library(xml2)
library(selectr)
library(httr)
library(jsonlite)
#Code
#start RSelenium
# using RSelenium to start firefox on the selenium server
remDr <- rsDriver(
  port = 4445L,
  browser = "firefox"
)
#remDr$open()
remDr <- remoteDriver(port = 4445L,browser = "firefox")
# open a new Tab on Chrome
remDr$open()
#navigate to your page
remDr$navigate("https://www.southtechhosting.com/SanJoseCity/CampaignDocsWebRetrieval/Search/SearchByElection.aspx")
Sys.sleep(2)
webElem <- remDr$findElement(using = "xpath", '//*[@id="ctl00_DefaultContent_ASPxRoundPanel1_btnFindFilers_CD"]')
webElem$clickElement()
Sys.sleep(1)
webElem2 <- remDr$findElement(using = "xpath", '//*[@id="ctl00_GridContent_gridFilers_DXCBtn0"]')
webElem2$clickElement()
Sys.sleep(1)
webElem3 <- remDr$findElement(using = "xpath", '//*[@id="ctl00_DefaultContent_gridFilingForms_DXCBtn0Img"]')
webElem3$clickElement()
Sys.sleep(1)
#Move
myframe <- remDr$findElement("xpath", '//*[@id="ctl00_GenericPopupSizeable_InnerPopupControl_CIF-1"]')
remDr$switchToFrame(myframe)

I think at this point everything works well but then I get the issue. I do not know if I am not able to move to the iframe (despite my code last lines worked), because this is what I get:

Now, I need to do click on the download button, but when I inspect that element, I am getting this:

I have searched and it tells that the element is hidden. Is there any way to make Rselenium do click on download?

I am asking about this because in a similar project, I am getting a window in same style but at the moment of inspecting I got this:

The button appears and I can copy the xpath, but I read in the description of element that is hidden in some way, so I think that is why my code can not find the element even after moving to iframe.

Any help would be very appreciated, I think if somebody can help me with the first example, I could solve my issue related to the second example explained at the end many thanks.


问:
How to authenticate user in Django
I am trying to log in a user in Django and redirect them back to the homepage with an if statement in the navbar that will display logout if the user is logged in or authenticated and register and login links if they're not authenticated.

However, when I click login it goes back to the homepage but none of the expected changes are visible, if you see my views.py file the view is supposed to print a message depending on the action taken but these messages are only displayed on the Django admin page. What am I not doing?

This is the login form:

```<code><form action="" method="POST">
            {% csrf_token %}
          <!-- Email input -->
          <div class="form-outline mb-4">
            <input type="email" id="user-email" class="form-control" name="login-email" placeholder="Enter email"/>
            <label class="form-label" for="user-email">Email address</label>
          </div>

          <!-- Password input -->
          <div class="form-outline mb-4">
            <input type="password" id="user-password" class="form-control" name="login-password" placeholder="Enter password"/>
            <label class="form-label" for="form2Example2">Password</label>
          </div>

          <!-- 2 column grid layout for inline styling -->
          <div class="row mb-4">
            <div class="col d-flex justify-content-center">
              <!-- Checkbox -->
              <div class="form-check">
                <input class="form-check-input" type="checkbox" value="" id="form2Example31" checked />
                <label class="form-check-label" for="form2Example31"> Remember me </label>
              </div>
            </div>

            <div class="col">
              <!-- Simple link -->
              <a href="#!">Forgot password?</a>
            </div>
          </div>

          <!-- Submit button -->
          <button type="submit" class="btn btn-primary btn-block mb-4">Login</button>

 </form>
</code>```

The login and register views:

```<code>def loginpage(request):
if request.user.is_authenticated:
    messages.warning(request, 'You are already logged in')
    return redirect('/')
else:
    if request.method == 'POST':
        email = request.POST['login-email']
        password = request.POST['login-password']

        if not email or not password:
            messages.error(request, "Email and password fields cannot be empty")
            return redirect('/login')

        user = authenticate(request, email=email, password=password)
        if user is not None:
            login(request, user)
            messages.success(request, "Logged in Successfully")
            return redirect('homepage')
        else:
            messages.error(request, "Invalid email or password")
            return redirect('loginpage')

return render(request, 'login.html')

def register(request):
if request.method== 'POST':
    form=SignUpForm(request.POST)
    if form.is_valid():
        form.save()
        username=form.cleaned_data.get('username')
        signup_user=User.objects.get(username=username)
        customer_group=Group.objects.get(name='Customer')
        customer_group.user_set.add(signup_user)
else:
    form= SignUpForm()
return render(request,'register.html',{'form':form})
</code>```

This is the code in the NavBar that is supposed to display login, register or logout

```<code> {% if request.user.is_authenticated %}
              <li class="nav-item">
                <a class="nav-link" href="{% url 'logoutpage' %}">Logout</a>
              </li>
 {% else %}
              <li class="nav-item">
                <a class="nav-link" href="{% url 'loginpage' %}">Login</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="{% url 'register' %}">Register</a>
              </li>
 {% endif %}
</code>```

urls.py

```<code>urlpatterns = [
path('', views.home, name='homepage'),
path('cart/', views.cart, name='cart'),
path('checkout/', views.checkout, name='checkout'),
path('categories/', views.categories, name='categories'),
path('categories/<str:slug>', views.categoryview, name='categoryview'),
path('categories/<str:cate_slug>/<str:prod_slug>', views.productview, name='productview'),
path('<slug:category_slug>', views.home, name='products_by_category'),
path('register/', views.register, name='register'),
path('login/',views.loginpage, name='loginpage'),
path('logout/', views.logoutpage, name='logoutpage')
]
</code>```

Title: How to authenticate user in Django

Body:
I am trying to log in a user in Django and redirect them back to the homepage with an if statement in the navbar that will display logout if the user is logged in or authenticated and register and login links if they're not authenticated.

However, when I click login it goes back to the homepage but none of the expected changes are visible, if you see my views.py file the view is supposed to print a message depending on the action taken but these messages are only displayed on the Django admin page. What am I not doing?

This is the login form:

<form action="" method="POST">
            {% csrf_token %}

            <input type="email" id="user-email" class="form-control" name="login-email" placeholder="Enter email"/>
            Email address

            <input type="password" id="user-password" class="form-control" name="login-password" placeholder="Enter password"/>
            Password

                <input class="form-check-input" type="checkbox" value="" id="form2Example31" checked />
                 Remember me

              Forgot password?

          <button type="submit" class="btn btn-primary btn-block mb-4">Login</button>

 </form>

The login and register views:

def loginpage(request):
if request.user.is_authenticated:
    messages.warning(request, 'You are already logged in')
    return redirect('/')
else:
    if request.method == 'POST':
        email = request.POST['login-email']
        password = request.POST['login-password']

        if not email or not password:
            messages.error(request, "Email and password fields cannot be empty")
            return redirect('/login')

        user = authenticate(request, email=email, password=password)
        if user is not None:
            login(request, user)
            messages.success(request, "Logged in Successfully")
            return redirect('homepage')
        else:
            messages.error(request, "Invalid email or password")
            return redirect('loginpage')

return render(request, 'login.html')

def register(request):
if request.method== 'POST':
    form=SignUpForm(request.POST)
    if form.is_valid():
        form.save()
        username=form.cleaned_data.get('username')
        signup_user=User.objects.get(username=username)
        customer_group=Group.objects.get(name='Customer')
        customer_group.user_set.add(signup_user)
else:
    form= SignUpForm()
return render(request,'register.html',{'form':form})

This is the code in the NavBar that is supposed to display login, register or logout

 {% if request.user.is_authenticated %}

                Logout

 {% else %}

                Login

                Register

 {% endif %}

urls.py

urlpatterns = [
path('', views.home, name='homepage'),
path('cart/', views.cart, name='cart'),
path('checkout/', views.checkout, name='checkout'),
path('categories/', views.categories, name='categories'),
path('categories/<str:slug>', views.categoryview, name='categoryview'),
path('categories/<str:cate_slug>/<str:prod_slug>', views.productview, name='productview'),
path('<slug:category_slug>', views.home, name='products_by_category'),
path('register/', views.register, name='register'),
path('login/',views.loginpage, name='loginpage'),
path('logout/', views.logoutpage, name='logoutpage')
]


问:
How to export MySQL database under the .db extension
Is it possible to export the MySQL database under the .db extension?  If it is possible how to do it?


问:
How to use Mockito.verify(), when the function is called using an executor-service and is executed as part of an infinite-loop runnable
```<code>@Service
public class Distributor {

  private ExecutorService nonBlockingService;

  private final Runnable pickAndPerform = new Runnable() {

        @Override
        public void run() {
            while(true) {
                 send(x,y);
            }
  }

  @PostConstruct
  public void main() {
        nonBlockingService = Executors.newFixedThreadPool(num_threads);
        nonBlockingService.submit(() -> {
            pickAndPerform.run();
        });
   }

   public void send(a, b){}
</code>```

How to verify the method call for send(x,y) in the runnable above.

Tried overriding the executor service with one that runs on the same thread where submitted. And called Distributor.main() manually, but that goes forever because of the loop.

I also tried mocking the executor service and using doAnswer().when(executor).submit(any(Runnable.class)) and implementing it so it will execute the runnable directly. But that again is the same thing as above I guess.

Body:
@Service
public class Distributor {

  private ExecutorService nonBlockingService;

  private final Runnable pickAndPerform = new Runnable() {

        @Override
        public void run() {
            while(true) {
                 send(x,y);
            }
  }

  @PostConstruct
  public void main() {
        nonBlockingService = Executors.newFixedThreadPool(num_threads);
        nonBlockingService.submit(() -> {
            pickAndPerform.run();
        });
   }

   public void send(a, b){}

How to verify the method call for send(x,y) in the runnable above.

Tried overriding the executor service with one that runs on the same thread where submitted. And called Distributor.main() manually, but that goes forever because of the loop.

I also tried mocking the executor service and using doAnswer().when(executor).submit(any(Runnable.class)) and implementing it so it will execute the runnable directly. But that again is the same thing as above I guess.


问:
WPF Caliburn.Micro ActivateItem triggers, but doesn't initialize only when called from code behind with datacontext
In my code behind, I am trying to trigger a new activeitem when a user signs in. The ActivateItem triggers but it does not go into the code behind for the view and initialize. When triggering it from buttons on the ShellView, it triggers the method and initializes.

```<code><Window x:Class="ProductivityTool.Views.ShellView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:model="clr-namespace:ProductivityTool.ViewModels"
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
    mc:Ignorable="d"
    d:DataContext="{x:Type model:ShellViewModel}"
    Title="Productivity Tool" Height="700" Width="900" MinWidth="900" MinHeight="700">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200" />
        <ColumnDefinition Width="1000*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="100" />
        <RowDefinition Height="840*" />

        <RowDefinition Height="60" />
    </Grid.RowDefinitions>

    <StackPanel x:Name="StackPanel" Orientation="Vertical" Grid.Column="0" Grid.Row="1">

        <Button x:Name="btnPhonebook"  HorizontalAlignment="Center" Width="auto" Margin="10">Load page one</Button>
        <Button x:Name="LoadPageTwo"  HorizontalAlignment="Center" Width="auto">Loadpagetwo</Button>

    </StackPanel>

    <!--content control is the main window of the ShellView, different pages are just different active items-->

    <xctk:WatermarkTextBox x:Name="textBoxLogin" Grid.Column="1" Margin="209,0,0,20" Grid.Row="2" Watermark="Enter company email or U-ID" Height="28" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="179" KeyDown="TextBoxLogin_KeyDown"/>

    <Button x:Name="Loginbtn"  Content="LOGIN" Click="LoginBtn_Click" Margin="10,0,0,20" Grid.Row="2" MaxHeight="80" MaxWidth="200" MinWidth="80" Height="30" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="179" Grid.Column="1"/>

    <Label x:Name="lblSignedInAs"  HorizontalContentAlignment="Center" Margin="10,26,0,0" Grid.Row="2" VerticalAlignment="Top" Height="26" Width="181"/>
    <Label x:Name="lblLogged" Content="Logged Out" HorizontalContentAlignment="Center"  Margin="10,0" Grid.Row="3" VerticalAlignment="Top" Width="181"/>

    <ContentControl Grid.Column="1" Grid.Row="1"
                    x:Name="ActiveItem"/>

</Grid>
</code>```

Here is the Code behind:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using ProductivityTool.ViewModels;
using ProductivityTool.Views;

namespace ProductivityTool.Views
{
    /// <summary>
    /// Interaction logic for ShellView.xaml
    /// </summary>
    public partial class ShellView : Window
    {

        public ShellViewModel _viewModel; //this is needed to access methods from the view model, format _viewModel.method();

        public ShellView()
        {

            InitializeComponent();

            _viewModel = new ShellViewModel();
            DataContext = _viewModel;
        }

        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {

           string loginCredentials;

            if (string.IsNullOrEmpty(loginCredentials = textBoxLogin.Text))
            {
                MessageBox.Show("Couldn't log in because no user ID or email was entered.");
            }
            else
            {

                if (textBoxLogin.Text.Length > 8)
                {

                         string emailUID = loginCredentials + "@company.com";
                         SqlConnection con = new SqlConnection("Data Source=source;Database=DB;Trusted_Connection=Yes;");
                         con.Open();

                            //If entered login is greater than 8, assume it's an email and compare it to email records

                         SqlCommand cmd = new SqlCommand("Select * from UProfile where Email='" + emailUID + "'", con);
                        cmd.CommandType = CommandType.Text;
                        SqlDataAdapter adapter = new SqlDataAdapter();
                        adapter.SelectCommand = cmd;
                        DataSet dataSet = new DataSet();
                        adapter.Fill(dataSet);

                    if (dataSet.Tables[0].Rows.Count > 0)
                    {
                        string username = dataSet.Tables[0].Rows[0]["UserName"].ToString();

                    }
                    else
                    {
                        MessageBox.Show("Failed to retrieve credentials from database");

                    }

                    lblLogged.Content = "Signed in as:";
                    lblSignedInAs.Content = dataSet.Tables[0].Rows[0]["UserName"].ToString(); //Display who is signed in currently

                    con.Close();

                }
                else
                {
                    //else if entered value is not greater than 8, assume it's a UID and compare it to those records

                        string emailUID = loginCredentials;
                        SqlConnection con = new SqlConnection("Data Source=source;Database=DB;Trusted_Connection=Yes;");
                        con.Open();

                        SqlCommand cmd = new SqlCommand("Select * from UProfile where UID='" + emailUID + "'", con);
                        cmd.CommandType = CommandType.Text;
                        SqlDataAdapter adapter = new SqlDataAdapter();
                        adapter.SelectCommand = cmd;
                        DataSet dataSet = new DataSet();
                        adapter.Fill(dataSet);

                    if (dataSet.Tables[0].Rows.Count > 0)
                    {
                        string username = dataSet.Tables[0].Rows[0]["UserName"].ToString();

                    }
                    else
                    {
                        MessageBox.Show("Failed to retrieve credentials from database");

                    }

                    lblLogged.Content = "Signed in as:";
                    lblSignedInAs.Content = dataSet.Tables[0].Rows[0]["UserName"].ToString(); //Display who is signed in currently

                    con.Close();

                    textBoxLogin.Text = ""; //clear the text box for next time

                }

                _viewModel.LoadPageTwo();
            }
        }

        //When login textbox is focus and the enter key is pressed, basically simulate a "login" button press to sign the user in
        private void TextBoxLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                Loginbtn.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
            }
        }
    }
}
</code>```
```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Caliburn.Micro;
using ProductivityTool.Models;

namespace ProductivityTool.ViewModels
{
    public class ShellViewModel : Conductor<object>
    {

        //private string _lblLogged;
        //private string lblLoggedInAs;

        public void LoadWelcomePage()
        {

            ActivateItem(new WelcomeViewModel());

            //ActivateItem(new FirstChildViewModel());

        }

        public void LoadPageTwo()
        {
            ActivateItem(new FirstChildViewModel());
        }

    }
}
</code>```

So if you press a button in shellview, it triggers either LoadPage methods and it then goes to the xaml.cs and initializes. But if I use the _viewModel.LoadPage to do the same thing, the method gets triggered but does not initialize anything. Why the difference?

```<code>
using System.Windows.Controls;

namespace ProductivityTool.Views
{
    /// <summary>
    /// Interaction logic for Welcome.xaml
    /// </summary>
    public partial class WelcomeView : UserControl
    {
        public WelcomeView()
        {
            InitializeComponent();
        }

    }
}
</code>```

Why does calling LoadPage from a button trigger the method and initialize, but calling LoadPage from _viewModel.LoadPage only trigger the method but not initialize? With breakpoints I can see it calling the methods and then skipping passed initialization but I don't understand why they are behaving differently. Welcomeview.xaml.cs and any other -view.xaml.cs files are all identical. Thanks in advance for any help.

Body:
In my code behind, I am trying to trigger a new activeitem when a user signs in. The ActivateItem triggers but it does not go into the code behind for the view and initialize. When triggering it from buttons on the ShellView, it triggers the method and initializes.

<Window x:Class="ProductivityTool.Views.ShellView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:model="clr-namespace:ProductivityTool.ViewModels"
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
    mc:Ignorable="d"
    d:DataContext="{x:Type model:ShellViewModel}"
    Title="Productivity Tool" Height="700" Width="900" MinWidth="900" MinHeight="700">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200" />
        <ColumnDefinition Width="1000*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="100" />
        <RowDefinition Height="840*" />

        <RowDefinition Height="60" />
    </Grid.RowDefinitions>

    <StackPanel x:Name="StackPanel" Orientation="Vertical" Grid.Column="0" Grid.Row="1">

        <Button x:Name="btnPhonebook"  HorizontalAlignment="Center" Width="auto" Margin="10">Load page one</Button>
        <Button x:Name="LoadPageTwo"  HorizontalAlignment="Center" Width="auto">Loadpagetwo</Button>

    </StackPanel>

    <xctk:WatermarkTextBox x:Name="textBoxLogin" Grid.Column="1" Margin="209,0,0,20" Grid.Row="2" Watermark="Enter company email or U-ID" Height="28" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="179" KeyDown="TextBoxLogin_KeyDown"/>

    <Button x:Name="Loginbtn"  Content="LOGIN" Click="LoginBtn_Click" Margin="10,0,0,20" Grid.Row="2" MaxHeight="80" MaxWidth="200" MinWidth="80" Height="30" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="179" Grid.Column="1"/>

    <ContentControl Grid.Column="1" Grid.Row="1"
                    x:Name="ActiveItem"/>

</Grid>

Here is the Code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using ProductivityTool.ViewModels;
using ProductivityTool.Views;

namespace ProductivityTool.Views
{
    ///
    /// Interaction logic for ShellView.xaml
    ///
    public partial class ShellView : Window
    {

        public ShellViewModel _viewModel; //this is needed to access methods from the view model, format _viewModel.method();

        public ShellView()
        {

            InitializeComponent();

            _viewModel = new ShellViewModel();
            DataContext = _viewModel;
        }

        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {

           string loginCredentials;

            if (string.IsNullOrEmpty(loginCredentials = textBoxLogin.Text))
            {
                MessageBox.Show("Couldn't log in because no user ID or email was entered.");
            }
            else
            {

                if (textBoxLogin.Text.Length > 8)
                {

                         string emailUID = loginCredentials + "@company.com";
                         SqlConnection con = new SqlConnection("Data Source=source;Database=DB;Trusted_Connection=Yes;");
                         con.Open();

                            //If entered login is greater than 8, assume it's an email and compare it to email records

                         SqlCommand cmd = new SqlCommand("Select * from UProfile where Email='" + emailUID + "'", con);
                        cmd.CommandType = CommandType.Text;
                        SqlDataAdapter adapter = new SqlDataAdapter();
                        adapter.SelectCommand = cmd;
                        DataSet dataSet = new DataSet();
                        adapter.Fill(dataSet);

                    if (dataSet.Tables[0].Rows.Count > 0)
                    {
                        string username = dataSet.Tables[0].Rows[0]["UserName"].ToString();

                    }
                    else
                    {
                        MessageBox.Show("Failed to retrieve credentials from database");

                    }

                    lblLogged.Content = "Signed in as:";
                    lblSignedInAs.Content = dataSet.Tables[0].Rows[0]["UserName"].ToString(); //Display who is signed in currently

                    con.Close();

                }
                else
                {
                    //else if entered value is not greater than 8, assume it's a UID and compare it to those records

                        string emailUID = loginCredentials;
                        SqlConnection con = new SqlConnection("Data Source=source;Database=DB;Trusted_Connection=Yes;");
                        con.Open();

                        SqlCommand cmd = new SqlCommand("Select * from UProfile where UID='" + emailUID + "'", con);
                        cmd.CommandType = CommandType.Text;
                        SqlDataAdapter adapter = new SqlDataAdapter();
                        adapter.SelectCommand = cmd;
                        DataSet dataSet = new DataSet();
                        adapter.Fill(dataSet);

                    if (dataSet.Tables[0].Rows.Count > 0)
                    {
                        string username = dataSet.Tables[0].Rows[0]["UserName"].ToString();

                    }
                    else
                    {
                        MessageBox.Show("Failed to retrieve credentials from database");

                    }

                    lblLogged.Content = "Signed in as:";
                    lblSignedInAs.Content = dataSet.Tables[0].Rows[0]["UserName"].ToString(); //Display who is signed in currently

                    con.Close();

                    textBoxLogin.Text = ""; //clear the text box for next time

                }

                _viewModel.LoadPageTwo();
            }
        }

        //When login textbox is focus and the enter key is pressed, basically simulate a "login" button press to sign the user in
        private void TextBoxLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                Loginbtn.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Caliburn.Micro;
using ProductivityTool.Models;

namespace ProductivityTool.ViewModels
{
    public class ShellViewModel : Conductor<object>
    {

        //private string _lblLogged;
        //private string lblLoggedInAs;

        public void LoadWelcomePage()
        {

            ActivateItem(new WelcomeViewModel());

            //ActivateItem(new FirstChildViewModel());

        }

        public void LoadPageTwo()
        {
            ActivateItem(new FirstChildViewModel());
        }

    }
}

So if you press a button in shellview, it triggers either LoadPage methods and it then goes to the xaml.cs and initializes. But if I use the _viewModel.LoadPage to do the same thing, the method gets triggered but does not initialize anything. Why the difference?

using System.Windows.Controls;

namespace ProductivityTool.Views
{
    ///
    /// Interaction logic for Welcome.xaml
    ///
    public partial class WelcomeView : UserControl
    {
        public WelcomeView()
        {
            InitializeComponent();
        }

    }
}

Why does calling LoadPage from a button trigger the method and initialize, but calling LoadPage from _viewModel.LoadPage only trigger the method but not initialize? With breakpoints I can see it calling the methods and then skipping passed initialization but I don't understand why they are behaving differently. Welcomeview.xaml.cs and any other -view.xaml.cs files are all identical. Thanks in advance for any help.


问:
What do I need to do to fix the error in this piece of code?
```<code> <div className="badge-container grow">
        <a
          href="https://buildspace.so/builds/ai-writer"
          target="_blank"
          rel="noreferrer"
        >
          <div className="badge">
            <Image src={buildspaceLogo} alt="buildspace logo" />
            <p>build with buildspace</p>
          </div>
        </a>
      </div>

  );
};

export default Home;
</code>```

It keeps telling me there is an error with the  line of code. I don't know how to fix it.

Body:
            <Image src={buildspaceLogo} alt="buildspace logo" />

build with buildspace

  );
};

export default Home;

It keeps telling me there is an error with the  line of code. I don't know how to fix it.


问:
Using padding in cnn layer distorts edges of feature maps
I try to implementing cnn for image denoising. I use noisy image fragments (size 32x32) and same-sized clear image for validation as a training set. I used the trained network on a noisy image and noticed that denoised image contains artifacts, like a grid  32x32 pixels. I visualised feature maps produced by convolution layers and noticed that layers with zero-padding give distorted edges. I found this topic in which as a solution of same problem describes convolution, last step of which (eg for 3x3 kernel) is operation divide result by 9 or 4, when using zero-padding.

In all articles about convolution operations that I read, this is not mentioned. Does anyone know where I can read more about this?


问:
Is there any solution how to fix network error while sending data in API?
I am getting network error and data is not sending in the API but the same code works fine on the other system when it is cloned.. Does anybody know ho to get rid of this network error</p>