问:
How to make whole screen scrollable in flutter
This is my Code for Body of Scaffold of the Screen

```<code>Container(
      child: Column(
        children: <Widget>[
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  VideoPlay(widget: widget),

                  TitleVideo(widget: widget),
                  Padding(
                    padding: const EdgeInsets.only(top: 1.0, left: 10),
                    child: Opacity(
                      opacity: 0.5,
                      child: Row(
                        children: <Widget>[
                          Text(widget.video.viewCount + " views "),
                          SizedBox(
                            width: 5,
                            child: Text("|"),
                          ),
                          Text(" ${timeago.format(widget.video.timestamp)}"),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  IconRow(
                    video: widget.video,
                  ),
                  //User Panel
                  subscribe_panel(),
                  SizedBox(
                    height: 310,
                    child: suggestedVideo(),
                  ),

                  // Suggestions list
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
</code>```

The "suggestion list" Contains This Code

```<code>    class suggestedVideo extends StatelessWidget {
    const suggestedVideo({Key? key,}) : super(key: key);
    @override
    Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: suggestedVideos.length,
      itemBuilder: (context, index) => VideoCard(
        video: suggestedVideos[index],
        press: () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      VideoScreen(video: suggestedVideos[index])));
        },
      ),
    );
  }
 }
</code>```

but The Screen is only scrolling the ListView Builder part rather than the whole screen,
I am trying to recreate youtube UI and for the VideoScrolling screen , I want to scroll the screen , by keeping the video at top and Every other widget being scrollable.

答:
This happens because when you try to scroll, it scrolls the ListView and not the SingleChildScrollView.
In order to solve that, add

```<code>physics: const NeverScrollableScrollPhysics()
</code>```

to your ListView.

You can also remove the SizedBox that wraps suggestedVideo() and add

```<code>shrinkWrap: true,
scrollDirection: Axis.vertical,
</code>```

to your ListView.

Body:
This is my Code for Body of Scaffold of the Screen

Container(
      child: Column(
        children: <Widget>[
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  VideoPlay(widget: widget),

                  TitleVideo(widget: widget),
                  Padding(
                    padding: const EdgeInsets.only(top: 1.0, left: 10),
                    child: Opacity(
                      opacity: 0.5,
                      child: Row(
                        children: <Widget>[
                          Text(widget.video.viewCount + " views "),
                          SizedBox(
                            width: 5,
                            child: Text("|"),
                          ),
                          Text(" ${timeago.format(widget.video.timestamp)}"),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  IconRow(
                    video: widget.video,
                  ),
                  //User Panel
                  subscribe_panel(),
                  SizedBox(
                    height: 310,
                    child: suggestedVideo(),
                  ),

                  // Suggestions list
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

The "suggestion list" Contains This Code

    class suggestedVideo extends StatelessWidget {
    const suggestedVideo({Key? key,}) : super(key: key);
    @override
    Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: suggestedVideos.length,
      itemBuilder: (context, index) => VideoCard(
        video: suggestedVideos[index],
        press: () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      VideoScreen(video: suggestedVideos[index])));
        },
      ),
    );
  }
 }

but The Screen is only scrolling the ListView Builder part rather than the whole screen,
I am trying to recreate youtube UI and for the VideoScrolling screen , I want to scroll the screen , by keeping the video at top and Every other widget being scrollable.

Body:
This happens because when you try to scroll, it scrolls the ListView and not the SingleChildScrollView.
In order to solve that, add

physics: const NeverScrollableScrollPhysics()

to your ListView.

You can also remove the SizedBox that wraps suggestedVideo() and add

shrinkWrap: true,
scrollDirection: Axis.vertical,

to your ListView.


来源: stackexchange

问:
Docker compose build always set ENV Value to port 80
I have following dockerfile:-

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build
WORKDIR /src
COPY ["src/CustomerManagement/CustomerAPI/CustomerAPI.csproj", "src/CustomerManagement/CustomerAPI/"]

COPY . .
WORKDIR "/src/src/CustomerManagement/CustomerAPI"
RUN dotnet build "CustomerAPI.csproj" -c Release -o /app
RUN dotnet restore -s https://api.nuget.org/v3/index.json -s https://www.myget.org/F/autoweb/api/v3/index.json

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

EXPOSE 5000/tcp
ENV ASPNETCORE_URLS=http://*:5000
HEALTHCHECK --interval=30s --timeout=3s --retries=1 CMD curl --silent --fail http://localhost:5000/hc || exit 1

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

Docker.compose file:-

```<code> customerapi:
    image: ${DOCKER_REGISTRY-}customerapi
    networks:
      - backendpool
    build:
      context: .
      dockerfile: src/CustomerManagement/CustomerAPI/Dockerfile
    depends_on:
      - sqlserver
      - rabbitmq
    ports:
      - "5000"
    environment:
      - ASPNETCORE_ENVIRONMENT=Production
</code>```

Problem descriptions:-

I have instructed dockerfile to expose port 5000. When i tried to build the compose file its build fine but it never expose port 5000. When I checked my docker configuration, it always set to port 80:-

docker container image configuration:- pull through (docker inspect cli)

```<code>"DockerVersion": "19.03.1",
 "Author": "",
 "Config": {
     "Hostname": "",
     "Domainname": "",
     "User": "",
     "AttachStdin": false,
     "AttachStdout": false,
     "AttachStderr": false,
     "Tty": false,
     "OpenStdin": false,
     "StdinOnce": false,
     "Env": [
         "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
         "ASPNETCORE_URLS=http://+:80",
         "DOTNET_RUNNING_IN_CONTAINER=true",
         "ASPNETCORE_VERSION=2.2.6"
     ],
     "Cmd": null,
     "Image": "sha256:1632908f5f238edcea0e99468a1584b859d6593bcd7e2a8943233c8d2bd4b983",
     "Volumes": null,
     "WorkingDir": "/app",
     "Entrypoint": [
         "dotnet",
         "CustomerAPI.dll"
     ],
     "OnBuild": null,
     "Labels": null
 },
</code>```

No matter what value you set in ENV key-value pair, it never sets this way and m pretty much struggling to understand how to tell docker compose file to set ENV value to a expose port in docker file???

launch settings.json file:-

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:5000",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "CustomerAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:5000"
    }
  }
}
</code>```

docker-compose.local.yml

```<code>version: '3.5'

services:

  customerapi:
    ports:
      - "5000:5000"
</code>```

building my docker image container

```<code>docker-compose -f docker-compose.yml -f docker-compose.local.yml build
</code>```

答:
You have to set the following environment variable inside the docker-compose file, in order to listen to the preferred port.

ENV ASPNETCORE_URLS=http://+:5000

ContentLicense: CC BY-SA 4.0

Body:
I have following dockerfile:-

FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build
WORKDIR /src
COPY ["src/CustomerManagement/CustomerAPI/CustomerAPI.csproj", "src/CustomerManagement/CustomerAPI/"]

COPY . .
WORKDIR "/src/src/CustomerManagement/CustomerAPI"
RUN dotnet build "CustomerAPI.csproj" -c Release -o /app
RUN dotnet restore -s https://api.nuget.org/v3/index.json -s https://www.myget.org/F/autoweb/api/v3/index.json

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

EXPOSE 5000/tcp
ENV ASPNETCORE_URLS=http://*:5000
HEALTHCHECK --interval=30s --timeout=3s --retries=1 CMD curl --silent --fail http://localhost:5000/hc || exit 1

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

Docker.compose file:-

 customerapi:
    image: ${DOCKER_REGISTRY-}customerapi
    networks:
      - backendpool
    build:
      context: .
      dockerfile: src/CustomerManagement/CustomerAPI/Dockerfile
    depends_on:
      - sqlserver
      - rabbitmq
    ports:
      - "5000"
    environment:
      - ASPNETCORE_ENVIRONMENT=Production

Problem descriptions:-

I have instructed dockerfile to expose port 5000. When i tried to build the compose file its build fine but it never expose port 5000. When I checked my docker configuration, it always set to port 80:-

docker container image configuration:- pull through (docker inspect cli)

"DockerVersion": "19.03.1",
 "Author": "",
 "Config": {
     "Hostname": "",
     "Domainname": "",
     "User": "",
     "AttachStdin": false,
     "AttachStdout": false,
     "AttachStderr": false,
     "Tty": false,
     "OpenStdin": false,
     "StdinOnce": false,
     "Env": [
         "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
         "ASPNETCORE_URLS=http://+:80",
         "DOTNET_RUNNING_IN_CONTAINER=true",
         "ASPNETCORE_VERSION=2.2.6"
     ],
     "Cmd": null,
     "Image": "sha256:1632908f5f238edcea0e99468a1584b859d6593bcd7e2a8943233c8d2bd4b983",
     "Volumes": null,
     "WorkingDir": "/app",
     "Entrypoint": [
         "dotnet",
         "CustomerAPI.dll"
     ],
     "OnBuild": null,
     "Labels": null
 },

No matter what value you set in ENV key-value pair, it never sets this way and m pretty much struggling to understand how to tell docker compose file to set ENV value to a expose port in docker file???

launch settings.json file:-

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:5000",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "CustomerAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:5000"
    }
  }
}

docker-compose.local.yml

version: '3.5'

services:

  customerapi:
    ports:
      - "5000:5000"

building my docker image container

docker-compose -f docker-compose.yml -f docker-compose.local.yml build


问:
Select2 not working inside bootstrap modal
I am trying to use select2 inside bootstrap modal but it is not getting the focus automatically as well as down and up arrows are not working for the populated list.

The same select2 works when I put it outside the modal popup.

When I searched, I found many are facing this same problem and found this post

Select2 doesn't work when embedded in a bootstrap modal

I implemented both the solutions from it

Removed tabindex from modal popup.

Commented code of enforceFocus function in modal.js file.

But it is still not working! Any idea what I could still be missing?

Edit1

It works on firefox when tabindex is removed from the modal div but not with IE9

Edit2

I found that removing tabindex is actually not getting recognized by IE9 because I can still hide the popup by escape key in IE but not in Firefox.

答:
Just use data attribute settings:
data-dropdown-parent="#bs-modal-id"</p>
```<code><select class="form-control" data-dropdown-parent="#bs-modal-id"></select>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just use data attribute settings:
data-dropdown-parent="#bs-modal-id"

