问:
Can OpenSea royalty payments be made to a smart contract?
The goal is to test whether OpenSea will make royalty payments to a smart contract instead of a regular wallet. I'm curious as to whether they will incur possibly higher gas charges when the recipient is a smart contract. I cannot find any documentation on this, and I'm happy to test it on https://testnets.opensea.io/, but I cannot find information on whether they actually pay out test royalties on the testnets platform.

Since I can't test it, back to the question: does anyone know if OpenSea will make royalty payment to a smart contract?

答:
Yes, royalties can be paid out to a smart contract (for example to a Payment Splitter). It says so on your collection's settings page, directly under the input where you provide the wallet address.

And no, they do currently not pay out any royalties on Testnet, so you need to test it live. Tip would be to maybe try testing it on Polygon, since the gas fees are minimal in comparison to Ethereum Mainnet right now.

Edit: https://docs.opensea.io/docs/frequently-asked-questions here's info about them not paying royalties on testnet.

When do I receive fees from secondary sales? Will I receive fees when testing on Rinkeby? We send secondary fees to developers and
creators once every two weeks, in one bulk transaction. In the future,
this process will be automated, so you'll receive fees straight away.

We don't currently send secondary fees on the Rinkeby test network.


来源: stackexchange

问:
Problems with function on Shell Script
Trying to test functions on ShellScript, but I keep receiving the answer: "Command not found"

```<code># Trying to create functions that receives arguments e have returns
# The function will receive two values and say hwo is bigger

bigger () {
if [$1 -gt $2]
then
   return $1
else
   return $2
fi
}

echo "Size does matter!!!!"
echo " "
printf "Enter the first number: - "
read data1
echo " "
printf "Enter the second number: - "
read data2
echo " "
printf "The bigger number is: - "
bigger $data1 $data2
</code>```

The result I get is:

enter image description here

