问:
How do I display the HTML GET request data on the same HTML page, using a separate PHP file to fetch it?
I'm trying to get data from a MySQL database, that is being selected from a dropdown in an HTML file, and have the data display on the same HTML page that it is being selected from. I already have the HTML and PHP working to retrieve the data and display it, but it is not displaying on the same page that the user requests it from, it is displaying on the PHP page.

Here is the HTML code for get_project_form.html :

```<code><html>
    <head>
        <title>Get Project Form</title>
        <!--Link this html page to the project_style.css page-->
        <link rel="stylesheet" type="text/css" href="project_style.css">
    </head>
    <body>
        <div class="container">
            <form action="get_project_action.php" autocomplete="off" method="get">
                <label for="Query Selections">Query Selections : (You can only select
                    all data from "Projects"
                    for now):</label>
                <select id="first_query" name="queries" required>
                    <option value="" disabled selected>Make a Selection</option>
                    <option value="Projects">Projects</option>
                </select><br />
                <input type="submit" value="Submit"><br />
        </div>
    </body>
</html>
</code>```

After you make the selection and click submit the data appears on a page with the URL,
http://localhost:8015/get_project_action.php?queries=Projects

Here is the code for the php file get_project_action.php :

```<code><?php
    echo "<table style='border: solid 1px black;'>";

    class TableRows extends RecursiveIteratorIterator
    {
        function __construct($it) {
            parent::__construct($it, self::LEAVES_ONLY);
        }

        function current() {
            return "<td style='width: 150px; border: 1px solid black;'>" .
                parent::current() . "</td>";
        }

        function beginChildren() {
            echo "<tr>";
        }

        function endChildren() {
            echo "</tr>" . "\n";
        }
    }

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "pmo";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
            $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $query = $_GET["queries"];
        $stmt = $conn->prepare("SELECT * FROM $query");
        $stmt->execute();

        // set the resulting array to associative
        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

        foreach (new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as
                 $k => $v) {
            echo $v;
        }
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
    $conn = null;
    echo "</table>";
?>
</code>```

I'd like to keep the HTML and PHP separate if possible. But from what I'm reading I'm guessing that isn't possible. I'm hearing that its best to keep the logic in a separate PHP file but that its best to put the rest of the PHP that does the displaying in the HTML file and change the .html file to a .php instead. But I was hoping there is a way to have the data display in the get_project_form.html page below the form somewhere without combining any of the PHP inside the get_project_form.html file and changing it to a .php. If this is possible, please show me how. If not, please feel free to show me how to do whatever is considered good practice for displaying the data on a web page. Any help will be highly appreciated!

答:
suppose in php file you are using $dropdownData array variable to store data from db.

```<code>//PHP file
<?php
   //query to fetch data from db.
   $dropdownData;
   $this->view('get_project_form.html',$dropdownData);
?>
</code>```

//Then use this array variable $dropdownData in ur HTML file with "for loop" to display
//HTML file
//you can also validate the $dropdownData if it's not empty; otherwise php will give error.

```<code><select id="first_query" name="queries" required>
<option value="" disabled selected>Make a Selection</option>
   <? foreach ($dropdownData as $val => $text) { ?>
       <option value="<? echo $val; ?>" > <? echo $text;?> </option>
   <? } ?>
</select>
</code>```

Body:
I'm trying to get data from a MySQL database, that is being selected from a dropdown in an HTML file, and have the data display on the same HTML page that it is being selected from. I already have the HTML and PHP working to retrieve the data and display it, but it is not displaying on the same page that the user requests it from, it is displaying on the PHP page.

Here is the HTML code for get_project_form.html :

        <title>Get Project Form</title>

        <link rel="stylesheet" type="text/css" href="project_style.css">

            <form action="get_project_action.php" autocomplete="off" method="get">
                Query Selections : (You can only select
                    all data from "Projects"
                    for now):
                <select id="first_query" name="queries" required>
                    <option value="" disabled selected>Make a Selection</option>
                    <option value="Projects">Projects</option>
                </select>

                <input type="submit" value="Submit">

After you make the selection and click submit the data appears on a page with the URL,
http://localhost:8015/get_project_action.php?queries=Projects

Here is the code for the php file get_project_action.php :

<?php
    echo "
";

    class TableRows extends RecursiveIteratorIterator
    {
        function __construct($it) {
            parent::__construct($it, self::LEAVES_ONLY);
        }

        function current() {
            return "" .
                parent::current() . "	";
        }

        function beginChildren() {
            echo "
";
        }

        function endChildren() {
            echo "
" . "\n";
        }
    }

    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "pmo";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
            $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $query = $_GET["queries"];
        $stmt = $conn->prepare("SELECT * FROM $query");
        $stmt->execute();

        // set the resulting array to associative
        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

        foreach (new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as
                 $k => $v) {
            echo $v;
        }
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
    $conn = null;
    echo "
";
?>

I'd like to keep the HTML and PHP separate if possible. But from what I'm reading I'm guessing that isn't possible. I'm hearing that its best to keep the logic in a separate PHP file but that its best to put the rest of the PHP that does the displaying in the HTML file and change the .html file to a .php instead. But I was hoping there is a way to have the data display in the get_project_form.html page below the form somewhere without combining any of the PHP inside the get_project_form.html file and changing it to a .php. If this is possible, please show me how. If not, please feel free to show me how to do whatever is considered good practice for displaying the data on a web page. Any help will be highly appreciated!

Body:
suppose in php file you are using $dropdownData array variable to store data from db.

//PHP file
<?php
   //query to fetch data from db.
   $dropdownData;
   $this->view('get_project_form.html',$dropdownData);
?>

//Then use this array variable $dropdownData in ur HTML file with "for loop" to display
//HTML file
//you can also validate the $dropdownData if it's not empty; otherwise php will give error.

<select id="first_query" name="queries" required>
<option value="" disabled selected>Make a Selection</option>
   <? foreach ($dropdownData as $val => $text) { ?>
       <option value="<? echo $val; ?>" > <? echo $text;?> </option>
   <? } ?>
</select>


来源: stackexchange

问:
Tensorflow installation error: not a supported wheel on this platform - Python 3.6.7 - pip 20.0.2
I know this question has been asked a couple of times but I can't seem to find a proper answer. I am trying to install tensorflow on my Windows x64 machine but keep on getting the error: ERROR: tensorflow_cpu-2.1.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform.

I work with :
- Python 3.6.7
- pip 20.0.2
- virtualenv 20.0.4

after activating the virtualenv:
.\venv\Scripts\activate

I try pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow_cpu-2.1.0-cp36-cp36m-win_amd64.whl

for which I get: ERROR: tensorflow_cpu-2.1.0-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform.

If anyone has ran on these issues, should I upgrade / downgrade any of these versions of Python, pip or virtualenv ?

答:
If you have conda installed, I can help you.

Start with conda base shell (start menu -> Anaconda -> Anaconda prompt).

1) create environment

```<code>conda create --name tensorflow21_env
</code>```

2) activate environment

```<code>conda activate tensorflow21_env
</code>```

3) install

conda install python=3.7

pip install tensorflow-cpu  #install tensorflow=2.1.0;

I worked with
Python 3.7.6 and pip 20.0.2.

pip installed package:

```<code>tensorflow_cpu-2.1.0-cp37-cp37m-win_amd64.whl
</code>```

I hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
If you have conda installed, I can help you.

Start with conda base shell (start menu -> Anaconda -> Anaconda prompt).

1) create environment

conda create --name tensorflow21_env

2) activate environment

conda activate tensorflow21_env

3) install

conda install python=3.7

pip install tensorflow-cpu  #install tensorflow=2.1.0;

I worked with
Python 3.7.6 and pip 20.0.2.

pip installed package:

tensorflow_cpu-2.1.0-cp37-cp37m-win_amd64.whl

I hope it helps.


问:
Azure Blobs billing break down of "All Other Operations"
I am looking at the billing for my Azure Storage Account and trying to understand managing its cost.

Currently my blobs cost is mostly under the "All Other Operations" category. Is there a way to see what operations these are?

I would like to reduce this cost, so the goal is to update my app so these operations are performed less, but I need to first identify what they are.

Below is the graph I get from cost analysis. (Storage accounts, Accumulated cost, grouped by meter)

答:
Short answer to your question is Yes.

Analysis:
According to my observation, I get "all other operations" when I group by "Meter" as shown in below screenshot.

And then if I export the results by clicking on "Export" and then when I filter the results for "Meter" column with "all other operations" then I observe that column named "ServiceTier" has "tiered block blob" as value (in my case). For reference, see below screenshot.

And then if I group by "Meter subcategory" as shown in below screenshot then I see "tiered block blob" (in my case).

And then if I export the results by clicking on "Export" and then when I filter the results for "Meter subCategory" column with "tiered block blob" then I observe that column named "ServiceTier" also has "tiered block blob". For reference, see below screenshot.

So based on above analysis, I believe that we can figure out the break down of "Meter" column with "all other operations" as "tiered block blob" in my case with the help of "Meter subcategory" and "ServiceTier". Similarly you would be able to figure out the break down of "Meter" column with "all other operations".

Hope this helps! Cheers!

Other related references: As per this and this Azure documents, there are many other operations on blobs excluding write, read, list operations so in your case any such operations might have fallen under "all other operations" category.


问:
How can I access random point without full reading?
I have a huge data set to train word2vec.

example is as follows.

```<code>15 24 0
22 23 1
11 15 0
22 27 1
...
</code>```

I want to randomly sample it.

I tried with codecs function and split function.

But that file is too big, so that code make memory error.

To avoid memory error, I use for and open(). for example,

```<code>for line in open(fileNM):
    train(line)
</code>```

But in this way, I can access data only in a sequential way.

How can I randomly access data with out full reading?

答:
if you know how many lines the file has you can use something like:</p>

```<code>import pandas
import random

row_count = 10000000
sample_size = 10000
file_name = "xyz.csv"
skip_set = set(np.random.choice(row_count, row_count-sample_size))
df = pandas.read_csv(file_name, sep=' ', skiprows=lambda x: x in skip_set)
</code>```

Body:
I have a huge data set to train word2vec.

example is as follows.

15 24 0
22 23 1
11 15 0
22 27 1
...

I want to randomly sample it.

I tried with codecs function and split function.

But that file is too big, so that code make memory error.

To avoid memory error, I use for and open(). for example,

for line in open(fileNM):
    train(line)

But in this way, I can access data only in a sequential way.

How can I randomly access data with out full reading?

Body:
if you know how many lines the file has you can use something like:

import pandas
import random

row_count = 10000000
sample_size = 10000
file_name = "xyz.csv"
skip_set = set(np.random.choice(row_count, row_count-sample_size))
df = pandas.read_csv(file_name, sep=' ', skiprows=lambda x: x in skip_set)