<select class="form-control" data-dropdown-parent="#bs-modal-id"></select>


问:
Adobe Reader shows embedded qualified timestamp could not be verified
I signed PDF document with Qualified Electronic Signature and Qualified Timestamp. For some reason Adobe Reader thinks the timestamp could not be verified. All other validators show the signature being valid PAdES-BASELINE-LT. What could the cause of it?

Exact error message "The signature includes an embedded timestamp but it could not be verified"

答:
As far as I know, Adobe Reader does not make use of the EU LOTL and EU MS TLs “directly” but rather use an Adobe-specific format (similar to the AATL) to configure trust anchors derived from the EU MS TLs.

So in general the content of the Adobe-specific EU TL can differ (desynchronization) from the latest published EU MS TLs.

Most probably, the timestamp has been generated by a "recently" qualified time-stamping service, which has not (yet ?) been included in the Adobe-specific EU TL.


问:
Get all subfolders of a specific public folder
I want to get all subfolders of a specific public subfolder.

The problem I face is that "Deep traversal queries are not allowed on public folders." so I am a bit lost at how to do that now.

Here is my code:

```<code>Function FindAllSubfolders(){
    $tfTargetidRoot = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)
    $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$tfTargetidRoot)

    $FolderPath = "/mydomain.com/parentfolder"
    $pfArray = $FolderPath.Split("/")
    for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
        $pfArray[$lint]
        $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
        $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$pfArray[$lint])
        $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)
        if ($findFolderResults.TotalCount -gt 0){
            foreach($folder in $findFolderResults.Folders){
                $tfTargetFolder = $folder
            }
        }
    }

    $folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10000)
    $folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
    $folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
    $folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
    $folderfindResults = $service.FindFolders($tfTargetFolder.id, $folderview)
    return $folderfindResults
}
</code>```

答:
Untested, but you can try this:</p>
```<code>$result = Get-PublicFolder -Identity "/mydomain.com/parentfolder" -Recurse -ResultSize Unlimited -ErrorAction SilentlyContinue | ForEach-Object {
    [PsCustomObject]@{
        FolderPath   = $_.Identity
        DisplayName  = $_.DisplayName
        EmailAddress = if ($_.MailEnabled) {$_.PrimarySmtpAddress.ToLower()} else {$null}
    }
}

# show the results
$result | Format-Table -AutoSize  # or Out-GridView if you prefer

# save as CSV file
$result | Export-Csv -Path 'X:\path\to\PublicFolders.csv' -NoTypeInformation
</code>```

Body:
I want to get all subfolders of a specific public subfolder.

The problem I face is that "Deep traversal queries are not allowed on public folders." so I am a bit lost at how to do that now.

Here is my code:

Function FindAllSubfolders(){
    $tfTargetidRoot = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)
    $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$tfTargetidRoot)

    $FolderPath = "/mydomain.com/parentfolder"
    $pfArray = $FolderPath.Split("/")
    for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
        $pfArray[$lint]
        $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
        $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$pfArray[$lint])
        $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)
        if ($findFolderResults.TotalCount -gt 0){
            foreach($folder in $findFolderResults.Folders){
                $tfTargetFolder = $folder
            }
        }
    }

    $folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10000)
    $folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
    $folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
    $folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
    $folderfindResults = $service.FindFolders($tfTargetFolder.id, $folderview)
    return $folderfindResults
}

Body:
Untested, but you can try this:

$result = Get-PublicFolder -Identity "/mydomain.com/parentfolder" -Recurse -ResultSize Unlimited -ErrorAction SilentlyContinue | ForEach-Object {
    [PsCustomObject]@{
        FolderPath   = $_.Identity
        DisplayName  = $_.DisplayName
        EmailAddress = if ($_.MailEnabled) {$_.PrimarySmtpAddress.ToLower()} else {$null}
    }
}

# show the results
$result | Format-Table -AutoSize  # or Out-GridView if you prefer

# save as CSV file
$result | Export-Csv -Path 'X:\path\to\PublicFolders.csv' -NoTypeInformation


问:
How to run two commands on Github Actions instance one after another?
So question seems easy but let me start with this, ";" "&" does not work.

The two commands to be ran on Github actions instance in CI/CD pipeline :

python3 manage.py runserver

python3 abc.py

After putting the command in the yaml file, only the first command runs and then the workflow is stuck there only and does not executes the second command.

I have tried putting in two separate blocks in workflow yaml file but no luck.

答:
There are two to run commands one after another on Github Actions.

On the same step:

   steps:
      - name: Run both python files
        run: |
          python manage.py runserver
          python abc.py
```
<p>On different steps (that will run in sequence):</p>
<pre class="lang-yaml prettyprint-override"><code>   steps:
      - name: Run first python file
        run: python manage.py runserver

      - name: Run second python file
        run: python abc.py
</code>```

Also, you don't need to inform python3, just python is enough, as you will use the setup/python action informing the version first.

Therefore, your whole workflow would probably look like this:

```<code>jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository content
        uses: actions/checkout@v2.3.4

      - name: Setup Python Version
        uses: actions/setup-python@v2
        with:
          python-version: 3.8

      - name: Install Python dependencies
        run: python -m pip install --upgrade pip [...] # if necessary

      - name: Execute Python scripts
        run: |
          python manage.py runserver
          python abc.py
</code>```

Body:
There are two to run commands one after another on Github Actions.

On the same step:

   steps:
      - name: Run both python files
        run: |
          python manage.py runserver
          python abc.py

On different steps (that will run in sequence):

   steps:
      - name: Run first python file
        run: python manage.py runserver

      - name: Run second python file
        run: python abc.py

Also, you don't need to inform python3, just python is enough, as you will use the setup/python action informing the version first.

Therefore, your whole workflow would probably look like this:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository content
        uses: actions/checkout@v2.3.4

      - name: Setup Python Version
        uses: actions/setup-python@v2
        with:
          python-version: 3.8

      - name: Install Python dependencies
        run: python -m pip install --upgrade pip [...] # if necessary

      - name: Execute Python scripts
        run: |
          python manage.py runserver
          python abc.py


问:
In Laravel 5.3, how to get the Job ID after we dispatch a job to the job queue?
In Laravel 5.3, in the controller, we can dispatch a job to the job queue like this:

```<code>$job = (new JobClass())->onQueue('queuename');
dispatch($job);
</code>```

In the Job class which is using InteractsWithQueue trait, in the handle function, we can get the Job ID like this:

```<code>$this->job->getJobId();
</code>```

But, I would like to get the Job ID in my controller after I use the dispatch($job).

How to get the Job ID in controller?

If there is no such function available, can we extend the dispatch helper function to add this function?

答:
Its a quite old question. But maybe who came across this post by google.
Laravel is firing an event after a job is queued. Illuminate\Queue\Events\JobQueued

You can add a listener to this event and reach almost all infos incl. The DB id int your event listener.

In your EventServiceProvider attach your listener. In my app it is the JobQueuedListener file

```<code>use Illuminate\Queue\Events\JobQueued;

protected $listen = [
        JobQueued::class =>[
            JobQueuedListener::class
        ],
</code>```

In the JobQueuedListener file you can now access the event var.

```<code>public function handle(JobQueued $event)
{
    $this->event  = $event;
    $mainListener = $event->job->class ?? '';
    if ($mainListener == 'App\Listeners\IpBlockedListener') {
        $this->addIdToIpBlockedModel();
    }

    }
</code>```

Body:
In Laravel 5.3, in the controller, we can dispatch a job to the job queue like this:

$job = (new JobClass())->onQueue('queuename');
dispatch($job);

In the Job class which is using InteractsWithQueue trait, in the handle function, we can get the Job ID like this:

$this->job->getJobId();

But, I would like to get the Job ID in my controller after I use the dispatch($job).

How to get the Job ID in controller?

If there is no such function available, can we extend the dispatch helper function to add this function?

Body:
Its a quite old question. But maybe who came across this post by google.
Laravel is firing an event after a job is queued. Illuminate\Queue\Events\JobQueued

You can add a listener to this event and reach almost all infos incl. The DB id int your event listener.

In your EventServiceProvider attach your listener. In my app it is the JobQueuedListener file

use Illuminate\Queue\Events\JobQueued;