答:
You have a syntax error and bash tries to interpret [1 as a command.
Add spaces to fix this

Change

```<code>if [$1 -gt $2]
</code>```

to

```<code>if [ "$1" -gt "$2" ]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Problems with function on Shell Script

Body:
Trying to test functions on ShellScript, but I keep receiving the answer: "Command not found"

# Trying to create functions that receives arguments e have returns
# The function will receive two values and say hwo is bigger

bigger () {
if [$1 -gt $2]
then
   return $1
else
   return $2
fi
}

echo "Size does matter!!!!"
echo " "
printf "Enter the first number: - "
read data1
echo " "
printf "Enter the second number: - "
read data2
echo " "
printf "The bigger number is: - "
bigger $data1 $data2

The result I get is:

enter image description here

Body:
You have a syntax error and bash tries to interpret [1 as a command.
Add spaces to fix this

Change

if [$1 -gt $2]

to

if [ "$1" -gt "$2" ]


问:
Importing files outside my App.js - React Native
I'm new to React Native and I'm currently trying to create a cookbook application with Expo. And I'm looking for a solution to shorten my importing in my App.js since they're all in the same folder. Here it looks like:

```<code>import Ampalaya from "./recipes/Ampalaya";
import AdobongSitaw from "./recipes/AdobongSitaw";
import BananaQue from "./recipes/BananaQue";
import Bibingka from "./recipes/Bibingka";
import BukoPie from "./recipes/BukoPie";
</code>```

And this is how I use these all I imported:

```<code><NavigationContainer>
        <StatusBar style="auto" />
        <Stack.Navigator>

          <Stack.Screen
            name="Ampalaya"
            component={Ampalaya}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="AdobongSitaw"
            component={AdobongSitaw}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BananaQue"
            component={BananaQue}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="Bibingka"
            component={Bibingka}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BukoPie"
            component={BukoPie}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
</code>```

答:
You can do like this

import {Ampalaya, AdobongSitaw, BananaQue, Bibingka, BukoPie} from "./recipes";

Body:
I'm new to React Native and I'm currently trying to create a cookbook application with Expo. And I'm looking for a solution to shorten my importing in my App.js since they're all in the same folder. Here it looks like:

import Ampalaya from "./recipes/Ampalaya";
import AdobongSitaw from "./recipes/AdobongSitaw";
import BananaQue from "./recipes/BananaQue";
import Bibingka from "./recipes/Bibingka";
import BukoPie from "./recipes/BukoPie";

And this is how I use these all I imported:

<NavigationContainer>
        <StatusBar style="auto" />
        <Stack.Navigator>

          <Stack.Screen
            name="Ampalaya"
            component={Ampalaya}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="AdobongSitaw"
            component={AdobongSitaw}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BananaQue"
            component={BananaQue}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="Bibingka"
            component={Bibingka}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BukoPie"
            component={BukoPie}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>


问:
Django 4.0 - Saving Multiple Options using MultipleChoiceField
I am trying to save Multiple Choice Fields in an array inside my database

I have no idea how to do this, I have a working solution by using the standard ChoiceField but it only saves one option at the moment

I want my values inside the database to show as for example "Beavers, Cubs" or "Scouts, Cubs"

How can I change my current code to do this?

(This is only my 2nd question so any constructive criticism will be appreciated)

models.py

class User(AbstractBaseUser, PermissionsMixin):
    # A full User model with admin-compliant permissions that uses a full-length email field as the username
    # Email and password are required but all other fields are optional
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    username = models.CharField(max_length=50, unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    section = models.CharField(max_length=30)
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin site.'))
    is_executive = models.BooleanField(_('executive status'), default=False,
        help_text=_('Designates that this user is part of the executive committee.'))
    is_superuser = models.BooleanField(_('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlencode(self.email)

    def get_full_name(self):
        # Returns the first_name plus the last_name, with a space in between
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        # Returns the short name (first name) for the user
        return self.first_name
```
<p>views.py</p>
<pre class="lang-py prettyprint-override"><code>def register(request):
    articles = Article.objects.filter(status=1).order_by('-date_posted')[:2]
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.username = request.POST.get('username')
            user.section = request.POST.get('section')
            user.second_section = request.POST.get('second_section')
            user.save()
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('login')
    else:
        form = UserRegisterForm()

    context = {
        'title': 'Register',
        'articles': articles,
        'form': form,
    }

    return render(request, 'accounts/register.html', context)
</code>```

forms.py

SECTION = [
    ('Beavers', 'Beavers'),
    ('Cubs', 'Cubs'),
    ('Scouts', 'Scouts'),
]

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    section = forms.ChoiceField(label='Childs Section', choices=SECTION, widget=forms.RadioSelect,
        help_text='Please select the section that your child currently attends.')
    """
    section = forms.MultipleChoiceField(label='Childs Section', choices=SECTION, widget=forms.CheckboxSelectMultiple,
        help_text='Please select the section(s) that your child currently attends.')
    """
    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'section']
```

答:
In the views.py change the following line

```<code>user.section = request.POST.get('section')
</code>```

to

```<code>user.section = ‘,’.join(request.POST.getlist('section'))
</code>```

Or change ‘section’ to be a JSONField and list to it.

Body:
I am trying to save Multiple Choice Fields in an array inside my database

I have no idea how to do this, I have a working solution by using the standard ChoiceField but it only saves one option at the moment

I want my values inside the database to show as for example "Beavers, Cubs" or "Scouts, Cubs"

How can I change my current code to do this?

(This is only my 2nd question so any constructive criticism will be appreciated)

models.py

class User(AbstractBaseUser, PermissionsMixin):
    # A full User model with admin-compliant permissions that uses a full-length email field as the username
    # Email and password are required but all other fields are optional
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    username = models.CharField(max_length=50, unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    section = models.CharField(max_length=30)
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin site.'))
    is_executive = models.BooleanField(_('executive status'), default=False,
        help_text=_('Designates that this user is part of the executive committee.'))
    is_superuser = models.BooleanField(_('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlencode(self.email)

    def get_full_name(self):
        # Returns the first_name plus the last_name, with a space in between
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        # Returns the short name (first name) for the user
        return self.first_name

views.py

def register(request):
    articles = Article.objects.filter(status=1).order_by('-date_posted')[:2]
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.username = request.POST.get('username')
            user.section = request.POST.get('section')
            user.second_section = request.POST.get('second_section')
            user.save()
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('login')
    else:
        form = UserRegisterForm()

    context = {
        'title': 'Register',
        'articles': articles,
        'form': form,
    }

    return render(request, 'accounts/register.html', context)

forms.py

SECTION = [
    ('Beavers', 'Beavers'),
    ('Cubs', 'Cubs'),
    ('Scouts', 'Scouts'),
]

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    section = forms.ChoiceField(label='Childs Section', choices=SECTION, widget=forms.RadioSelect,
        help_text='Please select the section that your child currently attends.')
    """
    section = forms.MultipleChoiceField(label='Childs Section', choices=SECTION, widget=forms.CheckboxSelectMultiple,
        help_text='Please select the section(s) that your child currently attends.')
    """
    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'section']

Body:
In the views.py change the following line

user.section = request.POST.get('section')

to

user.section = ‘,’.join(request.POST.getlist('section'))

Or change ‘section’ to be a JSONField and list to it.


问:
Curl request to a Kubernetes cluster type service
I am trying to send a curl request to a Kubernetes ClusterType service. Is there any way to perform curl requests to service?

I am deploying an application with Blue/Green deployment. So here need to verify the Blue version is properly working or not. So decide to send a curl request to the blue version. When I get 200 status, I will route all traffic to this version.

But now am facing that send curl request to the new version(Blue version) of the application.

答:
ClusterIP makes the Service only reachable from within the cluster. This is the default ServiceType. You can read more information about services here.

As the command in the first answer doesn't work, I'm posting the working solution:

kubectl run tmp-name --rm --image nginx -i --restart=Never -- /bin/bash -c 'curl -s clusterip:port'
```
<p>with the above command curl is working fine. You can use a service name instead of cluster IP address.</p>
<p><code>--restart=Never</code> is needed for using curl like this.</p>
<p><code>--rm</code> ensures the Pod is deleted when the shell exits.</p>
<h5>Edited:</h5>
<h3>But if you want to access your ClusterIp service from the host on which you run kubectl, you can use Port Forwarding.</h3>
<pre class="lang-sh prettyprint-override"><code>kubectl port-forward service/yourClusterIpServiceName 28015:yourClusterIpPort
</code>```

You will get output like this:

Forwarding from 127.0.0.1:28015 -> yourClusterIpPort
Forwarding from [::1]:28015 -> yourClusterIpPort
```
<p>after that you will be able to reach your ClusterIP service using this command:</p>
<pre class="lang-sh prettyprint-override"><code>curl localhost:28015
</code>```

More information about port forwarding is on the official documentation page.

Body:
ClusterIP makes the Service only reachable from within the cluster. This is the default ServiceType. You can read more information about services here.

As the command in the first answer doesn't work, I'm posting the working solution:

kubectl run tmp-name --rm --image nginx -i --restart=Never -- /bin/bash -c 'curl -s clusterip:port'

with the above command curl is working fine. You can use a service name instead of cluster IP address.

--restart=Never is needed for using curl like this.

--rm ensures the Pod is deleted when the shell exits.

Edited:

But if you want to access your ClusterIp service from the host on which you run kubectl, you can use Port Forwarding.

kubectl port-forward service/yourClusterIpServiceName 28015:yourClusterIpPort

You will get output like this:

Forwarding from 127.0.0.1:28015 -> yourClusterIpPort
Forwarding from [::1]:28015 -> yourClusterIpPort

after that you will be able to reach your ClusterIP service using this command:

curl localhost:28015

More information about port forwarding is on the official documentation page.


问:
Form.Close() doesn't close window immediately
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

```<code>public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }
</code>```

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

答:
Well, if the user closes the main form, then upon closing it your application will definitely exit, since your form is responsible for keeping the application alive when it was passed to Application.Run().

Now, if you want to close your app when a form is closed, in that form you do this:

```<code>protected override void OnFormClosed(FormClosedEventArgs e)
{
    base.OnFormClosed(e);
    Application.Exit();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

Body:
Well, if the user closes the main form, then upon closing it your application will definitely exit, since your form is responsible for keeping the application alive when it was passed to Application.Run().

Now, if you want to close your app when a form is closed, in that form you do this:

protected override void OnFormClosed(FormClosedEventArgs e)
{
    base.OnFormClosed(e);
    Application.Exit();
}


问:
Azure devops CI/CD docker build COPY Failed Path not found
I am hosting my own build-agent on my on-premises windows server.
However, when I either try to build my docker image using the default agent or my on-premisses agent, it cannot copy the .cproj files.

What I want, is to be able to build this image without the errors.
What I have tried so far is:

Changes work directory to: ../ , ../../ and ~/

Google for solutions, but this does not result in anything, because it is too specific or something.

Please note that it also does not work on an agent from DevOps itself (windows-2022)
Does anyone know what I could have done wrong or overlooked?

Directories:

src/Server/DockerFile

src/Server/Server.csproj

And so on for the other .csproj files

```<code>FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
ENV ASPNETCORE_URLS=https://+:5005;http://+:5006
WORKDIR /app
EXPOSE 5005
EXPOSE 5006

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /
COPY ["src/Server/Server.csproj", "src/Server/"]
COPY ["src/Application/Application.csproj", "src/Application/"]
COPY ["src/Domain/Domain.csproj", "src/Domain/"]
COPY ["src/Shared/Shared.csproj", "src/Shared/"]
COPY ["src/Infrastructure.Shared/Infrastructure.Shared.csproj", "src/Infrastructure.Shared/"]
COPY ["src/Infrastructure/Infrastructure.csproj", "src/Infrastructure/"]
COPY ["src/Client/Client.csproj", "src/Client/"]
COPY ["src/Client.Infrastructure/Client.Infrastructure.csproj", "src/Client.Infrastructure/"]
RUN dotnet restore "src/Server/Server.csproj" --disable-parallel
COPY . .
WORKDIR "src/Server"
RUN dotnet build "Server.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Server.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
WORKDIR /app/Files
WORKDIR /app
ENTRYPOINT ["dotnet", "DeDenDannenburcht.Server.dll"]
</code>```

My Pipeline

Pipeline Output

```<code>"C:\Program Files\Docker\Docker\resources\bin\docker.exe" build -f F:\agents\_work\1\s\src\Server\Dockerfile -t dedendannenburcht:166 --label com.azure.dev.image.system.teamfoundationcollectionuri=https://dev.azure.com/JeremiedevosBusiness/ --label com.azure.dev.image.build.sourceversion=ab657210c8696881754f36393adee9da7394ea19 --label image.base.ref.name=mcr.microsoft.com/dotnet/aspnet:6.0 --label image.base.digest=sha256:545da8027d0de13ac88716fc380201f05ad9b4834b5b2fd95eadf277e51318a7 F:\agents\_work\1\s\src\Server
#1 [internal] load build definition from Dockerfile
#1 sha256:5cec5c1a6e883854d5ef516a04f7fbc4f77cc63f74549820c4d061dbb560e514
#1 transferring dockerfile: 1.31kB done
#1 DONE 0.0s

#2 [internal] load .dockerignore
#2 sha256:8f7ecf610ac80d8ac3c3e64e4de2e264ecf11892bf7afc5ff6debe41dd69161b
#2 transferring context: 2B done
#2 DONE 0.0s

#4 [internal] load metadata for mcr.microsoft.com/dotnet/aspnet:6.0
#4 sha256:ac4494cbca04ddb415c76edcbcc7688784c2a6ea65dd656286c013738aa3b75f
#4 DONE 0.0s

#3 [internal] load metadata for mcr.microsoft.com/dotnet/sdk:6.0
#3 sha256:9eb4f6c3944cfcbfe18b9f1a753c769fc35341309a8d4a21f8937f47e94c712b
#3 DONE 0.1s

#5 [base 1/2] FROM mcr.microsoft.com/dotnet/aspnet:6.0
#5 sha256:50f1ddc10932c4a74c7af5704e931a9489c710faea4f2381fe2380827a900e00
#5 DONE 0.0s

#6 [base 2/2] WORKDIR /app
#6 sha256:bc3cf6c390e5fe0e66017b4845c8fcf3e56c7adac9f514a00c2c986024f377a4
#6 CACHED

#7 [final 1/4] WORKDIR /app
#7 sha256:3baba3edbb555769ad9a49e827de88d7dcc4f72ad6e2b42e576964e4a30eac96
#7 CACHED

#8 [build  1/14] FROM mcr.microsoft.com/dotnet/sdk:6.0@sha256:a3dd4dee05cd1369014244d03b28b602e6a2e1650210dd8633322e00379471ec
#8 sha256:ff704f84298cdcbd6cd764720a2e1a4dcd4b44ff415133896e77ad0c5d908001
#8 resolve mcr.microsoft.com/dotnet/sdk:6.0@sha256:a3dd4dee05cd1369014244d03b28b602e6a2e1650210dd8633322e00379471ec done
#8 sha256:0af6b8199917326984baa1452533da610b46f65bfbc5296c7f81cb72d3beec84 2.01kB / 2.01kB done
#8 sha256:dc243ad423c72b21b838c1362ca152823b0b379a546887d8c47c437357576fb2 7.31kB / 7.31kB done
#8 sha256:664e00cfda3df2ac7370c116f04a17d636fc041b62bdd9a0b88a60b987344269 0B / 136.50MB 0.1s
#8 sha256:a3dd4dee05cd1369014244d03b28b602e6a2e1650210dd8633322e00379471ec 2.17kB / 2.17kB done
#8 sha256:4253139ebd4dcee5f7878254306eb794d0f2a80ee4ca8d085d0b9e507412fb1e 0B / 25.36MB 0.1s

#10 sha256:aa96c6c99b71465c230e63fb1edea0588e2b25c39d6b44fc1381e7cbe48c15d9
#10 ERROR: "/src/Server/Server.csproj" not found: not found

#13 [build  5/14] COPY [src/Shared/Shared.csproj, src/Shared/]
#13 sha256:8fd70ae770f73428f5ff667da9b5080dff2b8035dbeb1247fe9e76d5890ad27d
#13 ERROR: "/src/Shared/Shared.csproj" not found: not found

#16 [build  8/14] COPY [src/Client/Client.csproj, src/Client/]
#16 sha256:33c15418c5097a788d8ef568338206ce45e5fea62b707a2be13c136b28ca43e9
#16 ERROR: "/src/Client/Client.csproj" not found: not found

#15 [build  7/14] COPY [src/Infrastructure/Infrastructure.csproj, src/Infrastructure/]
#15 sha256:4f643811b59a89db4a864a2a40a7ff2cc05709c3b123027874b72ff436af0d56
#15 ERROR: "/src/Infrastructure/Infrastructure.csproj" not found: not found

#17 [build  9/14] COPY [src/Client.Infrastructure/Client.Infrastructure.csproj, src/Client.Infrastructure/]
#17 sha256:b7385969b745977db24f702bc1c8f0b931cd675b9f44e70870ae2d918632e9b3
#17 ERROR: "/src/Client.Infrastructure/Client.Infrastructure.csproj" not found: not found

#14 [build  6/14] COPY [src/Infrastructure.Shared/Infrastructure.Shared.csproj, src/Infrastructure.Shared/]
#14 sha256:f101a94226cbf6f38fe9d908da512ded2bd68070207a6dd5c003d8967252c970
#14 ERROR: "/src/Infrastructure.Shared/Infrastructure.Shared.csproj" not found: not found

#12 [build  4/14] COPY [src/Domain/Domain.csproj, src/Domain/]
#12 sha256:152a7025db6bab6e2e456a9ab7ef8436cc9689411341ea38c362df78a0d058c1
#12 ERROR: "/src/Domain/Domain.csproj" not found: not found

#11 [build  3/14] COPY [src/Application/Application.csproj, src/Application/]
#11 sha256:1760818b73b46bb8ebf75492933a413de08fd2ab7a26cae37de4ae4a5f60b83e
#11 ERROR: "/src/Application/Application.csproj" not found: not found
------
 > [build  2/14] COPY [src/Server/Server.csproj, src/Server/]:
------
------
 > [build  3/14] COPY [src/Application/Application.csproj, src/Application/]:
------
------
 > [build  4/14] COPY [src/Domain/Domain.csproj, src/Domain/]:
------
------
 > [build  5/14] COPY [src/Shared/Shared.csproj, src/Shared/]:
------
------
 > [build  6/14] COPY [src/Infrastructure.Shared/Infrastructure.Shared.csproj, src/Infrastructure.Shared/]:
------
------
 > [build  7/14] COPY [src/Infrastructure/Infrastructure.csproj, src/Infrastructure/]:
------
------
 > [build  8/14] COPY [src/Client/Client.csproj, src/Client/]:
------
------
 > [build  9/14] COPY [src/Client.Infrastructure/Client.Infrastructure.csproj, src/Client.Infrastructure/]:
------
failed to compute cache key: "/src/Client.Infrastructure/Client.Infrastructure.csproj" not found: not found
##[error]The process 'C:\Program Files\Docker\Docker\resources\bin\docker.exe' failed with exit code 1
Finishing: Build an image

</code>```

答:
The Dockerfile is located under src\Server. The Build an image step calls docker build -f .\src\Server\Dockerfile .\src\Server which will not work because that is already one level too deep in the directory tree.

So there are several options:

Call docker build -f .\src\Server\Dockerfile . from the root directory, but use a custom shell script rather than the official Build an image step - it seems to have that kind of limitation.

Use relative paths in the Dockerfile like this:

```<code>COPY ["../src/Server/Server.csproj", "src/Server/"]
</code>```

Move the Dockerfile to the root directory.

Body:
I am hosting my own build-agent on my on-premises windows server.
However, when I either try to build my docker image using the default agent or my on-premisses agent, it cannot copy the .cproj files.

What I want, is to be able to build this image without the errors.
What I have tried so far is:

Changes work directory to: ../ , ../../ and ~/

Google for solutions, but this does not result in anything, because it is too specific or something.

Please note that it also does not work on an agent from DevOps itself (windows-2022)
Does anyone know what I could have done wrong or overlooked?

Directories:

src/Server/DockerFile

src/Server/Server.csproj

And so on for the other .csproj files

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
ENV ASPNETCORE_URLS=https://+:5005;http://+:5006
WORKDIR /app
EXPOSE 5005
EXPOSE 5006

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /
COPY ["src/Server/Server.csproj", "src/Server/"]
COPY ["src/Application/Application.csproj", "src/Application/"]
COPY ["src/Domain/Domain.csproj", "src/Domain/"]
COPY ["src/Shared/Shared.csproj", "src/Shared/"]
COPY ["src/Infrastructure.Shared/Infrastructure.Shared.csproj", "src/Infrastructure.Shared/"]
COPY ["src/Infrastructure/Infrastructure.csproj", "src/Infrastructure/"]
COPY ["src/Client/Client.csproj", "src/Client/"]
COPY ["src/Client.Infrastructure/Client.Infrastructure.csproj", "src/Client.Infrastructure/"]
RUN dotnet restore "src/Server/Server.csproj" --disable-parallel
COPY . .
WORKDIR "src/Server"
RUN dotnet build "Server.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Server.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
WORKDIR /app/Files
WORKDIR /app
ENTRYPOINT ["dotnet", "DeDenDannenburcht.Server.dll"]

My Pipeline

Pipeline Output

"C:\Program Files\Docker\Docker\resources\bin\docker.exe" build -f F:\agents\_work\1\s\src\Server\Dockerfile -t dedendannenburcht:166 --label com.azure.dev.image.system.teamfoundationcollectionuri=https://dev.azure.com/JeremiedevosBusiness/ --label com.azure.dev.image.build.sourceversion=ab657210c8696881754f36393adee9da7394ea19 --label image.base.ref.name=mcr.microsoft.com/dotnet/aspnet:6.0 --label image.base.digest=sha256:545da8027d0de13ac88716fc380201f05ad9b4834b5b2fd95eadf277e51318a7 F:\agents\_work\1\s\src\Server
#1 [internal] load build definition from Dockerfile
#1 sha256:5cec5c1a6e883854d5ef516a04f7fbc4f77cc63f74549820c4d061dbb560e514
#1 transferring dockerfile: 1.31kB done
#1 DONE 0.0s

#2 [internal] load .dockerignore
#2 sha256:8f7ecf610ac80d8ac3c3e64e4de2e264ecf11892bf7afc5ff6debe41dd69161b
#2 transferring context: 2B done
#2 DONE 0.0s

#4 [internal] load metadata for mcr.microsoft.com/dotnet/aspnet:6.0
#4 sha256:ac4494cbca04ddb415c76edcbcc7688784c2a6ea65dd656286c013738aa3b75f
#4 DONE 0.0s

#3 [internal] load metadata for mcr.microsoft.com/dotnet/sdk:6.0
#3 sha256:9eb4f6c3944cfcbfe18b9f1a753c769fc35341309a8d4a21f8937f47e94c712b
#3 DONE 0.1s

#5 [base 1/2] FROM mcr.microsoft.com/dotnet/aspnet:6.0
#5 sha256:50f1ddc10932c4a74c7af5704e931a9489c710faea4f2381fe2380827a900e00
#5 DONE 0.0s

#6 [base 2/2] WORKDIR /app
#6 sha256:bc3cf6c390e5fe0e66017b4845c8fcf3e56c7adac9f514a00c2c986024f377a4
#6 CACHED

#7 [final 1/4] WORKDIR /app
#7 sha256:3baba3edbb555769ad9a49e827de88d7dcc4f72ad6e2b42e576964e4a30eac96
#7 CACHED

#8 [build  1/14] FROM mcr.microsoft.com/dotnet/sdk:6.0@sha256:a3dd4dee05cd1369014244d03b28b602e6a2e1650210dd8633322e00379471ec
#8 sha256:ff704f84298cdcbd6cd764720a2e1a4dcd4b44ff415133896e77ad0c5d908001
#8 resolve mcr.microsoft.com/dotnet/sdk:6.0@sha256:a3dd4dee05cd1369014244d03b28b602e6a2e1650210dd8633322e00379471ec done
#8 sha256:0af6b8199917326984baa1452533da610b46f65bfbc5296c7f81cb72d3beec84 2.01kB / 2.01kB done
#8 sha256:dc243ad423c72b21b838c1362ca152823b0b379a546887d8c47c437357576fb2 7.31kB / 7.31kB done
#8 sha256:664e00cfda3df2ac7370c116f04a17d636fc041b62bdd9a0b88a60b987344269 0B / 136.50MB 0.1s
#8 sha256:a3dd4dee05cd1369014244d03b28b602e6a2e1650210dd8633322e00379471ec 2.17kB / 2.17kB done
#8 sha256:4253139ebd4dcee5f7878254306eb794d0f2a80ee4ca8d085d0b9e507412fb1e 0B / 25.36MB 0.1s

#10 sha256:aa96c6c99b71465c230e63fb1edea0588e2b25c39d6b44fc1381e7cbe48c15d9
#10 ERROR: "/src/Server/Server.csproj" not found: not found

#13 [build  5/14] COPY [src/Shared/Shared.csproj, src/Shared/]
#13 sha256:8fd70ae770f73428f5ff667da9b5080dff2b8035dbeb1247fe9e76d5890ad27d
#13 ERROR: "/src/Shared/Shared.csproj" not found: not found

#16 [build  8/14] COPY [src/Client/Client.csproj, src/Client/]
#16 sha256:33c15418c5097a788d8ef568338206ce45e5fea62b707a2be13c136b28ca43e9
#16 ERROR: "/src/Client/Client.csproj" not found: not found

#15 [build  7/14] COPY [src/Infrastructure/Infrastructure.csproj, src/Infrastructure/]
#15 sha256:4f643811b59a89db4a864a2a40a7ff2cc05709c3b123027874b72ff436af0d56
#15 ERROR: "/src/Infrastructure/Infrastructure.csproj" not found: not found

#17 [build  9/14] COPY [src/Client.Infrastructure/Client.Infrastructure.csproj, src/Client.Infrastructure/]
#17 sha256:b7385969b745977db24f702bc1c8f0b931cd675b9f44e70870ae2d918632e9b3
#17 ERROR: "/src/Client.Infrastructure/Client.Infrastructure.csproj" not found: not found

#14 [build  6/14] COPY [src/Infrastructure.Shared/Infrastructure.Shared.csproj, src/Infrastructure.Shared/]
#14 sha256:f101a94226cbf6f38fe9d908da512ded2bd68070207a6dd5c003d8967252c970
#14 ERROR: "/src/Infrastructure.Shared/Infrastructure.Shared.csproj" not found: not found

#12 [build  4/14] COPY [src/Domain/Domain.csproj, src/Domain/]
#12 sha256:152a7025db6bab6e2e456a9ab7ef8436cc9689411341ea38c362df78a0d058c1
#12 ERROR: "/src/Domain/Domain.csproj" not found: not found

#11 [build  3/14] COPY [src/Application/Application.csproj, src/Application/]
#11 sha256:1760818b73b46bb8ebf75492933a413de08fd2ab7a26cae37de4ae4a5f60b83e
#11 ERROR: "/src/Application/Application.csproj" not found: not found
------
 > [build  2/14] COPY [src/Server/Server.csproj, src/Server/]:
------
------
 > [build  3/14] COPY [src/Application/Application.csproj, src/Application/]:
------
------
 > [build  4/14] COPY [src/Domain/Domain.csproj, src/Domain/]:
------
------
 > [build  5/14] COPY [src/Shared/Shared.csproj, src/Shared/]:
------
------
 > [build  6/14] COPY [src/Infrastructure.Shared/Infrastructure.Shared.csproj, src/Infrastructure.Shared/]:
------
------
 > [build  7/14] COPY [src/Infrastructure/Infrastructure.csproj, src/Infrastructure/]:
------
------
 > [build  8/14] COPY [src/Client/Client.csproj, src/Client/]:
------
------
 > [build  9/14] COPY [src/Client.Infrastructure/Client.Infrastructure.csproj, src/Client.Infrastructure/]:
------
failed to compute cache key: "/src/Client.Infrastructure/Client.Infrastructure.csproj" not found: not found
##[error]The process 'C:\Program Files\Docker\Docker\resources\bin\docker.exe' failed with exit code 1
Finishing: Build an image

Body:
The Dockerfile is located under src\Server. The Build an image step calls docker build -f .\src\Server\Dockerfile .\src\Server which will not work because that is already one level too deep in the directory tree.

So there are several options:

Call docker build -f .\src\Server\Dockerfile . from the root directory, but use a custom shell script rather than the official Build an image step - it seems to have that kind of limitation.

Use relative paths in the Dockerfile like this:

COPY ["../src/Server/Server.csproj", "src/Server/"]

Move the Dockerfile to the root directory.


问:
Can't enter mount namespace created by a setuid process
A root-owned setuid bit daemon switches back to the real user and creates a mount namespace.

A user-owned executable with CAP_SYS_ADMIN and CAP_SYS_CHROOT bits set tries to enter that namespace and fails.

daemon.c:

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <unistd.h>

int main(int argc, const char* argv[])
{
  prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != -1 || (perror(0), exit(1), 0);

  setuid(getuid()) != -1 || (perror(0), exit(1), 0);
  setgid(getgid()) != -1 || (perror(0), exit(1), 0);

  cap_t cap = cap_init();
  cap || (perror(0), exit(1), 0);
  cap_value_t cap_values[] = {CAP_SYS_ADMIN};
  cap_set_flag(cap, CAP_EFFECTIVE, sizeof(cap_values) / sizeof(cap_values[0]), cap_values, CAP_SET) != -1 || (perror(0), exit(1), 0);
  cap_set_flag(cap, CAP_PERMITTED, sizeof(cap_values) / sizeof(cap_values[0]), cap_values, CAP_SET) != -1 || (perror(0), exit(1), 0);
  cap_set_proc(cap) != -1 || (perror(0), exit(1), 0);
  cap_free(cap) != -1 || (perror(0), exit(1), 0);

  unshare(CLONE_NEWNS) != -1 || (perror(0), exit(1), 0);

  pause();

  return 0;
}
```
<p><code>client.c</code>:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>

int main(int argc, const char* argv[])
{
  argc == 2 || (perror(0), exit(1), 0);

  const int fd = syscall(SYS_pidfd_open, atoi(argv[1]), 0);
  fd != -1 || (perror(0), exit(1), 0);

  setns(fd, CLONE_NEWNS) != -1 || (perror(0), exit(1), 0);

  return 0;
}
</code>```

build-run.sh:

#!/bin/bash

gcc -o daemon{,.c} -lcap
gcc -o client{,.c} -lcap

sudo chown root:root ./daemon; sudo chmod u+s ./daemon
sudo setcap cap_sys_admin,cap_sys_chroot+ep ./client

./daemon &
./client $!
```

Gives "Operation not permitted" - the setns() call fails. It has the correct capabilities, user namespace is the same. What's wrong?

答:
Try using:

```<code>sudo setcap cap_sys_admin,cap_sys_chroot,cap_sys_ptrace=ep ./client
</code>```

It looks like this detail of requiring the cap_sys_ptrace capability is buried in the kernel patch in a code comment:

```<code>+ * This syscall gets a copy of a file descriptor from another process
+ * based on the pidfd, and file descriptor number. It requires that
+ * the calling process has the ability to ptrace the process represented
+ * by the pidfd. The process which is having its file descriptor copied
+ * is otherwise unaffected.
</code>```

Body:
A root-owned setuid bit daemon switches back to the real user and creates a mount namespace.

A user-owned executable with CAP_SYS_ADMIN and CAP_SYS_CHROOT bits set tries to enter that namespace and fails.

daemon.c:

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <unistd.h>

int main(int argc, const char* argv[])
{
  prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != -1 || (perror(0), exit(1), 0);

  setuid(getuid()) != -1 || (perror(0), exit(1), 0);
  setgid(getgid()) != -1 || (perror(0), exit(1), 0);

  cap_t cap = cap_init();
  cap || (perror(0), exit(1), 0);
  cap_value_t cap_values[] = {CAP_SYS_ADMIN};
  cap_set_flag(cap, CAP_EFFECTIVE, sizeof(cap_values) / sizeof(cap_values[0]), cap_values, CAP_SET) != -1 || (perror(0), exit(1), 0);
  cap_set_flag(cap, CAP_PERMITTED, sizeof(cap_values) / sizeof(cap_values[0]), cap_values, CAP_SET) != -1 || (perror(0), exit(1), 0);
  cap_set_proc(cap) != -1 || (perror(0), exit(1), 0);
  cap_free(cap) != -1 || (perror(0), exit(1), 0);

  unshare(CLONE_NEWNS) != -1 || (perror(0), exit(1), 0);

  pause();

  return 0;
}

client.c:

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>

int main(int argc, const char* argv[])
{
  argc == 2 || (perror(0), exit(1), 0);

  const int fd = syscall(SYS_pidfd_open, atoi(argv[1]), 0);
  fd != -1 || (perror(0), exit(1), 0);

  setns(fd, CLONE_NEWNS) != -1 || (perror(0), exit(1), 0);

  return 0;
}

build-run.sh:

#!/bin/bash

gcc -o daemon{,.c} -lcap
gcc -o client{,.c} -lcap

sudo chown root:root ./daemon; sudo chmod u+s ./daemon
sudo setcap cap_sys_admin,cap_sys_chroot+ep ./client

./daemon &
./client $!

Gives "Operation not permitted" - the setns() call fails. It has the correct capabilities, user namespace is the same. What's wrong?

Body:
Try using:

sudo setcap cap_sys_admin,cap_sys_chroot,cap_sys_ptrace=ep ./client

It looks like this detail of requiring the cap_sys_ptrace capability is buried in the kernel patch in a code comment:

+ * This syscall gets a copy of a file descriptor from another process
+ * based on the pidfd, and file descriptor number. It requires that
+ * the calling process has the ability to ptrace the process represented
+ * by the pidfd. The process which is having its file descriptor copied
+ * is otherwise unaffected.


问:
How can I get OpenCV to work with Y16 format?
I am trying to get OpenCV to work with the See3Cam CU135, but as far as I can tell openCV is not compatible with the image format of the camera (Y16) and the manufacturer suggests making a custom openCV installation. I have tried the custom installation to no avail . Does anyone have any ideas how one could aproach the problem?
Thanks</p>

答: See3CAM_CU135 camera supported output is UYVY and MJPEG not Y16. Because See3CAM_CU135 camera has an onboard ISP to perform major image processing functions like debayering, WB control, Color correction and various other image quality improvement features, which also reduces the processing load in the host platform.  So you could not set Y16 in See3CAM_CU135 camera.</p>


问:
JavaScript: Decript string that has been encrypted in C#
I created this method to encryped string with a key:

```<code> public static string EncryptString(string key, string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }

            return Convert.ToBase64String(array);
        }
</code>```

But I also need this method in JS, to also decrypt the same string.

I am wondering about

AES, Encoding.UTF8.GetBytes, ICryptoTransform, Cryptostreammode, and MemoryStream.

Do these exist in JS?

IS this method even usable in JS?

答:
Using your C# code to encrypt a string via public static string EncryptString(string key, string plainText) I get following result:

```<code>EncryptString("xxxxxxxxxxxxxxxx", "Hello World") -> "yM377gXxX5Du71hgkPH+Fg=="
</code>```

To reverse this you can check out this Javascript code:

const key = "xxxxxxxxxxxxxxxx";
const msg = "yM377gXxX5Du71hgkPH+Fg==";

const decrypted = CryptoJS.AES.decrypt(
  msg,
  CryptoJS.enc.Utf8.parse(key),
  { mode: CryptoJS.mode.ECB }
);

console.log(decrypted.toString(CryptoJS.enc.Utf8));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script></code>```

Body:
I created this method to encryped string with a key:

 public static string EncryptString(string key, string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }

            return Convert.ToBase64String(array);
        }

But I also need this method in JS, to also decrypt the same string.

I am wondering about

AES, Encoding.UTF8.GetBytes, ICryptoTransform, Cryptostreammode, and MemoryStream.

Do these exist in JS?

IS this method even usable in JS?

Body:
Using your C# code to encrypt a string via public static string EncryptString(string key, string plainText) I get following result:

EncryptString("xxxxxxxxxxxxxxxx", "Hello World") -> "yM377gXxX5Du71hgkPH+Fg=="

To reverse this you can check out this Javascript code:

const key = "xxxxxxxxxxxxxxxx";
const msg = "yM377gXxX5Du71hgkPH+Fg==";

const decrypted = CryptoJS.AES.decrypt(
  msg,
  CryptoJS.enc.Utf8.parse(key),
  { mode: CryptoJS.mode.ECB }
);

console.log(decrypted.toString(CryptoJS.enc.Utf8));

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>


问:
Why does "L.insert(it--, i);" behave differently from "L.insert(it, i); it--;"?
These are two pieces of code that I ran under the C++11 standard. I expected the post-decrement of the iterator to produce the same effect, but these two pieces of code produce completely different results. Where is my understanding off?

list<int> L;

int main() {
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it--, i);
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 2 5 0 4 1 3
}
```
<pre class="lang-cpp prettyprint-override"><code>list<int> L;

int main() {
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it, i);
        it--;
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 5 4 3 2 1 0
}
</code>```

答:
Your code invokes undefined behaviour.

The begin iterator is not decrementable and the behavior is undefined if --container.begin() is evaluated.

https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator

As such, anything could happen.

Body:
These are two pieces of code that I ran under the C++11 standard. I expected the post-decrement of the iterator to produce the same effect, but these two pieces of code produce completely different results. Where is my understanding off?

list<int> L;

int main() {
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it--, i);
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 2 5 0 4 1 3
}

list<int> L;

int main() {
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it, i);
        it--;
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 5 4 3 2 1 0
}


问:
Getting Consent from DocuSign in a Console App context
I am struggling to get access tokens from .net console app context. I am getting them and they work, but they expire too fast.

I checked the other two threads in stackoverflow, in both answers it was stated, that once you get the consent per IK and per user, you don't have to do it anymore. However once I get the bearer token from the return_url and use it to request the access tokens a few minutes after the bearer was obtained, I get response with "error_description:expired_client_token".

So me manually obtaining bearer from the browser in order to set it as a parameter (again manually) in my console app and having the bearer expiration duration just a few minutes doesn't match "Consent is needed only once, ever, per a specific integration and a user".
I see that docusign uses cookies' values/expiration and can probably reverse engineer a GET call to account-d.docusign to get the bearer from the console app context, but that's not what I'd expect from an API provider.

For reference I'm using the following URL to manually get the bearer from the browser:
https://account-d.docusign.com/oauth/auth?response_type=code&scope=signature&client_id=d69848a8-2a93-4d03-ab40-bcabda8a7e8f&redirect_uri=https://www.docusign.com
But as stated above, it does expire in a few mins to get the aforementioned error_description
Thank you in advance!

答: The token in the response only lasts about 2 minutes. Its true that consent is only needed once, but your problem is not consent.</p>


问:
Android ViewBinding error in the inflate-method - missing or conflicting dependencies
After removing the existing DataBinding from the project, I also wanted to get rid of the kotlinx.android.synthetic and replace it with ViewBinding.

However, after enabling ViewBinding in my project, I'm still not able to do a proper setup.

Trying to invoke the ViewBinding into my MainActivity or in one of my fragments I get the following error in the inflate method:

```<code>Cannot access 'no_name_in_PSI_...' which is a supertype of 'com.example.projectname.databinding.ActivityMainBinding'. Check your module classpath for missing or conflicting dependencies
</code>```

For example:

MainActivity.kt

```<code>class MainActivity : BaseActivity<SharedViewModel>() {
      private lateinit var binding: ActivityMainBinding
      ...
      override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.AppTheme)
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
      }
}
</code>```

My build.gradle (:app) is properly set up:

build.gradle (:app)

```<code>android {
  ...
  buildFeatures {
        viewBinding true
    }
}
</code>```

I've used ViewBinding in another project of mine and it worked out of the box. Please help. Thank you so much.

答:
Try to remove .idea folder

Step 1- Remove .Idea Folder

Step 2- Close android studio

Step 3- Reopen android studio with same project path (This will genarate new
.Idea folder)

https://stackoverflow.com/a/71036526/4741746

Body:
After removing the existing DataBinding from the project, I also wanted to get rid of the kotlinx.android.synthetic and replace it with ViewBinding.

However, after enabling ViewBinding in my project, I'm still not able to do a proper setup.

Trying to invoke the ViewBinding into my MainActivity or in one of my fragments I get the following error in the inflate method:

Cannot access 'no_name_in_PSI_...' which is a supertype of 'com.example.projectname.databinding.ActivityMainBinding'. Check your module classpath for missing or conflicting dependencies

For example:

MainActivity.kt

class MainActivity : BaseActivity<SharedViewModel>() {
      private lateinit var binding: ActivityMainBinding
      ...
      override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.AppTheme)
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
      }
}

My build.gradle (:app) is properly set up:

build.gradle (:app)

android {
  ...
  buildFeatures {
        viewBinding true
    }
}

I've used ViewBinding in another project of mine and it worked out of the box. Please help. Thank you so much.


答:
```<code>L.insert(it, i);
it--;
</code>```

This inserts a node before it, then moves it backwards to the inserted node.

```<code>L.insert(it--, i);
</code>```

The order of operations is swapped: it moves the iterator backwards before insert() is called. There's no node to move back to so it causes undefined behavior.

Title: Why does "L.insert(it--, i);" behave differently from "L.insert(it, i); it--;"?

Body:
L.insert(it, i);
it--;

This inserts a node before it, then moves it backwards to the inserted node.

L.insert(it--, i);

The order of operations is swapped: it moves the iterator backwards before insert() is called. There's no node to move back to so it causes undefined behavior.


问:
grouping equal values - aggregate function problem
I've created a table that lists venues in which several events take place. The same event in the same venue can have a different price. The last column calculates the total revenue for one venue.

```<code>SELECT     venuename,
           eventname,
           totalprice,
           SUM(totalprice) OVER (PARTITION BY venuename)
    FROM venue
    INNER JOIN event e ON venue.venueid = e.venueid
    INNER JOIN listing l ON e.eventid = l.eventid;
