问:
absolute positioned element to the right above other content
I am trying to position a panel to the right of avatar icon. i want to make it look like the supabase dashboard.

i have the following already. iam using tailwindcss and tailwind/headlessui for the popover

```<code><Popover className="relative flex flex-col items-center">
     <Popover.Panel
                                className="absolute -top-32 right-0 z-50 w-screen max-w-[270px] px-4 sm:px-0 translate-x-full ">
                                <div className="overflow-hidden rounded-sm shadow ring-1 ring-black ring-opacity-5">
                                    <div className="block w-full h-12 bg-blue-50 py-3 px-3 content-center">
                                        <div>
                                            {
                                                (isLoading || isError) ? (
                                                    <div role="status" className="space-y-2.5 animate-pulse max-w">
                                                        <div className="h-2.5 bg-gray-200 rounded w-full"></div>
                                                    </div>
                                                ) : (
                                                    <h4 className="font-semibold">
                                                        {user.email}
                                                    </h4>
                                                )

                                            }
                                        </div>

                                    </div>
                                    <div className="relative grid grid-cols-1 gap-4 bg-white py-7 ">
                                        <div className="flex flex-col gap-6">

                                            <PanelItem content="Wishlist" href="/v/wishlist">
                                                <svg
                                                    width="24"
                                                    height="24"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                >
                                                    <path
                                                        d="M12.62 20.81C12.28 20.93 11.72 20.93 11.38 20.81C8.48 19.82 2 15.69 2 8.68998C2 5.59998 4.49 3.09998 7.56 3.09998C9.38 3.09998 10.99 3.97998 12 5.33998C13.01 3.97998 14.63 3.09998 16.44 3.09998C19.51 3.09998 22 5.59998 22 8.68998C22 15.69 15.52 19.82 12.62 20.81Z"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                        strokeLinecap="round"
                                                        strokeLinejoin="round"
                                                    />
                                                </svg>
                                            </PanelItem>

                                        </div>

                                    </div>
                                    <Button variant="primary" className="rounded-none" onClick={handleSignOut}>
                                        <span className="text-sm font-medium" >Sign Out</span>
                                    </Button>
                                </div>
  </Popover.Panel>

</Popover>

</code>```

it looks like this.

but should look like this

Body:
I am trying to position a panel to the right of avatar icon. i want to make it look like the supabase dashboard.

i have the following already. iam using tailwindcss and tailwind/headlessui for the popover

<Popover className="relative flex flex-col items-center">
     <Popover.Panel
                                className="absolute -top-32 right-0 z-50 w-screen max-w-[270px] px-4 sm:px-0 translate-x-full ">

                                            {
                                                (isLoading || isError) ? (

                                                ) : (

                                                        {user.email}

                                                )

                                            }

                                            <PanelItem content="Wishlist" href="/v/wishlist">
                                                <svg
                                                    width="24"
                                                    height="24"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                >
                                                    <path
                                                        d="M12.62 20.81C12.28 20.93 11.72 20.93 11.38 20.81C8.48 19.82 2 15.69 2 8.68998C2 5.59998 4.49 3.09998 7.56 3.09998C9.38 3.09998 10.99 3.97998 12 5.33998C13.01 3.97998 14.63 3.09998 16.44 3.09998C19.51 3.09998 22 5.59998 22 8.68998C22 15.69 15.52 19.82 12.62 20.81Z"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                        strokeLinecap="round"
                                                        strokeLinejoin="round"
                                                    />
                                                </svg>
                                            </PanelItem>

                                    <Button variant="primary" className="rounded-none" onClick={handleSignOut}>
                                        Sign Out
                                    </Button>

  </Popover.Panel>

</Popover>

it looks like this.

but should look like this


来源: stackexchange

问:
How to configure an Azure alert for the max cpu held over x time period
I currently have an alert that triggers on average cpu over 80% over the last 15 minutes.  However, we have instances that stay over 100% for hours or days while others are very look leaving the average under 80%.  I want to find those instances that are higher than 80% for an extended period of time.  But what I don't want is a spike and using the max seems only do just that, spend out alerts for spikes and not constants.  Anyway I can get such an alert configured?</p>

ContentLicense: CC BY-SA 4.0


问:
When I join a map of an object I get [object, Object]
I'm trying to join a map with a comma, like the following. It works fine without the join, however when I add the join on, I just get [object Object] , [object Object] , [object Object].

What am I doing wrong? I suspect it's something really simple.

```<code>{artist?.genres &&
                  artist?.genres.map((genre) => {
                    return (
                      <Box key={genre.id} cursor={"pointer"} role={"group"}>
                        <HStack spacing={1}>
                          <Text
                            textTransform={"uppercase"}
                            fontSize={"lg"}
                          >
                            {genre.name}
                          </Text>
                        </HStack>
                      </Box>
                    );
                  }).join(" , ")}
</code>```

Body:
I'm trying to join a map with a comma, like the following. It works fine without the join, however when I add the join on, I just get [object Object] , [object Object] , [object Object].

What am I doing wrong? I suspect it's something really simple.

{artist?.genres &&
                  artist?.genres.map((genre) => {
                    return (
                      <Box key={genre.id} cursor={"pointer"} role={"group"}>
                        <HStack spacing={1}>
                          <Text
                            textTransform={"uppercase"}
                            fontSize={"lg"}
                          >
                            {genre.name}
                          </Text>
                        </HStack>
                      </Box>
                    );
                  }).join(" , ")}


问:
How come my connecting DTW-Python lines aren't showing up in my time-series graphs?
I am trying to use dtw-python inside of a jupyter notebook in order to graph the Dynamic Time Warping between two time-series graphs.

I have successfully imported dtw-python into my jupyter notebook, but when I try to use dtw to plot my two time-series graphs, I keep getting errors and only the two graphs show up (not the dtw connecting lines between the graphs). Below is an image of my script that I have tried, that only plots the two graphs and not the connected dtw lines for comparison. I also receive this error message.

SCRIPT I AM USING

```<code>from dtw import *
import matplotlib.pyplot as plt

dtw(USA_Unemployment_Inflation['Inflation'], USA_Unemployment_Inflation['Unemployment'], keep_internals=True,
    step_pattern=rabinerJuangStepPattern(6, "c"))\
    .plot(type="twoway",offset=-2)
</code>```

ERROR MESSAGE I RECEIVE

```<code>KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3628             try:
-> 3629                 return self._engine.get_loc(casted_key)
   3630             except KeyError as err:

~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
C:\Users\Public\Documents\Wondershare\CreatorTemp\ipykernel_17236\2682910787.py in <module>
      2 import matplotlib.pyplot as plt
      3
----> 4 dtw(USA_Unemployment_Inflation['Inflation'], USA_Unemployment_Inflation['Unemployment'], keep_internals=True,
      5     step_pattern=rabinerJuangStepPattern(6, "c"))\
      6     .plot(type="twoway",offset=-2)

~\anaconda3\lib\site-packages\dtw\dtw.py in plot(self, type, **kwargs)
    122 """
    123         # ENDIMPORT
--> 124         return dtwPlot(self, type, **kwargs)
    125
    126

~\anaconda3\lib\site-packages\dtw\dtwPlot.py in dtwPlot(x, type, **kwargs)
     68         return dtwPlotAlignment(x, **kwargs)
     69     elif type == "twoway":
---> 70         return dtwPlotTwoWay(x, **kwargs)
     71     elif type == "threeway":
     72         return dtwPlotThreeWay(x, **kwargs)

~\anaconda3\lib\site-packages\dtw\dtwPlot.py in dtwPlotTwoWay(d, xts, yts, offset, ts_type, match_indices, match_col, xlab, ylab, **kwargs)
    192     col = []
    193     for i in idx:
--> 194         col.append([(d.index1[i], xts[d.index1[i]]),
    195                     (d.index2[i], -offset + yts[d.index2[i]])])
    196

~\anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    956
    957         elif key_is_scalar:
--> 958             return self._get_value(key)
    959
    960         if is_hashable(key):

~\anaconda3\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
   1067
   1068         # Similar to Index.get_value, but we do not fall back to positional
-> 1069         loc = self.index.get_loc(label)
   1070         return self.index._get_values_for_loc(self, loc, label)
   1071

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3629                 return self._engine.get_loc(casted_key)
   3630             except KeyError as err:
-> 3631                 raise KeyError(key) from err
   3632             except TypeError:
   3633                 # If we have a listlike key, _check_indexing_error will raise

KeyError: 0

</code>```

OUTPUT I RECEIVE WITHOUT THE DTW LINES CONNECTED BETWEEN THE TWO GRAPHS

If anyone has any tips to fix this so that my dtw lines actually show up, or if my syntax is incorrect please ANYTHING HELPS!! THANKS.

Body:
I am trying to use dtw-python inside of a jupyter notebook in order to graph the Dynamic Time Warping between two time-series graphs.

I have successfully imported dtw-python into my jupyter notebook, but when I try to use dtw to plot my two time-series graphs, I keep getting errors and only the two graphs show up (not the dtw connecting lines between the graphs). Below is an image of my script that I have tried, that only plots the two graphs and not the connected dtw lines for comparison. I also receive this error message.

SCRIPT I AM USING

from dtw import *
import matplotlib.pyplot as plt

dtw(USA_Unemployment_Inflation['Inflation'], USA_Unemployment_Inflation['Unemployment'], keep_internals=True,
    step_pattern=rabinerJuangStepPattern(6, "c"))\
    .plot(type="twoway",offset=-2)

ERROR MESSAGE I RECEIVE

KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3628             try:
-> 3629                 return self._engine.get_loc(casted_key)
   3630             except KeyError as err:

~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
C:\Users\Public\Documents\Wondershare\CreatorTemp\ipykernel_17236\2682910787.py in <module>
      2 import matplotlib.pyplot as plt
      3
----> 4 dtw(USA_Unemployment_Inflation['Inflation'], USA_Unemployment_Inflation['Unemployment'], keep_internals=True,
      5     step_pattern=rabinerJuangStepPattern(6, "c"))\
      6     .plot(type="twoway",offset=-2)