protected $listen = [
        JobQueued::class =>[
            JobQueuedListener::class
        ],

In the JobQueuedListener file you can now access the event var.

public function handle(JobQueued $event)
{
    $this->event  = $event;
    $mainListener = $event->job->class ?? '';
    if ($mainListener == 'App\Listeners\IpBlockedListener') {
        $this->addIdToIpBlockedModel();
    }

    }


问:
MS Access - Relationships
I inherited a project in Microsoft Access 2000 that has code, tables & queries. I need to convert this to SQL.

I see several queries with INNER JOINS with Select commands. So I am guessing the tables have relations set up?

I used the Relationships tools (Graphical Tool) & add all the tables. The relationships are not showing up.

How has the relationships setup?
How do I retrieve the relations that has been set?

答:
If the Relationship tool was not used to indicate the relationships and enforce referential integrity, you are out of luck as you can have relationships between tables without using the Relationship tool.

The joins show you the primary keys/foreign keys of the involved tables, so you probably have to reverse engineer the relationships from the JOIN clauses in the queries.

Title: MS Access - Relationships


问:
How to implement App Tracking Transparency in Flutter
I submitted my app to apple but it got rejected because i haven't added App transparency. SO far, i have imported the dependency into pubspec.yaml and i'm confused if there is more that i need to add to my main.dart in the below code, please help</p>
```<code>import 'dart:io';
import 'dart:ui';
import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:path_provider/path_provider.dart';
import 'app.dart';
import 'models/constants.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final TrackingStatus status =
  await AppTrackingTransparency.requestTrackingAuthorization();
  await EasyLocalization.ensureInitialized();
  await Firebase.initializeApp();
  Directory directory = await getApplicationDocumentsDirectory();
  Hive.init(directory.path);
  await Hive.openBox(Constants.bookmarkTag);
  await Hive.openBox(Constants.resentSearchTag);
  await Hive.openBox(Constants.notificationTag);
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark));

  runApp(
    EasyLocalization(
      supportedLocales: [Locale('en'), Locale('ar'), Locale('es')],
      path: 'assets/translations',
      fallbackLocale: Locale('en'),

      //Defaut language
      startLocale: Locale('en'),
      useOnlyLangCode: true,
      child: MyApp(),
    )
  );
}

</code>```

答:
Yes. For iOs you need to specify a key in the Info.plist.

Open file app/ios/Runner/Info.plist
and add the following line:

NSUserTrackingUsageDescription
This identifier will be used to deliver personalized ads to you.

As it is specified in the package:
https://pub.dev/packages/app_tracking_transparency

Body:
I submitted my app to apple but it got rejected because i haven't added App transparency. SO far, i have imported the dependency into pubspec.yaml and i'm confused if there is more that i need to add to my main.dart in the below code, please help

import 'dart:io';
import 'dart:ui';
import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:path_provider/path_provider.dart';
import 'app.dart';
import 'models/constants.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final TrackingStatus status =
  await AppTrackingTransparency.requestTrackingAuthorization();
  await EasyLocalization.ensureInitialized();
  await Firebase.initializeApp();
  Directory directory = await getApplicationDocumentsDirectory();
  Hive.init(directory.path);
  await Hive.openBox(Constants.bookmarkTag);
  await Hive.openBox(Constants.resentSearchTag);
  await Hive.openBox(Constants.notificationTag);
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark));

  runApp(
    EasyLocalization(
      supportedLocales: [Locale('en'), Locale('ar'), Locale('es')],
      path: 'assets/translations',
      fallbackLocale: Locale('en'),

      //Defaut language
      startLocale: Locale('en'),
      useOnlyLangCode: true,
      child: MyApp(),
    )
  );
}


问:
Test the lifecycle methods of a connected component + ReactJs + Jest
I am trying to test the componentWillRecieveProps of a connected component. Since I can't shallow render the component as it needs to be wrapped in a Provider, I am updating the props by setProps method of the child component.

setProps() usually will call the component lifecycle methods but since the testing here is on the child component, setProps() is not re rendering the wrapper and thus I am unable to test componentWillRecieveProps with new Props.

Any suggestions to test the connected component lifecycle methods?

```<code> test('calls componentWillReceiveProps', () => {
    const willReceiveProps = jest.fn();
    const props = {
        title: "Order",
        history,
        ordersStatus: true,
        status: 'loaded',
        dispatch: jest.fn()
    }

    const newProps = {
        ...props,
        status: 'failed'
    }

    wrapper = mount(<Provider store={store}><MyComponent {...props} /></Provider>)
    wrapper.setProps({ children: <MyComponent {...newProps} /> });
    // New props are updated from above, expect componentWillReceiveProps to be called here
    OrderpickupDashboard.prototype.componentWillReceiveProps = willReceiveProps;
    wrapper.update();
    expect(willReceiveProps).toBeTruthy();
    // expect(willReceiveProps).toBeCalled();
    // This statement isn't working as the lifecycle method isn't called, how can we make the
       test call componentWillReceiveProps

});
</code>```

答:
I think you can export non connected "MyComponent" for testing purposes. This way you can simulate prop changes and verify your render output easily.

For example,

MyComponent.jsx

```<code>export class MyComponentComp extends React.Component<Props, State> {
 // use this for testing
}

export default connect(mapStateToProps, dispatchToProps)(MyComponentComp)
</code>```

"componentWillReceiveProps" is deprecated may be try updating that as well.

Body:
I am trying to test the componentWillRecieveProps of a connected component. Since I can't shallow render the component as it needs to be wrapped in a Provider, I am updating the props by setProps method of the child component.

setProps() usually will call the component lifecycle methods but since the testing here is on the child component, setProps() is not re rendering the wrapper and thus I am unable to test componentWillRecieveProps with new Props.

Any suggestions to test the connected component lifecycle methods?

 test('calls componentWillReceiveProps', () => {
    const willReceiveProps = jest.fn();
    const props = {
        title: "Order",
        history,
        ordersStatus: true,
        status: 'loaded',
        dispatch: jest.fn()
    }

    const newProps = {
        ...props,
        status: 'failed'
    }

    wrapper = mount(<Provider store={store}><MyComponent {...props} /></Provider>)
    wrapper.setProps({ children: <MyComponent {...newProps} /> });
    // New props are updated from above, expect componentWillReceiveProps to be called here
    OrderpickupDashboard.prototype.componentWillReceiveProps = willReceiveProps;
    wrapper.update();
    expect(willReceiveProps).toBeTruthy();
    // expect(willReceiveProps).toBeCalled();
    // This statement isn't working as the lifecycle method isn't called, how can we make the
       test call componentWillReceiveProps

});

Body:
I think you can export non connected "MyComponent" for testing purposes. This way you can simulate prop changes and verify your render output easily.

For example,

MyComponent.jsx

export class MyComponentComp extends React.Component<Props, State> {
 // use this for testing
}

export default connect(mapStateToProps, dispatchToProps)(MyComponentComp)

"componentWillReceiveProps" is deprecated may be try updating that as well.


问:
CSS pseudo element positioning - partial border above header
I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element.  It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

I have tried absolute positioning, different displays but nothing works.

https://codepen.io/lol4000/pen/dyZvmGK

```<code> <img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w" sizes="(max-width: 420px) 100vw, 420px">            <h2 class="sub-title">Test English subtitle</h2><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.</p> <p>Donec mattis vulputate tellus, vel tincidunt purus condimentum vel. </p>Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis. <p>In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus. </p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>

h2.sub-title {font-size:28px;display: block;}
h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

.wp-post-image {
    float: left;
    margin: 0 15px 10px 0;}
</code>```

答:
Update: Ok, so we use display: inline-block; in heading to properly define the role of the box in the page, which is inline. Since there is no wrapper element in our content, we do not need to do anything else (except the relative and absolute positioning). Also, I used the float: left; on the img since we want img to be on the far left and the rest of the content overflow in its right.

h2.sub-title {
  font-size: 28px;
  position: relative;
  display: inline-block;
}

h2.sub-title::before {
  position: absolute;
  height: 8px;
  width: 130px;
  left: 0;
  top: -10px;
  background: #441A6D;
  display: block;
  content: "";
}