</code>```

venue
event
totalprice
sum

Venue A
Event A
5
30

Venue A
Event A
10
30

Venue A
Event B
5
30

Venue A
Event A
5
30

Venue A
Event B
5
30

Venue B
Event C
3
15

Venue B
Event D
6
15

Venue B
Event D
6
15

Now i want to group up equal events and calculate the total revenue of one event in a venue.

The result should look something like this:

venue
event
totalprice
sum

Venue A
Event A
20
30

Venue A
Event B
10
30

Venue B
Event C
3
15

Venue B
Event D
12
15

My idea to solve this was something like this:

```<code>SELECT venuename,
       eventname,
       SUM(totalprice),
       SUM(totalprice) OVER (PARTITION BY venuename)
FROM venue
INNER JOIN event e ON venue.venueid = e.venueid
INNER JOIN listing l ON e.eventid = l.eventid
GROUP BY eventname;
</code>```

But this doesn't seem to be possible since vanuename has to be part of an aggregate function as well. But i can't really come up with an idea to solve this problem.

Hope anyone of you guys can help me with this.

greetings

答:
You can combine an agrregate and a window function</p>
```<code>SELECT venuename,
       eventname,
       SUM(totalprice) totalprice,
       SUM(SUM(totalprice)) OVER (PARTITION BY venuename) sum