问:
Generate API key for API Endpoints from Firebase
I've got an API in cloud run that I want to secure using API keys.  I've been using https://cloud.google.com/endpoints/docs/openapi/get-started-cloud-run#configure_esp to configure the endpoints for the API.  I've successfully created the API and the developer portal.  My goal is for users to log in to a mobile and/or web app (using Firebase) and then be able to generate an API key that allows them to access the API.  I've only found documentation on manually creating API keys for users: https://cloud.google.com/endpoints/docs/openapi/restricting-api-access-with-api-keys#create-an-api-key-for-each-caller.  </p>

<p>My authentication scheme is a common pattern (github, for example, uses this pattern) and I'm surprised its so difficult on GCP. I was able to successfully implement this scheme in AWS.  What am I missing?  </p>

答:
You have missed nothing, it's simply not possible. API key security is not recommended by Google (weaker than OAuth2 authentication mechanism) and all the operations around the API key are only available for Google internal call.

Did you try to validate by yourself an API key? Same result: not possible. Only Cloud Endpoint can do this by calling internal Google API, nothing public.

If you use Firebase, I recommend you to use Firebase Auth to authenticate the users on your API. It's integrated to CLoud Endpoint and you simply have to update your security definition.

Body:
I've got an API in cloud run that I want to secure using API keys.  I've been using https://cloud.google.com/endpoints/docs/openapi/get-started-cloud-run#configure_esp to configure the endpoints for the API.  I've successfully created the API and the developer portal.  My goal is for users to log in to a mobile and/or web app (using Firebase) and then be able to generate an API key that allows them to access the API.  I've only found documentation on manually creating API keys for users: https://cloud.google.com/endpoints/docs/openapi/restricting-api-access-with-api-keys#create-an-api-key-for-each-caller.

My authentication scheme is a common pattern (github, for example, uses this pattern) and I'm surprised its so difficult on GCP. I was able to successfully implement this scheme in AWS.  What am I missing?


问:
Share link on Google+
Is it possible to share/post to Google+ without using the +1 button?

e.g. Like a normal tweet button works with a url link: http://twitter.com/share?url=httpetcetcetc

答:
i used following links in my wordpress website for sharing my blogs,they work fine:

whatsapp share : https://wa.me/?text=(some-text)(your-link)

facebook share: https://www.facebook.com/sharer/sharer.php?u=(your-link)

linkedin share: http://www.linkedin.com/shareArticle?mini=true&url=(your-link)

google-plus : https://plus.google.com/share?url=(your-link)

twitter share: http://www.twitter.com/share?url=(your-link)

ContentLicense: CC BY-SA 3.0

Title: Share link on Google+


问:
How to use hasNext() from the Scanner class?
Input Format

Read some unknown n lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.

Output Format

For each line, print the line number, followed by a single space, and then the line content received as input:

Sample Output

```<code>Hello world
I am a file
Read me until end-of-file.
</code>```

Here is my solution. The problem being I am not able to proceed till EOF.
But the output is just:

```<code>Hello world
</code>```

Here is my code:

```<code>public class Solution {

    public static void main(String[] args) {
        check(1);  // call check method
    }

    static void check(int count) {
        Scanner s = new Scanner(System.in);
        if(s.hasNext() == true) {
            String ns = s.nextLine();
            System.out.println(count + " " + ns);
            count++;
            check(count);
        }
    }
}
</code>```

答:
you can try like this to get desired result:

public class EOF {

```<code>public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    for(int i =1;scan.hasNext();i++) {
        String line = scan.nextLine();
        System.out.println(i + " " + line);
    }
    scan.close();
}
</code>```

}

Body:
Input Format

Read some unknown n lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.

Output Format

For each line, print the line number, followed by a single space, and then the line content received as input:

Sample Output

Hello world
I am a file
Read me until end-of-file.

Here is my solution. The problem being I am not able to proceed till EOF.
But the output is just:

Hello world

Here is my code:

public class Solution {

    public static void main(String[] args) {
        check(1);  // call check method
    }

    static void check(int count) {
        Scanner s = new Scanner(System.in);
        if(s.hasNext() == true) {
            String ns = s.nextLine();
            System.out.println(count + " " + ns);
            count++;
            check(count);
        }
    }
}

Body:
you can try like this to get desired result:

public class EOF {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    for(int i =1;scan.hasNext();i++) {
        String line = scan.nextLine();
        System.out.println(i + " " + line);
    }
    scan.close();
}

}


问:
How do I set permissions on dynamically linked files?
I have an InstallScript installer that utilizes dynamic file links for several components. These components contain configuration files that standard users should be able to edit. We recently discovered that when these files are installed on Windows Server 08, the permissions are set to full access for the Administrators group, but only read & execute access for the Users group.  The typical install location is C:\programName.

I've tried creating new files manually as an admin (right click - new text file) in the C:\programName directory, and they are generated with identical permissions. I'm assuming that this is just the standard permission setup for new files.

Is there any way, within InstallShield, to set the permissions for dynamically linked files or the directory containing them?

I've looked for permission settings in

Organization -> Components

Application Data -> Files and Folders

but I haven't found anything. The documentation on dynamic file links makes no mention of permissions.

We are using InstallShield 2010.

答:
In "Files and Folders" page right-click the file or folder, select Properties and click the Permissions button. In the "Permissions" dialog you can then right-click in the Name(s) list and use the New context menu option to add a new permission.

If the option is not available for a file, you can try setting it on the parent folder.


问:
No ports, no connectivity to Docker compose stack
I am new to Docker-compose and I am struggling to run my Tomcat+Postgres stack.

I have "successfully" launched the stack, in the sense that my Java Web Application successfully connects to Postgresql and deploys into Tomcat.

But no port is mapped and the hosts are not reachable. But the hosts can reach themselves.