img {
  margin: 0 15px 10px 0;
  max-width: 100%;
  height: auto;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img src="https://via.placeholder.com/200x200">
  <h2 class="sub-title">Test English subtitle</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.</p>
  <p>Donec mattis vulputate tellus, vel tincidunt purus condimentum vel. </p>Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis.
  <p>In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus. </p>
  <p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero
    enim.
  </p>
  <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>
  <p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero
    enim.
  </p>
  <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>
</div></code>```

Body:
I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element.  It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

I have tried absolute positioning, different displays but nothing works.

https://codepen.io/lol4000/pen/dyZvmGK

Test English subtitle

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.

Donec mattis vulputate tellus, vel tincidunt purus condimentum vel.
Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis.
In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus.

Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.

Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.

Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.

Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.

h2.sub-title {font-size:28px;display: block;}
h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

.wp-post-image {
    float: left;
    margin: 0 15px 10px 0;}

Body:
Update: Ok, so we use display: inline-block; in heading to properly define the role of the box in the page, which is inline. Since there is no wrapper element in our content, we do not need to do anything else (except the relative and absolute positioning). Also, I used the float: left; on the img since we want img to be on the far left and the rest of the content overflow in its right.

h2.sub-title {
  font-size: 28px;
  position: relative;
  display: inline-block;
}

h2.sub-title::before {
  position: absolute;
  height: 8px;
  width: 130px;
  left: 0;
  top: -10px;
  background: #441A6D;
  display: block;
  content: "";
}

img {
  margin: 0 15px 10px 0;
  max-width: 100%;
  height: auto;
  float: left;
}

<div>
  <img src="https://via.placeholder.com/200x200">
  <h2 class="sub-title">Test English subtitle</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.</p>
  <p>Donec mattis vulputate tellus, vel tincidunt purus condimentum vel. </p>Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis.
  <p>In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus. </p>
  <p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero
    enim.
  </p>
  <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>
  <p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero
    enim.
  </p>
  <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>
</div>


问:
Can't access wp-admin page, getting ERR_TOO_MANY_REDIRECTIONS (Tried everything!)
So the site was working fine just last week. Today I tried to access the wp-admin page to log in and after slow loading, for a bit, I get an error saying it was redirecting too many times and failed. After lots of research, I tried every method the other articles suggested but nothing worked.

Here is what I tried:

Cleared out my cookies, and cache

Tried other laptops & phones

Used a VPN to see if it was my ISP somehow

Disabled all plugins by renaming the plugins folder

Disabled the theme by renaming the themes folder

Deleted .htaccess file but all that did was cause the wp-admin page to display a 403 Forbidden page. After loading the normal site (aka: mysite.com) the .htaccess got regenerated and I was back at square one.

Added this code to wp-config.php as per this link https://wordpress.stackexchange.com/questions/302965/too-many-redirects-only-when-trying-to-access-wp-admin-page (Tried at the top of the file and the end).

```<code>if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
  $_SERVER['HTTPS']='on';
</code>```

Tried to define WP_HOME and WP_SITEURL in wp-config.php

None of the above worked and none fixed it. Please note only the wp-admin page has this issue. The site itself loads but I can't access the admin page which is a disaster and I don't know what to do. I hope one of you can help me. Thanks!

答: For anyone who might be facing this issue, the culprit was the .htaccess file under the wp-admin folder. It had a Deny from all written in it which blocked access to everything. Not sure what added it since I definitely did not. When I changed it to Allow from all it worked fine.

Body:
So the site was working fine just last week. Today I tried to access the wp-admin page to log in and after slow loading, for a bit, I get an error saying it was redirecting too many times and failed. After lots of research, I tried every method the other articles suggested but nothing worked.

Here is what I tried:

Cleared out my cookies, and cache

Tried other laptops & phones

Used a VPN to see if it was my ISP somehow

Disabled all plugins by renaming the plugins folder

Disabled the theme by renaming the themes folder

Deleted .htaccess file but all that did was cause the wp-admin page to display a 403 Forbidden page. After loading the normal site (aka: mysite.com) the .htaccess got regenerated and I was back at square one.

Added this code to wp-config.php as per this link https://wordpress.stackexchange.com/questions/302965/too-many-redirects-only-when-trying-to-access-wp-admin-page (Tried at the top of the file and the end).

if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
  $_SERVER['HTTPS']='on';

Tried to define WP_HOME and WP_SITEURL in wp-config.php

None of the above worked and none fixed it. Please note only the wp-admin page has this issue. The site itself loads but I can't access the admin page which is a disaster and I don't know what to do. I hope one of you can help me. Thanks!


问:
Cannot select element on DWR 921 Router management page
I'm trying to use Selenium in Python to send sms using my Dlink DWR-921 router. But I can't select any element on the document. I tried td, table, body but none of them works. I also tried on browser javascript for the above elements as well. Using document.getElementsByTagName(), but I get empty HTMLCollection. May I know why the element in the page is not selectable?

Update: To ensure the dom last been properly and fully loaded. I took a screenshot and confirmed that the DOM has been loaded everytime it run.

Router model: DLink DWR-921

SW Version: V01.01.3.016

答:
Try to look for an input tag.

Also, it may be that the elements are inside an Iframe. Selenium doesn't "know" how to locate elements inside iframes, so you need to tell me to go into the iframe:

```<code>driver.switchTo().frame("firstframe");
</code>```

or

```<code>driver.switchTo().frame(0);
</code>```

Body:
Try to look for an input tag.

Also, it may be that the elements are inside an Iframe. Selenium doesn't "know" how to locate elements inside iframes, so you need to tell me to go into the iframe:

driver.switchTo().frame("firstframe");

or

driver.switchTo().frame(0);


问:
How do I allow/deny specific java method call from an XSL in Java?
Main goal: I would like to control which classes and or methods that are allowed to be called when parsing an XSL-file via Java.

Using a TransformerFactory:

```<code>TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
...
transformer.transform(in, out);
</code>```

It is possible to call Java-methods by having this is in the XSL-file:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="java">
...
<currentDay><xsl:value-of select="java:util.Date.new()" /></currentDate>
</code>```

Meaning java:util.Date.net() is new Date().toString().

I know I can use:

```<code>factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
</code>```

But that denies everything.

Two questions:

1) How do I control which specific Java-methods that are allowed to be called?

2) If it is not possible using TransformerFactory, what other XSL libraries can I use to control this?

答:
It looks from your example as if you are using the Xalan XSLT processor (Java extensibility varies from one processor to another).

If you move to Saxon, then by default you will NOT be able to call arbitrary Java methods from your XSLT code, you will only be able to call extension functions that have been explicitly registered as "integrated extension functions". This seems to be what you are asking for.

Body:
Main goal: I would like to control which classes and or methods that are allowed to be called when parsing an XSL-file via Java.

Using a TransformerFactory:

TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
...
transformer.transform(in, out);

It is possible to call Java-methods by having this is in the XSL-file:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="java">
...
<currentDay><xsl:value-of select="java:util.Date.new()" /></currentDate>

Meaning java:util.Date.net() is new Date().toString().

I know I can use:

factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);

But that denies everything.

Two questions:

1) How do I control which specific Java-methods that are allowed to be called?

2) If it is not possible using TransformerFactory, what other XSL libraries can I use to control this?


问:
I am storing data in MongoDB and want to fetch that data based on user query
I am storing data in MongoDB, now I have created a flask webpage which lets user submit an ID and based on ID (which is stored in database) it should return that data. My requirement is that after entering ID and clicking on Submit button, Flask should display a message or prompt which contains the data. I am kind of stuck. Below is the code.

app.py

```<code>@app.route('/status', methods = ["GET", "POST"])
def status():

    return render_template("status.html")
</code>```

status.html

```<code><h1 id="title">Check Status</h1>
<div id="form-outer">
  <p id="description">
    Enter Complaint ID
  </p>
  <form id="survey-form" method="get">
    <div class="rowTab">
      <div class="labels">
        <label id="name-label" for="name">Enter Complaint ID: </label>
      </div>
      <div class="rightTab">
        <input autofocus type="text" name="id" id="id" class="input-field" placeholder="Enter ID" required>
      </div>
    </div>

    <button id="submit" type="submit">Submit</button>
    <button id="reset" type="reset">Reset</button>
  </form>
</div>
</body>
</html>
</code>```

ID is stored in database already. In simpler terms, I want the code to search for that specific ID and return the associated data of that ID. How should I code the status function to do that?

答:
In your case you have to do this :

first you have to change the method to POST since you are posting data.

Then you need add the action with the url you are send data to in your case it would be status

```<code><h1 id="title">Check Status</h1>
<div id="form-outer">
  <p id="description">
    Enter Complaint ID
  </p>
  <form id="survey-form" action="{{ url_for('status')}}" method="POST">
    <div class="rowTab">
      <div class="labels">
        <label id="name-label" for="name">Enter Complaint ID: </label>
      </div>
      <div class="rightTab">
        <input autofocus type="text" name="id" id="id" class="input-field" placeholder="Enter ID" required>
      </div>
    </div>

    <button id="submit" type="submit">Submit</button>
    <button id="reset" type="reset">Reset</button>
  </form>
</div>
</body>
</html>
</code>```

in app.py you need to receive the var from the form you need to use request module

```<code>from flask import request
</code>```

then your function need look like this

```<code>@app.route('/status', methods=['POST', 'GET'])
def status():
    if request.method == 'POST':
        your_var = request.form['id']
    return render_template('status.html')
</code>```

hope this solve your issue

Body:
I am storing data in MongoDB, now I have created a flask webpage which lets user submit an ID and based on ID (which is stored in database) it should return that data. My requirement is that after entering ID and clicking on Submit button, Flask should display a message or prompt which contains the data. I am kind of stuck. Below is the code.

app.py

@app.route('/status', methods = ["GET", "POST"])
def status():

    return render_template("status.html")

status.html

Check Status

    Enter Complaint ID

  <form id="survey-form" method="get">

        Enter Complaint ID:

        <input autofocus type="text" name="id" id="id" class="input-field" placeholder="Enter ID" required>

    <button id="submit" type="submit">Submit</button>
    <button id="reset" type="reset">Reset</button>
  </form>

ID is stored in database already. In simpler terms, I want the code to search for that specific ID and return the associated data of that ID. How should I code the status function to do that?

Body:
In your case you have to do this :

first you have to change the method to POST since you are posting data.