FROM venue
INNER JOIN event e ON venue.venueid = e.venueid
INNER JOIN listing l ON e.eventid = l.eventid
GROUP BY venuename, eventname;
</code>```

Body:
I've created a table that lists venues in which several events take place. The same event in the same venue can have a different price. The last column calculates the total revenue for one venue.

SELECT     venuename,
           eventname,
           totalprice,
           SUM(totalprice) OVER (PARTITION BY venuename)
    FROM venue
    INNER JOIN event e ON venue.venueid = e.venueid
    INNER JOIN listing l ON e.eventid = l.eventid;

venue
event
totalprice
sum

Venue A
Event A
5
30

Venue A
Event A
10
30

Venue A
Event B
5
30

Venue A
Event A
5
30

Venue A
Event B
5
30

Venue B
Event C
3
15

Venue B
Event D
6
15

Venue B
Event D
6
15

Now i want to group up equal events and calculate the total revenue of one event in a venue.

The result should look something like this:

venue
event
totalprice
sum

Venue A
Event A
20
30

Venue A
Event B
10
30

Venue B
Event C
3
15

Venue B
Event D
12
15

My idea to solve this was something like this:

SELECT venuename,
       eventname,
       SUM(totalprice),
       SUM(totalprice) OVER (PARTITION BY venuename)
FROM venue
INNER JOIN event e ON venue.venueid = e.venueid
INNER JOIN listing l ON e.eventid = l.eventid
GROUP BY eventname;

But this doesn't seem to be possible since vanuename has to be part of an aggregate function as well. But i can't really come up with an idea to solve this problem.

Hope anyone of you guys can help me with this.

greetings

Body:
You can combine an agrregate and a window function

SELECT venuename,
       eventname,
       SUM(totalprice) totalprice,
       SUM(SUM(totalprice)) OVER (PARTITION BY venuename) sum
FROM venue
INNER JOIN event e ON venue.venueid = e.venueid
INNER JOIN listing l ON e.eventid = l.eventid
GROUP BY venuename, eventname;


问:
CSS Grid not centering the top row
I have an issue with the top row in the following layout. It would not center and just stay on the left part of the two columns.

It need it to be on the center like the bottom part. The one on the bottom works fine at centering itself even though I used the same way via CSS Grid. Please check the image I attached.

#about-container {
  grid-area: first;
}

#ul-first {
  grid-area: second;
}

#ul-second {
  grid-area: third;
}

#ul-third {
  grid-area: fourth;
}

.footer-links {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    "first first"
    "second third"
    "fourth fourth";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="footer-links">
  <div class="about-container">
    <div class="about">
      <h1>Title</h1>
      <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, aperiam quaerat? Nam reprehenderit, amet minus illum natus facere accusamus aut voluptatem. Sapiente ipsa praesentium unde, voluptatem assumenda facilis asperiores eum!</p>
    </div>
  </div>
  <div class="list" id="ul-first">
    <ul>
      <li>Why Buy From Us</li>
      <li>Company Policy</li>
      <li>Maintenance</li>
      <li>Financing</li>
    </ul>
  </div>
  <div class="list" id="ul-second">
    <ul>
      <li>Request a Quote</li>
      <li>Get in Touch with Us</li>
      <li>Book Preventive Maintenance</li>
    </ul>
  </div>
  <div class="list" id="ul-third">
    <ul>
      <li>Nissan GT-R</li>
      <li>Mitsubishi Lancer</li>
      <li>Toyota Corolla Touring</li>
      <li>McLaren P1</li>
    </ul>
  </div>
</section></code>```