The following is my project layout (I use Palantir's Gradle Docker plugin)

edcom3-docker/

edcom3-tomcat/

build.gradle

src/main/

docker/Dockerfile

resources

webapps/edcom3.war

(Other stuff I am too lazy to list)

edcom3-postgres/

build.gradle

src/main/

docker/Dockerfile

src/main/docker/

docker-compose.yml

.env

Thanks to Gradle Docker plugin, the context is built into $baseDir/build/docker

The following is my current docker-compose.yml. I needed to expand the directory structure to justify links

```<code>version: '3'
services:
  edcom3-postgres:
    build: ../../../edcom3-postgres/build/docker
    image: edcom3-postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: postgres
#    networks:
#      - edcom3-net
    expose:
      - "5432/tcp"
    ports:
    - "${EDCOM3_SQL_PORT}:5432"
    volumes:
      - "edcom3-postgres-data:/var/lib/postgresql/data"
  edcom3-tomcat:
    depends_on:
      - edcom3-postgres
    build: ../../../edcom3-tomcat/build/docker
    image: edcom3-tomcat
    expose:
      - "8009/tcp"
      - "8080/tcp"
    ports:
    - "${EDCOM3_AJP_PORT}:8009"
    volumes:
      - "edcom3-config-location:/home/tomcat"
      - "edcom3-file-repository:/mnt/fileRepository"
      - "edcom3-logs:/mnt/phoenix-logs"
      - "edcom3-tomcat-logs:/usr/local/tomcat/logs"
    restart: always
#    networks:
#      - edcom3-net
    links:
      - edcom3-postgres

#networks:
#  edcom3-net:
#    driver: bridge
#    internal: true

volumes:
  edcom3-config-location:
  edcom3-file-repository:
  edcom3-logs:
  edcom3-tomcat-logs:
  edcom3-postgres-data:
</code>```

What I have tried

I run first gradle :edcom3-tomcat:docker and :edcom3-postgres:gradle to build the contexts.

Then I cd into src/main/docker of the main project, where the above docker-compose is located, and launch the stack.

```<code>edcom3-tomcat_1    | 06-Feb-2020 15:51:12.943 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/usr/local/tomcat/webapps/edcom3.war] has finished in [66,278] ms
</code>```

The stack starts and the application is deployed. As you can see, I have instructed docker-compose to expose AJP port (variables are bound to port 50000 and 50001) so that Apache can reverse-proxy into Tomcat. Apache is a stand-alone container.

But I can't find the port bindings in docker ps

```<code>[docker@DOCKER01 ~]$ docker ps
CONTAINER ID        IMAGE                            COMMAND                  CREATED             STATUS                      PORTS                                                      NAMES
78acb0e5ff5d        edcom3-tomcat                    "catalina.sh run"        11 minutes ago      Up 11 minutes (unhealthy)                                                              edcom3_edcom3-tomcat_1
60bbed143adf        edcom3-postgres                  "docker-entrypoint.s…"   16 minutes ago      Up 16 minutes (unhealthy)                                                              edcom3_edcom3-postgres_1
23265ae20793        postgres:11.6-alpine             "docker-entrypoint.s…"   7 weeks ago         Up 2 days                   192.168.0.72:5432->5432/tcp                                postgres11
9c8b0eda42e9        portainer/portainer:1.23.0       "/portainer --ssl --…"   7 weeks ago         Up 2 days                   192.168.0.72:8000->8000/tcp, 192.168.0.72:9000->9000/tcp   keen_grothendieck
63985a2c656f        initech/sqlserver2017:20191204   "/opt/mssql/bin/nonr…"   2 months ago        Up 2 days (healthy)         192.168.0.72:1433->1433/tcp                                sqlserver2017
09589b076513        oracle/database:12.2.0.1-SE2     "/bin/sh -c 'exec $O…"   2 months ago        Up 2 days (healthy)         192.168.0.72:1521->1521/tcp, 192.168.0.72:5500->5500/tcp   oracle12c
</code>```

Considerations: (un)commenting the network in the compose file has no effect.

I can clearly see that the containers are reported unhealthy. I tried to remove the health check from their Dockerfiles but it had no effect: the container is not determined its health but still no port available

Then I tried to ping the containers within their network (network block in docker-compose commented out). From my Windows workstation

```<code>> docker inspect 4ce2be94fbe8 (tomcat)

....

                    "NetworkID": "8196b4a9dab76b899494f427286c0a9250ba4b74f8e4c6dbb8cd4459243509ac",
                    "EndpointID": "17d969ad49fe127870f73e63211e309f23d37a23d2918edb191381ffd7b2aaff",
                    "Gateway": "172.25.0.1",
                    "IPAddress": "172.25.0.3",

....
</code>```

(Oh, cool, the server is listening on port 8080 on that)

```<code>> telnet 172.25.0.1 8009
(connection failed)

> tracert 172.25.0.1
(a number of nodes)
</code>```

It is interesting to see tracert result (which I have omitted). Basically Windows 10 tries to reach 172.25.x.x, which is notably a class 16 private IP address, through the main gateway, only to be ignored by our external ISP (4 external hosts appear in the trace)

Okay, Windows has not configured routing tables.

Let's try on our docker server running CentOS

```<code>$ docker inspect 60bbed143adf

.....

                    "NetworkID": "10a52bc3f822f756f5b76c300787be5af255afd061453add0c70664f69ee06c8",
                    "EndpointID": "f054747f6a5d0370916caa74b8c01c3e7b30d255e06ebb9d0c450bf1db38efb1",
                    "Gateway": "172.19.0.1",
                    "IPAddress": "172.19.0.2",
                    "IPPrefixLen": 16,
.....

[docker@DOCKER01 ssl]$ telnet 172.19.0.3 8009
Trying 172.19.0.3...
Connected to 172.19.0.3.
Escape character is '^]'.
</code>```

It's interesting that I can finally access the network

Conclusion: question

Can somebody help me understand why can't I map port 8009 (AJP) from the web container to the host machine? If I can achieve that, the web application will be available to Apache load balancer via AJP protocol

答:
I have found that the edcom3-net was the main culprit to blame.

My issue was caused by a number of unfortunate coincidences, so let me put order on that.

Ports not exposed with network

Simply put, I have found that if you connect a Docker container to an internal network, it won't publish ports on the host. It must be connected to the host network to publish ports. If you comment the network part on the docker-compose file, ports will be successfully publishes

Host up but not reachable when internal network is in use

I found this to be another aspect, which requires me additional investigation and rather a separate Q&A.

What I have discovered is that when you attach a container to an internal network, it will obtain its own private IP address and not expose the ports. Still, the container has IP address and ports available. There are two noticeable things here

1. If you run a load balancer on another Docker container (this time on the host network)

You will have a hard time reaching the target container. You must configure routing tables to link multiple networks.

2. If the load balancer runs on the Docker host, instead

It should be easier to set a reverse proxy. However, I had the unfortunate coincidence to run this scenarion on a Windows host. And Docker Desktop, in my case, did not set the routing tables. Even after docker network inspecting the network edcom3-net several times, the 172.16.x.x address of Tomcat was routed via the main gateway

Body:
I am new to Docker-compose and I am struggling to run my Tomcat+Postgres stack.

I have "successfully" launched the stack, in the sense that my Java Web Application successfully connects to Postgresql and deploys into Tomcat.

But no port is mapped and the hosts are not reachable. But the hosts can reach themselves.

The following is my project layout (I use Palantir's Gradle Docker plugin)

edcom3-docker/

edcom3-tomcat/

build.gradle

src/main/

docker/Dockerfile

resources

webapps/edcom3.war

(Other stuff I am too lazy to list)

edcom3-postgres/

build.gradle

src/main/

docker/Dockerfile

src/main/docker/

docker-compose.yml

.env

Thanks to Gradle Docker plugin, the context is built into $baseDir/build/docker

The following is my current docker-compose.yml. I needed to expand the directory structure to justify links

version: '3'
services:
  edcom3-postgres:
    build: ../../../edcom3-postgres/build/docker
    image: edcom3-postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: postgres
#    networks:
#      - edcom3-net
    expose:
      - "5432/tcp"
    ports:
    - "${EDCOM3_SQL_PORT}:5432"
    volumes:
      - "edcom3-postgres-data:/var/lib/postgresql/data"
  edcom3-tomcat:
    depends_on:
      - edcom3-postgres
    build: ../../../edcom3-tomcat/build/docker
    image: edcom3-tomcat
    expose:
      - "8009/tcp"
      - "8080/tcp"
    ports:
    - "${EDCOM3_AJP_PORT}:8009"
    volumes:
      - "edcom3-config-location:/home/tomcat"
      - "edcom3-file-repository:/mnt/fileRepository"
      - "edcom3-logs:/mnt/phoenix-logs"
      - "edcom3-tomcat-logs:/usr/local/tomcat/logs"
    restart: always
#    networks:
#      - edcom3-net
    links:
      - edcom3-postgres

#networks:
#  edcom3-net:
#    driver: bridge
#    internal: true

volumes:
  edcom3-config-location:
  edcom3-file-repository:
  edcom3-logs:
  edcom3-tomcat-logs:
  edcom3-postgres-data:

What I have tried

I run first gradle :edcom3-tomcat:docker and :edcom3-postgres:gradle to build the contexts.

Then I cd into src/main/docker of the main project, where the above docker-compose is located, and launch the stack.

edcom3-tomcat_1    | 06-Feb-2020 15:51:12.943 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/usr/local/tomcat/webapps/edcom3.war] has finished in [66,278] ms

The stack starts and the application is deployed. As you can see, I have instructed docker-compose to expose AJP port (variables are bound to port 50000 and 50001) so that Apache can reverse-proxy into Tomcat. Apache is a stand-alone container.

But I can't find the port bindings in docker ps

[docker@DOCKER01 ~]$ docker ps
CONTAINER ID        IMAGE                            COMMAND                  CREATED             STATUS                      PORTS                                                      NAMES
78acb0e5ff5d        edcom3-tomcat                    "catalina.sh run"        11 minutes ago      Up 11 minutes (unhealthy)                                                              edcom3_edcom3-tomcat_1
60bbed143adf        edcom3-postgres                  "docker-entrypoint.s…"   16 minutes ago      Up 16 minutes (unhealthy)                                                              edcom3_edcom3-postgres_1
23265ae20793        postgres:11.6-alpine             "docker-entrypoint.s…"   7 weeks ago         Up 2 days                   192.168.0.72:5432->5432/tcp                                postgres11
9c8b0eda42e9        portainer/portainer:1.23.0       "/portainer --ssl --…"   7 weeks ago         Up 2 days                   192.168.0.72:8000->8000/tcp, 192.168.0.72:9000->9000/tcp   keen_grothendieck
63985a2c656f        initech/sqlserver2017:20191204   "/opt/mssql/bin/nonr…"   2 months ago        Up 2 days (healthy)         192.168.0.72:1433->1433/tcp                                sqlserver2017
09589b076513        oracle/database:12.2.0.1-SE2     "/bin/sh -c 'exec $O…"   2 months ago        Up 2 days (healthy)         192.168.0.72:1521->1521/tcp, 192.168.0.72:5500->5500/tcp   oracle12c

Considerations: (un)commenting the network in the compose file has no effect.

I can clearly see that the containers are reported unhealthy. I tried to remove the health check from their Dockerfiles but it had no effect: the container is not determined its health but still no port available

Then I tried to ping the containers within their network (network block in docker-compose commented out). From my Windows workstation

> docker inspect 4ce2be94fbe8 (tomcat)

....

                    "NetworkID": "8196b4a9dab76b899494f427286c0a9250ba4b74f8e4c6dbb8cd4459243509ac",
                    "EndpointID": "17d969ad49fe127870f73e63211e309f23d37a23d2918edb191381ffd7b2aaff",
                    "Gateway": "172.25.0.1",
                    "IPAddress": "172.25.0.3",

....

(Oh, cool, the server is listening on port 8080 on that)

> telnet 172.25.0.1 8009
(connection failed)

> tracert 172.25.0.1
(a number of nodes)

It is interesting to see tracert result (which I have omitted). Basically Windows 10 tries to reach 172.25.x.x, which is notably a class 16 private IP address, through the main gateway, only to be ignored by our external ISP (4 external hosts appear in the trace)

Okay, Windows has not configured routing tables.

Let's try on our docker server running CentOS

$ docker inspect 60bbed143adf

.....

                    "NetworkID": "10a52bc3f822f756f5b76c300787be5af255afd061453add0c70664f69ee06c8",
                    "EndpointID": "f054747f6a5d0370916caa74b8c01c3e7b30d255e06ebb9d0c450bf1db38efb1",
                    "Gateway": "172.19.0.1",
                    "IPAddress": "172.19.0.2",
                    "IPPrefixLen": 16,
.....

[docker@DOCKER01 ssl]$ telnet 172.19.0.3 8009
Trying 172.19.0.3...
Connected to 172.19.0.3.
Escape character is '^]'.

It's interesting that I can finally access the network

Conclusion: question

Can somebody help me understand why can't I map port 8009 (AJP) from the web container to the host machine? If I can achieve that, the web application will be available to Apache load balancer via AJP protocol


问:
Overwrite style for specific pages
I don't know if this is possible, but this is what I am trying to achieve.
For class category icon and icon-location-pin-4 styles are generating automatically in code. Actually they are defined inside the plugin in wp. If I change color there, it reflects on all pages.

For some pages on the site, I don't want to have these colors displayed, I want specific colors just for few sites and those colors will remain always.

```<code><span class="category-icon" style="background-color: #649744;">
   <i class="icon-location-pin-4" style="color: #ffffff; "></i>
</span>
</code>```

I am not sure how to achieve this, or it is possible? On some pages, the code will look like.. This is what I want to achieve.

```<code><span class="category-icon" style="background-color: #fff;">
   <i class="icon-location-pin-4" style="color: #000; "></i>
</span>
</code>```

I am having two rows in same section, I want it to apply only for second row..

```<code><div class="listing-details footer-section">
    <ul class="preview-category-list">
        <li>
            <a href="">
                <span class="category-icon" style="background-color: #281784;">
                    <i class="fa fa-ticket" style="color: #fff; "></i>
                </span>
                <span class="category-name">Category 1</span>
            </a>
        </li>

    </ul>
</div>
<div class="listing-details footer-section">
    <ul class="preview-category-list">
        <li>
            <a href="">
                <span class="category-icon" style="background-color: #281784;">
                    <i class="icon-location-pin-4" style="color: #fff; "></i>
                </span>
                <span class="category-name">Category 2</span>
            </a>
        </li>

    </ul>
</div>
</code>```

I want to make changes for for backgorund where icon-location-pin-4 is printed out, not for code above. But when I change backgorund, it gets applied for code above too

答:
Is it possible? Nearly certainly.

You can make the CSS selector more specific to include/exclude whatever is required.
Without seeing the DOM of the pages involved, it is impossible to be exact, but if for instance you only wanted this on 1 page, select an element unique to that page that is a parent of the target element.

Re; the other raised question, targetting only the 2nd instance of something we can use nth-child() - although, it is far better to be able to generate the HTML ourselves, and attach a custom class we can target with CSS that way - but we can't always get what we want :).

Using the updated code from above, take some HTML that looks like this:

```<code><!-- page #1 example -->

<div class="pretend-body-page-1"> <!-- pretend this is the body on page 1 -->
  <div class="listing-details footer-section">
      <ul class="preview-category-list">
          <li>
              <a href="">
                  <span class="category-icon" style="background-color: #281784;">
                      <i class="fa fa-ticket" style="color: #fff; ">fa fa-ticket placeholder / example text, due to not having font awesome in code pen - should be removed</i>
                  </span>
                  <span class="category-name">Category 1</span>
              </a>
          </li>
      </ul>
  </div>
  <div class="listing-details footer-section">
      <ul class="preview-category-list">
          <li>
              <a href="">
                  <span class="category-icon" style="background-color: #281784;">
                      <i class="icon-location-pin-4" style="color: #fff; ">fa fa-ticket placeholder / example text, due to not having font awesome in code pen - should be removed</i>
                  </span>
                  <span class="category-name">Category 2</span>
              </a>
          </li>
      </ul>
  </div>
</div>

<hr/>
<span style="color: white;">fake page divide</span>
<hr/>

<!-- page #2 example -->

<div class="pretend-body-page-2"> <!-- pretend this is the body on page 2 -->
  <div class="listing-details footer-section">
      <ul class="preview-category-list">
          <li>
              <a href="">
                  <span class="category-icon" style="background-color: #281784;">
                      <i class="fa fa-ticket" style="color: #fff; ">fa fa-ticket placeholder / example text, due to not having font awesome in code pen - should be removed</i>
                  </span>
                  <span class="category-name">Category 1</span>
              </a>
          </li>
      </ul>
  </div>
  <div class="listing-details footer-section">
      <ul class="preview-category-list">
          <li>
              <a href="">
                  <span class="category-icon" style="background-color: #281784;">
                      <i class="icon-location-pin-4" style="color: #fff; ">fa fa-ticket placeholder / example text, due to not having font awesome in code pen - should be removed</i>
                  </span>
                  <span class="category-name">Category 2</span>
              </a>
          </li>
      </ul>
  </div>
</div>
</code>```

The following CSS hopefully is selecting/achieving what you've requested:

```<code>// only target this element on the specific page
div.pretend-body-page-2 i.icon-location-pin-4:nth-child(1) {
    /**
      Unfortunately !important is required to override the 'inline style' used in the html
      <i style="{inline_style}"

      Ideally we would avoid inline style, as well as the use of !important,
      as nothing can override !important.

      It is better to rely on the specificity of selectors to target elements
    */
    color: #00ae12 !important;
}
</code>```

https://codepen.io/mikeyjk/pen/KKpMmpv

Edit:

I need to modify cat-icon set it to white color, and icon-location-pin-check-2 to black color, in that case the only pin will be showing no green color around. But only changes for regions, where icon-location-pin-check-2 no on cat above.

I think you're asking for a few different things not in the original question.. but here's my best effort interpretation..:

CSS for modifying the background colour of .cat-icon:

```<code>.cat-icon { background-color: #ffffff !important; }
.cat-icon i { color: #000000 !important; }
</code>```

CSS for modifying the color of .icon-location-pin-check-2 to black:

```<code>.buttons.button-1 { color: #000000; }
</code>```

I think you might need to attach a screenshot demonstrating what changes you need if that is still not it, I'm finding it a bit confusing understanding the requirements.

Double edit:

Okay, thanks for the screenshot, I think this is what you are asking for:

```<code>.lf-item-container .listing-details:nth-child(3) .cat-icon {
    background-color: black !important;
    color: white !important;
}
</code>```

In english, taking the parent of both of those rows, identifying which row we want to target (the 3rd under the parent .lf-item-container), then specifying the element we want to modify.

If you added another row to that container, this CSS would be an issue.
As mentioned in a perfect world we could change the HTML output to make the CSS a bit simpler.

Title: Overwrite style for specific pages

Body:
I don't know if this is possible, but this is what I am trying to achieve.
For class category icon and icon-location-pin-4 styles are generating automatically in code. Actually they are defined inside the plugin in wp. If I change color there, it reflects on all pages.

For some pages on the site, I don't want to have these colors displayed, I want specific colors just for few sites and those colors will remain always.

I am not sure how to achieve this, or it is possible? On some pages, the code will look like.. This is what I want to achieve.

I am having two rows in same section, I want it to apply only for second row..

                Category 1

                Category 2

I want to make changes for for backgorund where icon-location-pin-4 is printed out, not for code above. But when I change backgorund, it gets applied for code above too

Body:
Is it possible? Nearly certainly.

You can make the CSS selector more specific to include/exclude whatever is required.
Without seeing the DOM of the pages involved, it is impossible to be exact, but if for instance you only wanted this on 1 page, select an element unique to that page that is a parent of the target element.

Re; the other raised question, targetting only the 2nd instance of something we can use nth-child() - although, it is far better to be able to generate the HTML ourselves, and attach a custom class we can target with CSS that way - but we can't always get what we want :).

Using the updated code from above, take some HTML that looks like this:

<!-- page #1 example -->

<div class="pretend-body-page-1"> <!-- pretend this is the body on page 1 -->
  <div class="listing-details footer-section">
      <ul class="preview-category-list">
          <li>
              <a href="">
                  <span class="category-icon" style="background-color: #281784;">
                      <i class="fa fa-ticket" style="color: #fff; ">fa fa-ticket placeholder / example text, due to not having font awesome in code pen - should be removed</i>
                  </span>
                  <span class="category-name">Category 1</span>
              </a>
          </li>
      </ul>
  </div>
  <div class="listing-details footer-section">
      <ul class="preview-category-list">
          <li>
              <a href="">
                  <span class="category-icon" style="background-color: #281784;">
                      <i class="icon-location-pin-4" style="color: #fff; ">fa fa-ticket placeholder / example text, due to not having font awesome in code pen - should be removed</i>
                  </span>
                  <span class="category-name">Category 2</span>
              </a>
          </li>
      </ul>
  </div>
</div>

<hr/>
<span style="color: white;">fake page divide</span>
<hr/>

<!-- page #2 example -->

<div class="pretend-body-page-2"> <!-- pretend this is the body on page 2 -->
  <div class="listing-details footer-section">
      <ul class="preview-category-list">
          <li>
              <a href="">
                  <span class="category-icon" style="background-color: #281784;">
                      <i class="fa fa-ticket" style="color: #fff; ">fa fa-ticket placeholder / example text, due to not having font awesome in code pen - should be removed</i>
                  </span>
                  <span class="category-name">Category 1</span>
              </a>
          </li>
      </ul>
  </div>
  <div class="listing-details footer-section">
      <ul class="preview-category-list">
          <li>
              <a href="">
                  <span class="category-icon" style="background-color: #281784;">
                      <i class="icon-location-pin-4" style="color: #fff; ">fa fa-ticket placeholder / example text, due to not having font awesome in code pen - should be removed</i>
                  </span>
                  <span class="category-name">Category 2</span>
              </a>
          </li>
      </ul>
  </div>
</div>

The following CSS hopefully is selecting/achieving what you've requested:

// only target this element on the specific page
div.pretend-body-page-2 i.icon-location-pin-4:nth-child(1) {
    /**
      Unfortunately !important is required to override the 'inline style' used in the html
      <i style="{inline_style}"

      Ideally we would avoid inline style, as well as the use of !important,
      as nothing can override !important.

      It is better to rely on the specificity of selectors to target elements
    */
    color: #00ae12 !important;
}

https://codepen.io/mikeyjk/pen/KKpMmpv

Edit:

I need to modify cat-icon set it to white color, and icon-location-pin-check-2 to black color, in that case the only pin will be showing no green color around. But only changes for regions, where icon-location-pin-check-2 no on cat above.

I think you're asking for a few different things not in the original question.. but here's my best effort interpretation..:

CSS for modifying the background colour of .cat-icon:

.cat-icon { background-color: #ffffff !important; }
.cat-icon i { color: #000000 !important; }

CSS for modifying the color of .icon-location-pin-check-2 to black:

.buttons.button-1 { color: #000000; }

I think you might need to attach a screenshot demonstrating what changes you need if that is still not it, I'm finding it a bit confusing understanding the requirements.

Double edit:

Okay, thanks for the screenshot, I think this is what you are asking for:

.lf-item-container .listing-details:nth-child(3) .cat-icon {
    background-color: black !important;
    color: white !important;
}

In english, taking the parent of both of those rows, identifying which row we want to target (the 3rd under the parent .lf-item-container), then specifying the element we want to modify.

If you added another row to that container, this CSS would be an issue.
As mentioned in a perfect world we could change the HTML output to make the CSS a bit simpler.


问:
MyBatis Mapper with several SQLs in one method using DB2
I need to execute several SQL statements in one MyBatis Mapper method, because the SQLs are dependend on each other. With H2, this is no problem:

```<code>    @Delete("DELETE FROM DETAIL_TABLE " +
        "      WHERE MASTER_ID IN " +
        "              (SELECT ID FROM MASTER WHERE BUSINESS_KEY = #{businessKey});" +
        "DELETE FROM MASTER " +
        "      WHERE BUSINESS_KEY = #{businessKey}; ")
void delete(@Param("businessKey") Integer businessKey);
</code>```

When switching to DB2 the statement does not work anymore, because the JDBC driver throws the following exception:

```<code>Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=?;DELETE FROM MASTER       WHERE;TAIL WHERE BUSINESS_KEY =;<space>, DRIVER=4.26.14
</code>```

This is just an easy example to demonstrate the issue. I am aware that you can send a cascading delete statement in the shown situation.

I read a StackOverflow post, that multiple SQL statements in one call are not supported by some JDBC drivers and are not recommended, but sometimes you need to execute different SQLs in a certain order, so defining several MyBatis mapper methods does not solve the issue.

Does anybody has any idea how this can be achieved?

答:
On the DB2 side, you can run a compound statement

```<code>  "BEGIN ATOMIC" +
  "  DELETE FROM DETAIL_TABLE" +
  "        WHERE MASTER_ID IN" +
  "                (SELECT ID FROM MASTER WHERE BUSINESS_KEY = #{businessKey});" +
  "  DELETE FROM MASTER" +
  "        WHERE BUSINESS_KEY = #{businessKey};" +
  "END"
</code>```

or create and call a stored procedure

Body:
I need to execute several SQL statements in one MyBatis Mapper method, because the SQLs are dependend on each other. With H2, this is no problem:

    @Delete("DELETE FROM DETAIL_TABLE " +
        "      WHERE MASTER_ID IN " +
        "              (SELECT ID FROM MASTER WHERE BUSINESS_KEY = #{businessKey});" +
        "DELETE FROM MASTER " +
        "      WHERE BUSINESS_KEY = #{businessKey}; ")
void delete(@Param("businessKey") Integer businessKey);

When switching to DB2 the statement does not work anymore, because the JDBC driver throws the following exception:

Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=?;DELETE FROM MASTER       WHERE;TAIL WHERE BUSINESS_KEY =;<space>, DRIVER=4.26.14

This is just an easy example to demonstrate the issue. I am aware that you can send a cascading delete statement in the shown situation.

I read a StackOverflow post, that multiple SQL statements in one call are not supported by some JDBC drivers and are not recommended, but sometimes you need to execute different SQLs in a certain order, so defining several MyBatis mapper methods does not solve the issue.

Does anybody has any idea how this can be achieved?

Body:
On the DB2 side, you can run a compound statement

  "BEGIN ATOMIC" +
  "  DELETE FROM DETAIL_TABLE" +
  "        WHERE MASTER_ID IN" +
  "                (SELECT ID FROM MASTER WHERE BUSINESS_KEY = #{businessKey});" +
  "  DELETE FROM MASTER" +
  "        WHERE BUSINESS_KEY = #{businessKey};" +
  "END"

or create and call a stored procedure


问:
C# - Constant value '4294901760' cannot be converted to a 'int'
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

```<code>// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;
</code>```

If I put an (int) cast around it like so, I get another error:

```<code>// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;
</code>```

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

答:
This should get you around the unchecked:</p>

```<code>public const int RED = 0xffff << 16;
</code>```

Body:
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;

If I put an (int) cast around it like so, I get another error:

// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

Body:
This should get you around the unchecked:

public const int RED = 0xffff << 16;


问:
How to update table value in wordpress with update query?
Here is the code, I am updating col name custom_status of wp_users table for post data user email. Insert works fine, but the update query is not working.

Code Here:

```<code>if (isset($_POST["email_type"]) == 'News' ) {
    $wpdb->update('wp_users', array('custom_status' => 'News'), WHERE, array('user_email' => $_POST["user_email"] ));
}
</code>```

Thanks for the suggestions.

答:
You should add third argument which row you will update for example:

```<code>if (isset($_POST["email_type"]) == 'News' ) {
    $wpdb->update('wp_users', array('custom_status' => 'News'), array( 'ID' => 1 ));
}
</code>```

Hope help you.

Body:
Here is the code, I am updating col name custom_status of wp_users table for post data user email. Insert works fine, but the update query is not working.

Code Here:

if (isset($_POST["email_type"]) == 'News' ) {
    $wpdb->update('wp_users', array('custom_status' => 'News'), WHERE, array('user_email' => $_POST["user_email"] ));
}

Thanks for the suggestions.

Body:
You should add third argument which row you will update for example:

if (isset($_POST["email_type"]) == 'News' ) {
    $wpdb->update('wp_users', array('custom_status' => 'News'), array( 'ID' => 1 ));
}

Hope help you.


问:
What is the purpose of the post request object at the end of my patient resource generated with Synthea?
I have generated a patient with the default settings using Synthea. The first entry in the bundle generated is as follows:

```<code>{
  "fullUrl": "urn:uuid:0100411a-6826-40d8-bfc7-baba56c9945b",
  "resource": {
    // Patient resource here
  },
  "request": {
    "method": "POST",
    "url": "Patient"
  }
}
</code>```

Why does Synthea generate a POST request at the end of each entry?

答: So this Bundle can be used as a transaction or a batch, that is - when the bundle is sent to the server, the server will know what operation (method) to do with this resource and on what endpoint (url).

Body:
I have generated a patient with the default settings using Synthea. The first entry in the bundle generated is as follows:

{
  "fullUrl": "urn:uuid:0100411a-6826-40d8-bfc7-baba56c9945b",
  "resource": {
    // Patient resource here
  },
  "request": {
    "method": "POST",
    "url": "Patient"
  }
}

Why does Synthea generate a POST request at the end of each entry?


问:
Convert a list of flat objects to list of nested objects in C# (recursive?)
I hope someone can help me with this...

Let's say I have this basic bookmark class:

public class FlatBookmark
{
    public int PageIndex { get; set; }
    public string Path { get; set; }
}
```

<p>And a 'flat' list of bookmarks:</p>

<pre class="lang-cs prettyprint-override"><code>List<FlatBookmark> flatBookmarks = new List<FlatBookmark>()
{
    new FlatBookmark() { Path = "Category 1||Page 1", PageIndex = 0 },
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 1", PageIndex = 1 },
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 2", PageIndex = 2 },
    new FlatBookmark() { Path = "Category 1||Page 2", PageIndex = 3 },
    new FlatBookmark() { Path = "Category 1||Page 2", PageIndex = 4 }, // Ignore (path already exists)
    new FlatBookmark() { Path = "Category 1||Page 2", PageIndex = 5 }, // Ignore (path already exists)
    new FlatBookmark() { Path = "Category 1||Page 3", PageIndex = 6 },
    new FlatBookmark() { Path = "", PageIndex = 123 }, // Empty or null paths should be completely ignored
    new FlatBookmark() { Path = null, PageIndex = 321 }, // Empty or null paths should be completely ignored
    new FlatBookmark() { Path = "Category 2||Page 1", PageIndex = 7 },
    new FlatBookmark() { Path = "Category 2||Page 2", PageIndex = 8 },
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 1", PageIndex = 9 }, // Create a new 'Category1' root, because it is separated by the previous one
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 1", PageIndex = 10 }, // Ignore (path already exists)
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 2", PageIndex = 11 },
};
</code>```

I now want to populate a new List<Bookmark> with nested bookmarks, splitted on any given string of the Path, and where the Title becomes the last part of the Path.

public class Bookmark
{
    public int PageIndex { get; set; }
    public string Title { get; set; }
    public List<Bookmark> Bookmarks; // Nested children
}
```

<p>Like this:</p>

```Category 1: PageIndex=0
    Page 1: PageIndex=0
        Attachment 1: PageIndex=1
        Attachment 2: PageIndex=2
    Page 2: PageIndex=3
    Page 3: PageIndex=6
Category 2: PageIndex=7
    Page 1: PageIndex=7
    Page 2: PageIndex=8
Category 1: PageIndex=9
    Page 1: PageIndex=9
        Attachment 1: PageIndex=9
        Attachment 2: PageIndex=11
```

<p>I created a Unit test for it:</p>

<pre class="lang-cs prettyprint-override"><code>// Category 1
Assert.AreEqual("Category 1", bookmarks[0].Title);
Assert.AreEqual(0, bookmarks[0].PageIndex);

Assert.AreEqual("Page 1", bookmarks[0].Bookmarks[0].Title);
Assert.AreEqual(0, bookmarks[0].Bookmarks[0].PageIndex);

Assert.AreEqual("Attachment 1", bookmarks[0].Bookmarks[0].Bookmarks[0].Title);
Assert.AreEqual(1, bookmarks[0].Bookmarks[0].Bookmarks[0].PageIndex);

Assert.AreEqual("Attachment 2", bookmarks[0].Bookmarks[0].Bookmarks[1].Title);
Assert.AreEqual(2, bookmarks[0].Bookmarks[0].Bookmarks[1].PageIndex);

Assert.AreEqual("Page 2", bookmarks[0].Bookmarks[1].Title);
Assert.AreEqual(3, bookmarks[0].Bookmarks[1].PageIndex);

Assert.AreEqual("Page 3", bookmarks[0].Bookmarks[2].Title);
Assert.AreEqual(6, bookmarks[0].Bookmarks[2].PageIndex);

// Category 2
Assert.AreEqual("Category 2", bookmarks[1].Title);
Assert.AreEqual(7, bookmarks[1].PageIndex);

Assert.AreEqual("Page 1", bookmarks[1].Bookmarks[0].Title);
Assert.AreEqual(7, bookmarks[1].Bookmarks[0].PageIndex);

Assert.AreEqual("Page 2", bookmarks[1].Bookmarks[1].Title);
Assert.AreEqual(8, bookmarks[1].Bookmarks[1].PageIndex);

// Category 1 again (not combined with the first one, because there was another category in between)
Assert.AreEqual("Category 1", bookmarks[2].Title);
Assert.AreEqual(9, bookmarks[2].PageIndex);

Assert.AreEqual("Page 1", bookmarks[2].Bookmarks[0].Title);
Assert.AreEqual(9, bookmarks[2].Bookmarks[0].PageIndex);

Assert.AreEqual("Attachment 1", bookmarks[2].Bookmarks[0].Bookmarks[0].Title);
Assert.AreEqual(9, bookmarks[2].Bookmarks[0].Bookmarks[0].PageIndex);

Assert.AreEqual("Attachment 2", bookmarks[2].Bookmarks[0].Bookmarks[1].Title);
Assert.AreEqual(11, bookmarks[2].Bookmarks[0].Bookmarks[1].PageIndex);
</code>```

I'm stuck on the recursive part (I think...), I can loop through each FlatBookmark, and split the path (string[] parts = bookmark.Split('/')), and then for each part I want to somehow look back if it has any parents, or should have any parent, and if not: create them...

Can someone perhaps point me in the right direction of how to create a method like this?

It should basically have no limit on the amount of nested elements...

--- UPDATE ---

Updated the flatBookmark list with a different separator

Require separation of the path on any given string

Removed the requirement of the 'Path' in the output Bookmark (Title is enough)

Extra requirement: The order of the flatBookmarks should be preserved; multiple bookmarks on the same level with the same title should only be combined when there is no other title between them

--- SOLUTION ---

This is the solution I came up with:

public List<Bookmark> CreateNestedBookmarks(List<FlatBookmark> flatBookmarks, string separator = "/")
{
    // Create a 'root' bookmark list (happens for every nested level, with recursion)
    var bookmarks = new List<Bookmark>();

    foreach (var flatBookmark in flatBookmarks)
    {
        if(!string.IsNullOrWhiteSpace(flatBookmark.Path))
        {
            // Only use the title
            string title = flatBookmark.Path.Split(new string[] { separator }, StringSplitOptions.None)[0];
            bool exists = bookmarks.LastOrDefault()?.Title == title;

            // Add the bookmark to the list if it's not already added before and not empty/null
            if (!exists && !string.IsNullOrWhiteSpace(title))
            {
                bookmarks.Add(new Bookmark()
                {
                    Title = title,
                    PageIndex = flatBookmark.PageIndex
                });
            }
        }
    }

    // Fetch the nested bookmarks for each 'root'-bookmark
    foreach(var bookmark in bookmarks)
    {
        bool found = false;
        List<FlatBookmark> childBookmarks = new List<FlatBookmark>();

        foreach (var flatBookmark in flatBookmarks)
        {
            if(!string.IsNullOrWhiteSpace(flatBookmark.Path))
            {
                string[] splittedPath = flatBookmark.Path.Split(new string[] { separator }, StringSplitOptions.None);
                string title = splittedPath[0];

                if (title == bookmark.Title)
                {
                    // Strip the first part of the path
                    flatBookmark.Path = string.Join(separator, splittedPath.Skip(1).Take(splittedPath.Length - 1));
                    childBookmarks.Add(flatBookmark);
                    found = true;
                }
                else
                {
                    // Stop iteration when a new title is found, with this way it keeps the input order intact
                    // Multiple bookmarks on the same level with the same title should only be combined when there is no different title in between
                    // Cat1
                    // Cat2
                    // Cat1
                    if (found)
                    {
                        break;
                    }
                }
            }
        }

        // Create nested bookmarks (if they exist)
        if(childBookmarks.Count > 0)
        {
            bookmark.Bookmarks = CreateNestedBookmarks(childBookmarks, separator);
        }
    }
    return bookmarks;
}
```

答:
I give you a starting point as pseudo code:

```<code>public List<Bookmark> ParseFlatBookmarks (List<FlatBookmark> flatBookmarks)
{
    // define the list of local root bookmarks.

    // loop over the FLAT bookmarks

        // look only for the root bookmark in each path
        // (ex. in Path = "Category 1/Page 1" you will look for "Category 1")

        // then you check if found bookmark is already present in your root bookmarks list, if it is not than you create it and add it to the list.

    // loop over found root bookmarks

        // create a list of all the FLAT bookmarks that has current root bookmark as root
        // (ex. if you have "Category 1" as current root bookmark you will have a list containing "Category 1/Page 1", "Category 1/Page 1/Attachment 1", etc. and the last one will be "Category 1/Page 3".

        // to recursively navigate the FLAT bookmarks you will need to adjust their path.
        // To do that just remove root bookmark from path
        // (ex. if you currently have "Category 1" as root bookmark "Category 1/Page 1" as FLAT bookmark, you will have to set its path as "Page 1")

        // recursive call passing currently root bookmark's FLAT bookmark children as parameter
        // add found bookmarks to the currently root bookmark

    // return list of root bookmarks
}
</code>```

On top of that you will have to check when the path is empty (it means you've navigated all the way to the child bookmarks

The unique feature you've asked should be covered when you check if a just found bookmark as the same title as one previously stored.

If you can't adjust their path, you could always create new flat bookmarks with adjusted paths.

I hope I gave you some ideas to solve your problem

Body:
I hope someone can help me with this...

Let's say I have this basic bookmark class:

public class FlatBookmark
{
    public int PageIndex { get; set; }
    public string Path { get; set; }
}

And a 'flat' list of bookmarks:

List<FlatBookmark> flatBookmarks = new List<FlatBookmark>()
{
    new FlatBookmark() { Path = "Category 1||Page 1", PageIndex = 0 },
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 1", PageIndex = 1 },
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 2", PageIndex = 2 },
    new FlatBookmark() { Path = "Category 1||Page 2", PageIndex = 3 },
    new FlatBookmark() { Path = "Category 1||Page 2", PageIndex = 4 }, // Ignore (path already exists)
    new FlatBookmark() { Path = "Category 1||Page 2", PageIndex = 5 }, // Ignore (path already exists)
    new FlatBookmark() { Path = "Category 1||Page 3", PageIndex = 6 },
    new FlatBookmark() { Path = "", PageIndex = 123 }, // Empty or null paths should be completely ignored
    new FlatBookmark() { Path = null, PageIndex = 321 }, // Empty or null paths should be completely ignored
    new FlatBookmark() { Path = "Category 2||Page 1", PageIndex = 7 },
    new FlatBookmark() { Path = "Category 2||Page 2", PageIndex = 8 },
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 1", PageIndex = 9 }, // Create a new 'Category1' root, because it is separated by the previous one
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 1", PageIndex = 10 }, // Ignore (path already exists)
    new FlatBookmark() { Path = "Category 1||Page 1||Attachment 2", PageIndex = 11 },
};

I now want to populate a new List<Bookmark> with nested bookmarks, splitted on any given string of the Path, and where the Title becomes the last part of the Path.

public class Bookmark
{
    public int PageIndex { get; set; }
    public string Title { get; set; }
    public List<Bookmark> Bookmarks; // Nested children
}

Like this:

Category 1: PageIndex=0
    Page 1: PageIndex=0
        Attachment 1: PageIndex=1
        Attachment 2: PageIndex=2
    Page 2: PageIndex=3
    Page 3: PageIndex=6
Category 2: PageIndex=7
    Page 1: PageIndex=7
    Page 2: PageIndex=8
Category 1: PageIndex=9
    Page 1: PageIndex=9
        Attachment 1: PageIndex=9
        Attachment 2: PageIndex=11

I created a Unit test for it:

// Category 1
Assert.AreEqual("Category 1", bookmarks[0].Title);
Assert.AreEqual(0, bookmarks[0].PageIndex);

Assert.AreEqual("Page 1", bookmarks[0].Bookmarks[0].Title);
Assert.AreEqual(0, bookmarks[0].Bookmarks[0].PageIndex);

Assert.AreEqual("Attachment 1", bookmarks[0].Bookmarks[0].Bookmarks[0].Title);
Assert.AreEqual(1, bookmarks[0].Bookmarks[0].Bookmarks[0].PageIndex);

Assert.AreEqual("Attachment 2", bookmarks[0].Bookmarks[0].Bookmarks[1].Title);
Assert.AreEqual(2, bookmarks[0].Bookmarks[0].Bookmarks[1].PageIndex);

Assert.AreEqual("Page 2", bookmarks[0].Bookmarks[1].Title);
Assert.AreEqual(3, bookmarks[0].Bookmarks[1].PageIndex);

Assert.AreEqual("Page 3", bookmarks[0].Bookmarks[2].Title);
Assert.AreEqual(6, bookmarks[0].Bookmarks[2].PageIndex);

// Category 2
Assert.AreEqual("Category 2", bookmarks[1].Title);
Assert.AreEqual(7, bookmarks[1].PageIndex);

Assert.AreEqual("Page 1", bookmarks[1].Bookmarks[0].Title);
Assert.AreEqual(7, bookmarks[1].Bookmarks[0].PageIndex);

Assert.AreEqual("Page 2", bookmarks[1].Bookmarks[1].Title);
Assert.AreEqual(8, bookmarks[1].Bookmarks[1].PageIndex);

// Category 1 again (not combined with the first one, because there was another category in between)
Assert.AreEqual("Category 1", bookmarks[2].Title);
Assert.AreEqual(9, bookmarks[2].PageIndex);

Assert.AreEqual("Page 1", bookmarks[2].Bookmarks[0].Title);
Assert.AreEqual(9, bookmarks[2].Bookmarks[0].PageIndex);

Assert.AreEqual("Attachment 1", bookmarks[2].Bookmarks[0].Bookmarks[0].Title);
Assert.AreEqual(9, bookmarks[2].Bookmarks[0].Bookmarks[0].PageIndex);

Assert.AreEqual("Attachment 2", bookmarks[2].Bookmarks[0].Bookmarks[1].Title);
Assert.AreEqual(11, bookmarks[2].Bookmarks[0].Bookmarks[1].PageIndex);

I'm stuck on the recursive part (I think...), I can loop through each FlatBookmark, and split the path (string[] parts = bookmark.Split('/')), and then for each part I want to somehow look back if it has any parents, or should have any parent, and if not: create them...

Can someone perhaps point me in the right direction of how to create a method like this?

It should basically have no limit on the amount of nested elements...

--- UPDATE ---

Updated the flatBookmark list with a different separator

Require separation of the path on any given string

Removed the requirement of the 'Path' in the output Bookmark (Title is enough)

Extra requirement: The order of the flatBookmarks should be preserved; multiple bookmarks on the same level with the same title should only be combined when there is no other title between them

--- SOLUTION ---

This is the solution I came up with:

public List<Bookmark> CreateNestedBookmarks(List<FlatBookmark> flatBookmarks, string separator = "/")
{
    // Create a 'root' bookmark list (happens for every nested level, with recursion)
    var bookmarks = new List<Bookmark>();

    foreach (var flatBookmark in flatBookmarks)
    {
        if(!string.IsNullOrWhiteSpace(flatBookmark.Path))
        {
            // Only use the title
            string title = flatBookmark.Path.Split(new string[] { separator }, StringSplitOptions.None)[0];
            bool exists = bookmarks.LastOrDefault()?.Title == title;

            // Add the bookmark to the list if it's not already added before and not empty/null
            if (!exists && !string.IsNullOrWhiteSpace(title))
            {
                bookmarks.Add(new Bookmark()
                {
                    Title = title,
                    PageIndex = flatBookmark.PageIndex
                });
            }
        }
    }

    // Fetch the nested bookmarks for each 'root'-bookmark
    foreach(var bookmark in bookmarks)
    {
        bool found = false;
        List<FlatBookmark> childBookmarks = new List<FlatBookmark>();

        foreach (var flatBookmark in flatBookmarks)
        {
            if(!string.IsNullOrWhiteSpace(flatBookmark.Path))
            {
                string[] splittedPath = flatBookmark.Path.Split(new string[] { separator }, StringSplitOptions.None);
                string title = splittedPath[0];

                if (title == bookmark.Title)
                {
                    // Strip the first part of the path
                    flatBookmark.Path = string.Join(separator, splittedPath.Skip(1).Take(splittedPath.Length - 1));
                    childBookmarks.Add(flatBookmark);
                    found = true;
                }
                else
                {
                    // Stop iteration when a new title is found, with this way it keeps the input order intact
                    // Multiple bookmarks on the same level with the same title should only be combined when there is no different title in between
                    // Cat1
                    // Cat2
                    // Cat1
                    if (found)
                    {
                        break;
                    }
                }
            }
        }

        // Create nested bookmarks (if they exist)
        if(childBookmarks.Count > 0)
        {
            bookmark.Bookmarks = CreateNestedBookmarks(childBookmarks, separator);
        }
    }
    return bookmarks;
}

Body:
I give you a starting point as pseudo code:

public List<Bookmark> ParseFlatBookmarks (List<FlatBookmark> flatBookmarks)
{
    // define the list of local root bookmarks.

    // loop over the FLAT bookmarks

        // look only for the root bookmark in each path
        // (ex. in Path = "Category 1/Page 1" you will look for "Category 1")

        // then you check if found bookmark is already present in your root bookmarks list, if it is not than you create it and add it to the list.

    // loop over found root bookmarks

        // create a list of all the FLAT bookmarks that has current root bookmark as root
        // (ex. if you have "Category 1" as current root bookmark you will have a list containing "Category 1/Page 1", "Category 1/Page 1/Attachment 1", etc. and the last one will be "Category 1/Page 3".

        // to recursively navigate the FLAT bookmarks you will need to adjust their path.
        // To do that just remove root bookmark from path
        // (ex. if you currently have "Category 1" as root bookmark "Category 1/Page 1" as FLAT bookmark, you will have to set its path as "Page 1")

        // recursive call passing currently root bookmark's FLAT bookmark children as parameter
        // add found bookmarks to the currently root bookmark

    // return list of root bookmarks
}

On top of that you will have to check when the path is empty (it means you've navigated all the way to the child bookmarks

The unique feature you've asked should be covered when you check if a just found bookmark as the same title as one previously stored.

If you can't adjust their path, you could always create new flat bookmarks with adjusted paths.

I hope I gave you some ideas to solve your problem


问:
How do I use the lines of a file as arguments of a command?
Say, I have a file foo.txt specifying N arguments

```<code>arg1
arg2
...
argN
</code>```

which I need to pass to the command my_command

How do I use the lines of a file as arguments of a command?

答:
After editing @Wesley Rice's answer a couple times, I decided my changes were just getting too big to continue changing his answer instead of writing my own. So, I decided I need to write my own!

Read each line of a file in and operate on it line-by-line like this:

```<code>#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r line
do
  echo "$line"
done < "$input"
</code>```

This comes directly from author Vivek Gite here: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/. He gets the credit!

Syntax: Read file line by line on a Bash Unix & Linux shell:

  1. The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line

  2. while read -r line; do COMMAND; done < input.file

  3. The -r option passed to read command prevents backslash escapes from being interpreted.

  4. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed -

  5. while IFS= read -r line; do COMMAND_on $line; done < input.file

And now to answer this now-closed question which I also had: Is it possible to `git add` a list of files from a file? - here's my answer:

Note that FILES_STAGED is a variable containing the absolute path to a file which contains a bunch of lines where each line is a relative path to a file I'd like to do git add on. This code snippet is about to become part of the "eRCaGuy_dotfiles/useful_scripts/sync_git_repo_to_build_machine.sh" file in this project, to enable easy syncing of files in development from one PC (ex: a computer I code on) to another (ex: a more powerful computer I build on): https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.

```<code>while IFS= read -r line
do
    echo "  git add \"$line\""
    git add "$line"
done < "$FILES_STAGED"
</code>```

References:

Where I copied my answer from: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/

For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/

Related:

How to read contents of file line-by-line and do git add on it: Is it possible to `git add` a list of files from a file?

Body:
Say, I have a file foo.txt specifying N arguments

arg1
arg2
...
argN

which I need to pass to the command my_command

How do I use the lines of a file as arguments of a command?

Body:
After editing @Wesley Rice's answer a couple times, I decided my changes were just getting too big to continue changing his answer instead of writing my own. So, I decided I need to write my own!

Read each line of a file in and operate on it line-by-line like this:

#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r line
do
  echo "$line"
done < "$input"

This comes directly from author Vivek Gite here: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/. He gets the credit!

Syntax: Read file line by line on a Bash Unix & Linux shell:

  1. The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line

  2. while read -r line; do COMMAND; done < input.file

  3. The -r option passed to read command prevents backslash escapes from being interpreted.

  4. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed -

  5. while IFS= read -r line; do COMMAND_on $line; done < input.file

And now to answer this now-closed question which I also had: Is it possible to `git add` a list of files from a file? - here's my answer:

Note that FILES_STAGED is a variable containing the absolute path to a file which contains a bunch of lines where each line is a relative path to a file I'd like to do git add on. This code snippet is about to become part of the "eRCaGuy_dotfiles/useful_scripts/sync_git_repo_to_build_machine.sh" file in this project, to enable easy syncing of files in development from one PC (ex: a computer I code on) to another (ex: a more powerful computer I build on): https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.

while IFS= read -r line
do
    echo "  git add \"$line\""
    git add "$line"
done < "$FILES_STAGED"

References:

Where I copied my answer from: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/

For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/

Related:

How to read contents of file line-by-line and do git add on it: Is it possible to `git add` a list of files from a file?


问:
PromQL query to graph the rate of incoming requests
I am new to prometheus. I am using a NewCounterVec to log incoming http requests. I used that based on many other people's code that I found on git hub.

Suppose this is how my metric is defined (in go)

```<code>httpRequests = prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "http_requests_total",
        Help: "Incoming http requests.",
    },
    []string{"path", "status"},
)
</code>```

path the incoming url path and status is the http response status.
What will be my promQL queries (to draw a graph) for

Incoming requests per minute

Rate of failure based on http status
code (status code >=400)

I tried rate(http_requests_total[5m])[30m:1m]
based on this, but that cannot be shown on a graph. It throws an error Error executing query: invalid expression type "range vector" for range query, must be Scalar or instant Vector

答:
Incoming requests per minute

rate(http_requests_total[5m]) * 60

Rate of failure based on http status code (status code >=400)

rate(http_requests_total{status=~"[45].."}[5m])

This is however fragile, and will return nothing if there have been no 4xx or 5xx status codes.

Body:
I am new to prometheus. I am using a NewCounterVec to log incoming http requests. I used that based on many other people's code that I found on git hub.

Suppose this is how my metric is defined (in go)

httpRequests = prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "http_requests_total",
        Help: "Incoming http requests.",
    },
    []string{"path", "status"},
)

path the incoming url path and status is the http response status.
What will be my promQL queries (to draw a graph) for

Incoming requests per minute

Rate of failure based on http status
code (status code >=400)

I tried rate(http_requests_total[5m])[30m:1m]
based on this, but that cannot be shown on a graph. It throws an error Error executing query: invalid expression type "range vector" for range query, must be Scalar or instant Vector


问:
Get Data In Array
I stuck at get data from array. Bellow is example image array.
I want to get data weather icon but I got error core.js:15724 ERROR TypeError: Cannot read property '0' of undefined

This my code

```<code>weatherDaily(){
    this.commonService.getWeatherInfoDaily()
    .subscribe(
      (res) => {
        this.daily = res['list'];
        this.icon = res['list']['weather'][0]['icon'];
        console.log(this.icon);

      }
    )
  }
</code>```

答:
It's supposed to be:

```<code>this.icon = res['list'][0]['weather'][0]['icon'];
</code>```

It is however advised to use interfaces when getting data from an API. This will give you code hinting, and makes it much easier to refactor if the API changes for some reason:

```<code>export interface WeatherListResponse {
  dt: number;
  // ... etc
}

export interface WeatherResponse {
  cod: string;
  message: number;
  cnt: number;
  list: WeatherListResponse[];
}
</code>```

You can then use the generic typings on the HttpClient to hint the compiler to what response it receives, and you will get an error if you do not use the correct properties:

```<code>getWeatherInfoDaily(): Observable<WeatherResponse> {
  return this.http.get<WeatherResponse>(...);
}

weatherDaily() {
  this.commonService.getWeatherInfoDaily().subscribe((res) => {
    this.daily = res.list;
    // this.icon = res.list.weather[0].icon; <-- TypeScript error
    this.icon = res.list[0].weather[0].icon;

    // if you are using the latest typescript, you can use optional chaining:
    this.icon = res.list[0]?.weather[0]?.icon;

    console.log(this.icon);
  })
}
</code>```

Title: Get Data In Array

Body:
I stuck at get data from array. Bellow is example image array.
I want to get data weather icon but I got error core.js:15724 ERROR TypeError: Cannot read property '0' of undefined

This my code

weatherDaily(){
    this.commonService.getWeatherInfoDaily()
    .subscribe(
      (res) => {
        this.daily = res['list'];
        this.icon = res['list']['weather'][0]['icon'];
        console.log(this.icon);

      }
    )
  }

Body:
It's supposed to be:

this.icon = res['list'][0]['weather'][0]['icon'];

It is however advised to use interfaces when getting data from an API. This will give you code hinting, and makes it much easier to refactor if the API changes for some reason:

export interface WeatherListResponse {
  dt: number;
  // ... etc
}

export interface WeatherResponse {
  cod: string;
  message: number;
  cnt: number;
  list: WeatherListResponse[];
}

You can then use the generic typings on the HttpClient to hint the compiler to what response it receives, and you will get an error if you do not use the correct properties:

getWeatherInfoDaily(): Observable<WeatherResponse> {
  return this.http.get<WeatherResponse>(...);
}

weatherDaily() {
  this.commonService.getWeatherInfoDaily().subscribe((res) => {
    this.daily = res.list;
    // this.icon = res.list.weather[0].icon; <-- TypeScript error
    this.icon = res.list[0].weather[0].icon;

    // if you are using the latest typescript, you can use optional chaining:
    this.icon = res.list[0]?.weather[0]?.icon;

    console.log(this.icon);
  })
}


问:
Creating custom FunctionQuery in Solr
I want to create a custom Solr FunctionQuery so that I would be able to get the actual length of field (in terms). The results might look like this :

```<code>{
  "responseHeader":{
    "status":0,
    "QTime":8,
    "params":{
      "q":"python",
      "indent":"on",
      "fl":"title,score,[features efi.query=python store=myfeature_store]",
      "wt":"json"}},
  "response":{"numFound":793,"start":0,"maxScore":0.33828905,"docs":[
      {
        "title":"Newest 'python' Questions - Stack Overflow",
        "score":0.33828905,
        "[features]":"titleLength=5"},
      ]
  }}
</code>```

The only helpful link I'm able to find is this. But it does not explain the topic very well. I'm very new to Solr, so step-wise procedure will be helpful.

EDIT

I've created a js script called count.js as follows:

```<code>function WordCount(str) {
  return str.split(" ").length;
}

function processAdd(cmd) {
    doc = cmd.solrDoc;  // org.apache.solr.common.SolrInputDocument
    var title = doc.getFieldValue("title");
    var count = WordCount(title);
    doc.setField("title_count", count);
    logger.info("count-script#count: title_count=" + count);
}

function processDelete(cmd) {
  // no-op
}

function processMergeIndexes(cmd) {
  // no-op
}

function processCommit(cmd) {
  // no-op
}

function processRollback(cmd) {
  // no-op
}

function finish() {
  // no-op
}
</code>```

Also, I've added following entries in solrconfig.xml:

```<code><initParams path="/update/**">
    <lst name="defaults">
      <str name="update.chain">script</str>
    </lst>
  </initParams>

<updateRequestProcessorChain name="script">
    <processor class="solr.StatelessScriptUpdateProcessorFactory">
      <str name="script">count.js</str>
    </processor>
    <processor class="solr.RunUpdateProcessorFactory" />
  </updateRequestProcessorChain>
</code>```

I've a few questions now:

For this to work, do I have to re-index the documents using Nutch ?

How to check if it's working? Will a simple solr query work like http://localhost:8983/solr/nutch/select?indent=on&q=*:*&wt=json ?

答:
You could use the Update Request Processor. Quite a few ways to do it.

Check out the CountFieldValuesUpdateProcessorFactory

You basically clone your field and do a count on it. But this will work only when your source field is multi-valued. That is, before feeding it to Solr, you tokenize them. You configure this in your SolrConfig.xml

```<code>    <updateRequestProcessorChain name="word-counter">
  <processor class="solr.CloneFieldUpdateProcessorFactory">
    <str name="source">title</str>
    <str name="dest">title_count</str>
  </processor>
  <processor class="solr.CountFieldValuesUpdateProcessorFactory">
    <str name="fieldName">title_count</str>
  </processor>
  <processor class="solr.DefaultValueUpdateProcessorFactory">
    <str name="fieldName">title_count</str>
    <int name="value">0</int>
  </processor>
  <processor class="solr.LogUpdateProcessorFactory" />
  <processor class="solr.RunUpdateProcessorFactory" />
</updateRequestProcessorChain>
</code>```

But remember, this requires that you have "title" as multi-valued which may not be ideal. You can have an additional field something like "title_multi" and mask your process.

Alternatively, you can use a ScriptUpdateProcessor and do perform your counting logic in Javascript.

Title: Creating custom FunctionQuery in Solr

Body:
I want to create a custom Solr FunctionQuery so that I would be able to get the actual length of field (in terms). The results might look like this :

{
  "responseHeader":{
    "status":0,
    "QTime":8,
    "params":{
      "q":"python",
      "indent":"on",
      "fl":"title,score,[features efi.query=python store=myfeature_store]",
      "wt":"json"}},
  "response":{"numFound":793,"start":0,"maxScore":0.33828905,"docs":[
      {
        "title":"Newest 'python' Questions - Stack Overflow",
        "score":0.33828905,
        "[features]":"titleLength=5"},
      ]
  }}

The only helpful link I'm able to find is this. But it does not explain the topic very well. I'm very new to Solr, so step-wise procedure will be helpful.

EDIT

I've created a js script called count.js as follows:

function WordCount(str) {
  return str.split(" ").length;
}

function processAdd(cmd) {
    doc = cmd.solrDoc;  // org.apache.solr.common.SolrInputDocument
    var title = doc.getFieldValue("title");
    var count = WordCount(title);
    doc.setField("title_count", count);
    logger.info("count-script#count: title_count=" + count);
}

function processDelete(cmd) {
  // no-op
}

function processMergeIndexes(cmd) {
  // no-op
}

function processCommit(cmd) {
  // no-op
}

function processRollback(cmd) {
  // no-op
}

function finish() {
  // no-op
}

Also, I've added following entries in solrconfig.xml:

<initParams path="/update/**">
    <lst name="defaults">
      <str name="update.chain">script</str>
    </lst>
  </initParams>

<updateRequestProcessorChain name="script">
    <processor class="solr.StatelessScriptUpdateProcessorFactory">
      <str name="script">count.js</str>
    </processor>
    <processor class="solr.RunUpdateProcessorFactory" />
  </updateRequestProcessorChain>

I've a few questions now:

For this to work, do I have to re-index the documents using Nutch ?

How to check if it's working? Will a simple solr query work like http://localhost:8983/solr/nutch/select?indent=on&q=*:*&wt=json ?

Body:
You could use the Update Request Processor. Quite a few ways to do it.

Check out the CountFieldValuesUpdateProcessorFactory

You basically clone your field and do a count on it. But this will work only when your source field is multi-valued. That is, before feeding it to Solr, you tokenize them. You configure this in your SolrConfig.xml

    <updateRequestProcessorChain name="word-counter">
  <processor class="solr.CloneFieldUpdateProcessorFactory">
    <str name="source">title</str>
    <str name="dest">title_count</str>
  </processor>
  <processor class="solr.CountFieldValuesUpdateProcessorFactory">
    <str name="fieldName">title_count</str>
  </processor>
  <processor class="solr.DefaultValueUpdateProcessorFactory">
    <str name="fieldName">title_count</str>
    <int name="value">0</int>
  </processor>
  <processor class="solr.LogUpdateProcessorFactory" />
  <processor class="solr.RunUpdateProcessorFactory" />
</updateRequestProcessorChain>

But remember, this requires that you have "title" as multi-valued which may not be ideal. You can have an additional field something like "title_multi" and mask your process.

Alternatively, you can use a ScriptUpdateProcessor and do perform your counting logic in Javascript.


问:
Navigation controller default animation not working in API success block SWIFT
Default navigation controller animation is not working inside the API success block.

```<code>API.shared.sendData(url: APIPath.getData, requestType: .post, params: [:], objectType: RootObj.self) { (data) in
            guard let responseData = data else { return }
            print(responseData)
            if responseData.success! {
                if responseData.data != nil {
                    self.data = responseData.data
                    let vc = Utilities.shared.getViewController(identifier: MyViewController.className, storyboardType: .user) as! MyViewController
                    vc.data = self.data
                    self.navigationController?.pushViewController(vc, animated: true)
                } else {
                    self.showAlertOK(APP_NAME, message: responseData.message ?? "Data not found")
                }
            } else {
                self.showAlertOK(APP_NAME, message: responseData.message ?? "Response Failure")
            }
        }
</code>```

If I call pushViewController outside the API block, then the default right to left animation is shown of navigation controller. Please help me how to achieve the default animation inside API block?

答:
Probably you are calling that pushViewController from the background thread. You should always do UI manipulations from main thread only. Use:</p>

```<code>DispatchQueue.main.async {
   self.navigationController?.pushViewController(vc, animated: true)
}
</code>```

Body:
Default navigation controller animation is not working inside the API success block.

API.shared.sendData(url: APIPath.getData, requestType: .post, params: [:], objectType: RootObj.self) { (data) in
            guard let responseData = data else { return }
            print(responseData)
            if responseData.success! {
                if responseData.data != nil {
                    self.data = responseData.data
                    let vc = Utilities.shared.getViewController(identifier: MyViewController.className, storyboardType: .user) as! MyViewController
                    vc.data = self.data
                    self.navigationController?.pushViewController(vc, animated: true)
                } else {
                    self.showAlertOK(APP_NAME, message: responseData.message ?? "Data not found")
                }
            } else {
                self.showAlertOK(APP_NAME, message: responseData.message ?? "Response Failure")
            }
        }

If I call pushViewController outside the API block, then the default right to left animation is shown of navigation controller. Please help me how to achieve the default animation inside API block?

Body:
Probably you are calling that pushViewController from the background thread. You should always do UI manipulations from main thread only. Use:

DispatchQueue.main.async {
   self.navigationController?.pushViewController(vc, animated: true)
}


问:
Python Flask cannot set debug mode to true
I have set up my first Flask project with PyCharm and this is my app.py file:

```<code>from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'TEST'

if __name__ == '__main__':
    app.run(debug=True)
</code>```

I want to run my project in debug mode so that I do not have to restart the server every time something changes. I provide the app.run function with a debug=True parameter, but this does not seem to change the debug flag. The application does start however and I do see "TEST" on the page, but this is with the debug flag set to False.

I also tried to directly change my env variable with os.environ["FLASK_DEBUG"] = "True", but this did not affect the flag also.

Any advice?

答: Run your flask app in command line instead of PyCharm. python3 app.py

Body:
I have set up my first Flask project with PyCharm and this is my app.py file:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'TEST'

if __name__ == '__main__':
    app.run(debug=True)

I want to run my project in debug mode so that I do not have to restart the server every time something changes. I provide the app.run function with a debug=True parameter, but this does not seem to change the debug flag. The application does start however and I do see "TEST" on the page, but this is with the debug flag set to False.

I also tried to directly change my env variable with os.environ["FLASK_DEBUG"] = "True", but this did not affect the flag also.

Any advice?


问:
Laravel - how to confirm destroy method in a popup?
I have multiple forms which delete data from my Laravel application and I was wondering. How can I best make this more user friendly by having to confirm the deletion of these items?

This is the code that I currently use to remove records in a table (without confirmation).

```<code><td class="col">
    <form action="{{ route('campaigns.destroy', $campaign->id) }}" method="POST">
        @csrf
        @method('DELETE')
        <button type="submit" class="btn btn-danger btn-sm float-right" title="Verwijderen">
            <i class="fa fa-times"></i>
        </button>
    </form>
</td>
</code>```

This is what my destroy method looks like

```<code>public function destroy(Campaign $campaign): RedirectResponse
{
    $campaign->delete();

    return redirect()->route('campaigns.index');
}
</code>```

What I have tried

I have tried to use javascripts native confirm() function. But this turns out really ugly so that's why it is not an option for me.

答:
You may use sweetalert2

```<code><td class="col">
   <button type="button" data-url="{{ route('campaigns.destroy', $campaign->id) }}" class="btn btn-danger btn-sm float-right" title="Verwijderen">
        <i class="fa fa-times"></i>
   </button>
</td>
</code>```

JS

```<code>$(document).on('click', '.btn-danger', function (e) {
    e.preventDefault();
    var url = $(this).data('url');
    var token = "{{ csrf_token() }}";
    swal({
            title: "Are you sure!",
            type: "error",
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes!",
            showCancelButton: true,
        },
        function() {
            $.ajax({
                type: "POST",
                url: url,
                data: {_token: token, _method: 'DELETE'},
                success: function (data) {
                     //
                }
            });
    });
});
</code>```

Body:
I have multiple forms which delete data from my Laravel application and I was wondering. How can I best make this more user friendly by having to confirm the deletion of these items?

This is the code that I currently use to remove records in a table (without confirmation).

    <form action="{{ route('campaigns.destroy', $campaign->id) }}" method="POST">
        @csrf
        @method('DELETE')
        <button type="submit" class="btn btn-danger btn-sm float-right" title="Verwijderen">

        </button>
    </form>

This is what my destroy method looks like

public function destroy(Campaign $campaign): RedirectResponse
{
    $campaign->delete();

    return redirect()->route('campaigns.index');
}

What I have tried

I have tried to use javascripts native confirm() function. But this turns out really ugly so that's why it is not an option for me.

Body:
You may use sweetalert2

<td class="col">
   <button type="button" data-url="{{ route('campaigns.destroy', $campaign->id) }}" class="btn btn-danger btn-sm float-right" title="Verwijderen">
        <i class="fa fa-times"></i>
   </button>
</td>

JS

$(document).on('click', '.btn-danger', function (e) {
    e.preventDefault();
    var url = $(this).data('url');
    var token = "{{ csrf_token() }}";
    swal({
            title: "Are you sure!",
            type: "error",
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes!",
            showCancelButton: true,
        },
        function() {
            $.ajax({
                type: "POST",
                url: url,
                data: {_token: token, _method: 'DELETE'},
                success: function (data) {
                     //
                }
            });
    });
});