Then you need add the action with the url you are send data to in your case it would be status

<h1 id="title">Check Status</h1>
<div id="form-outer">
  <p id="description">
    Enter Complaint ID
  </p>
  <form id="survey-form" action="{{ url_for('status')}}" method="POST">
    <div class="rowTab">
      <div class="labels">
        <label id="name-label" for="name">Enter Complaint ID: </label>
      </div>
      <div class="rightTab">
        <input autofocus type="text" name="id" id="id" class="input-field" placeholder="Enter ID" required>
      </div>
    </div>

    <button id="submit" type="submit">Submit</button>
    <button id="reset" type="reset">Reset</button>
  </form>
</div>
</body>
</html>

in app.py you need to receive the var from the form you need to use request module

from flask import request

then your function need look like this

@app.route('/status', methods=['POST', 'GET'])
def status():
    if request.method == 'POST':
        your_var = request.form['id']
    return render_template('status.html')

hope this solve your issue


问:
Discordjs TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client
I'm making a bot for ddiscord and I can't solve this error:
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.

```<code>const { Client, Intents } = require('discord.js');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

const config = require('./config.json')
const dotenv = require('dotenv')
dotenv.config()

const privateMessage = require('./private-message');
const test = require('./test.js')

const mySecret = process.env['TOKEN'];

client.on('ready', () => {
  console.log(`${client.user.tag} has logged in.`);
});
</code>```

and this is the complete error:

```<code>D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:548
      throw new TypeError('CLIENT_MISSING_INTENTS');
      ^

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
    at Client._validateOptions (D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:548:13)
    at new Client (D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:76:10)
    at Object.<anonymous> (D:\user\Bots\dadobot2801\a\test.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\user\Bots\dadobot2801\a\index.js:10:14) {
  [Symbol(code)]: 'CLIENT_MISSING_INTENTS'
}
</code>```

Any ideas?

答: I had this problem before so i know how to fix it. You need to enable these 3 intents as seen in the image above.

Body:
I'm making a bot for ddiscord and I can't solve this error:
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.

const { Client, Intents } = require('discord.js');

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

const config = require('./config.json')
const dotenv = require('dotenv')
dotenv.config()

const privateMessage = require('./private-message');
const test = require('./test.js')

const mySecret = process.env['TOKEN'];

client.on('ready', () => {
  console.log(`${client.user.tag} has logged in.`);
});

and this is the complete error:

D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:548
      throw new TypeError('CLIENT_MISSING_INTENTS');
      ^

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
    at Client._validateOptions (D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:548:13)
    at new Client (D:\user\Bots\dadobot2801\a\node_modules\discord.js\src\client\Client.js:76:10)
    at Object.<anonymous> (D:\user\Bots\dadobot2801\a\test.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\user\Bots\dadobot2801\a\index.js:10:14) {
  [Symbol(code)]: 'CLIENT_MISSING_INTENTS'
}

Any ideas?


问:
Invalid JSON payload received. Unknown name error- Needle Post Request to Google PubSub API
I am using the following code to do a Post request to Google PubSub API:

```<code>  pushMessages = async function()
    {
      //const collection = context.services.get(`mongodb-atlas`).db(`billing`).collection(`projectdata`);
      var needle = require('needle');

    var postData = {
        "message": "hello world"
    }

     needle
      .post('https://pubsub.googleapis.com/v1/projects/topicname:publish', postData, { json: true },
      function(err, resp) {
      if (err)
        console.log('Error: ' + JSON.stringify(err.message));
      else
        console.log('OK.'+ JSON.stringify(resp.body));
      });
}

</code>```

and I keep getting:

```<code>{"error":{"code":400,"message":"Invalid JSON payload received. Unknown name \"message\": Cannot find field.","status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.BadRequest","fieldViolations":[{"description":"Invalid JSON payload received. Unknown name \"message\": Cannot find field."}]}]}}.
</code>```

Any hint on how to solve this issue?

答:
You need a base64-encoded string to publish into google pub/sub as show on the documentation page. So, not just making the data into a json will work, you also need to encode it.

Please take as reference the node.js client libraries for cloud pub/sub.

```<code>const data = JSON.stringify({foo: 'bar'});
const dataBuffer = Buffer.from(data);
const messageId = await pubSubClient.topic(topicName).publish(dataBuffer);
...
</code>```

Also you can check the API rest/v1/projects.topics/publish details on this link.

Body:
I am using the following code to do a Post request to Google PubSub API:

  pushMessages = async function()
    {
      //const collection = context.services.get(`mongodb-atlas`).db(`billing`).collection(`projectdata`);
      var needle = require('needle');

    var postData = {
        "message": "hello world"
    }

     needle
      .post('https://pubsub.googleapis.com/v1/projects/topicname:publish', postData, { json: true },
      function(err, resp) {
      if (err)
        console.log('Error: ' + JSON.stringify(err.message));
      else
        console.log('OK.'+ JSON.stringify(resp.body));
      });
}

and I keep getting:

{"error":{"code":400,"message":"Invalid JSON payload received. Unknown name \"message\": Cannot find field.","status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.BadRequest","fieldViolations":[{"description":"Invalid JSON payload received. Unknown name \"message\": Cannot find field."}]}]}}.

Any hint on how to solve this issue?

Body:
You need a base64-encoded string to publish into google pub/sub as show on the documentation page. So, not just making the data into a json will work, you also need to encode it.

Please take as reference the node.js client libraries for cloud pub/sub.

const data = JSON.stringify({foo: 'bar'});
const dataBuffer = Buffer.from(data);
const messageId = await pubSubClient.topic(topicName).publish(dataBuffer);
...

Also you can check the API rest/v1/projects.topics/publish details on this link.


问:
php7.4 unable to read memcached data saved by pylibmc
I keep getting these errors trying to read memcached variables stored by python3 scripts runnnig pylibmc.

PHP Warning:  Memcached::get(): could not decompress value: unrecognised compression type in xxx

I'm saving some test data using this python3 script:

```<code>#!/usr/bin/env python3
import json
import pylibmc

mc = pylibmc.Client(["127.0.0.1"], binary=True,
     behaviors={"cas": True, "tcp_nodelay": True,"ketama": True})

mc.set('testvar', json.dumps('{"greeting": "Hello", "title": "Mr"}'), 3600)
</code>```

Using telnet to fetch the variable from memcached shows the data is NOT compressed, but saved in clear text:

```<code>ubuntu@server:~/bin$ telnet localhost 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
get testvar
VALUE testvar 16 81
"{\"greeting\": \"Hello\", \"title\": \"Mr\"}"
END
^]
telnet> quit
Connection closed.
</code>```

I have set the compression limit in the php-memcached settings to a huge number:

/etc/php/7.4/cli/conf.d/25-memcached.ini contains:

```<code>extension=memcached.so
; You need to install php-igbinary package to use igbinary serializer
; and php-msgpack to use msgpack serializer
memcached.serializer=php
memcached.compression_threshold=9999999999
</code>```

The PHP script trying to read the data:

```<code><?php
    echo ini_get("memcached.compression_threshold") . "\n";
    $mc = new Memcached();
    $mc->addServer('localhost', 11211);

    $data = json_decode($mc->get('testvar'));
    echo $data;
    echo "\n";

?>
</code>```

and the output:

```<code>9999999999
PHP Warning:  Memcached::get(): could not decompress value: unrecognised compression type in /home/ubuntu/bin/memcache_get.php on line 6
</code>```

This is on a freshly installed Ubuntu 20 LTS system with python 3.8.10 and pylibmc Version: 1.6.1

Any hints anyone?

答:
Saving to memcached from python as UTF-8 seems to work:

```<code>mc.set('testvar', json.dumps('{"greeting": "Hello", "title": "Mr"}').encode('UTF-8'), 3600)
</code>```

makes it readable for php.

Body:
I keep getting these errors trying to read memcached variables stored by python3 scripts runnnig pylibmc.

PHP Warning:  Memcached::get(): could not decompress value: unrecognised compression type in xxx

I'm saving some test data using this python3 script:

#!/usr/bin/env python3
import json
import pylibmc

mc = pylibmc.Client(["127.0.0.1"], binary=True,
     behaviors={"cas": True, "tcp_nodelay": True,"ketama": True})

mc.set('testvar', json.dumps('{"greeting": "Hello", "title": "Mr"}'), 3600)

Using telnet to fetch the variable from memcached shows the data is NOT compressed, but saved in clear text:

ubuntu@server:~/bin$ telnet localhost 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
get testvar
VALUE testvar 16 81
"{\"greeting\": \"Hello\", \"title\": \"Mr\"}"
END
^]
telnet> quit
Connection closed.

I have set the compression limit in the php-memcached settings to a huge number:

/etc/php/7.4/cli/conf.d/25-memcached.ini contains:

extension=memcached.so
; You need to install php-igbinary package to use igbinary serializer
; and php-msgpack to use msgpack serializer
memcached.serializer=php
memcached.compression_threshold=9999999999

The PHP script trying to read the data:

<?php
    echo ini_get("memcached.compression_threshold") . "\n";
    $mc = new Memcached();
    $mc->addServer('localhost', 11211);

    $data = json_decode($mc->get('testvar'));
    echo $data;
    echo "\n";

?>

and the output:

9999999999
PHP Warning:  Memcached::get(): could not decompress value: unrecognised compression type in /home/ubuntu/bin/memcache_get.php on line 6

This is on a freshly installed Ubuntu 20 LTS system with python 3.8.10 and pylibmc Version: 1.6.1

Any hints anyone?

Body:
Saving to memcached from python as UTF-8 seems to work:

mc.set('testvar', json.dumps('{"greeting": "Hello", "title": "Mr"}').encode('UTF-8'), 3600)

makes it readable for php.


问:
Sort a list of object w.r.t to a particular member/state in descending order
I have a list of java object that have 4 members.

```<code>int id;
String name;
String age;
int order;
</code>```

I am using his code to sort object fields in ascending order according to if condition.

```<code>Collections.sort(list, new Comparator<com.MyObject>() {

          public int compare(com.MyObject object1, com.MyObject object2) {

            if(myString.equalsIgnoreCase("name")){
            return object1.getName().compareTo(object2.getName());

          }else if(myString.equalsIgnoreCase("age")){
            return object1.getAge().compareTo(object2.getAge());

          }else{
            return object1.getOrder() - object2.getOrder();
          }
      }
  });
</code>```

I want to add another condition if(myString.equalsIgnoreCase("nameReverse")) If this will be the case the list should be sorted in descending order.

答:
The Collections class has a reverseOrder method which returns a reverse Comparator for a given comparator. IMO, it would be more cleaner to not modify the Comparator if all you want to do is get a reverse Comparator.

A bit of sample code:

```<code>public class Person {

    public static void testComparator() {
        Person p1 = new Person("c");
        Person p2 = new Person("a");
        Person p3 = new Person("b");
        List<Person> persons = Arrays.asList(p1, p2, p3);
        Collections.sort(persons, PersonComparator.INSTANCE);
        System.out.println("After normal sorting: " + persons);
        Collections.sort(persons, Collections.reverseOrder(PersonComparator.INSTANCE));
        System.out.println("After reverse sorting: " + persons);
    }

    public Person(String name) { this.name = name; }

    public String name;

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Person [name=").append(name).append("]");
        return builder.toString();
    }

}

class PersonComparator implements Comparator<Person> {

    public static final PersonComparator INSTANCE = new PersonComparator();

    @Override
    public int compare(Person o1, Person o2) {
        return o1.name.compareTo(o2.name);
    }

}
</code>```

Body:
I have a list of java object that have 4 members.

int id;
String name;
String age;
int order;

I am using his code to sort object fields in ascending order according to if condition.

Collections.sort(list, new Comparator<com.MyObject>() {

          public int compare(com.MyObject object1, com.MyObject object2) {

            if(myString.equalsIgnoreCase("name")){
            return object1.getName().compareTo(object2.getName());

          }else if(myString.equalsIgnoreCase("age")){
            return object1.getAge().compareTo(object2.getAge());

          }else{
            return object1.getOrder() - object2.getOrder();
          }
      }
  });

I want to add another condition if(myString.equalsIgnoreCase("nameReverse")) If this will be the case the list should be sorted in descending order.

Body:
The Collections class has a reverseOrder method which returns a reverse Comparator for a given comparator. IMO, it would be more cleaner to not modify the Comparator if all you want to do is get a reverse Comparator.

A bit of sample code:

public class Person {

    public static void testComparator() {
        Person p1 = new Person("c");
        Person p2 = new Person("a");
        Person p3 = new Person("b");
        List<Person> persons = Arrays.asList(p1, p2, p3);
        Collections.sort(persons, PersonComparator.INSTANCE);
        System.out.println("After normal sorting: " + persons);
        Collections.sort(persons, Collections.reverseOrder(PersonComparator.INSTANCE));
        System.out.println("After reverse sorting: " + persons);
    }

    public Person(String name) { this.name = name; }

    public String name;

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Person [name=").append(name).append("]");
        return builder.toString();
    }

}

class PersonComparator implements Comparator<Person> {

    public static final PersonComparator INSTANCE = new PersonComparator();

    @Override
    public int compare(Person o1, Person o2) {
        return o1.name.compareTo(o2.name);
    }

}


问:
color a cell base on column name with jquery
I need to color a cell if the value is "ok" and if the cell is part of the column named "name".