答:
Just use this useful trick to center most anything

element {
  text-align: center;
}
```
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#about-container{
    grid-area: first;
}
#ul-first{
    grid-area: second;
}
#ul-second{
    grid-area: third;
}
#ul-third{
    grid-area: fourth;
}
.footer-links{
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    grid-template-areas:
        "first first"
        "second third"
        "fourth fourth";
}
h1 {
  text-align: center;
}</code>```

Title

 Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, aperiam quaerat? Nam reprehenderit, amet minus illum natus facere accusamus aut voluptatem. Sapiente ipsa praesentium unde, voluptatem assumenda facilis asperiores eum!

Why Buy From Us

Company Policy

Maintenance

Financing

Request a Quote

Get in Touch with Us

Book Preventive Maintenance

Nissan GT-R

Mitsubishi Lancer

Toyota Corolla Touring

McLaren P1

```

Title: CSS Grid not centering the top row

Body:
I have an issue with the top row in the following layout. It would not center and just stay on the left part of the two columns.

It need it to be on the center like the bottom part. The one on the bottom works fine at centering itself even though I used the same way via CSS Grid. Please check the image I attached.

#about-container {
  grid-area: first;
}

#ul-first {
  grid-area: second;
}

#ul-second {
  grid-area: third;
}

#ul-third {
  grid-area: fourth;
}

.footer-links {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    "first first"
    "second third"
    "fourth fourth";
}

Title

 Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, aperiam quaerat? Nam reprehenderit, amet minus illum natus facere accusamus aut voluptatem. Sapiente ipsa praesentium unde, voluptatem assumenda facilis asperiores eum!

Why Buy From Us

Company Policy

Maintenance

Financing

Request a Quote

Get in Touch with Us

Book Preventive Maintenance

Nissan GT-R

Mitsubishi Lancer

Toyota Corolla Touring

McLaren P1

Body:
Just use this useful trick to center most anything

element {
  text-align: center;
}

#about-container{
    grid-area: first;
}
#ul-first{
    grid-area: second;
}
#ul-second{
    grid-area: third;
}
#ul-third{
    grid-area: fourth;
}
.footer-links{
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    grid-template-areas:
        "first first"
        "second third"
        "fourth fourth";
}
h1 {
  text-align: center;
}

<section class="footer-links">
            <div class="about-container">
                <div class="about">
                    <h1>Title</h1>
                    <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed, aperiam quaerat? Nam reprehenderit, amet minus illum natus facere accusamus aut voluptatem. Sapiente ipsa praesentium unde, voluptatem assumenda facilis asperiores eum!</p>
                </div>
            </div>
            <div class="list" id="ul-first">
                <ul>
                    <li><a href="#">Why Buy From Us</a></li>
                    <li><a href="#">Company Policy</a></li>
                    <li><a href="#">Maintenance</a></li>
                    <li><a href="#">Financing</a></li>
                </ul>
            </div>
            <div class="list" id="ul-second">
                <ul>
                    <li><a href="#">Request a Quote</a></li>
                    <li><a href="#">Get in Touch with Us</a></li>
                    <li><a href="#">Book Preventive Maintenance</a></li>
                </ul>
            </div>
            <div class="list" id="ul-third">
                <ul>
                    <li><a href="#">Nissan GT-R</a></li>
                    <li><a href="#">Mitsubishi Lancer</a></li>
                    <li><a href="#">Toyota Corolla Touring</a></li>
                    <li><a href="#">McLaren P1</a></li>
                </ul>
            </div>
        </section>


问:
Terms of Consent popup not showing at signup
I am following this sample in order to enhance an existent custom policy. However, can't get prompted for the Terms of Conditions checkbox at local signup even though  I've specified it as a required field on the output claims.

The technical profile:

<TechnicalProfile Id="LocalAccountSignUpWithLogonEmail-HasEmailFlagged">
    <DisplayName>Sign Up with Local Email</DisplayName>
    <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    <Metadata>
      <Item Key="IpAddressClaimReferenceId">IpAddress</Item>
      <Item Key="ContentDefinitionReferenceId">api.localaccountsignup</Item>
      <Item Key="language.button_continue">Sign Up</Item>
      <Item Key="EnforceEmailVerification">False</Item>
    </Metadata>
    <CryptographicKeys>
      <Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSigningKeyContainer" />
    </CryptographicKeys>
    <InputClaimsTransformations>
      <InputClaimsTransformation ReferenceId="GetCurrentDateTime" />
    </InputClaimsTransformations>
    <InputClaims>
      <InputClaim ClaimTypeReferenceId="email" />
      <InputClaim ClaimTypeReferenceId="givenName" />
      <InputClaim ClaimTypeReferenceId="extension_termsOfUseConsentChoice" DefaultValue="AgreeToTermsOfUseConsentNo" />
    </InputClaims>
    <DisplayClaims>
      <DisplayClaim ClaimTypeReferenceId="email" Required="true" />
      <DisplayClaim ClaimTypeReferenceId="givenName" Required="true" />
      <DisplayClaim ClaimTypeReferenceId="password" Required="true" />
    </DisplayClaims>
    <OutputClaims>
      <OutputClaim ClaimTypeReferenceId="objectId" />
      <OutputClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" DefaultValue="true" />
      <OutputClaim ClaimTypeReferenceId="authenticationSource" />
      <OutputClaim ClaimTypeReferenceId="newUser" />

      <OutputClaim ClaimTypeReferenceId="password" />
      <OutputClaim ClaimTypeReferenceId="givenName"/>
      <OutputClaim ClaimTypeReferenceId="displayName"/>
      <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Email" />
      <OutputClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
      <OutputClaim ClaimTypeReferenceId="extension_termsOfUseConsentChoice" Required="true" />
    </OutputClaims>
    <OutputClaimsTransformations>
      <OutputClaimsTransformation ReferenceId="CopyGivenName" />
    </OutputClaimsTransformations>
    <ValidationTechnicalProfiles>
      <ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonEmail" />
      <ValidationTechnicalProfile ReferenceId="AAD-WriteUserHasPassword" />
    </ValidationTechnicalProfiles>
    <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD"/>
  </TechnicalProfile>
```