~\anaconda3\lib\site-packages\dtw\dtw.py in plot(self, type, **kwargs)
    122 """
    123         # ENDIMPORT
--> 124         return dtwPlot(self, type, **kwargs)
    125
    126

~\anaconda3\lib\site-packages\dtw\dtwPlot.py in dtwPlot(x, type, **kwargs)
     68         return dtwPlotAlignment(x, **kwargs)
     69     elif type == "twoway":
---> 70         return dtwPlotTwoWay(x, **kwargs)
     71     elif type == "threeway":
     72         return dtwPlotThreeWay(x, **kwargs)

~\anaconda3\lib\site-packages\dtw\dtwPlot.py in dtwPlotTwoWay(d, xts, yts, offset, ts_type, match_indices, match_col, xlab, ylab, **kwargs)
    192     col = []
    193     for i in idx:
--> 194         col.append([(d.index1[i], xts[d.index1[i]]),
    195                     (d.index2[i], -offset + yts[d.index2[i]])])
    196

~\anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    956
    957         elif key_is_scalar:
--> 958             return self._get_value(key)
    959
    960         if is_hashable(key):

~\anaconda3\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
   1067
   1068         # Similar to Index.get_value, but we do not fall back to positional
-> 1069         loc = self.index.get_loc(label)
   1070         return self.index._get_values_for_loc(self, loc, label)
   1071

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3629                 return self._engine.get_loc(casted_key)
   3630             except KeyError as err:
-> 3631                 raise KeyError(key) from err
   3632             except TypeError:
   3633                 # If we have a listlike key, _check_indexing_error will raise

KeyError: 0

OUTPUT I RECEIVE WITHOUT THE DTW LINES CONNECTED BETWEEN THE TWO GRAPHS

If anyone has any tips to fix this so that my dtw lines actually show up, or if my syntax is incorrect please ANYTHING HELPS!! THANKS.


问:
How can I easily implement an interface with a single property that implements that interface?
```<code>public interface IStuff
{
    public int A { get; }
    public event EventHandler StuffHappened;
}

public class Stuff : IStuff
{
    public int A { get; private set; }
    public event EventHandler StuffHappened;
}

public class WorkerA : IStuff
{
    Stuff stuff = new();
    public int A => stuff.A;
    public event EventHandler StuffHappened
    {
        add => stuff.StuffHappened += value;
        remove => stuff.StuffHappened -= value;
    }
}

public class WorkerB : IStuff
{
    // same as WorkerA
}

public class WorkerC : IStuff
{
    // same as WorkerA
}
</code>```

If I have several classes that need to implement the same interface in the same way, but they can't inherit the same base class (perhaps they are already inheriting something else), is there a way to write a helper class that implements the interface and just have that as a property in the several classes that need to implement the interface and have those classes implement the interface by wrapping the helper class WITHOUT having to wrap every single property of the helper class? Wrapping events is especially the worst! I find myself in this situation so often that it's worth my time to write this post. Thanks

Body:
public interface IStuff
{
    public int A { get; }
    public event EventHandler StuffHappened;
}

public class Stuff : IStuff
{
    public int A { get; private set; }
    public event EventHandler StuffHappened;
}

public class WorkerA : IStuff
{
    Stuff stuff = new();
    public int A => stuff.A;
    public event EventHandler StuffHappened
    {
        add => stuff.StuffHappened += value;
        remove => stuff.StuffHappened -= value;
    }
}

public class WorkerB : IStuff
{
    // same as WorkerA
}

public class WorkerC : IStuff
{
    // same as WorkerA
}

If I have several classes that need to implement the same interface in the same way, but they can't inherit the same base class (perhaps they are already inheriting something else), is there a way to write a helper class that implements the interface and just have that as a property in the several classes that need to implement the interface and have those classes implement the interface by wrapping the helper class WITHOUT having to wrap every single property of the helper class? Wrapping events is especially the worst! I find myself in this situation so often that it's worth my time to write this post. Thanks


问:
Unable to find module variable by typehint
I have following code:

one.py

```<code>class Apple:
    def __init__(self):
        self.a: int = 0

    def set_a(self):
        self.a = 1

    def get_a(self):
        return self.a

obj_a: Apple = Apple()
obj_a.set_a()
</code>```

Now, I am importing obj_a in other module.

two.py

```<code>from one import obj_a

a: int = obj_a.get_a()
print(a)  # ok, it prints 1
</code>```

But I am getting error from mypy as below:
error: Module "one" has no attribute "obj_a"  [attr-defined]

Body:
I have following code:

one.py

class Apple:
    def __init__(self):
        self.a: int = 0

    def set_a(self):
        self.a = 1

    def get_a(self):
        return self.a

obj_a: Apple = Apple()
obj_a.set_a()

Now, I am importing obj_a in other module.

two.py

from one import obj_a

a: int = obj_a.get_a()
print(a)  # ok, it prints 1

But I am getting error from mypy as below:
error: Module "one" has no attribute "obj_a"  [attr-defined]


问:
Why to use SDL_gfx library to draw when I can just use SDL_RenderDrawLine
So I am currently working on an physics engine and I have to draw stuff to the screen and heard about a sdl library called sdl_gfx. The thing I wonder is why would I use that library to render shapes on screen when I could do it by the methods provided by the base sdl library such as SDL_RenderDrawLine. To comprehend this, I searched for the "lineColor" function in the source code of the SDL_GFX library and obviously it does lots of other things than "SDL_RenderDrawLine" method. But I wish to know what is the difference.</p>


问:
Can't restart UWP application via CoreApplication.RequestRestartAsync
I'm trying to restart the application, but I get NotInForeground error every time.

I tried to close every other application and loop the restart attempt to make sure it is in foreground like this

```<code>var loopRestart = true;
            while (loopRestart)
            {
                var failureReason = await CoreApplication.RequestRestartAsync("-fastInit -level 1");
                loopRestart = failureReason == AppRestartFailureReason.NotInForeground;
            }
</code>```

With or without parameters (from one of the examples found on the internet) it just won't let me do it. When I do CoreApplication.GetCurrentView() is says that the window is ActivatedInForeground quickwatch. At this point I'm lost. Version is 2004

Body:
I'm trying to restart the application, but I get NotInForeground error every time.

I tried to close every other application and loop the restart attempt to make sure it is in foreground like this

var loopRestart = true;
            while (loopRestart)
            {
                var failureReason = await CoreApplication.RequestRestartAsync("-fastInit -level 1");
                loopRestart = failureReason == AppRestartFailureReason.NotInForeground;
            }

With or without parameters (from one of the examples found on the internet) it just won't let me do it. When I do CoreApplication.GetCurrentView() is says that the window is ActivatedInForeground quickwatch. At this point I'm lost. Version is 2004


问:
How to create a circular alluvial plot in R?
I have been looking through alluvial plots in r on Stack Overflow and all of the ones I see are either horizontal or vertical but not circular. Does anyone know if this is possible to do in r? So far the code i've been working on has just led me to a horizontal plot and my goal is to show how all these species are under the same label, but in the horizontal that is not expressed clearly.

Here is some example data:

```<code>  Sample Species   Label
1    L1      Fish    Seafood
2    L2      Shark   Seafood
3    L3      Fish    Seafood
4    L4      Crab    Seafood
5    L5      Crab    Seafood
6    L6      Shark   Seafood
7    L7      Seal    Seafood
8    L8      Crab    Seafood
9    L9      Fish    Seafood
10   L0      Fish    Seafood
</code>```

Code I have been working on:

```<code>ggplot(data = Sample.ID,
       aes(axis1 = Sample, axis2 = Species, axis3 = Label)) +
  scale_x_discrete(limits = c("Sample", "Species", "Label"), expand = c(.2, .05)) +
  xlab("Classification") +
  geom_alluvium(aes(fill = Species)) +
  theme_minimal() +
  ggtitle("Sample to Species to Label")
</code>```

Which gives me a plot like this

I would like a plot that looks like this, so that the thickness of the line emphasizes how many fall under the same label.

If anyone has any tips on how to create a circular plot in ggplot that would be incredibly helpful! Or any tips on how to more clearly express they are all falling under the same category. Thank you!

Body:
I have been looking through alluvial plots in r on Stack Overflow and all of the ones I see are either horizontal or vertical but not circular. Does anyone know if this is possible to do in r? So far the code i've been working on has just led me to a horizontal plot and my goal is to show how all these species are under the same label, but in the horizontal that is not expressed clearly.

Here is some example data:

  Sample Species   Label
1    L1      Fish    Seafood
2    L2      Shark   Seafood
3    L3      Fish    Seafood
4    L4      Crab    Seafood
5    L5      Crab    Seafood
6    L6      Shark   Seafood
7    L7      Seal    Seafood
8    L8      Crab    Seafood
9    L9      Fish    Seafood
10   L0      Fish    Seafood

Code I have been working on:

ggplot(data = Sample.ID,
       aes(axis1 = Sample, axis2 = Species, axis3 = Label)) +
  scale_x_discrete(limits = c("Sample", "Species", "Label"), expand = c(.2, .05)) +
  xlab("Classification") +
  geom_alluvium(aes(fill = Species)) +
  theme_minimal() +
  ggtitle("Sample to Species to Label")

Which gives me a plot like this

I would like a plot that looks like this, so that the thickness of the line emphasizes how many fall under the same label.

If anyone has any tips on how to create a circular plot in ggplot that would be incredibly helpful! Or any tips on how to more clearly express they are all falling under the same category. Thank you!


问:
Creating a custom OIDC claim/field on Google Identity
I am trying to create a custom claim in google identity for my application (xcreds) to pull from. Basically I'm trying to use xcreds mac password syncing tool and currently it works for users whos' usernames match their email format (jsmith) matches jsmith on the laptop local account. However, we have some users with local mac usernames named incorrectly (joesmith) that don't correctly match to the cloud record (jsmith)

I need to add a field to the OIDC record, say "LocalAccount" where I specify the local account name for the user account and then xcreds can pull from that name returned by Google.

The part im struggling with is how to add a custom OIDC claim to the google identity record. I understand this is possible with azure (doc here but I've not found a way to do this with Google Identity (google workspace, cloud, etc).

Is there a way to use one of the existing fields returned maybe?

https://accounts.google.com/.well-known/openid-configuration

```<code>"claims_supported": [
  "aud",
  "email",
  "email_verified",
  "exp",
  "family_name",
  "given_name",
  "iat",
  "iss",
  "locale",
  "name",
  "picture",
  "sub"
</code>```

Maybe this just isn't possible, but wanted to ask the friendly hivemind :)

Documentation and research has not given me much to go on.

Body:
I am trying to create a custom claim in google identity for my application (xcreds) to pull from. Basically I'm trying to use xcreds mac password syncing tool and currently it works for users whos' usernames match their email format (jsmith) matches jsmith on the laptop local account. However, we have some users with local mac usernames named incorrectly (joesmith) that don't correctly match to the cloud record (jsmith)

I need to add a field to the OIDC record, say "LocalAccount" where I specify the local account name for the user account and then xcreds can pull from that name returned by Google.

The part im struggling with is how to add a custom OIDC claim to the google identity record. I understand this is possible with azure (doc here but I've not found a way to do this with Google Identity (google workspace, cloud, etc).

Is there a way to use one of the existing fields returned maybe?

https://accounts.google.com/.well-known/openid-configuration

"claims_supported": [
  "aud",
  "email",
  "email_verified",
  "exp",
  "family_name",
  "given_name",
  "iat",
  "iss",
  "locale",
  "name",
  "picture",
  "sub"

Maybe this just isn't possible, but wanted to ask the friendly hivemind :)

Documentation and research has not given me much to go on.


问:
WPF Grid MinHeight/MinWidth 'Auto' analogue?
Very commonly, inside a grid the layout behavior I want for a row/column is to have a minimum height/width that sizes exactly to the largest contained control's dimensions, but will also allow for automatically sizing larger if space is available. This is so common that I feel like this should be the default behavior, honestly, but I can't even seem to achieve it at all.

The scaling/resizing behavior I want is achieved through setting a row/column definition to a width/height of '*', the 'size to fit' behavior through using 'Auto' instead, and there is indeed a min width/height property; however this minimum does not accept 'Auto' as in input, so while something like <RowDefinition Height="*" MinHeight="Auto"/> would achieve the effect I want if it worked, it does not.

The workaround I've been using is to simply manually set the minimum dimension with some hardcoded value that seems appropriate, but for several obvious reasons this is far less desirable than having the code do the sizing for you.

Is there a good way of doing this in the general case that I am overlooking? I expect it will probably require an extra hoop or two to jump through (e.x. custom class extending grid to get the functionality I want) but hopefully I'm just missing something obvious.

Thanks.


问:
How to restart a program upon a certain action
I'm writing a program where it asks you yes or no questions and then responds to those. Instead of manually writing all the questions I wanted to have the program randomly select some questions from a list and print them out. This part I have achieved by using the random function but I also want it to repeat itself by restarting from the top and picking another random question. I got pretty close with a while True loop and a for loop, but it doesn't work.

I have already tried using a for loop and a while True, sadly, I could not figure out how to make it work.

I have seen a few posts on this but none of which answer my question.


问:
Why auto mapper throw Null Refrence Exception when mapping object to data transfer object
First of all I have read many similar topics but really I'm confused why I'm getting null refrence exception.

I have an Entity named SendCommentConfiguration :

```<code>public class SendCommentConfiguration
{
    public int Id { get; set; }
    public string Configuration { get; set; }
}
</code>```

And DTO of it named SendCommentConfigurationDTO :

```<code>public class SendCommentConfigurationDTO
{
    public int Id { get; set; }
    public string Configuration { get; set; }
}
</code>```

Configuration property is a json object that saved in database.

This is my mapper profile :

```<code>public class MapperProfiles : Profile
{
    public MapperProfiles()
    {
        CreateMap<CommentDTO, Comment>().ReverseMap();
        CreateMap<ReviewDTO, Review>().ReverseMap();
        CreateMap<WebsiteDTO, Websites>().ReverseMap();
        CreateMap<CommentGroupDTO, CommentGroup>().ReverseMap();
        CreateMap<SendCommentConfigurationDTO, SendCommentConfiguration>().ReverseMap();
    }
}
</code>```

And here I'm mapping SendCommentConfiguration to SendCommentConfigurationDTO :

```<code>public async Task<IEnumerable<SendCommentConfigurationDTO>> GetAllSendRequests()
    {
        var result = await _reportsRepository.GetAllSendRequests();
        var mappedResult = _mapper.Map<IEnumerable<SendCommentConfigurationDTO>>(result);

        return mappedResult;
    }
</code>```

Result variable is not null and has 55 records of SendCommentConfiguration Model but when I'am mapping to DTO, MappedResult is null and I'm getting NullRefrence Exception.

Body:
First of all I have read many similar topics but really I'm confused why I'm getting null refrence exception.

I have an Entity named SendCommentConfiguration :

public class SendCommentConfiguration
{
    public int Id { get; set; }
    public string Configuration { get; set; }
}

And DTO of it named SendCommentConfigurationDTO :

public class SendCommentConfigurationDTO
{
    public int Id { get; set; }
    public string Configuration { get; set; }
}

Configuration property is a json object that saved in database.

This is my mapper profile :

public class MapperProfiles : Profile
{
    public MapperProfiles()
    {
        CreateMap<CommentDTO, Comment>().ReverseMap();
        CreateMap<ReviewDTO, Review>().ReverseMap();
        CreateMap<WebsiteDTO, Websites>().ReverseMap();
        CreateMap<CommentGroupDTO, CommentGroup>().ReverseMap();
        CreateMap<SendCommentConfigurationDTO, SendCommentConfiguration>().ReverseMap();
    }
}

And here I'm mapping SendCommentConfiguration to SendCommentConfigurationDTO :

public async Task<IEnumerable<SendCommentConfigurationDTO>> GetAllSendRequests()
    {
        var result = await _reportsRepository.GetAllSendRequests();
        var mappedResult = _mapper.Map<IEnumerable<SendCommentConfigurationDTO>>(result);

        return mappedResult;
    }

Result variable is not null and has 55 records of SendCommentConfiguration Model but when I'am mapping to DTO, MappedResult is null and I'm getting NullRefrence Exception.


问:
Selenium Selenoid File Server not running in Browser Container
selenium is unable to download any files from the browsers due to a 502 error on my coworkers machine, none of my other coworkers are seeing the issue, just this one dude. We are using Firefox.

After looking at the Selenoid code a bit I learned that the containers the Browser runs in uses a File Server on port 8080 to allow downloading files from the container, but I discovered that this File Server is not running within these containers.

I verified this through this command:

```<code>docker exec -it <browser_container> curl 127.0.0.1:8080
</code>```

On my machine I get a 200 response:

```<code>```
test.xlsx
```
</code>```

But when I run this command on his machine I get this error:

```<code>Failed to connect to 127.0.0.1 port 8080 after 8 ms: Connection refused
</code>```

This is indicative that the File Server is not running within his Browser Containers. I've been trying many different firefox arguments and I've restart selenoid and the docker containers and still can't figure out what's going on, I'm completely lost right now. If anyone knows what might be going on I would be appreciative, or even if anyone has any idea how to gain more information into what's going on.

Here is the Firefox options we are using

```<code>options = webdriver.FirefoxOptions()
      options.add_argument('--width=1600')
      options.add_argument('--height=900')
      options.set_preference('browser.download.dir', '/home/selenium/Downloads')
</code>```

And our browsers.json file

```<code>{
        "chrome": {
                "default": "105.0",
                "versions": {
                        "105.0": {
                                "image": "selenoid/vnc_chrome:105.0",
                                "port": "4444",
                                "path": "/",
                                "env": ["TZ=America/Denver"]
                        }
                },
                "caps": {
                        "loggingPrefs": {"browser": "ALL"},
                        "enableVNC": true,
                        "browserName": "chrome",
                        "timeZone": "America/Denver",
                        "sessionTimeout": "1m30s"
                }
        },
        "firefox": {
                "default": "latest",
                "versions": {
                        "latest": {
                                "image": "selenoid/firefox",
                                "port": "4444",
                                "path": "/wd/hub",
                                "env": ["TZ=America/Denver"]
                        }
                },
                "caps": {
                        "loggingPrefs": {"browser": "ALL"},
                        "enableVNC": true,
                        "browserName": "firefox",
                        "timeZone": "America/Denver",
                        "sessionTimeout": "1m30s"
                }
        }
}
</code>```

We do have a custom docker-compose.yml file for starting the selenoid and selenoid_ui containers, here is the file just in case that setup matters, I doubt the issue lies here.

```<code>version: "3.9"

networks:
  selenoid_net:
    name: selenoid_net
    attachable: true
    ipam:
      config:
        - subnet: 172.198.1.0/24

services:
  selenoid:
    image: aerokube/selenoid
    restart: always
    networks:
      selenoid_net:
    ports:
      - "4444:4444"
    environment:
      - OVERRIDE_VIDEO_OUTPUT_DIR=${VIDEO_OUTPUT}/video
      - TZ=America/Denver
    volumes:
      - "/etc/selenoid:/etc/selenoid"
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "${VIDEO_OUTPUT}/video:${VIDEO_OUTPUT}/video"
      - "${VIDEO_OUTPUT}/logs:${VIDEO_OUTPUT}/logs"
      - "${PWD}:/etc/browsers"
    command: ["-conf", "/etc/browsers/browsers.json",
              "-video-output-dir", "${VIDEO_OUTPUT}/video",
              "-log-output-dir", "${VIDEO_OUTPUT}/logs",
              "-limit", "6",
              "-timeout", "1m30s","-container-network", 'selenoid_net']

  selenoid-ui:
    image: "aerokube/selenoid-ui:latest"
    restart: always
    networks:
      selenoid_net:
    links:
      - "selenoid"
    ports:
      - "8080:8080"
    command: ["--selenoid-uri", "http://selenoid:4444"]
</code>```

Body:
selenium is unable to download any files from the browsers due to a 502 error on my coworkers machine, none of my other coworkers are seeing the issue, just this one dude. We are using Firefox.

After looking at the Selenoid code a bit I learned that the containers the Browser runs in uses a File Server on port 8080 to allow downloading files from the container, but I discovered that this File Server is not running within these containers.

I verified this through this command:

docker exec -it <browser_container> curl 127.0.0.1:8080

On my machine I get a 200 response:

test.xlsx

But when I run this command on his machine I get this error:

Failed to connect to 127.0.0.1 port 8080 after 8 ms: Connection refused

This is indicative that the File Server is not running within his Browser Containers. I've been trying many different firefox arguments and I've restart selenoid and the docker containers and still can't figure out what's going on, I'm completely lost right now. If anyone knows what might be going on I would be appreciative, or even if anyone has any idea how to gain more information into what's going on.

Here is the Firefox options we are using

options = webdriver.FirefoxOptions()
      options.add_argument('--width=1600')
      options.add_argument('--height=900')
      options.set_preference('browser.download.dir', '/home/selenium/Downloads')

And our browsers.json file

{
        "chrome": {
                "default": "105.0",
                "versions": {
                        "105.0": {
                                "image": "selenoid/vnc_chrome:105.0",
                                "port": "4444",
                                "path": "/",
                                "env": ["TZ=America/Denver"]
                        }
                },
                "caps": {
                        "loggingPrefs": {"browser": "ALL"},
                        "enableVNC": true,
                        "browserName": "chrome",
                        "timeZone": "America/Denver",
                        "sessionTimeout": "1m30s"
                }
        },
        "firefox": {
                "default": "latest",
                "versions": {
                        "latest": {
                                "image": "selenoid/firefox",
                                "port": "4444",
                                "path": "/wd/hub",
                                "env": ["TZ=America/Denver"]
                        }
                },
                "caps": {
                        "loggingPrefs": {"browser": "ALL"},
                        "enableVNC": true,
                        "browserName": "firefox",
                        "timeZone": "America/Denver",
                        "sessionTimeout": "1m30s"
                }
        }
}

We do have a custom docker-compose.yml file for starting the selenoid and selenoid_ui containers, here is the file just in case that setup matters, I doubt the issue lies here.

version: "3.9"

networks:
  selenoid_net:
    name: selenoid_net
    attachable: true
    ipam:
      config:
        - subnet: 172.198.1.0/24

services:
  selenoid:
    image: aerokube/selenoid
    restart: always
    networks:
      selenoid_net:
    ports:
      - "4444:4444"
    environment:
      - OVERRIDE_VIDEO_OUTPUT_DIR=${VIDEO_OUTPUT}/video
      - TZ=America/Denver
    volumes:
      - "/etc/selenoid:/etc/selenoid"
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "${VIDEO_OUTPUT}/video:${VIDEO_OUTPUT}/video"
      - "${VIDEO_OUTPUT}/logs:${VIDEO_OUTPUT}/logs"
      - "${PWD}:/etc/browsers"
    command: ["-conf", "/etc/browsers/browsers.json",
              "-video-output-dir", "${VIDEO_OUTPUT}/video",
              "-log-output-dir", "${VIDEO_OUTPUT}/logs",
              "-limit", "6",
              "-timeout", "1m30s","-container-network", 'selenoid_net']

  selenoid-ui:
    image: "aerokube/selenoid-ui:latest"
    restart: always
    networks:
      selenoid_net:
    links:
      - "selenoid"
    ports:
      - "8080:8080"
    command: ["--selenoid-uri", "http://selenoid:4444"]


问:
How can I query AWS Batch for jobs matching multiple jobStatus values in AWS PHP SDK Version 3?
I am currently working on a PHP project using the AWS PHP SDK. I have a data import process that utilizes AWS batch. The PHP application needs to be able to check AWS for jobs that are not complete, prior to letting the user start a new job.

I am currently using the listJobs() call on the BacthClint like so, following an example given by the documentation:

```<code><?php

$client = new Aws\Batch\BatchClient([
    ...
]);

$jobs = $client->listJobs([
    'jobQueue' => '...',
    'jobStatus' => 'RUNNING',
]);
</code>```

However, I would like to get jobs matching the statuses of SUBMITTED, PENDING, RUNNABLE and STARTING as well as RUNNING.

The docs make it seem like I could submit the following value, as a pipe delinted list. But this syntax caused the request to fail:

```<code><?php

$jobs = $client->listJobs([
    'jobQueue' => '...',
    'jobStatus' => 'SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING',
]);
</code>```

Error:

```<code>Error executing request, Exception : Invalid job status SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING. Valid statuses are [SUBMITTED, PENDING, RUNNABLE, STARTING, RUNNING, SUCCEEDED, FAILED]
</code>```

Is there some kind of way that I can submit multiple values under the 'jobStatus' input?

If not, is there some other way I can do this utilizing the AWS PHP SDK?

Note:

It looks like there is a 'filters' feature listed under the heading "Parameter Details" and "Parameter Syntax" secotion in the documentation example from before. This seems to suggest that something like this should work:

```<code><?php

$jobs = $client->listJobs([
    'jobQueue' => '...',
    'filters' => [
        'name' => 'jobStatus',
        'values' => ['SUBMITTED', 'PENDING', 'RUNNABLE', 'STARTING', 'RUNNING']
    ]
]);
</code>```

"You can filter the results by job status with the jobStatus parameter. If you don't specify a status, only RUNNING jobs are returned."

"The job status used to filter jobs in the specified queue. If the filters parameter is specified, the jobStatus parameter is ignored and jobs with any status are returned. If you don't specify a status, only RUNNING jobs are returned."

However this seems to return blank result sets.

Body:
I am currently working on a PHP project using the AWS PHP SDK. I have a data import process that utilizes AWS batch. The PHP application needs to be able to check AWS for jobs that are not complete, prior to letting the user start a new job.

I am currently using the listJobs() call on the BacthClint like so, following an example given by the documentation:

<?php

$client = new Aws\Batch\BatchClient([
    ...
]);

$jobs = $client->listJobs([
    'jobQueue' => '...',
    'jobStatus' => 'RUNNING',
]);

However, I would like to get jobs matching the statuses of SUBMITTED, PENDING, RUNNABLE and STARTING as well as RUNNING.

The docs make it seem like I could submit the following value, as a pipe delinted list. But this syntax caused the request to fail:

<?php

$jobs = $client->listJobs([
    'jobQueue' => '...',
    'jobStatus' => 'SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING',
]);

Error:

Error executing request, Exception : Invalid job status SUBMITTED|PENDING|RUNNABLE|STARTING|RUNNING. Valid statuses are [SUBMITTED, PENDING, RUNNABLE, STARTING, RUNNING, SUCCEEDED, FAILED]

Is there some kind of way that I can submit multiple values under the 'jobStatus' input?

If not, is there some other way I can do this utilizing the AWS PHP SDK?

Note:

It looks like there is a 'filters' feature listed under the heading "Parameter Details" and "Parameter Syntax" secotion in the documentation example from before. This seems to suggest that something like this should work:

<?php

$jobs = $client->listJobs([
    'jobQueue' => '...',
    'filters' => [
        'name' => 'jobStatus',
        'values' => ['SUBMITTED', 'PENDING', 'RUNNABLE', 'STARTING', 'RUNNING']
    ]
]);

"You can filter the results by job status with the jobStatus parameter. If you don't specify a status, only RUNNING jobs are returned."

"The job status used to filter jobs in the specified queue. If the filters parameter is specified, the jobStatus parameter is ignored and jobs with any status are returned. If you don't specify a status, only RUNNING jobs are returned."

However this seems to return blank result sets.


问:
.aspnetcore.identity.Application cookie not set in the production environment
I have created a abp.io version 7.0-rc2 solution using the starter template.

I have chosen a tiered solution with separate authserver project(OpenIdDict) and Blazor-server as UI project. The solution works fine when I launch the AuthServer, HttpApi.Host and Blazor server UI client on localhost using development environment.

But this doesn't work in the production environment with nginx reverse proxy and using kestrel to serve the application.(The Https configuration has been done.)

The issue is, that the admin does not have some permissions after login, although I have checked with the database, all the permissions have been granted to admin.
I have checked the cookies of the blazor project domain in my browser, the .aspnetcore.identity.application cookie is not set. Of course the permission check will not pass without cookie.

The cookie has been returned from the authserver while logging in. The set-cookie does exist in the response header from authserver login form submission, as I checked using browser developer tool, but not set finally to the browser after the login process.

Then I made an experiment. I made changes to my appsettings.development.json in my blazor server UI project to let the AuthServer and HttpApi.Host running in the Production environment, and run the Blazor server on my development pc(localhost), let the blazor server using the production authserver and call the production API server too. Only the blazor server ui itself is running locally. It works then fine. The aspnetcore.identity.application cookie(localhost domain) is then successfully set to the browser.And the permissions are also successfully authorized.

I am not quite familiar with how the cookies are set in asp.net or Abp.Could somebody give me a hint, what could be the problem in the production environment? Or what should I check to find the problems out?

Thank you very much.


问:
`QMessageBox` and `QAccessible::Alert` does not play any sound in Qt6.4.1
After installing qt 6.4.1 from the online installer, I compiled old code, and the message boxes were not playing any sound.
I saw that QMessageBox plays its sound via QAccessibleEvent so I tried this

```<code>QAccessibleEvent event(this, QAccessible::Alert);
QAccessible::updateAccessibility(&event);
</code>```

But no sound is played!
I tried QSoundEffect and didn't work at first but it turned to be a bug in qt 6.4.1 and renaming "mfplat.dll" to "mfplat.dll.dll" next to the application solved it but the message box and accessibility sound are not played yet.
Is this a problem or qt removed playing alert sound with accessibility?

Body:
After installing qt 6.4.1 from the online installer, I compiled old code, and the message boxes were not playing any sound.
I saw that QMessageBox plays its sound via QAccessibleEvent so I tried this

QAccessibleEvent event(this, QAccessible::Alert);
QAccessible::updateAccessibility(&event);

But no sound is played!
I tried QSoundEffect and didn't work at first but it turned to be a bug in qt 6.4.1 and renaming "mfplat.dll" to "mfplat.dll.dll" next to the application solved it but the message box and accessibility sound are not played yet.
Is this a problem or qt removed playing alert sound with accessibility?


问:
Rails search engine remove incomplete search
Hello and thanks in advance, I´m creating a search engine using ruby on rails. so when the user puts data in the search box, the data is pushed to a query table. right now I´m using turbo frame request so you don't need to press the search button to save data on the query column, this is my issue:

the user looks for the current query: "how can you learn ruby?" but when you take too much time to type, the query column is going to save how can, in consequence, assuming that you have a search name: where is your father's house?, in the query column if you type slow, it is going to appear, where, where is, where are you, etc. what I want is to compare the complete query and erase the others that are incomplete.

this is my search box controller

```<code>    if params[:query].present?
      @articles = Article.where("title LIKE ?", "%#{params[:query]}%")
      Search.create(query: params[:query], user_id: current_user.id)
      save_search(params[:query], actual_user[:user_id])

    else

      @articles = Article.all
    end

   if turbo_frame_request?
      render partial: "articles", locals: { articles: @articles}
   else
    render :index
   end
</code>```

this is my search box on views

```<code>
<%= form_with(url: articles_path, method: :get, data: {
  controller: "search-form", turbo_frame: "articles", turbo_action: "advance"}) do |form| %>
  <%= form.label :query, "Search by article" %>
  <div>
    <%= form.text_field :query, data: { action: "input->search-form#search" } %>

    <%= form.submit "Search" %>

</code>```

so basically i want the code to compare the data on the query table, and erase the incomplete search

Body:
Hello and thanks in advance, I´m creating a search engine using ruby on rails. so when the user puts data in the search box, the data is pushed to a query table. right now I´m using turbo frame request so you don't need to press the search button to save data on the query column, this is my issue:

the user looks for the current query: "how can you learn ruby?" but when you take too much time to type, the query column is going to save how can, in consequence, assuming that you have a search name: where is your father's house?, in the query column if you type slow, it is going to appear, where, where is, where are you, etc. what I want is to compare the complete query and erase the others that are incomplete.

this is my search box controller

    if params[:query].present?
      @articles = Article.where("title LIKE ?", "%#{params[:query]}%")
      Search.create(query: params[:query], user_id: current_user.id)
      save_search(params[:query], actual_user[:user_id])

    else

      @articles = Article.all
    end

   if turbo_frame_request?
      render partial: "articles", locals: { articles: @articles}
   else
    render :index
   end

this is my search box on views

<%= form_with(url: articles_path, method: :get, data: {
  controller: "search-form", turbo_frame: "articles", turbo_action: "advance"}) do |form| %>
  <%= form.label :query, "Search by article" %>

    <%= form.text_field :query, data: { action: "input->search-form#search" } %>

    <%= form.submit "Search" %>

so basically i want the code to compare the data on the query table, and erase the incomplete search


问:
Cannot update UseSprings duration
I'm trying to update duration in a useSprings.

```<code>  const [styles, api] = useSpring(() => ({
    ref: springsRef,
    from: {
      n: 0,
    },
    n: 1,
    config: { ...config.gentle, duration: 2000, easing: easings.easeInOutQuart },
  }));
</code>```

There are some other factors I want to take into account for duration..however if I try and set the duration here as indicated in the docs the animation doesn't run. If I just add a api.start() it runs fine.

```<code>useEffect(() => {
 api({
    reset: true,
    onRest,
  });
  api.start({config: {duration: newDuration}});
  api.resume();

}, [])
</code>```

Title: Cannot update UseSprings duration

Body:
I'm trying to update duration in a useSprings.

  const [styles, api] = useSpring(() => ({
    ref: springsRef,
    from: {
      n: 0,
    },
    n: 1,
    config: { ...config.gentle, duration: 2000, easing: easings.easeInOutQuart },
  }));

There are some other factors I want to take into account for duration..however if I try and set the duration here as indicated in the docs the animation doesn't run. If I just add a api.start() it runs fine.

useEffect(() => {
 api({
    reset: true,
    onRest,
  });
  api.start({config: {duration: newDuration}});
  api.resume();

}, [])


问:
Do Java AWS Lambda best practices change when using GraalVM?
From AWS Lambda best practices:

Minimize your deployment package size to its runtime necessities

Minimize the complexity of your dependencies

I've been looking into frameworks such as quarkus-amazon-lambda and MICRONAUT 2: AWS LAMBDA FUNCTIONS and my understanding is they provide and encourage the use of "best of breed" libraries that are GraalVM friendly.

To date, my take on creating AWS Lambdas is keep dependencies to a minimum, keep the artifact small.

In the GraalVM native world, do the above quoted statements still hold true, or are we saying be more liberal with dependencies because cold start was the big issue?

EDIT:

From @jarmod in the comments:

Also be aware that SnapStart may change the equation here.

It certainly has for me, today I made the decision to go with Plain Old Java and SnapStart. This solved the cold start problem and for me, that was the big driver for auditioning these frameworks. IMO AWS Lambdas are fairly simple functions and I don't feel the need to drag in deps.

Incidentally, looking at LEVERAGING AWS LAMBDA SNAPSTART WITH THE MICRONAUT FRAMEWORK SnapStart is comparable to native for "Hello World" but when starting the framework, native is ~twice as fast. It's quite anecdotal but from this I read small jars with SnapStart fast as native, big jars with SnapStart slower than native. This makes me lean towards sticking with Plain Old Java and sticking by AWS best practise.


问:
ResizeCanvas behaviour unknown prop in Graphin when using React functional component
I have a simple functional component with G6 React wrapper Graphin.

```<code>const TheGraph = () => {
 return (
    <Graphin
      data={data}
      fitView={true}
      layout={{
        type: 'gForce',
        linkDistance: 10,
        preventOverlap: true,
        workerEnabled: true,
        gpuEnabled: true,
        maxIteration: 300,
      }}
    >
      <DragNode/>
      <ResizeCanvas graphDOM={ ??? what to put here ??? }/>
      <ActivateRelations trigger="click"/>
    </Graphin>
  )
}
</code>```

The issue is with this behaviour, in the documentation it says I have to pass "this.graphDOM", and it's mandatory. But thismeans nothing in a functional component. Plus, I have no idea what graphDOM is or where to get it from.

Body:
I have a simple functional component with G6 React wrapper Graphin.

const TheGraph = () => {
 return (
    <Graphin
      data={data}
      fitView={true}
      layout={{
        type: 'gForce',
        linkDistance: 10,
        preventOverlap: true,
        workerEnabled: true,
        gpuEnabled: true,
        maxIteration: 300,
      }}
    >
      <DragNode/>
      <ResizeCanvas graphDOM={ ??? what to put here ??? }/>
      <ActivateRelations trigger="click"/>
    </Graphin>
  )
}

The issue is with this behaviour, in the documentation it says I have to pass "this.graphDOM", and it's mandatory. But thismeans nothing in a functional component. Plus, I have no idea what graphDOM is or where to get it from.


问:
Cannot solve Xcode = Image has Unassigned Children error
Xcode = "Unassigned Children" error:

(Xcode 14.1, 14.2)

I've begun with the treatises presented in great numbers throughout SO.

Initially, it looks solved with "Individual Scales", until I change from Individual Scales to Single Scale, whereupon the "Unassigned Children" re-appears.

I have dragged the Unassigned images UP TO the Individual Scales which temporarily helps UNTIL I switch Scales as just stated.

I have also selected the unassigned image(s) and deleted via delete button. Clean and Build. NO HELP.

It's obvious that this error would cause my iOS App to be rejected.

So, what am I doing wrong?

Appreciate it.


问:
Check security in nested entities POST / PUT
Using Api Platform 2.5 / SF 4.4, I have some entities people can POST / PUT with their nested relations.

For example, I can post a Customer with:

```<code>POST /api/customers
{
   "lastname": "Doe",
   "firstname" : "John",
   "addresses": [
      {
         "@type": "ContactAddress",
         "name": "My address",
         "address": "Somewhere not so far",
      },
      {
         "@type": "ContactAddress",
         "name": "Address of my offices",
         "address": "Somewhere a little more far",
      },
   ]
}
</code>```

I just tested and my point is that I can POST an existing address:

```<code>POST /api/customers
{
   "lastname": "Doe",
   "firstname" : "John",
   "addresses": [
      {
         "@id": "/apip/addresses/3",
         "@type": "ContactAddress",
         "name": "My address",
         "address": "Somewhere not so far",
      },
   ]
}
</code>```

It will remove the link between the Address identified by ID = 3 and its previous Customer and set to the new customer. I face the same issue with a PUT.

Using a voter on the post_denormalize makes the nested relation already related to the new Customer, I can't access the previous relation of the Address.

Does anyone faced the same problem? From now, the easiest point I found is to get the Address entity from Doctrine, but it's ugly.

Body:
Using Api Platform 2.5 / SF 4.4, I have some entities people can POST / PUT with their nested relations.

For example, I can post a Customer with:

POST /api/customers
{
   "lastname": "Doe",
   "firstname" : "John",
   "addresses": [
      {
         "@type": "ContactAddress",
         "name": "My address",
         "address": "Somewhere not so far",
      },
      {
         "@type": "ContactAddress",
         "name": "Address of my offices",
         "address": "Somewhere a little more far",
      },
   ]
}

I just tested and my point is that I can POST an existing address:

POST /api/customers
{
   "lastname": "Doe",
   "firstname" : "John",
   "addresses": [
      {
         "@id": "/apip/addresses/3",
         "@type": "ContactAddress",
         "name": "My address",
         "address": "Somewhere not so far",
      },
   ]
}

It will remove the link between the Address identified by ID = 3 and its previous Customer and set to the new customer. I face the same issue with a PUT.

Using a voter on the post_denormalize makes the nested relation already related to the new Customer, I can't access the previous relation of the Address.

Does anyone faced the same problem? From now, the easiest point I found is to get the Address entity from Doctrine, but it's ugly.


问:
Curious case of printf not working correctly on Apple Silicon (M2)
I'm slowly getting used to aarch64 by translating trivial C programs to asm and learn on the go but is stuck here:

```<code>/*
int power(int i): a function to calculate exponential power
*/
.global     power       //function prologue to declare it as global
.p2align    2           // align for better access - align 2^2 bytes
power:                  // a label to start the proc
    .cfi_startproc      // declare proc start
    cmp     w1, #0      // check if base is 0
    b.eq    end         // if true then just return 0
    mov     x8, x1      // i = exp, x8 is i
    mov     x9, x0      // use x0 as result, so x9 is base
    subs    x8, x8, #1  // since we count down to 0, sub 1
loop:
    mul     w0, w0, w9  // result = result * base (w0 is part of x0)
    subs    w8, w8, #1  // i = i - 1 (w0 is part of x8)
    b.ne    loop        // if i != 0 then loop
end:
    ret                 // return to caller
    .cfi_endproc        // end proc

/**
Main function
*/
.global     _main      // Provide program starting address to linker
.align      4           // Make sure everything is aligned properly

// Setup the parameters to print hello world
// and then call the Kernel to do it.
_main:
    .cfi_startproc
    .cfi_def_cfa_offset     16

// print the power
    mov     x0, #2
    mov     x1, #3
    bl      power
    bl      print_number
    bl      println // <--------- omit this line and the output will be gone

// exit
    mov     X0, #0          // return 0
    mov     X16, #1         // syscall 1 terminate program
    svc     #0x80           // call kernel
    .cfi_endproc

/* static functions*/
.p2align    2
print_number:
    .cfi_startproc
    // stack stuff
    sub     sp, sp, #32             // substract 32 from sp
    stp     x29, x30, [sp, #16]     // store ?
    add     x29, sp, #16
    // call frame stuff
    .cfi_def_cfa    w29, 16
    .cfi_offset     w30, -8
    .cfi_offset     w29, -16
    // grab the args
    mov     x8, x0
    str     x8, [sp]
    // load string using two instructions
    // load the 4kb page from this instruction
    // can either use LDR or STR to read or write address inside
    // this page or ADD to calculate the final address using
    // the last 12 bit denoted by @PAGEOFF
    adrp    x0, format_string@PAGE
    add     x0, x0, format_string@PAGEOFF
    bl      _printf

    // refresh stack stuff
    ldp     x29,x30, [sp, #16]
    add     sp, sp, #32
    ret
    .cfi_endproc

// println: print a newline
.p2align    2
println:
    .cfi_startproc
    //stackstuff
    sub     sp, sp, #32         // sp = sp - 32
    stp     x29, x30, [sp, #16] // store stuff
    add     x29, sp, #16        // x29 = sp + 16
    //callframe
    .cfi_def_cfa    w29, 16
    .cfi_offset     w30, -8
    .cfi_offset     w29, -16

    mov     x8, x0
    str     x8, [sp]
    adrp   x0, newline@PAGE
    add     x0, x0, newline@PAGEOFF
    bl      _printf

    //refresh stack
    ldp x29, x30, [sp, #16]
    add     sp, sp, #32
    ret
    .cfi_endproc

/** Data */
.data
format_string:      .asciz  "Number is: %d"
newline:            .asciz  "\n"

</code>```

basically I will get no output at all if I omit line 38. And when compile a C file to test it out, my printf turns out like this:

```<code>Number is: 3%
</code>```

The % is not supposed to be there. I suspect that I simplified the call too much by taking out some instructions but I'm not familiar enough with aarch64 to figure out what's wrong. Can you help point me to the right direction?

Thanks,

Body:
I'm slowly getting used to aarch64 by translating trivial C programs to asm and learn on the go but is stuck here:

/*
int power(int i): a function to calculate exponential power
*/
.global     power       //function prologue to declare it as global
.p2align    2           // align for better access - align 2^2 bytes
power:                  // a label to start the proc
    .cfi_startproc      // declare proc start
    cmp     w1, #0      // check if base is 0
    b.eq    end         // if true then just return 0
    mov     x8, x1      // i = exp, x8 is i
    mov     x9, x0      // use x0 as result, so x9 is base
    subs    x8, x8, #1  // since we count down to 0, sub 1
loop:
    mul     w0, w0, w9  // result = result * base (w0 is part of x0)
    subs    w8, w8, #1  // i = i - 1 (w0 is part of x8)
    b.ne    loop        // if i != 0 then loop
end:
    ret                 // return to caller
    .cfi_endproc        // end proc

/**
Main function
*/
.global     _main      // Provide program starting address to linker
.align      4           // Make sure everything is aligned properly

// Setup the parameters to print hello world
// and then call the Kernel to do it.
_main:
    .cfi_startproc
    .cfi_def_cfa_offset     16

// print the power
    mov     x0, #2
    mov     x1, #3
    bl      power
    bl      print_number
    bl      println // <--------- omit this line and the output will be gone

// exit
    mov     X0, #0          // return 0
    mov     X16, #1         // syscall 1 terminate program
    svc     #0x80           // call kernel
    .cfi_endproc

/* static functions*/
.p2align    2
print_number:
    .cfi_startproc
    // stack stuff
    sub     sp, sp, #32             // substract 32 from sp
    stp     x29, x30, [sp, #16]     // store ?
    add     x29, sp, #16
    // call frame stuff
    .cfi_def_cfa    w29, 16
    .cfi_offset     w30, -8
    .cfi_offset     w29, -16
    // grab the args
    mov     x8, x0
    str     x8, [sp]
    // load string using two instructions
    // load the 4kb page from this instruction
    // can either use LDR or STR to read or write address inside
    // this page or ADD to calculate the final address using
    // the last 12 bit denoted by @PAGEOFF
    adrp    x0, format_string@PAGE
    add     x0, x0, format_string@PAGEOFF
    bl      _printf

    // refresh stack stuff
    ldp     x29,x30, [sp, #16]
    add     sp, sp, #32
    ret
    .cfi_endproc

// println: print a newline
.p2align    2
println:
    .cfi_startproc
    //stackstuff
    sub     sp, sp, #32         // sp = sp - 32
    stp     x29, x30, [sp, #16] // store stuff
    add     x29, sp, #16        // x29 = sp + 16
    //callframe
    .cfi_def_cfa    w29, 16
    .cfi_offset     w30, -8
    .cfi_offset     w29, -16

    mov     x8, x0
    str     x8, [sp]
    adrp   x0, newline@PAGE
    add     x0, x0, newline@PAGEOFF
    bl      _printf

    //refresh stack
    ldp x29, x30, [sp, #16]
    add     sp, sp, #32
    ret
    .cfi_endproc

/** Data */
.data
format_string:      .asciz  "Number is: %d"
newline:            .asciz  "\n"

basically I will get no output at all if I omit line 38. And when compile a C file to test it out, my printf turns out like this:

Number is: 3%

The % is not supposed to be there. I suspect that I simplified the call too much by taking out some instructions but I'm not familiar enough with aarch64 to figure out what's wrong. Can you help point me to the right direction?

Thanks,


问:
Spark Link items across quarters
I have data as below in a pyspark dataframe:

Quarter A
Quarter B
Item 1
Item 2

1
3
A
C

2
3
B
C

2
5
B
E

3
4
C
D

3
5
C
E

4
5
D
E

2
3
F
G

In the above examples A, B,C, D and E refer to the same item recorded at different quarters with different IDs. F and G relate to another item at quarters 2 and 3. The rows refer to known links between these items. That is in row 2 we are being told that item B in quarter 2 is the same item as item C in quarter 3.

What I want to do is assign one ID, the id of the first time they appeared to all entries, where we can calculate with the links provided that the items are the same items. So in the above example we would get:

Quarter A
Quarter B
Item 1
Item 2
item ID

1
3
A
C
A

2
3
B
C
A

2
5
B
E
A

3
4
C
D
A

3
5
C
E
A

4
5
D
E
A

2
3
F
G
F

As the first rows all relate to the same item and the last to another. The real data contains millions of such rows with different combinations of known links across different quarters (though always no more than over 5 quarters).

I have tried to do this via joins, but this requires numerous joins and seems very inefficient. The order is clearly critical and can be liable to issues with how the IDs are assigned.

The other idea is to use a window function over the item 1 id. Returning a list of all the IDs that ID appears with. So as below:

Quarter A
Quarter B
Item 1
Item 2
ID list

1
3
A
C
A, C

2
3
B
C
B, C, E

2
5
B
E
B, C, E

3
4
C
D
C, D, E

3
5
C
E
C, D, E

4
5
D
E
D, E

2
3
F
G
F, G

From this we can how the items are linked, as there is a trail of IDs from A to E (and F to G) across the records, with no common elements for different items. However I cannot work out the logic to do this comparison to get from these lists to the final item ID. Can you help using only pyspark APIs?

Title: Spark Link items across quarters


问:
window.location returns the previous path in React
I am trying the get the URL of the current page in a TS file in React.

I have something like this

```<code>export class TrackerClient implements AnalyticsClient {
  private tracker: typeof Tracker;

  sendEvent = ({ category, action, name, value }: sendEventProps): void => {
    console.log('sendEvent', { hash: window.location.hash, location: window.location });
    // Strangely `location` logs the present route and `hash` logs the previous route

    this.tracker = tracker.track({category, action, name, value, url: window.location.hash})
  }
}
</code>```

currently, when sendEvent is called, the following happens

```<code>currentPage: hash1
currentPage: hash2, location.hash returns hash1
currentPage: hash3, location.hash returns hash2
currentPage: hash4, location.hash returns hash3
</code>```

Please what could be the problem and how can window.location.hash log the present route?

Body:
I am trying the get the URL of the current page in a TS file in React.

I have something like this

export class TrackerClient implements AnalyticsClient {
  private tracker: typeof Tracker;

  sendEvent = ({ category, action, name, value }: sendEventProps): void => {
    console.log('sendEvent', { hash: window.location.hash, location: window.location });
    // Strangely `location` logs the present route and `hash` logs the previous route

    this.tracker = tracker.track({category, action, name, value, url: window.location.hash})
  }
}

currently, when sendEvent is called, the following happens

currentPage: hash1
currentPage: hash2, location.hash returns hash1
currentPage: hash3, location.hash returns hash2
currentPage: hash4, location.hash returns hash3

Please what could be the problem and how can window.location.hash log the present route?


问:
Laravel Livewire hide checked checkbox
in my laravel project in livewire component i need to hide/set display none or something a checked checkbox and later i need to show again if its needed . Any solutions? I could simply delete it but i wanna store it in DB

I tried do this:
https://larainfo.com/blogs/laravel-livewire-show-and-hide-div-example

but its hidding my all input checkboxes

here is my Livewire component code:

```<code><?php

namespace App\Http\Livewire\Tasks\Types;

use App\Http\Livewire\Forms\BaseForm;
use App\Models\Task\Task;
use App\Models\Task\TaskStatus;
use App\Models\Task\TaskType;
use App\Models\Task\TaskTypeStatus;
use Livewire\Component;
use App\Traits\HasPosition;
use Mpdf\Tag\Input;

class TaskTypeStatusModal extends BaseForm
{
    public $task_type_id = 0;
    public $availableStatuses = [];
    public $selectedStatuses = [];
    public $selectedStatusesList = [];

    public function mount($params = [])
    {
        $this->task_type_id = $params['task_type_id'];
        $this->title = 'Edytuj statusy';

        $this->availableStatuses = TaskStatus::orderBy('position')->get();
        $this->selectedStatuses = TaskTypeStatus::where('task_type_id', $this->task_type_id)->pluck('task_status_id');
        $this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get();
    }

    public function submit()
    {
        foreach ($this->selectedStatuses as $status) {
            TaskTypeStatus::create([
                'task_type_id' => $this->task_type_id,
                'task_status_id' => $status,
            ]);
        }

        $this->closeFromModal();
        $this->emit( 'Zapisano');
        $this->emit('list:refresh');
    }

    public function render()

    {
        return view('livewire.tasks.types.task-type-status-modal',[
            $this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get()
            ]);

    }

    public function reorder($list)
    {
        foreach ($list as $item) {
             TaskTypeStatus::find($item['value'])->update(['position' => $item['order']]);
        }

    }

    public function deleteStatus($id)
    {
        TaskTypeStatus::find($id)->delete();

    }

</code>```

and here is my blade code:

```<code><div>
    <form wire:submit.prevent="submit">
        <div class="modal-header">
            <h5 class="modal-title">{{ $title }}</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close" wire:click.prevent="closeFromModal">
                <span aria-hidden="true">×</span>
            </button>
        </div>
        <div class="modal-body">
            <h6>Wybierz statusy</h6>
            @forelse($availableStatuses as $availableStatus)
                <div class="form-check checkbox">
                    <input class="form-check-input" name="status-{{ $availableStatus->id }}"   id="status-{{ $availableStatus->id }}" wire:key="status-{{ $availableStatus->id }}"
                           wire:model.defer="selectedStatuses" type="checkbox" value="{{ $availableStatus->id }}"
                           wire:click="$toggle">
                    <label class="form-check-label" for="status-{{ $availableStatus->id }}">{{ $availableStatus->name }}</label>

                </div>
            @empty
                <tr>
                    <td colspan="3">{{ __('Brak dostępnych statusów') }}</td>
                </tr>
            @endforelse
            <hr>
            <h6>Dodane statusy</h6>
            <tr><span style="color:#3c4b64;font-size: 9pt"><b>{{ __('Przeciągnij za nazwę, aby zmienić kolejność.') }}</b></span></tr>
                    <ul class="list-group" wire:sortable="reorder">
                        @forelse ($selectedStatusesList as $selectedStatus)
                                <li class="list-group-item" value="{{ $selectedStatus->id }}"  wire:sortable.item="{{ $selectedStatus->id }}" wire:key="selectedStatus-{{ $selectedStatus->id }}">
                                <td wire:sortable.handle>{{ __($selectedStatus->taskStatus->name) }}
                                    <div class="float-right">
                                        <button wire:click.prevent="deleteStatus({{ $selectedStatus->id }})" class="btn btn-sm btn-danger">{{ __('Usuń') }}</button>
                                    </div>
                                </td>
                            </li>
                        @empty
                            <tr>
                                <td colspan="3">{{ __('Brak dodanych statusów') }}</td>
                            </tr>
                        @endforelse
                    </ul>
        </div>
        <div class="modal-footer">
            <button wire:click.prevent="closeFromModal" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
            <button type="submit" class="btn btn-primary">Zapisz</button>
        </div>
    </form>
</div>
</code>```

Title: Laravel Livewire hide checked checkbox

Body:
in my laravel project in livewire component i need to hide/set display none or something a checked checkbox and later i need to show again if its needed . Any solutions? I could simply delete it but i wanna store it in DB

I tried do this:
https://larainfo.com/blogs/laravel-livewire-show-and-hide-div-example

but its hidding my all input checkboxes

here is my Livewire component code:

<?php

namespace App\Http\Livewire\Tasks\Types;

use App\Http\Livewire\Forms\BaseForm;
use App\Models\Task\Task;
use App\Models\Task\TaskStatus;
use App\Models\Task\TaskType;
use App\Models\Task\TaskTypeStatus;
use Livewire\Component;
use App\Traits\HasPosition;
use Mpdf\Tag\Input;

class TaskTypeStatusModal extends BaseForm
{
    public $task_type_id = 0;
    public $availableStatuses = [];
    public $selectedStatuses = [];
    public $selectedStatusesList = [];

    public function mount($params = [])
    {
        $this->task_type_id = $params['task_type_id'];
        $this->title = 'Edytuj statusy';

        $this->availableStatuses = TaskStatus::orderBy('position')->get();
        $this->selectedStatuses = TaskTypeStatus::where('task_type_id', $this->task_type_id)->pluck('task_status_id');
        $this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get();
    }

    public function submit()
    {
        foreach ($this->selectedStatuses as $status) {
            TaskTypeStatus::create([
                'task_type_id' => $this->task_type_id,
                'task_status_id' => $status,
            ]);
        }

        $this->closeFromModal();
        $this->emit( 'Zapisano');
        $this->emit('list:refresh');
    }

    public function render()

    {
        return view('livewire.tasks.types.task-type-status-modal',[
            $this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get()
            ]);

    }

    public function reorder($list)
    {
        foreach ($list as $item) {
             TaskTypeStatus::find($item['value'])->update(['position' => $item['order']]);
        }

    }

    public function deleteStatus($id)
    {
        TaskTypeStatus::find($id)->delete();

    }

and here is my blade code:

    <form wire:submit.prevent="submit">

{{ $title }}

            <button type="button" class="close" data-dismiss="modal" aria-label="Close" wire:click.prevent="closeFromModal">
                ×
            </button>

Wybierz statusy

            @forelse($availableStatuses as $availableStatus)

                    <input class="form-check-input" name="status-{{ $availableStatus->id }}"   id="status-{{ $availableStatus->id }}" wire:key="status-{{ $availableStatus->id }}"
                           wire:model.defer="selectedStatuses" type="checkbox" value="{{ $availableStatus->id }}"
                           wire:click="$toggle">
                    id }}">{{ $availableStatus->name }}

            @empty

                    {{ __('Brak dostępnych statusów') }}

            @endforelse

Dodane statusy

{{ __('Przeciągnij za nazwę, aby zmienić kolejność.') }}

                        @forelse ($selectedStatusesList as $selectedStatus)

id }}"  wire:sortable.item="{{ $selectedStatus->id }}" wire:key="selectedStatus-{{ $selectedStatus->id }}">
                                {{ __($selectedStatus->taskStatus->name) }}

                                        <button wire:click.prevent="deleteStatus({{ $selectedStatus->id }})" class="btn btn-sm btn-danger">{{ __('Usuń') }}</button>

                        @empty

                                {{ __('Brak dodanych statusów') }}

                        @endforelse

            <button wire:click.prevent="closeFromModal" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
            <button type="submit" class="btn btn-primary">Zapisz</button>

    </form>


问:
How Can I Generate a Separate Image of each Segmentation in a Picture?
I'm trying to make my image data-labelling process a bit easier for myself. What I'm trying to do is I'm trying to segment an image using detectron2 instance segmentation models (https://github.com/facebookresearch/detectron2/blob/main/MODEL_ZOO.md). Honestly, I don't mind using any other segmentation model like DETR or something similar that could get the job done.

Essentially, I'm feeding an image like the following into the model: Unsegmented Tennis Match

I then use a segmentation model to generate the following output: Segmented Tennis Match.

However, what I am trying to do is get each instance in the image as its own image (kind of like a sticker). In other words, after inputting the very first image above of an unsegmented Tennis Match, I'd like to have the following images downloaded to the same folder I'm running my Python file:

Segmented Tennis Ball

Segmented Tennis Racket

Segmented Person

If anyone could provide me with a simple script to do so, that would be great (it would be more so appreciated if I could run and test this script on a Google Colab notebook directly). Thanks in advance!

I tried using the Detectron2 segmentation models by themselves but all this does is overlay masks onto the original image. Instead, I would like to have separate instances in the image instead of masks of different colours displayed on the original picture.

This is how my code looks so far:

```<code>
import torch

import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()

from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog, DatasetCatalog

import cv2
from google.colab.patches import cv2_imshow

image = cv2.imread("./RogerFederer.jpg")
cv2_imshow(image)

cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml"))
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml")

cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.6

viz = Visualizer(image[:,:,::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]))
output = viz.draw_instance_predictions(outputs["instances"].to("cpu"))
cv2_imshow(output.get_image()[:,:,::-1])

</code>```

Again, I'm open to changing my code or using a different image segmentation library

Body:
I'm trying to make my image data-labelling process a bit easier for myself. What I'm trying to do is I'm trying to segment an image using detectron2 instance segmentation models (https://github.com/facebookresearch/detectron2/blob/main/MODEL_ZOO.md). Honestly, I don't mind using any other segmentation model like DETR or something similar that could get the job done.

Essentially, I'm feeding an image like the following into the model: Unsegmented Tennis Match

I then use a segmentation model to generate the following output: Segmented Tennis Match.

However, what I am trying to do is get each instance in the image as its own image (kind of like a sticker). In other words, after inputting the very first image above of an unsegmented Tennis Match, I'd like to have the following images downloaded to the same folder I'm running my Python file:

Segmented Tennis Ball

Segmented Tennis Racket

Segmented Person

If anyone could provide me with a simple script to do so, that would be great (it would be more so appreciated if I could run and test this script on a Google Colab notebook directly). Thanks in advance!

I tried using the Detectron2 segmentation models by themselves but all this does is overlay masks onto the original image. Instead, I would like to have separate instances in the image instead of masks of different colours displayed on the original picture.

This is how my code looks so far:

import torch

import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()

from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog, DatasetCatalog

import cv2
from google.colab.patches import cv2_imshow

image = cv2.imread("./RogerFederer.jpg")
cv2_imshow(image)

cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml"))
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x.yaml")

cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.6

viz = Visualizer(image[:,:,::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]))
output = viz.draw_instance_predictions(outputs["instances"].to("cpu"))
cv2_imshow(output.get_image()[:,:,::-1])

Again, I'm open to changing my code or using a different image segmentation library


问:
PHP7-8 - How to check if caught Throwable i warning?
Well, it is exactly what I want to know. How to check if caught Throwable is a warning?

```<code>        try {
           // Some code that generates warnings
        } catch (Throwable $t) {
           // How to check what $t is? Warning, Exception, or something else?
        }
</code>```

Specifically, here I need just a warning. Thanks

EDIT: forgot to say, I do not have control over the code that generates error.

Body:
Well, it is exactly what I want to know. How to check if caught Throwable is a warning?

        try {
           // Some code that generates warnings
        } catch (Throwable $t) {
           // How to check what $t is? Warning, Exception, or something else?
        }

Specifically, here I need just a warning. Thanks

EDIT: forgot to say, I do not have control over the code that generates error.


问:
How can I execute a script in specific dir with subprocess?
When I need to execute a script-B from script-A, I am using subprocess call to start that script-B in a specific directory-B, but it executes as though it is in the directory-A of the script-A which is calling it with subprocess.

Script-B creates files. The files that it creates should be created in directory-B, but they are generated in directory-A instead.

Below: PATH is directory-B, self is script-B.

I am trying

```<code>PATH = some_directory
# Get current script name

self = os.path.basename(__file__)

# Copy old-self to desired directory.
os.popen(f"copy {self} {PATH}\\{self}")

# Open new-self in selected dir
subprocess.call([f"{PATH}\{self}"])
</code>```

Body:
When I need to execute a script-B from script-A, I am using subprocess call to start that script-B in a specific directory-B, but it executes as though it is in the directory-A of the script-A which is calling it with subprocess.

Script-B creates files. The files that it creates should be created in directory-B, but they are generated in directory-A instead.

Below: PATH is directory-B, self is script-B.

I am trying

PATH = some_directory
# Get current script name

self = os.path.basename(__file__)

# Copy old-self to desired directory.
os.popen(f"copy {self} {PATH}\\{self}")

# Open new-self in selected dir
subprocess.call([f"{PATH}\{self}"])


问:
Identical strings don't seem to be treated as identical for the if statement
I am writing a small program to read a list of passwords and search for a password that has been inputted by the user. For some reason, even if I deliberately enter a password that is in the file, it doesn't print that the password is found.
Below is the full code. It just seems whatever I do I cannot compare two strings!

```<code>fn main() -> io::Result<()> {
    let user_password: String = user_input::get_user_input("Enter password:");

    let file: File = File::open("passwords.txt")?;
    let reader: BufReader<File> = BufReader::new(file);

    for line in reader.lines() {
        let line: String = line.unwrap();
        if line == user_password {
            println!("Password file contains {}!", user_password);
            break;
        }
    }

    Ok(())
}

</code>```

Just before the if statement, I did:

```<code>println!("{}:{}", line, user_password);
</code>```

and it was identical!

I have tried

```<code>if line.contains(&user_password)
</code>```

and I have also tried the functional route doing

```<code>reader.lines().for_each(|line| {
    // the same if statement as above
});
</code>```

EDIT: As requested, here is the code for get_user_input(), apologies for not including that before.

```<code>use std::io;

pub fn get_user_input(prompt: &str) -> String {
    println!("{}", prompt);

    let mut user_input: String = String::new();

    io::stdin().read_line(&mut user_input).expect("Failed to read line");

    user_input
}
</code>```

Body:
I am writing a small program to read a list of passwords and search for a password that has been inputted by the user. For some reason, even if I deliberately enter a password that is in the file, it doesn't print that the password is found.
Below is the full code. It just seems whatever I do I cannot compare two strings!

fn main() -> io::Result<()> {
    let user_password: String = user_input::get_user_input("Enter password:");

    let file: File = File::open("passwords.txt")?;
    let reader: BufReader<File> = BufReader::new(file);

    for line in reader.lines() {
        let line: String = line.unwrap();
        if line == user_password {
            println!("Password file contains {}!", user_password);
            break;
        }
    }

    Ok(())
}

Just before the if statement, I did:

println!("{}:{}", line, user_password);

and it was identical!

I have tried

if line.contains(&user_password)

and I have also tried the functional route doing

reader.lines().for_each(|line| {
    // the same if statement as above
});

EDIT: As requested, here is the code for get_user_input(), apologies for not including that before.

use std::io;

pub fn get_user_input(prompt: &str) -> String {
    println!("{}", prompt);

    let mut user_input: String = String::new();

    io::stdin().read_line(&mut user_input).expect("Failed to read line");

    user_input
}


问:
Concatenate Numpy arrays of different shape
I would like to create a numpy array by concatenating two or more numpy arrays with shape (1, x, 1) where x is variable.

Here is the problem in detail.

```<code>x1 = #numpy array with shape (x,)
x2 = #numpy array with shape (y,)

#create batch
x1 = np.expand_dims(x1, 0) #shape (1, x)
x2 = np.expand_dims(x2, 0) #shape (1, y)

#add channel dimension
x1 = np.expand_dims(x1, -1) #shape (1, x, 1)
x2 = np.expand_dims(x2, -1) #shape (1, y, 1)

#merge the two arrays
x = np.concatenate((x1, x2), axis=0)
#expected shape (2, ??, 1)

</code>```

Note the expected shape (2, ??, 1). I am wondering if what I am trying to do is doable.

Executing this code raises a ValueError:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 138241 and the array at index 1 has size 104321

Body:
I would like to create a numpy array by concatenating two or more numpy arrays with shape (1, x, 1) where x is variable.

Here is the problem in detail.

x1 = #numpy array with shape (x,)
x2 = #numpy array with shape (y,)

#create batch
x1 = np.expand_dims(x1, 0) #shape (1, x)
x2 = np.expand_dims(x2, 0) #shape (1, y)

#add channel dimension
x1 = np.expand_dims(x1, -1) #shape (1, x, 1)
x2 = np.expand_dims(x2, -1) #shape (1, y, 1)

#merge the two arrays
x = np.concatenate((x1, x2), axis=0)
#expected shape (2, ??, 1)

Note the expected shape (2, ??, 1). I am wondering if what I am trying to do is doable.

Executing this code raises a ValueError:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 138241 and the array at index 1 has size 104321


问:
My <Link> tag from react-scroll seems to have no destination, but it is passed to it in code
I  am trying to make a smooth transition to my second panel of the page by making anchor, as I read on the internet the proper way to do this is by using react.scroll but after doing everything like on the internet my   tag simply don't work, while inspecting it with the browser it shows and  tag with no destination to go to.

my app comopnent is site in this project:
`

```<code>import React, {Component} from 'react';
import Firstpanel from "./firstpanel";
import Secondpanel from "./secondpanel";
import Thirdpanel from "./thirdpanel";

class Site extends Component {
    render() {
        return (
            <div className={"h-screen snap-y snap-mandatory overflow-x-hidden"}>
                <div className={"snap-start bg-[url('../public/images/banner_cropped.png')] bg-dark-grey bg-blend-multiply bg-[length:100vw_100vh]  h-screen w-screen "}>
                    <Firstpanel></Firstpanel>
                    <Secondpanel></Secondpanel>
                    <Thirdpanel></Thirdpanel>
                </div>
            </div>
        );
    }
}

export default Site;
</code>```

`

then my first panel:
`

```<code>import React, {Component} from 'react';
import {Link} from "react-scroll";

class Firstpanel extends Component {
    render() {
        return (
            <section className={" w-screen h-screen flex justify-center items-center flex-col gap-20"}>
                <h1 className={"font-bold text-8xl text-beige select-none"}>Welcome to the coding world!</h1>
                <p className={"font-bold text-4xl text-beige select-none"}>This site is going to be my personal portfolio for future projects</p>
                <Link className={"w-16 h-16 rounded-full mt-12 animate-bounce"} to="sec" spy={true} smooth={true}>
                <div className={"rounded-full w-16 h-16 bg-[url('../public/images/second_white_arrow_down.png')] bg-cover cursor-pointer"} type="button">
                </div></Link>
            </section>
        );
    }
}

export default Firstpanel;
</code>```

`

and my second panel:
`

```<code>import React, {Component} from 'react';

class Secondpanel extends Component {
    render() {
        return (
            <section  className={"snap-start bg-dark-grey h-screen w-screen"}>
                <h1 id="home">Hi Paul</h1>
            </section>
        );
    }
}

export default Secondpanel;
</code>```

`

I tried play with the react.scroll, but even after that it alwyas did nothing

Body:
I  am trying to make a smooth transition to my second panel of the page by making anchor, as I read on the internet the proper way to do this is by using react.scroll but after doing everything like on the internet my   tag simply don't work, while inspecting it with the browser it shows and  tag with no destination to go to.

my app comopnent is site in this project:
`

import React, {Component} from 'react';
import Firstpanel from "./firstpanel";
import Secondpanel from "./secondpanel";
import Thirdpanel from "./thirdpanel";

class Site extends Component {
    render() {
        return (

                    <Firstpanel></Firstpanel>
                    <Secondpanel></Secondpanel>
                    <Thirdpanel></Thirdpanel>

        );
    }
}

export default Site;

`

then my first panel:
`

import React, {Component} from 'react';
import {Link} from "react-scroll";

class Firstpanel extends Component {
    render() {
        return (

Welcome to the coding world!

This site is going to be my personal portfolio for future projects

                <Link className={"w-16 h-16 rounded-full mt-12 animate-bounce"} to="sec" spy={true} smooth={true}>

</Link>

        );
    }
}

export default Firstpanel;

`

and my second panel:
`

import React, {Component} from 'react';

class Secondpanel extends Component {
    render() {
        return (

Hi Paul

        );
    }
}

export default Secondpanel;

`

I tried play with the react.scroll, but even after that it alwyas did nothing