var intervalId = window.setInterval(function(){
    var tableRow = $("td").filter(function() {

        if($(this).text() === "ok") {
            $(this).addClass( "table-danger" );
        }

    }).closest("tr");
  }, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table-danger {
  background: red;
}</code>```

            Header 1
            Header 2
            name

            ok;
            aa;
            ok

            cc;
            aa;
            else

            bb;
            aa;
            else

            bb;
            aa;
            ok

```

I can do the color with that function, but it will color all cell with "ok".
How can I adapt my function ?

答:
If you do not know in advance which column number it will be you can loop over thead and find out:

```<code>$('thead th').each(function(i) {
  if($(this).text() == 'name'){
    columnNr = i+1;
  }
});
</code>```

let columnNr;

$('thead th').each(function(i) {
  if($(this).text() == 'name'){
    columnNr = i+1;
  }
});

var tableRow = $("td:nth-child("+columnNr+")").each(function() {

  if ($(this).text() === "ok") {
    $(this).addClass("table-danger");
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table-danger {
  background: red;
}</code>```

            Header 1
            Header 2
            name

            ok
            aa;
            ok

            cc;
            aa;
            else

            bb;
            aa;
            else

            bb;
            aa;
            ok

```

Body:
I need to color a cell if the value is "ok" and if the cell is part of the column named "name".

var intervalId = window.setInterval(function(){
    var tableRow = $("td").filter(function() {

        if($(this).text() === "ok") {
            $(this).addClass( "table-danger" );
        }

    }).closest("tr");
  }, 1000);

.table-danger {
  background: red;
}

            Header 1
            Header 2
            name

            ok;
            aa;
            ok

            cc;
            aa;
            else

            bb;
            aa;
            else

            bb;
            aa;
            ok

I can do the color with that function, but it will color all cell with "ok".
How can I adapt my function ?

Body:
If you do not know in advance which column number it will be you can loop over thead and find out:

$('thead th').each(function(i) {
  if($(this).text() == 'name'){
    columnNr = i+1;
  }
});

let columnNr;

$('thead th').each(function(i) {
  if($(this).text() == 'name'){
    columnNr = i+1;
  }
});

var tableRow = $("td:nth-child("+columnNr+")").each(function() {

  if ($(this).text() === "ok") {
    $(this).addClass("table-danger");
  }

});

.table-danger {
  background: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>ok</td> <!-- NO color -->
            <td>aa;</td>
            <td>ok</td>  <!-- color -->
        </tr>
        <tr>
            <td>cc;</td>
            <td>aa;</td>
            <td>else</td>
        </tr>
        <tr>
            <td>bb;</td>
            <td>aa;</td>
            <td>else</td>
        </tr>
        <tr>
            <td>bb;</td>
            <td>aa;</td>
            <td>ok</td>
        </tr>
    </tbody>
</table>


问:
How to build grouped tree array from flat array in php
i am trying to re format a array as tree, main array and child arrays should be grouped by "name" property.

my flat array is like

```<code>$flat = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 2, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 4, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 5, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 6, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 7, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 8, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 9, 'parent_id' => 7, 'name' => 'ch3-1'],
    ['id' => 10, 'parent_id' => 7, 'name' => 'ch3-1']
];
</code>```

i could build tree structure by

```<code>$tree = buildTree($flat, 'parent_id', 'id');

function buildTree(array $flatList)
{
    $grouped = [];
    foreach ($flatList as $node) {
        $grouped[$node['parent_id']][] = $node;
    }

    $fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
        foreach ($siblings as $k => $sibling) {
            $id = $sibling['id'];
            if (isset($grouped[$id])) {
                $sibling['children'] = $fnBuilder($grouped[$id]);
            }
            $siblings[$k] = $sibling;
        }
        return $siblings;
    };

    return $fnBuilder($grouped[0]);
}
</code>```

this works perfectly.

But what i want is build nested array should be grouped by it's "name" property.

so the final output should be like

```<code>[
  "root1": [{
      "id": 1,
      "parent_id": 0,
      "name": "root1",
      "children": [
        "ch-1": [{
            "id": 3,
            "parent_id": 1,
            "name": "ch-1",
            "children": [
              "ch-1-1": [{
                  "id": 5,
                  "parent_id": 3,
                  "name": "ch-1-1"
                },
                {
                  "id": 6,
                  "parent_id": 3,
                  "name": "ch-1-1"
                }
              ]
            ]
          },
          {
            "id": 4,
            "parent_id": 1,
            "name": "ch-1"
          }
        ]
      ]
    },
    {
      "id": 2,
      "parent_id": 0,
      "name": "root1"
    }
  ],
  "root2": [{
      "id": 7,
      "parent_id": 0,
      "name": "root2",
      "children": [
        "ch3-1": [{
            "id": 9,
            "parent_id": 7,
            "name": "ch3-1"
          },
          {
            "id": 10,
            "parent_id": 7,
            "name": "ch3-2"
          }
        ]
      ]
    },
    {
      "id": 8,
      "parent_id": 0,
      "name": "root2"
    }
  ]
]
</code>```

I have been stuck here almost for couple of days. Please help me to solve this problem.
Thank you.

答:
```<code>function buildTree2(array $flatList)
{
    $groupedchildren = [];
    $groupedparents = [];
    foreach ($flatList as $node) {
        if($node['parent_id'] == 0){
            $groupedparents[$node['parent_id']][] = $node;
        }else{
            $groupedchildren[$node['parent_id']][] = $node;
        }
    }

    $namegroupedparents = [];
    foreach ($groupedparents as $parent_group) {
        foreach ($parent_group as $node) {
            $namegroupedparents[$node['name']][] = $node;
        }
    }

    $namegroupedchildren = [];
    foreach ($groupedchildren as $children_group) {
        foreach ($children_group as $node) {
            $namegroupedchildren[$node['name']][] = $node;
        }
    }

    $fnBuilder = function (&$namegroupedparents) use (&$fnBuilder, $namegroupedchildren) {
        foreach($namegroupedparents as &$named){
            foreach($named as &$parentgroup){
                $id = $parentgroup['id'];
                foreach($namegroupedchildren as $thename => $namedall){
                    foreach($namedall as $childgroup){
                        if($childgroup['parent_id'] == $id){
                            if(isset($parentgroup['children'])){
                                if(!in_array($childgroup, $parentgroup['children'][$thename])){
                                    $parentgroup['children'][$thename][] = $childgroup;
                                }
                            }else{
                                $parentgroup['children'][$thename][] = $childgroup;
                            }
                            $fnBuilder($parentgroup['children']);
                        }
                    }
                }
            }
        }
        return;
    };

    $fnBuilder($namegroupedparents);

    return $namegroupedparents;
}
</code>```

This is working for your current array, but I don't know if it is going to work with different input.

It groups by parent_id then by name while putting the 0 parents in a different array than the rest of the children. Then it builds the children array by recursion.

Body:
i am trying to re format a array as tree, main array and child arrays should be grouped by "name" property.

my flat array is like

$flat = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 2, 'parent_id' => 0, 'name' => 'root1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 4, 'parent_id' => 1, 'name' => 'ch-1'],
    ['id' => 5, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 6, 'parent_id' => 3, 'name' => 'ch-1-1'],
    ['id' => 7, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 8, 'parent_id' => 0, 'name' => 'root2'],
    ['id' => 9, 'parent_id' => 7, 'name' => 'ch3-1'],
    ['id' => 10, 'parent_id' => 7, 'name' => 'ch3-1']
];

i could build tree structure by

$tree = buildTree($flat, 'parent_id', 'id');

function buildTree(array $flatList)
{
    $grouped = [];
    foreach ($flatList as $node) {
        $grouped[$node['parent_id']][] = $node;
    }

    $fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
        foreach ($siblings as $k => $sibling) {
            $id = $sibling['id'];
            if (isset($grouped[$id])) {
                $sibling['children'] = $fnBuilder($grouped[$id]);
            }
            $siblings[$k] = $sibling;
        }
        return $siblings;
    };

    return $fnBuilder($grouped[0]);
}

this works perfectly.

But what i want is build nested array should be grouped by it's "name" property.

so the final output should be like

[
  "root1": [{
      "id": 1,
      "parent_id": 0,
      "name": "root1",
      "children": [
        "ch-1": [{
            "id": 3,
            "parent_id": 1,
            "name": "ch-1",
            "children": [
              "ch-1-1": [{
                  "id": 5,
                  "parent_id": 3,
                  "name": "ch-1-1"
                },
                {
                  "id": 6,
                  "parent_id": 3,
                  "name": "ch-1-1"
                }
              ]
            ]
          },
          {
            "id": 4,
            "parent_id": 1,
            "name": "ch-1"
          }
        ]
      ]
    },
    {
      "id": 2,
      "parent_id": 0,
      "name": "root1"
    }
  ],
  "root2": [{
      "id": 7,
      "parent_id": 0,
      "name": "root2",
      "children": [
        "ch3-1": [{
            "id": 9,
            "parent_id": 7,
            "name": "ch3-1"
          },
          {
            "id": 10,
            "parent_id": 7,
            "name": "ch3-2"
          }
        ]
      ]
    },
    {
      "id": 8,
      "parent_id": 0,
      "name": "root2"
    }
  ]
]

I have been stuck here almost for couple of days. Please help me to solve this problem.
Thank you.

Body:
function buildTree2(array $flatList)
{
    $groupedchildren = [];
    $groupedparents = [];
    foreach ($flatList as $node) {
        if($node['parent_id'] == 0){
            $groupedparents[$node['parent_id']][] = $node;
        }else{
            $groupedchildren[$node['parent_id']][] = $node;
        }
    }

    $namegroupedparents = [];
    foreach ($groupedparents as $parent_group) {
        foreach ($parent_group as $node) {
            $namegroupedparents[$node['name']][] = $node;
        }
    }

    $namegroupedchildren = [];
    foreach ($groupedchildren as $children_group) {
        foreach ($children_group as $node) {
            $namegroupedchildren[$node['name']][] = $node;
        }
    }

    $fnBuilder = function (&$namegroupedparents) use (&$fnBuilder, $namegroupedchildren) {
        foreach($namegroupedparents as &$named){
            foreach($named as &$parentgroup){
                $id = $parentgroup['id'];
                foreach($namegroupedchildren as $thename => $namedall){
                    foreach($namedall as $childgroup){
                        if($childgroup['parent_id'] == $id){
                            if(isset($parentgroup['children'])){
                                if(!in_array($childgroup, $parentgroup['children'][$thename])){
                                    $parentgroup['children'][$thename][] = $childgroup;
                                }
                            }else{
                                $parentgroup['children'][$thename][] = $childgroup;
                            }
                            $fnBuilder($parentgroup['children']);
                        }
                    }
                }
            }
        }
        return;
    };

    $fnBuilder($namegroupedparents);

    return $namegroupedparents;
}

This is working for your current array, but I don't know if it is going to work with different input.

It groups by parent_id then by name while putting the 0 parents in a different array than the rest of the children. Then it builds the children array by recursion.


问:
Mobaxterm: Connect through SSH gateway (jump host) gives Error as "Remote side unexpectedly closed network connection"
I am using Mobaxterm to ssh to customer servers but from a jump host.

The Option which works fine:

when I open mobaxterm --> create a new ssh connection --> enter the hostname (jump host in my case) and username --> and when I try to connect to this session, it works fine and then I need to manually ssh to customer servers after I get connected to jump host.

The Option which does not work:

when I open mobaxterm --> create a new ssh connection --> enter the customer hostname --> under Network setting --> I enable "Connect through SSH gateway (jump host) and enter jump server hostname and username --> save the session.
When I try to connect to this session, it gives error as "Remote side unexpectedly closed network connection".

Can someone assist to solve it.

答:
I think you confuse which one to be added as the jump host. As an example, I will use 3.45.67.89 jump host to connect to 192.168.0.100 target host.

Create a new session, and:

Add 192.168.0.100 as your remote host. Specify username and port if necessary.

In Advanced SSH settings tab, check Use private key and insert the credentials for the target host

Go to Network settings tab and configure your jump host by clicking the SSH gateway (jump host) button

Add 3.45.67.89 jump host to one of the jump hosts without forgetting the jump host credentials. Specify username and port.

Click OK and then OK again

If nothing is wrong the SSH connection should work like there's no jump host.

TLDR; the jump host should be added to SSH gateway (jump host), not as a remote host.


问:
What is the difference?
When the total record count is higher (in millions ) then the iterator_1 is set with very minimal value like in a few thousand.
But when the data is less, both are having the same set of records. In iterator_1 fetching only the values and then setting iterator. In iterator_2 fetching all records and setting iterator.

Ideally, both are the same right? But getting inconsistent outputs. can someone please help to understand?

```<code>TableResult results = bigquery.query(queryConfig);
Iterator<FieldValueList> iterator_1 = results.getValues().iterator();
Iterator<FieldValueList> iterator_2 = results.iterateAll().iterator();
</code>```

答:
This is really about the Page<ResourceT> interface which is implemented by TableResult.

Many Google APIs implement list operations (or query operations in this particular case) using pagination. The Page<ResourceT> interface represents a page within this paginated result - an implementation is expected to know how to fetch not only the resources within the current page, but subsequent pages as well.

So if you have a query that returns 25 results, 10 per page, then calling getValues() on the first page will immediately return the first 10 resources, and stop. iterateAll() will return an iterator that makes additional API calls as necessary (but lazily), returning all 25 results before being exhausted.

If you just want to get all the results of the query, use iterateAll(), being aware that it can take a long time and make additional API calls as you iterate. If you want the immediately-available results within the current page, use getValues().

Title: What is the difference?

Body:
When the total record count is higher (in millions ) then the iterator_1 is set with very minimal value like in a few thousand.
But when the data is less, both are having the same set of records. In iterator_1 fetching only the values and then setting iterator. In iterator_2 fetching all records and setting iterator.

Ideally, both are the same right? But getting inconsistent outputs. can someone please help to understand?

TableResult results = bigquery.query(queryConfig);
Iterator<FieldValueList> iterator_1 = results.getValues().iterator();
Iterator<FieldValueList> iterator_2 = results.iterateAll().iterator();


问:
scraping price from CSS selector in apify with apify/web-scraper
starting to use Apify, i was trying to build one simple Actor to scrape price from competitor page that is in CSS
td class="param-value productshipping-param"

i have tried this function already:

```<code>async function pageFunction(context) {
  const $ = context.jQuery;
  return {
    url: context.request.url,
    value: +$('[class="param-value productshipping-param"]').text().trim(),
  };
}
</code>```

But still i got no results :/

Thanks for help

答:
It is better to use class selectors like this:</p>
```<code>$('.param-value.productshipping-param')
</code>```

Body:
starting to use Apify, i was trying to build one simple Actor to scrape price from competitor page that is in CSS
td class="param-value productshipping-param"

i have tried this function already:

async function pageFunction(context) {
  const $ = context.jQuery;
  return {
    url: context.request.url,
    value: +$('[class="param-value productshipping-param"]').text().trim(),
  };
}

But still i got no results :/

Thanks for help

Body:
It is better to use class selectors like this:

$('.param-value.productshipping-param')


问:
Error while trying to run Terraform Apply , Web App Authentication Error
I get the below error while trying to run Terraform Apply.

```<code>Error: updating Authentication Settings for App Service "app-cont-sa-fe-predev-cus-bb2e": web.AppsClient#UpdateAuthSettings: Failure responding to request: StatusCode=400 -- Original Error: autorest/azure: Service returned an error. Status=400 Code="BadRequest" Message="Cannot execute the request for site app-cont-sa-fe-predev-cus-bb2e because the site is running on auth version v2." Details=[{"Message":"Cannot execute the request for site app-cont-sa-fe-predev-cus-bb2e because the site is running on auth version v2."},{"Code":"BadRequest"},{"ErrorEntity":{"Code":"BadRequest","ExtendedCode":"04534","Message":"Cannot execute the request for site app-cont-sa-fe-predev-cus-bb2e because the site is running on auth version v2.","MessageTemplate":"Cannot execute the request for site {0} because the site is running on auth version {1}.","Parameters":["app-cont-sa-fe-predev-cus-bb2e","v2"]}}]
    │
    │   with azurerm_app_service.fe,
    │   on resources.app.tf line 59, in resource "azurerm_app_service" "fe":
    │   59: resource "azurerm_app_service" "fe" {
</code>```

Can anyone tell me what do i need to change in my below resource block so that i don't get the error. Thanks

```<code>resource "azurerm_app_service" "fe" {
  location            = module.resourcegroup.resource_group.location
  resource_group_name = module.resourcegroup.resource_group.name
  tags                = module.resourcegroup.resource_group.tags
  app_service_plan_id = azurerm_app_service_plan.default.id
  name                = module.names-web-app-fe.location.app_service.name_unique
  identity { type = "SystemAssigned" }
  auth_settings {
    enabled                       = true
    default_provider              = "AzureActiveDirectory"
    issuer                        = format("https://sts.windows.net/%s/", data.azurerm_client_config.default.tenant_id)
    runtime_version               = "~1"
    token_store_enabled           = true
    unauthenticated_client_action = "RedirectToLoginPage"
    additional_login_params = {
      "response_type" = "code id_token",
      "resource"      = azuread_application.app-fe.application_id
    }
    active_directory {
      client_id         = azuread_application.app-fe.object_id
      client_secret     = azuread_application_password.fe-app-sp-secret.application_object_id
      allowed_audiences = [format("https://%s.azurewebsites.net", module.names-web-app-fe.location.app_service.name_unique)]
    }
  }
  site_config {
    always_on                = true
    app_command_line         = ""
    default_documents        = []
    dotnet_framework_version = "v4.0"
    ftps_state               = "Disabled"
    health_check_path        = ""
    http2_enabled            = true
    linux_fx_version         = "STATICSITE|1.0"
    local_mysql_enabled      = false
    managed_pipeline_mode    = "Integrated"
    min_tls_version          = "1.2"
    #pre_warmed_instance_count = 0
    python_version            = "3.4"
    remote_debugging_enabled  = false
    remote_debugging_version  = "VS2019"
    use_32_bit_worker_process = false
    websockets_enabled        = false
    windows_fx_version        = ""
    cors {
      allowed_origins     = []
      support_credentials = false
    }
  }
  app_settings = {
    "WEBSITE_DNS_SERVER"     = "168.63.129.16"
    "WEBSITE_VNET_ROUTE_ALL" = "1"
  }
}
</code>```

I guess there were changes from Azure side wrt authentication and because of which i am getting this error.

答:
Terraform uses Auth V1 Settings instead of using Auth V2 setting for the Web App. Currently only Azure CLI cmdlet and ARM Templates allow the auth_settings_v2 to be configured. This might be available in the upcoming version of azurerm provider i.e. v3.0.0 as mentioned under Feature details: New Data Sources / Resources for App Service & Function Apps .

As for the error which you are getting , I tried creating a App Service in Azure using similar code as yours and it didn't provide any error in the initial creation but after I go to portal and under authentication setting , I upgrade the authentication settings to v2 . I start receiving the same error while trying to update the application from terraform like below :

In order to avoid the error , if you are using terraform to create and manage the web app , then please don't upgrade Web Authentication Settings .

Body:
I get the below error while trying to run Terraform Apply.

Error: updating Authentication Settings for App Service "app-cont-sa-fe-predev-cus-bb2e": web.AppsClient#UpdateAuthSettings: Failure responding to request: StatusCode=400 -- Original Error: autorest/azure: Service returned an error. Status=400 Code="BadRequest" Message="Cannot execute the request for site app-cont-sa-fe-predev-cus-bb2e because the site is running on auth version v2." Details=[{"Message":"Cannot execute the request for site app-cont-sa-fe-predev-cus-bb2e because the site is running on auth version v2."},{"Code":"BadRequest"},{"ErrorEntity":{"Code":"BadRequest","ExtendedCode":"04534","Message":"Cannot execute the request for site app-cont-sa-fe-predev-cus-bb2e because the site is running on auth version v2.","MessageTemplate":"Cannot execute the request for site {0} because the site is running on auth version {1}.","Parameters":["app-cont-sa-fe-predev-cus-bb2e","v2"]}}]
    │
    │   with azurerm_app_service.fe,
    │   on resources.app.tf line 59, in resource "azurerm_app_service" "fe":
    │   59: resource "azurerm_app_service" "fe" {

Can anyone tell me what do i need to change in my below resource block so that i don't get the error. Thanks

resource "azurerm_app_service" "fe" {
  location            = module.resourcegroup.resource_group.location
  resource_group_name = module.resourcegroup.resource_group.name
  tags                = module.resourcegroup.resource_group.tags
  app_service_plan_id = azurerm_app_service_plan.default.id
  name                = module.names-web-app-fe.location.app_service.name_unique
  identity { type = "SystemAssigned" }
  auth_settings {
    enabled                       = true
    default_provider              = "AzureActiveDirectory"
    issuer                        = format("https://sts.windows.net/%s/", data.azurerm_client_config.default.tenant_id)
    runtime_version               = "~1"
    token_store_enabled           = true
    unauthenticated_client_action = "RedirectToLoginPage"
    additional_login_params = {
      "response_type" = "code id_token",
      "resource"      = azuread_application.app-fe.application_id
    }
    active_directory {
      client_id         = azuread_application.app-fe.object_id
      client_secret     = azuread_application_password.fe-app-sp-secret.application_object_id
      allowed_audiences = [format("https://%s.azurewebsites.net", module.names-web-app-fe.location.app_service.name_unique)]
    }
  }
  site_config {
    always_on                = true
    app_command_line         = ""
    default_documents        = []
    dotnet_framework_version = "v4.0"
    ftps_state               = "Disabled"
    health_check_path        = ""
    http2_enabled            = true
    linux_fx_version         = "STATICSITE|1.0"
    local_mysql_enabled      = false
    managed_pipeline_mode    = "Integrated"
    min_tls_version          = "1.2"
    #pre_warmed_instance_count = 0
    python_version            = "3.4"
    remote_debugging_enabled  = false
    remote_debugging_version  = "VS2019"
    use_32_bit_worker_process = false
    websockets_enabled        = false
    windows_fx_version        = ""
    cors {
      allowed_origins     = []
      support_credentials = false
    }
  }
  app_settings = {
    "WEBSITE_DNS_SERVER"     = "168.63.129.16"
    "WEBSITE_VNET_ROUTE_ALL" = "1"
  }
}

I guess there were changes from Azure side wrt authentication and because of which i am getting this error.


问:
Basic JSF: is it possible to SET a property value in EL?
I need to do something like this:

```<code><a4j:support even="onclick" action="#{myBean.myProperty = null}"/>
</code>```

I would like to know if this is possible and which would be the proper syntax if so.

答:
Bean setter methods are called on form submission but based on your example why not do something like:

```<code><a4j:support event="onclick" action="#{myBean.resetMyProperty}"/>
</code>```

And in your bean your resetMyProperty method would set the myProperty to null

Body:
I need to do something like this:

<a4j:support even="onclick" action="#{myBean.myProperty = null}"/>

I would like to know if this is possible and which would be the proper syntax if so.

Body:
Bean setter methods are called on form submission but based on your example why not do something like:

<a4j:support event="onclick" action="#{myBean.resetMyProperty}"/>

And in your bean your resetMyProperty method would set the myProperty to null