答:
It turns out that I was using DisplayClaim and OutputClaim the wrong way. The following fixed the issue.

<DisplayClaims>
    <DisplayClaim ClaimTypeReferenceId="email" Required="true" />
    <DisplayClaim ClaimTypeReferenceId="givenName" Required="true" />
    <DisplayClaim ClaimTypeReferenceId="password" Required="true" />
  <DisplayClaim ClaimTypeReferenceId="reenterPassword"
    <DisplayClaim ClaimTypeReferenceId="extension_termsOfUseConsentChoice" Required="true" />
  Required="true" />
  </DisplayClaims>
  <OutputClaims>
    <OutputClaim ClaimTypeReferenceId="objectId" />
    <OutputClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" DefaultValue="true" />
    <OutputClaim ClaimTypeReferenceId="authenticationSource" />
    <OutputClaim ClaimTypeReferenceId="newUser" />
    <OutputClaim ClaimTypeReferenceId="password" />
    <OutputClaim ClaimTypeReferenceId="givenName"/>
    <OutputClaim ClaimTypeReferenceId="displayName"/>
    <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Email" />
    <OutputClaim ClaimTypeReferenceId="extension_termsOfUseConsentChoice" />
  </OutputClaims>
```


问:
Android decode json data
How to decode this Json data in android i reied the following code

```<code> [
   {"data":
      {"url":
       {
         "url": "http://www.xxxxxx.com/story.html", "title":"some data","source_url": "www.somesite.com", "summary": "\n \n \n \n \n somedata again"
       }
      }
   }
 ]
</code>```

Java code

EDIT:

```<code>   HttpPost post = new HttpPost(postURL);
    MultipartEntity reqEntity = new MultipartEntity();

   HttpResponse response = client.execute(post);
  HttpEntity resEntity = response.getEntity();

    String r1 = EntityUtils.toString(resEntity);
    System.out.println("printing response now "+r1);

    //Toast.makeText(getApplicationContext(), "data received"+r1, Toast.LENGTH_LONG).show();
    JSONObject json = new JSONObject(r1);
    JSONArray venues = json.getJSONObject("data")
              .getJSONArray("url")
              .getJSONObject(0)
              .getJSONArray("url");

    Toast.makeText(getApplicationContext(), "data received"+venues, Toast.LENGTH_LONG).show();
</code>```

答:
If venus should be the url itself, the code should be:</p>

```<code>JSONArray json = new JSONArray(r1);
String venues = json.getJSONObject(0)
                .getJSONObject("data")
                .getJSONObject("url")
                .getString("url");
</code>```

Title: Android decode json data

Body:
How to decode this Json data in android i reied the following code

 [
   {"data":
      {"url":
       {
         "url": "http://www.xxxxxx.com/story.html", "title":"some data","source_url": "www.somesite.com", "summary": "\n \n \n \n \n somedata again"
       }
      }
   }
 ]

Java code

EDIT:

   HttpPost post = new HttpPost(postURL);
    MultipartEntity reqEntity = new MultipartEntity();

   HttpResponse response = client.execute(post);
  HttpEntity resEntity = response.getEntity();

    String r1 = EntityUtils.toString(resEntity);
    System.out.println("printing response now "+r1);

    //Toast.makeText(getApplicationContext(), "data received"+r1, Toast.LENGTH_LONG).show();
    JSONObject json = new JSONObject(r1);
    JSONArray venues = json.getJSONObject("data")
              .getJSONArray("url")
              .getJSONObject(0)
              .getJSONArray("url");

    Toast.makeText(getApplicationContext(), "data received"+venues, Toast.LENGTH_LONG).show();

Body:
If venus should be the url itself, the code should be:

JSONArray json = new JSONArray(r1);
String venues = json.getJSONObject(0)
                .getJSONObject("data")
                .getJSONObject("url")
                .getString("url");


问:
PostgreSQL - Constraint with differents data types
In PostgreSQL, I need a constraint to control if a value(s) is/are exists. This constraint is applied in an uuid[] data type column. It must check if each values of the array exists in an other column of the same table, in a uuid data type column.

I'm able to write a constraint with two similar data types, but how to run the same logic with two differents data types ?

In my case: check values in an uuid[] array with an uuid type.

Table

```<code>CREATE TABLE IF NOT EXISTS public.contact
(
    uuid uuid NOT NULL DEFAULT uuid_generate_v4(),
    name character varying COLLATE pg_catalog."default" NOT NULL,
    parent_uuid uuid,
    parent_name character varying COLLATE pg_catalog."default",
    child_uuids uuid[],
    child_names character varying[],
    CONSTRAINT contact_pk PRIMARY KEY (uuid),
    CONSTRAINT name_uk UNIQUE (name)
)

TABLESPACE pg_default;
</code>```

First constraint (parent): Ok

```<code>-- Check if parent_uuid exists in public.contact
ALTER TABLE public.contact ADD CONSTRAINT parent_uuid_fk FOREIGN KEY (parent_uuid)
REFERENCES public.contact (uuid) MATCH FULL
ON DELETE SET NULL ON UPDATE CASCADE;
</code>```

Second constraint (children): Incompatible types: uuid[] and uuid

```<code>-- Check if child_uuids exists in public.contact
ALTER TABLE public.contact ADD CONSTRAINT child_uuids_fk FOREIGN KEY (child_uuids)
REFERENCES public.contact (uuid) MATCH FULL
ON DELETE SET NULL ON UPDATE CASCADE;
</code>```

答:
There is no good way to do that.

You cannot create a constraint like that.

What you can do is to create a trigger function that tries to verify the condition and throws an error if it is violated. But such triggers are always susceptible to race conditions unless you use the SERIALIZABLE transaction isolation level, which incurs a performance penalty.

I would say that the only good solution here is to redesign and use a junction table to implement the relationship rather than an array. Then the problem would go away.

Body:
In PostgreSQL, I need a constraint to control if a value(s) is/are exists. This constraint is applied in an uuid[] data type column. It must check if each values of the array exists in an other column of the same table, in a uuid data type column.

I'm able to write a constraint with two similar data types, but how to run the same logic with two differents data types ?

In my case: check values in an uuid[] array with an uuid type.

Table

CREATE TABLE IF NOT EXISTS public.contact
(
    uuid uuid NOT NULL DEFAULT uuid_generate_v4(),
    name character varying COLLATE pg_catalog."default" NOT NULL,
    parent_uuid uuid,
    parent_name character varying COLLATE pg_catalog."default",
    child_uuids uuid[],
    child_names character varying[],
    CONSTRAINT contact_pk PRIMARY KEY (uuid),
    CONSTRAINT name_uk UNIQUE (name)
)

TABLESPACE pg_default;

First constraint (parent): Ok

-- Check if parent_uuid exists in public.contact
ALTER TABLE public.contact ADD CONSTRAINT parent_uuid_fk FOREIGN KEY (parent_uuid)
REFERENCES public.contact (uuid) MATCH FULL
ON DELETE SET NULL ON UPDATE CASCADE;

Second constraint (children): Incompatible types: uuid[] and uuid

-- Check if child_uuids exists in public.contact
ALTER TABLE public.contact ADD CONSTRAINT child_uuids_fk FOREIGN KEY (child_uuids)
REFERENCES public.contact (uuid) MATCH FULL
ON DELETE SET NULL ON UPDATE CASCADE;


问:
How can I create a JavaScript filter function for multiple filters at once

My Problem:

I'm having a website where I can compare products stored inside an array (with objects). I want to add different filters from array inside of an object that get applied together.

For two filters I can easily do it (see my code below). I just compare two objects and use a filter depending on their content.

But what would be a good approach to use the filter if there are more than two objects. Can I loop through the object and compare if the arrays are empty?

With my current approach I would have to extend my code for every new filter and it would balloon.

What I'm trying to do:

I want to check which filter objects have any data in their "feature" array (that array gets filled after the user clicks a filter on the site) and if they have I want to use these arrays to filter the main filteredArray array.

My current Object:

```<code>features_collection: {
    aspect_ratio_object: {
      features: [],
      value: "Aspect Ratio",
    },
    performance_rating_object: {
      features: [],
      value: "Performance Rating",
    },
  },
</code>```

My Filter Function:

```<code>    if (
      features_collection.aspect_ratio_object.features.length &&
      features_collection.performance_rating_object.features.length
    ) {
      return filteredArray.filter(
        (obj) =>
          features_collection.aspect_ratio_object.features.includes(
            obj[features_collection.aspect_ratio_object.value]
          ) &&
          features_collection.performance_rating_object.features.includes(
            obj[features_collection.performance_rating_object.value]
          )
      );
    } else if (
      features_collection.aspect_ratio_object.features.length ||
      features_collection.performance_rating_object.features.length
    ) {
      return filteredArray.filter(
        (obj) =>
          features_collection.aspect_ratio_object.features.includes(
            obj[features_collection.aspect_ratio_object.value]
          ) ||
          features_collection.performance_rating_object.features.includes(
            obj[features_collection.performance_rating_object.value]
          )
      );
    }
  },
</code>```

Further Notes:

I can also change my object. I could change it into an array of objects if that would make things easier?

答:
You obviously have too loop through your object.

Here is your loop code for features_collection:

```<code>features_collection.forEach(function (item, index) {
  console.log(item, index);
});
</code>```

Body:
My Problem:

I'm having a website where I can compare products stored inside an array (with objects). I want to add different filters from array inside of an object that get applied together.

For two filters I can easily do it (see my code below). I just compare two objects and use a filter depending on their content.

But what would be a good approach to use the filter if there are more than two objects. Can I loop through the object and compare if the arrays are empty?

With my current approach I would have to extend my code for every new filter and it would balloon.

What I'm trying to do:

I want to check which filter objects have any data in their "feature" array (that array gets filled after the user clicks a filter on the site) and if they have I want to use these arrays to filter the main filteredArray array.

My current Object:

features_collection: {
    aspect_ratio_object: {
      features: [],
      value: "Aspect Ratio",
    },
    performance_rating_object: {
      features: [],
      value: "Performance Rating",
    },
  },

My Filter Function:

    if (
      features_collection.aspect_ratio_object.features.length &&
      features_collection.performance_rating_object.features.length
    ) {
      return filteredArray.filter(
        (obj) =>
          features_collection.aspect_ratio_object.features.includes(
            obj[features_collection.aspect_ratio_object.value]
          ) &&
          features_collection.performance_rating_object.features.includes(
            obj[features_collection.performance_rating_object.value]
          )
      );
    } else if (
      features_collection.aspect_ratio_object.features.length ||
      features_collection.performance_rating_object.features.length
    ) {
      return filteredArray.filter(
        (obj) =>
          features_collection.aspect_ratio_object.features.includes(
            obj[features_collection.aspect_ratio_object.value]
          ) ||
          features_collection.performance_rating_object.features.includes(
            obj[features_collection.performance_rating_object.value]
          )
      );
    }
  },

Further Notes:

I can also change my object. I could change it into an array of objects if that would make things easier?

Body:
You obviously have too loop through your object.

Here is your loop code for features_collection:

features_collection.forEach(function (item, index) {
  console.log(item, index);
});


问:
Spark Prometheus metrics name contain random generated data?
Metric names that Spark 3.2.0 generates are as follows:

```<code>metrics_spark_a929f03bcd084dd08ffe5a3c9ba71018_driver_DAGScheduler_stage_waitingStages_Number{type="gauges"} 0
metrics_spark_a929f03bcd084dd08ffe5a3c9ba71018_driver_DAGScheduler_messageProcessingTime_50thPercentile{type="timers"} 24749.0
</code>```

I suspect that the part a929f03bcd084dd08ffe5a3c9ba71018 is random generated. How can one write proper Grafana queries to match these metrics? Is it possible to configure Spark not to add these hashes into the metric names? Whare is the purpose for these random hashes in the metrics naming?

(Checked Spark's example spark.metrics.conf for 3.2.0, but found no option to configure this.)

答:
In Spark properties, you can specify following:

```<code>    "spark.metrics.namespace": "myapp"
</code>```

So you will obtain:

```<code>metrics_myapp_driver_BlockManager_memory_maxOffHeapMem_MB_Number{type="gauges"} 0
</code>```

Source

Body:
Metric names that Spark 3.2.0 generates are as follows:

metrics_spark_a929f03bcd084dd08ffe5a3c9ba71018_driver_DAGScheduler_stage_waitingStages_Number{type="gauges"} 0
metrics_spark_a929f03bcd084dd08ffe5a3c9ba71018_driver_DAGScheduler_messageProcessingTime_50thPercentile{type="timers"} 24749.0

I suspect that the part a929f03bcd084dd08ffe5a3c9ba71018 is random generated. How can one write proper Grafana queries to match these metrics? Is it possible to configure Spark not to add these hashes into the metric names? Whare is the purpose for these random hashes in the metrics naming?

(Checked Spark's example spark.metrics.conf for 3.2.0, but found no option to configure this.)

Body:
In Spark properties, you can specify following:

    "spark.metrics.namespace": "myapp"

So you will obtain:

metrics_myapp_driver_BlockManager_memory_maxOffHeapMem_MB_Number{type="gauges"} 0

Source


问:
How to render dynamic translations in NuxtI18n?
I want to render list based on translations of 2 languages , one list for Arabic and one for English how can I do it?

```<code><i18n lang="json5">
en:{

},
ar:{
}
</i18n>
</code>```

I want to use these lists eg

```<code>  englishNameList: [
      { name: '', id: 1 },
      { name: '', id: 2 },
      { name: '', id: 3 },
      { name: '', id: 4 },
      { name: '', id: 5 },
    ],

  arabicNameList: [
      { name: '', id: 1 },
      { name: '', id: 2 },
      { name: '', id: 3 },
      { name: '', id: 4 },
      { name: '', id: 5 },
    ],
</code>```

I want to add these list into i18n json5 so It could be rendered into v-autocomplete

```<code> <v-autocomplete
            ref="selectedJob"
            v-model="selectedJob"
            :rules="[requiredRule]"
            :dense="$vuetify.breakpoint.mobile"
            outlined
            color="black"
            :items="englishNameList"
            item-text="name"
            item-value="id"

          >

          </v-autocomplete>
</code>```

I want pass data to :items based on translations from i18n json5?
How can I do it?

Thanks

答:
Depends on your usage if you want to use i18n inside html you have to use {{ $t(the variable of string or simply 'translate able string') }} .
Otherwise if u wanna use it on JS side of the component you have to use this.$t(the variable of string or simply 'translate able string').
I assume that from your data the Name key inside your arrays are translate able, you don`t need to create 2 separate list for each one. Just introduce the names in en and ar. Then use $t to change between locales.</p>

Body:
I want to render list based on translations of 2 languages , one list for Arabic and one for English how can I do it?

<i18n lang="json5">
en:{

},
ar:{
}
</i18n>

I want to use these lists eg

  englishNameList: [
      { name: '', id: 1 },
      { name: '', id: 2 },
      { name: '', id: 3 },
      { name: '', id: 4 },
      { name: '', id: 5 },
    ],

  arabicNameList: [
      { name: '', id: 1 },
      { name: '', id: 2 },
      { name: '', id: 3 },
      { name: '', id: 4 },
      { name: '', id: 5 },
    ],

I want to add these list into i18n json5 so It could be rendered into v-autocomplete

 <v-autocomplete
            ref="selectedJob"
            v-model="selectedJob"
            :rules="[requiredRule]"
            :dense="$vuetify.breakpoint.mobile"
            outlined
            color="black"
            :items="englishNameList"
            item-text="name"
            item-value="id"

          >

          </v-autocomplete>

I want pass data to :items based on translations from i18n json5?
How can I do it?

Thanks


问:
Rails form keeps returning a nomethoderror
```<code>        <%= form_for rating_ballot, :html => { :class => 'rating_ballot' } do |f| %>
            <%= f.label("value_1", content_tag(:span, '1'), {:class=>"rating", :id=>"1"})
            radio_button_tag("rating[value]", 1, current_user_rating == 1, :class => 'rating_button') %>
            <%= f.label("value_2", content_tag(:span, '2'), {:class=>"rating", :id=>"2"})
            radio_button_tag("rating[value]", 2, current_user_rating == 2, :class => 'rating_button') %>
            <%= f.label("value_3", content_tag(:span, '3'), {:class=>"rating", :id=>"3"})
            radio_button_tag("rating[value]", 3, current_user_rating == 3, :class => 'rating_button') %>
            <%= f.label("value_4", content_tag(:span, '4'), {:class=>"rating", :id=>"4"})
            radio_button_tag("rating[value]", 4, current_user_rating == 4, :class => 'rating_button') %>
            <%= f.label("value_5", content_tag(:span, '5'), {:class=>"rating", :id=>"5"})
            radio_button_tag("rating[value]", 5, current_user_rating == 5, :class => 'rating_button') %>

            <%= hidden_field_tag("message", msg.message) %>
            <%= f.submit :Submit %>
        <%- end -%>
</code>```

This is my form, I'm trying to create a system for users to rank messages in a "star" system form this tutorial. I have followed all the instructions on the tutorial but when I include this form I get a nomethoderror undefined method 'ratings_path'. In my home_helper I have

```<code>  def rating_ballot
    if @rating = current_user.ratings.find_by_id(params[:msg])
      @rating
    else
      current_user.ratings.new
    end
  end

  def current_user_rating
    if @rating = current_user.ratings.find_by_id(params[:msg])
      @rating.value
    else
      "N/A"
    end
  end
</code>```

Why am I getting this error? Thanks

答:
This is a routing problem. *_path are known as path helpers. Run rake routes to see what routes you have. You'll likely need to add new routes for your actions in order to use the path helpers. From your code, I'm guessing you'll need:

resources :ratings

But it's anyones guess what the rest of your application looks like.

Body:
        <%= form_for rating_ballot, :html => { :class => 'rating_ballot' } do |f| %>
            <%= f.label("value_1", content_tag(:span, '1'), {:class=>"rating", :id=>"1"})
            radio_button_tag("rating[value]", 1, current_user_rating == 1, :class => 'rating_button') %>
            <%= f.label("value_2", content_tag(:span, '2'), {:class=>"rating", :id=>"2"})
            radio_button_tag("rating[value]", 2, current_user_rating == 2, :class => 'rating_button') %>
            <%= f.label("value_3", content_tag(:span, '3'), {:class=>"rating", :id=>"3"})
            radio_button_tag("rating[value]", 3, current_user_rating == 3, :class => 'rating_button') %>
            <%= f.label("value_4", content_tag(:span, '4'), {:class=>"rating", :id=>"4"})
            radio_button_tag("rating[value]", 4, current_user_rating == 4, :class => 'rating_button') %>
            <%= f.label("value_5", content_tag(:span, '5'), {:class=>"rating", :id=>"5"})
            radio_button_tag("rating[value]", 5, current_user_rating == 5, :class => 'rating_button') %>

            <%= hidden_field_tag("message", msg.message) %>
            <%= f.submit :Submit %>
        <%- end -%>

This is my form, I'm trying to create a system for users to rank messages in a "star" system form this tutorial. I have followed all the instructions on the tutorial but when I include this form I get a nomethoderror undefined method 'ratings_path'. In my home_helper I have

  def rating_ballot
    if @rating = current_user.ratings.find_by_id(params[:msg])
      @rating
    else
      current_user.ratings.new
    end
  end

  def current_user_rating
    if @rating = current_user.ratings.find_by_id(params[:msg])
      @rating.value
    else
      "N/A"
    end
  end

Why am I getting this error? Thanks


问:
POST: register return The GET method is not supported for this route. Supported methods: POST in laravel-api 8
After I deployed my project to server the Route: register start return this:

```<code>"message": "The GET method is not supported for this route. Supported methods: POST.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",
</code>```

in localhost, it worked Succesful !!!

My route list is:

| POST| api/register | App\Http\Controllers\Auth\UserAuthController@register

My route in api.php:

```<code>Route::post('register', [UserAuthController::class, 'register']);
</code>```

Controller:

```<code>class UserAuthController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|confirmed',
            'phone_number' => 'required|numeric|unique:users,phone_number',
            'country' => 'required|string',
            'city' => 'required|string',
            'address' => 'string',
            'VIP' => 'boolean'
        ]);

        $data['password'] = bcrypt($request->password);

        $user = User::create($data);

        $token = $user->createToken('API Token')->accessToken;

        return response(['user' => $user, 'token' => $token], 201);
    }
</code>```

答:
The problem was from the host not the project, When you face this problem and the project worked in your local host but facing this problem in the server just check if you enable HTTPS protocol in cPanel or in .htacsses in the root path.

After you do this your project should work successfully.

Body:
After I deployed my project to server the Route: register start return this:

"message": "The GET method is not supported for this route. Supported methods: POST.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",

in localhost, it worked Succesful !!!

My route list is:

| POST| api/register | App\Http\Controllers\Auth\UserAuthController@register

My route in api.php:

Route::post('register', [UserAuthController::class, 'register']);

Controller:

class UserAuthController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|confirmed',
            'phone_number' => 'required|numeric|unique:users,phone_number',
            'country' => 'required|string',
            'city' => 'required|string',
            'address' => 'string',
            'VIP' => 'boolean'
        ]);

        $data['password'] = bcrypt($request->password);

        $user = User::create($data);

        $token = $user->createToken('API Token')->accessToken;

        return response(['user' => $user, 'token' => $token], 201);
    }