问:
Bad Request - This combination of host and port requires TLS. with Spring Boot
I'm newbie with Spring Boot.

I'm trying to make a https call to a service, I have a Privake key to secure connection.

I hit:

```<code>http://localhost:8081/points/12345/search
</code>```

I tried with https:// but I get from Postman:

```<code>Could not get any response
There was an error connecting to https://localhost:8081/points/12345/search.
</code>```

From the moment I wrote

```<code>server.ssl.key-store=classpath:KeyStore.jks
server.ssl.key-store-password=test
</code>```

in application.properties, I get the error message:

Bad Request - This combination of host and port requires TLS

I have deleted all my code in my controller, I just let the endpoint so that I can invoke it.

```<code>@RestController
@SpringBootApplication
public class MainApplication {
    @RequestMapping(value = "/points/{point}/search", method = RequestMethod.GET)
    public PointsType getPoint(@PathVariable(value = "point") String point) {
        System.out.println("hi"); // Never printed
        return null;
    }
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}
</code>```

Here is the file application.properties:

```<code>spring.application.name=sge
server.port=8081
server.ssl.key-store=classpath:KeyStore.jks
server.ssl.key-store-password=test
server.ssl.key-alias=homologation-staging
server.ssl.trust-store=classpath:TrustStore.jks
server.ssl.trust-store-password=test
server.ssl.client-auth=need
security.require-ssl=true
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
</code>```

What should I do ?

答: I used https:// at the beginning instead of http://, it worked for me.

Body:
I'm newbie with Spring Boot.

I'm trying to make a https call to a service, I have a Privake key to secure connection.

I hit:

http://localhost:8081/points/12345/search

I tried with https:// but I get from Postman:

Could not get any response
There was an error connecting to https://localhost:8081/points/12345/search.

From the moment I wrote

server.ssl.key-store=classpath:KeyStore.jks
server.ssl.key-store-password=test

in application.properties, I get the error message:

Bad Request - This combination of host and port requires TLS

I have deleted all my code in my controller, I just let the endpoint so that I can invoke it.

@RestController
@SpringBootApplication
public class MainApplication {
    @RequestMapping(value = "/points/{point}/search", method = RequestMethod.GET)
    public PointsType getPoint(@PathVariable(value = "point") String point) {
        System.out.println("hi"); // Never printed
        return null;
    }
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

Here is the file application.properties:

spring.application.name=sge
server.port=8081
server.ssl.key-store=classpath:KeyStore.jks
server.ssl.key-store-password=test
server.ssl.key-alias=homologation-staging
server.ssl.trust-store=classpath:TrustStore.jks
server.ssl.trust-store-password=test
server.ssl.client-auth=need
security.require-ssl=true
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto

What should I do ?


来源: stackexchange

问:
Vertx/RxJava/WebClient/ApiGateway/Reactive
I am working on Apigateway using vert.x and RxJava. I want to send reactive request for 2 Apis, get response from both of them and send combined JSON by HttpServer. But onComplete() executes to early and returns empty JSON. I think the problem arises from asynchronous character of the vert.x but I don't exactly what's wrong.

Here is my method:

```<code>private void dispatchBoth(RoutingContext routingContext) {

    Observer<String> observer = new Observer<String>() {

        JsonArray jsonArray = new JsonArray();

        @Override
        public void onSubscribe(Disposable disposable) {
            System.out.println("Start");

        }

        @Override
        public void onNext(String s) {
            Thread t = new Thread(() -> {
                if(s=="/api/userApi/selectAllUsers") {

                        WebClient client = WebClient.create(vertx);
                            client
                                .get(8081, "localhost", s)
                                .send(ar->{
                                    if (ar.succeeded()) {
                                        HttpResponse<Buffer> response = ar.result();

                                        jsonArray.addAll(response.bodyAsJsonArray());
                                        System.out.println(jsonArray.encodePrettily());

                                    } else {
                                        System.out.println("Something went wrong " + ar.cause().getMessage());
                                    }
                                });

                }else if(s=="/api/holidayApi/selectAllHolidays") {
                        WebClient client = WebClient.create(vertx);
                        client
                                .get(8080, "localhost", s)
                                .send(ar -> {

                                    if (ar.succeeded()) {

                                        HttpResponse<Buffer> response = ar.result();

                                        jsonArray.addAll(response.bodyAsJsonArray());
                                       //  System.out.println(jsonArray.encodePrettily());

                                    } else {
                                        System.out.println("Something went wrong " + ar.cause().getMessage());
                                    }
                                });
                    }
                });
                t.start();
        }
        @Override
        public void onError(Throwable throwable) {

        }

        @Override
        public void onComplete() {
                System.out.println(jsonArray.encodePrettily());
                routingContext.response().end(jsonArray.encodePrettily());
        }
    };
    Observable.fromArray(com).subscribe(observer);
}
</code>```

And that's the output I get on the console:

```<code>[ ]
[ {
  "holidayId" : 2,
  "userId" : 3,
  "place" : "Poland",
  "date" : {
    "year" : 2016,
    "month" : "DECEMBER",
    "dayOfMonth" : 29,
    "dayOfWeek" : "THURSDAY",
    "era" : "CE",
    "dayOfYear" : 364,
    "leapYear" : true,
    "monthValue" : 12,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
}, {
  "holidayId" : 10,
  "userId" : 1,
  "place" : "Netherland",
  "date" : {
    "year" : 2020,
    "month" : "JANUARY",
    "dayOfMonth" : 21,
    "dayOfWeek" : "TUESDAY",
    "era" : "CE",
    "dayOfYear" : 21,
    "leapYear" : true,
    "monthValue" : 1,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
}, {
  "userId" : 1,
  "name" : "Kacper",
  "phone_number" : "667667202"
}, {
  "userId" : 3,
  "name" : "Kamil",
  "phone_number" : "6734583443"
}, {
  "userId" : 4,
  "name" : "Janek",
  "phone_number" : "231253575"
}, {
  "userId" : 5,
  "name" : "Grzegorz",
  "phone_number" : "123456789"
}, {
  "userId" : 6,
  "name" : "Justin",
  "phone_number" : "111000111"
}, {
  "userId" : 8,
  "name" : "Mike",
  "phone_number" : "997"
}, {
  "userId" : 9,
  "name" : "Gorge",
  "phone_number" : "991"
} ]
</code>```

答:
I see that you are starting a new thread in onNext()? When you start a new thread using Thread.start(), it will carry on its work in parallel and the current Observable.onNext() will consider the work complete. This will cause onComplete() to be called.

There is no one waiting for the thread's job  to be completed. Hope you see what I mean.

Now, I am not familiar with vert.x, but going by RxJava ways, there seems to be no need for the use of Thread. You may remove it and keep the rest of the logic directly in the onNext() method.

ContentLicense: CC BY-SA 4.0

Body:
I am working on Apigateway using vert.x and RxJava. I want to send reactive request for 2 Apis, get response from both of them and send combined JSON by HttpServer. But onComplete() executes to early and returns empty JSON. I think the problem arises from asynchronous character of the vert.x but I don't exactly what's wrong.

Here is my method:

private void dispatchBoth(RoutingContext routingContext) {

    Observer<String> observer = new Observer<String>() {

        JsonArray jsonArray = new JsonArray();

        @Override
        public void onSubscribe(Disposable disposable) {
            System.out.println("Start");

        }

        @Override
        public void onNext(String s) {
            Thread t = new Thread(() -> {
                if(s=="/api/userApi/selectAllUsers") {

                        WebClient client = WebClient.create(vertx);
                            client
                                .get(8081, "localhost", s)
                                .send(ar->{
                                    if (ar.succeeded()) {
                                        HttpResponse<Buffer> response = ar.result();

                                        jsonArray.addAll(response.bodyAsJsonArray());
                                        System.out.println(jsonArray.encodePrettily());

                                    } else {
                                        System.out.println("Something went wrong " + ar.cause().getMessage());
                                    }
                                });

                }else if(s=="/api/holidayApi/selectAllHolidays") {
                        WebClient client = WebClient.create(vertx);
                        client
                                .get(8080, "localhost", s)
                                .send(ar -> {

                                    if (ar.succeeded()) {

                                        HttpResponse<Buffer> response = ar.result();

                                        jsonArray.addAll(response.bodyAsJsonArray());
                                       //  System.out.println(jsonArray.encodePrettily());

                                    } else {
                                        System.out.println("Something went wrong " + ar.cause().getMessage());
                                    }
                                });
                    }
                });
                t.start();
        }
        @Override
        public void onError(Throwable throwable) {

        }

        @Override
        public void onComplete() {
                System.out.println(jsonArray.encodePrettily());
                routingContext.response().end(jsonArray.encodePrettily());
        }
    };
    Observable.fromArray(com).subscribe(observer);
}

And that's the output I get on the console:

[ ]
[ {
  "holidayId" : 2,
  "userId" : 3,
  "place" : "Poland",
  "date" : {
    "year" : 2016,
    "month" : "DECEMBER",
    "dayOfMonth" : 29,
    "dayOfWeek" : "THURSDAY",
    "era" : "CE",
    "dayOfYear" : 364,
    "leapYear" : true,
    "monthValue" : 12,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
}, {
  "holidayId" : 10,
  "userId" : 1,
  "place" : "Netherland",
  "date" : {
    "year" : 2020,
    "month" : "JANUARY",
    "dayOfMonth" : 21,
    "dayOfWeek" : "TUESDAY",
    "era" : "CE",
    "dayOfYear" : 21,
    "leapYear" : true,
    "monthValue" : 1,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
}, {
  "userId" : 1,
  "name" : "Kacper",
  "phone_number" : "667667202"
}, {
  "userId" : 3,
  "name" : "Kamil",
  "phone_number" : "6734583443"
}, {
  "userId" : 4,
  "name" : "Janek",
  "phone_number" : "231253575"
}, {
  "userId" : 5,
  "name" : "Grzegorz",
  "phone_number" : "123456789"
}, {
  "userId" : 6,
  "name" : "Justin",
  "phone_number" : "111000111"
}, {
  "userId" : 8,
  "name" : "Mike",
  "phone_number" : "997"
}, {
  "userId" : 9,
  "name" : "Gorge",
  "phone_number" : "991"
} ]


问:
Pickeling results of postgresql query via psycopg2
I'm querying the PostgreSQL database via the psycopg2 library. The response of the query this way is cursor object file. Because of the size of the query, I'm trying to avoid re-query it and instead - save the query result as a pickle.

Unfortunately, when I trying to execute code for that:

```<code>import psycopg2
import pickle

# Connect to an existing database
conn = psycopg2.connect(dbname="DB", user="my_user", password="****", host="12.34.56.78")

# Open a cursor to perform database operations
cur = conn.cursor()

# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM my_table[...];")

# Attempt to pickle the output
pickle_out = open("output.pickle","wb")
pickle.dump(cur, pickle_out)
pickle_out.close()

# Close communication with the database
cur.close()
conn.close()
</code>```

An error massage raised:

```<code>TypeError: can't pickle psycopg2.extensions.cursor objects
</code>```

What is a straight forward way to save the results of SQL query via python for future use?

Note: I am not obligated to use the pickle. It just seemed like an optimal solution to me.

答:
I think you need cur.fetchall() after cur.execute() and its variations.
https://psycopg.org/docs/cursor.html for more details.

For example:

```<code>import numpy as np
import psycopg2
import pickle

# Connect to an existing database
conn = psycopg2.connect(dbname="DB", user="my_user", password="****", host="12.34.56.78")

# Open a cursor to perform database operations
cur = conn.cursor()

# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM my_table[...];")
cur_out = np.asarray(cur.fetchall())

# Attempt to pickle the output
# Attempt to pickle the output
pickle_out = open("output.pickle","wb")
pickle.dump(cur_out, pickle_out)
pickle_out.close()
</code>```

Body:
I'm querying the PostgreSQL database via the psycopg2 library. The response of the query this way is cursor object file. Because of the size of the query, I'm trying to avoid re-query it and instead - save the query result as a pickle.

Unfortunately, when I trying to execute code for that:

import psycopg2
import pickle

# Connect to an existing database
conn = psycopg2.connect(dbname="DB", user="my_user", password="****", host="12.34.56.78")

# Open a cursor to perform database operations
cur = conn.cursor()

# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM my_table[...];")

# Attempt to pickle the output
pickle_out = open("output.pickle","wb")
pickle.dump(cur, pickle_out)
pickle_out.close()

# Close communication with the database
cur.close()
conn.close()

An error massage raised:

TypeError: can't pickle psycopg2.extensions.cursor objects

What is a straight forward way to save the results of SQL query via python for future use?

Note: I am not obligated to use the pickle. It just seemed like an optimal solution to me.

Body:
I think you need cur.fetchall() after cur.execute() and its variations.
https://psycopg.org/docs/cursor.html for more details.

For example:

import numpy as np
import psycopg2
import pickle

# Connect to an existing database
conn = psycopg2.connect(dbname="DB", user="my_user", password="****", host="12.34.56.78")

# Open a cursor to perform database operations
cur = conn.cursor()

# Query the database and obtain data as Python objects
cur.execute("SELECT * FROM my_table[...];")
cur_out = np.asarray(cur.fetchall())

# Attempt to pickle the output
# Attempt to pickle the output
pickle_out = open("output.pickle","wb")
pickle.dump(cur_out, pickle_out)
pickle_out.close()


问:
Scanf in C # windows form?
my question is why I can't
recognize keyboard input in windows form?
Can someone put me a sample code?

I want to be able to read keyboard input from a textbox in windows form and display with a button it in a messagebox for testing, but that doesn't read anything.

```<code>public button1_click(object sender, EventArgs e)
{
    string s = Console.Readline();

    Convert.ToInt32(s);
    MessageBox.Show(s);
}
</code>```

答:
Because there is no Console in Windows forms you can not read from it. On Textbox you can subscribe to events and do what you want.
Microsoft docs</p>

Title: Scanf in C # windows form?

Body:
my question is why I can't
recognize keyboard input in windows form?
Can someone put me a sample code?

I want to be able to read keyboard input from a textbox in windows form and display with a button it in a messagebox for testing, but that doesn't read anything.

public button1_click(object sender, EventArgs e)
{
    string s = Console.Readline();

    Convert.ToInt32(s);
    MessageBox.Show(s);
}


问:
Dealing with message box asynchronious
There is a function that returns true/false only after a button on messageBox is clicked dealing with extjs messagebox asynchronious.

```<code>function mayGo(){
var clicked=false;
var may=false;

        Ext.Msg.show({
            title:'del?',
            msg: 'the items will be deleted?',
            buttons: Ext.Msg.YESNO,
            fn: function (button){
                    if (button=='yes'){clicked=true;may=true;}
                    if (button=='no'){clicked=true;may=false;}
                }
        });

        newf();
        function wait(){
alert("alert2");
                var t=setTimeout(newf(), 5000);

        }
        function newf(){
            if (!clicked){alert("alert1");wait();}
        }
        return may;}
</code>```

The function continues executing. What is wrong? Why the timeout doesn't work?

答:
remove parens from

```<code>var t=setTimeout(newf(), 5000);
</code>```

so you get:

```<code>var t=setTimeout(newf, 5000);
</code>```

newf was executed, so you where actually setting a timeout on the return value of newf. It was equivalent to:

```<code>var und = newf(); // returns undefined
var t = setTimeout( und , 5000 ); // wont work.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Dealing with message box asynchronious

Body:
There is a function that returns true/false only after a button on messageBox is clicked dealing with extjs messagebox asynchronious.

function mayGo(){
var clicked=false;
var may=false;

        Ext.Msg.show({
            title:'del?',
            msg: 'the items will be deleted?',
            buttons: Ext.Msg.YESNO,
            fn: function (button){
                    if (button=='yes'){clicked=true;may=true;}
                    if (button=='no'){clicked=true;may=false;}
                }
        });

        newf();
        function wait(){
alert("alert2");
                var t=setTimeout(newf(), 5000);

        }
        function newf(){
            if (!clicked){alert("alert1");wait();}
        }
        return may;}

The function continues executing. What is wrong? Why the timeout doesn't work?

Body:
remove parens from

var t=setTimeout(newf(), 5000);

so you get:

var t=setTimeout(newf, 5000);

newf was executed, so you where actually setting a timeout on the return value of newf. It was equivalent to:

var und = newf(); // returns undefined
var t = setTimeout( und , 5000 ); // wont work.


问:
React: setState() hook, initial color not being set
I am trying to set a basic like item, similar to facebook likes to be a color of black when the page first renders, and then using React hooks, useState() and useEffect() to change the color when the state of likes changes. However, I have got the color to render, but it is also rendering on load so not changing from black to green when a user clicks "like" and changes the like state.

```<code>import React, { useState, useEffect } from "react";

function Update() {
  **const [like, updateLikes] = useState(0);
  const [dislike, updateDislikes] = useState(0);
  const [likeColor, setLikeColor] = useState("black");
  const [dislikeColor, setDislikeColor] = useState("black");
  useEffect(() => {
    setLikeColor("green");
  }, [like]);
  useEffect(() => {
    setDislikeColor("red");
  }, [dislike]);**

  return (
    <div className="updateDiv">
      <span className="update">
        <img className="profilePic" src="https://picsum.photos/50/50" alt="" />
        <div className="name">Username</div>
        <div className="time">08:30am</div>
        <div className="text">Reading a good book!</div>
        <div className="likes">
          Likes:
          **<p style={{ color: likeColor }}>{like}</p>**
        </div>
        <div className="dislikes">
          Dislikes:
          <p style={{ color: dislikeColor }}>{dislike}</p>
        </div>
        <button type="submit" onClick={() => updateLikes(like + 1)}>
          Like
        </button>
        <button type="submit" onClick={() => updateDislikes(dislike + 1)}>
          Dislike
        </button>
        <hr />
      </span>
    </div>
  );
}

export default Update;

</code>```

So, I want the initial color of the like
 element to be black when the page is first rendered, and then the useEffect methods to be called to change the color of said element when the state of "like" changes, but at the moment the color is being set when the page renders, so it isn't being initialised as black.

Probably a quick fix, but I'm starting to bang my head against the wall :D

答:
Because Your are calling setLikeColor and setDislikeColor under useEffect hook and initially useEffect is running and change the color.You can do like below :

import React, { useState, useEffect } from "react";

function Update() {
  const [like, updateLikes] = useState(0);
  const [dislike, updateDislikes] = useState(0);
  const [likeColor, setLikeColor] = useState("black");
  const [dislikeColor, setDislikeColor] = useState("black");
  useEffect(() => {
    console.log("useEffect");

    if (like > 0) {
      setLikeColor("green");
    }
  }, [like]);
  useEffect(() => {
    if (dislike > 0) {
      setDislikeColor("red");
    }
  }, [dislike]);

  return (

Username

08:30am

Reading a good book!

          Likes:
{like}

          Dislikes:

{dislike}

        <button type="submit" onClick={() => updateLikes(like + 1)}>
          Like
        </button>
        <button type="submit" onClick={() => updateDislikes(dislike + 1)}>
          Dislike
        </button>

  );
}

export default Update;```

Body:
I am trying to set a basic like item, similar to facebook likes to be a color of black when the page first renders, and then using React hooks, useState() and useEffect() to change the color when the state of likes changes. However, I have got the color to render, but it is also rendering on load so not changing from black to green when a user clicks "like" and changes the like state.

import React, { useState, useEffect } from "react";

function Update() {
  **const [like, updateLikes] = useState(0);
  const [dislike, updateDislikes] = useState(0);
  const [likeColor, setLikeColor] = useState("black");
  const [dislikeColor, setDislikeColor] = useState("black");
  useEffect(() => {
    setLikeColor("green");
  }, [like]);
  useEffect(() => {
    setDislikeColor("red");
  }, [dislike]);**

  return (

Username

08:30am

Reading a good book!

          Likes:
          **
{like}
**

          Dislikes:

{dislike}

        <button type="submit" onClick={() => updateLikes(like + 1)}>
          Like
        </button>
        <button type="submit" onClick={() => updateDislikes(dislike + 1)}>
          Dislike
        </button>

  );
}

export default Update;

So, I want the initial color of the like
 element to be black when the page is first rendered, and then the useEffect methods to be called to change the color of said element when the state of "like" changes, but at the moment the color is being set when the page renders, so it isn't being initialised as black.

Probably a quick fix, but I'm starting to bang my head against the wall :D

Body:
Because Your are calling setLikeColor and setDislikeColor under useEffect hook and initially useEffect is running and change the color.You can do like below :

import React, { useState, useEffect } from "react";

function Update() {
  const [like, updateLikes] = useState(0);
  const [dislike, updateDislikes] = useState(0);
  const [likeColor, setLikeColor] = useState("black");
  const [dislikeColor, setDislikeColor] = useState("black");
  useEffect(() => {
    console.log("useEffect");

    if (like > 0) {
      setLikeColor("green");
    }
  }, [like]);
  useEffect(() => {
    if (dislike > 0) {
      setDislikeColor("red");
    }
  }, [dislike]);

  return (
    <div className="updateDiv">
      <span className="update">
        <img className="profilePic" src="https://picsum.photos/50/50" alt="" />
        <div className="name">Username</div>
        <div className="time">08:30am</div>
        <div className="text">Reading a good book!</div>
        <div className="likes">
          Likes:<p style={{ color: likeColor }}>{like}</p>
        </div>
        <div className="dislikes">
          Dislikes:
          <p style={{ color: dislikeColor }}>{dislike}</p>
        </div>
        <button type="submit" onClick={() => updateLikes(like + 1)}>
          Like
        </button>
        <button type="submit" onClick={() => updateDislikes(dislike + 1)}>
          Dislike
        </button>
        <hr />
      </span>
    </div>
  );
}

export default Update;


问:
How to copy one row in a .csv file to another row with python
I am trying to merge the strings from the first two rows of a .csv file into one row in python.
I am using a file with over 150 columns.

Right now it looks like this:

;; Test1; Test1; Test1; Test 2; Test 2; Test2

Name;Birthday; Points Q1; Points Q2; Points Q3; Points Q1; Points Q2; Points Q3

but I need to merge the information into one row, that looks like this:

Name;Birthday;Test1 PointsQ1; Test1 Points Q2; Test1 Points Q3; Test2 Points Q1;...

答:
Ok, I managed to do it by converting the .csv file into an array.</p>

```<code>def addheader(inputfile):

 results = []
 with open(inputfile, "r") as r:
      reader = csv.reader(r, delimiter=';')
          for row in reader:
           i = i+1
           if i < x:
                results.append(row)

      i = 0
      x = len(results[0])-1

      while i < x:
           i = i+1
           results[1][i] = results[0][i] + " " + results[1][i]
</code>```

Body:
Ok, I managed to do it by converting the .csv file into an array.

def addheader(inputfile):

 results = []
 with open(inputfile, "r") as r:
      reader = csv.reader(r, delimiter=';')
          for row in reader:
           i = i+1
           if i < x:
                results.append(row)

      i = 0
      x = len(results[0])-1

      while i < x:
           i = i+1
           results[1][i] = results[0][i] + " " + results[1][i]


问:
MySQL performance tuning for DELETE query
Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

```<code>DELETE FROM storefront_categories
WHERE userid IN (SELECT userid
                FROM MASTER
                where expirydate<'2020-2-4'
                )
</code>```

At the same time, this query took only 4.69 seconds only to execute.

```<code>DELETE FROM storefront_categories
WHERE userid NOT IN (SELECT userid FROM MASTER)
</code>```

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.

答:
The query looks fine as it is.

I would suggest the following indexes for optimization:

```<code>master(expiry_date, userid)
storefront_categories(userid)
</code>```

The first index is a covering index for the subquery on master: it means that the database should be able to execute the subquery by looking at the index only (whereas with just expiry_date in the index, it still needs to look at the table data to fetch the related userid).

The second index lets the database optimize the in operation.

Body:
Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

DELETE FROM storefront_categories
WHERE userid IN (SELECT userid
                FROM MASTER
                where expirydate<'2020-2-4'
                )

At the same time, this query took only 4.69 seconds only to execute.

DELETE FROM storefront_categories
WHERE userid NOT IN (SELECT userid FROM MASTER)

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.

Body:
The query looks fine as it is.

I would suggest the following indexes for optimization:

master(expiry_date, userid)
storefront_categories(userid)

The first index is a covering index for the subquery on master: it means that the database should be able to execute the subquery by looking at the index only (whereas with just expiry_date in the index, it still needs to look at the table data to fetch the related userid).

The second index lets the database optimize the in operation.


问:
How call a controller from javascript after press a button
I created a controller that returns a pdf, my problem is that I can't recall it from javascript, by pressing the button with the click action.

I have tried with ajax.rpc and rpc.query but to no avail. If I go to the url I can download the file.

Is there any way to get the file that the controller returns?

答:
My solution:

$.ajax({
    url: url,
    type: 'GET',
    success: function() {
       window.location = url;
 }
});
```


问:
GLPaint Sample: how to create the view programmatically?
I need to draw something on an image, like in the GLPaint sample from Apple, but I need to create the EAGL surface where render the OpenGL programmatically.

In the sample is instatiated in the MainWindow.xib

If I try to create the view  programmatically with something like:

```<code>self.drawingView = [[PaintingView alloc] initWithCoder:nil];
drawingView.frame = CGRectMake(0, 0, 320, 380);
[self.view addSubview:drawingView];
</code>```

I got this error:

```<code>failed to make complete framebuffer object 8cd6
</code>```

Maybe something related to the init? Any hints? Thanks.

答:
From a quick glance inside the source, Apple have put all of the significant initialisation stuff for PaintingView inside initWithCoder:, from lines 77 to 168. That's part of the NSCoding protocol, which is used for archiving and unarchiving objects from files. If you call initWithCoder:nil, quite probably the UIView implementation of initWithCoder isn't able to get some relevant value that it needs. At a guess, it probably starts being size zero, which isn't a valid size for a framebuffer object.

I'd suggest you replace initWithCoder:(NSCoder *)coder with initWithFrame:(CGRect)frame, calling the same on super at line 86. For an even better implementation, implement both initWithFrame: and initWithCoder:, having the two call a common section for everything enclosed in the if((self = [super initWithXXX:argument])) block.

Body:
I need to draw something on an image, like in the GLPaint sample from Apple, but I need to create the EAGL surface where render the OpenGL programmatically.

In the sample is instatiated in the MainWindow.xib

If I try to create the view  programmatically with something like:

self.drawingView = [[PaintingView alloc] initWithCoder:nil];
drawingView.frame = CGRectMake(0, 0, 320, 380);
[self.view addSubview:drawingView];

I got this error:

failed to make complete framebuffer object 8cd6

Maybe something related to the init? Any hints? Thanks.


问:
Do I fit the scaler on X or X_train when I have train,dev and test sets?
Here is my data

```<code>X = X.reshape((-1, 784))
y = y.reshape((-1,1))
X_test = X_test.reshape((-1, 784))
y_test = y_test.reshape((-1,1))

X_train, X_val, y_train, y_val = train_test_split(X,
                                                  y,
                                                  test_size=0.1,
                                                  random_state=1)
</code>```

Do I fit the X or X_train in the .fit ?

```<code>scaler = MinMaxScaler()
scaler.fit(X_train)
</code>```

or

```<code>scaler = MinMaxScaler()
scaler.fit(X)
</code>```

The transform will be as follows

```<code>X_train = scaler.transform(X_train)
X_val = scaler.transform(X_val)
y_test = scaler.transform(y_test)
</code>```

答:
fit will give you min and max value which is used on unseen datasets, you have to use fit on train , and transform on test and dev set  </p>

```<code>from sklearn.preprocessing import MinMaxScaler
data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
</code>```

<p>doing fit on train data will give you min and max value which you need to used on new data 1.e test or dev </p>

```<code>scaler = MinMaxScaler()

scaler.fit(data)

scaler.data_min_
#op
array([-1.,  2.])

scaler.data_max_
#op
array([ 1., 18.])

#now using formuala
x = (x-min(x))/(max(x)- min(x))
new_data = [[25,42]]

(25-(-1))/1-(-1)  # for 25
#op
13.0

(42 - (2))/(18 - (2)) #for 42
#op
2.5

scaler.transform([[25,42]])  # it uses the min and max value which we get using fit
#op
array([[13. ,  2.5]])
</code>```

Body:
Here is my data

X = X.reshape((-1, 784))
y = y.reshape((-1,1))
X_test = X_test.reshape((-1, 784))
y_test = y_test.reshape((-1,1))

X_train, X_val, y_train, y_val = train_test_split(X,
                                                  y,
                                                  test_size=0.1,
                                                  random_state=1)

Do I fit the X or X_train in the .fit ?

scaler = MinMaxScaler()
scaler.fit(X_train)

or

scaler = MinMaxScaler()
scaler.fit(X)

The transform will be as follows

X_train = scaler.transform(X_train)
X_val = scaler.transform(X_val)
y_test = scaler.transform(y_test)

Body:
fit will give you min and max value which is used on unseen datasets, you have to use fit on train , and transform on test and dev set

from sklearn.preprocessing import MinMaxScaler
data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]

doing fit on train data will give you min and max value which you need to used on new data 1.e test or dev

scaler = MinMaxScaler()

scaler.fit(data)

scaler.data_min_
#op
array([-1.,  2.])

scaler.data_max_
#op
array([ 1., 18.])

#now using formuala
x = (x-min(x))/(max(x)- min(x))
new_data = [[25,42]]

(25-(-1))/1-(-1)  # for 25
#op
13.0

(42 - (2))/(18 - (2)) #for 42
#op
2.5

scaler.transform([[25,42]])  # it uses the min and max value which we get using fit
#op
array([[13. ,  2.5]])


问:
HTML5 download attribute not working when download external PDF file on Chrome
The code is very simple:

```<code><a download href="http://www.pdf995.com/samples/pdf.pdf">Download</a>
</code>```

I expect it to save the pdf file but it always open the file on the browser.

It works with other file type, just have problem with PDF file.

答:
If the URL that you're trying to fetch has an Access-Control-Allow-Origin header, you can work around this by using fetch and blobs:

function forceDownload(blob, filename) {
  // Create an invisible anchor element
  const anchor = document.createElement('a');
  anchor.style.display = 'none';
  anchor.href = window.URL.createObjectURL(blob);
  anchor.setAttribute('download', filename);
  document.body.appendChild(anchor);

  // Trigger the download by simulating click
  anchor.click();

  // Clean up
  window.URL.revokeObjectURL(anchor.href);
  document.body.removeChild(anchor);
}

function downloadResource(url, filename) {
  fetch(url, {
    headers: new Headers({
      Origin: window.location.origin,
    }),
    mode: 'cors',
  })
    .then(response => response.blob())
    .then(blob => forceDownload(blob, filename))
    .catch(e => console.error(e));
}

downloadResource('https://memegen.link/xy/fetch/all_the_things.jpg?watermark=none');
```

This has a few limitations:

the file size limit of blobs is about 500MB

some websites will not allow for cross-origin requests, leading to errors like this one below

Failed to load https://example.com/example.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access.

Ref 1: Leeroy in https://stackoverflow.com/a/49500465/1268612

Ref 2: https://davidwalsh.name/javascript-download

Full explanation: https://blog.logrocket.com/programmatic-file-downloads-in-the-browser-9a5186298d5c/

Body:
The code is very simple:

Download

I expect it to save the pdf file but it always open the file on the browser.

It works with other file type, just have problem with PDF file.

Body:
If the URL that you're trying to fetch has an Access-Control-Allow-Origin header, you can work around this by using fetch and blobs:

function forceDownload(blob, filename) {
  // Create an invisible anchor element
  const anchor = document.createElement('a');
  anchor.style.display = 'none';
  anchor.href = window.URL.createObjectURL(blob);
  anchor.setAttribute('download', filename);
  document.body.appendChild(anchor);

  // Trigger the download by simulating click
  anchor.click();

  // Clean up
  window.URL.revokeObjectURL(anchor.href);
  document.body.removeChild(anchor);
}

function downloadResource(url, filename) {
  fetch(url, {
    headers: new Headers({
      Origin: window.location.origin,
    }),
    mode: 'cors',
  })
    .then(response => response.blob())
    .then(blob => forceDownload(blob, filename))
    .catch(e => console.error(e));
}

downloadResource('https://memegen.link/xy/fetch/all_the_things.jpg?watermark=none');

This has a few limitations:

the file size limit of blobs is about 500MB

some websites will not allow for cross-origin requests, leading to errors like this one below

Failed to load https://example.com/example.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access.

Ref 1: Leeroy in https://stackoverflow.com/a/49500465/1268612

Ref 2: https://davidwalsh.name/javascript-download

Full explanation: https://blog.logrocket.com/programmatic-file-downloads-in-the-browser-9a5186298d5c/


问:
Handling errors in NGXS (angular) with global error handler
I'd like to handle errors in NGXS in two ways. The first way is handling an error on the store dispatch in a component. The second way is a global angular error handler as a fallback for when the error is unhandled (not handled by first way).

But the problem is that the global error handler is always called by NGRX when there is an error in an action handler.

So given this code in the component:

```<code>this.store.dispatch(new FetchAction())
   .subscribe( error: () => console.log('fetch error occured'))
</code>```

this action handler:

```<code>fetch() {
   return this.http.get('..');
}
</code>```

and this global error handler:

```<code>export class GlobalErrorHandler extends ErrorHandler {
   handleError(err: any) {
      console.log('unexpected error occured');
   }
}
</code>```

There would be two error messages in the console. One from the subscribe of the dispatch and one from the global error handler because there was an error in the action handler.

Now I could catch errors in the action handler but that would be the wrong place to do so because the action handler shouldn't know that an error from this action is handled in a component.

I made a stackblitz which shows two errors in the console when clicking the button: https://stackblitz.com/edit/ngxs-error-throw-r42fkb?file=src/app/app.component.ts

答:
I have the same problem. But as the documentation says it is by design. Error is beging propagated to main ErrorHandler despite you do handle on the upper level.

If an unhandled exception is thrown inside an action, the error will be propagated to the ErrorHandler and you can also catch it subscribing to the dispatch Observable. If you subscribe to the dispatch Observable the error will be caught twice, once in the ErrorHandler and on your dispatch handle

Body:
I'd like to handle errors in NGXS in two ways. The first way is handling an error on the store dispatch in a component. The second way is a global angular error handler as a fallback for when the error is unhandled (not handled by first way).

But the problem is that the global error handler is always called by NGRX when there is an error in an action handler.

So given this code in the component:

this.store.dispatch(new FetchAction())
   .subscribe( error: () => console.log('fetch error occured'))

this action handler:

fetch() {
   return this.http.get('..');
}

and this global error handler:

export class GlobalErrorHandler extends ErrorHandler {
   handleError(err: any) {
      console.log('unexpected error occured');
   }
}

There would be two error messages in the console. One from the subscribe of the dispatch and one from the global error handler because there was an error in the action handler.

Now I could catch errors in the action handler but that would be the wrong place to do so because the action handler shouldn't know that an error from this action is handled in a component.

I made a stackblitz which shows two errors in the console when clicking the button: https://stackblitz.com/edit/ngxs-error-throw-r42fkb?file=src/app/app.component.ts


问:
Reversing a linked list issue
I am trying to reverse a linked and this is my implementation:

```<code>import copy
# ...

def reverse(linked_list):
    """
    Reverse the inputted linked list

    Args:
       linked_list(obj): Linked List to be reversed
    Returns:
       obj: Reveresed Linked List
    """

    if linked_list.head is None:
        return linked_list

    copy_list = copy.copy(linked_list)

    current = copy_list.head
    while current.next is not None:
        new_head = current.next
        tail = current.next.next
        new_head.next = copy_list.head
        current.next = tail
        copy_list.head = new_head

    return copy_list
</code>```

Consider that the list is populated like this:

```<code>myList = LinkedList()
for value in [1, 2, 3, 4, 5]:
    myList.append(value)

# myList = [1, 2, 3, 4, 5]

</code>```

so myList now contains: [1, 2, 3, 4, 5] - so far so good..

but then I reverse it:

```<code>reversed = reverse(myList)

# reversed = [5, 4, 3, 2, 1]
# myList = [1]
</code>```

and the result is that reversed indeed contains a reversed list [5, 4, 3, 2, 1], but as a side effect this changes the contents of myList to: [1].

So it looks like whenever I am reversing the list, instead of working with a copy of it, I am changing the original list too.
Not sure why because I explicitly create a copy copy_list = copy.copy(linked_list) and then base my work on it.

Would appreciate if you could give me hint.

PS: I know that similar questions have been asked before, but I am not interested in a general solution, I am interested more in finding out what's wrong in my implementation.

Additional classes:

```<code>class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            return

        node = self.head
        while node.next:
            node = node.next

        node.next = Node(value)

    def __iter__(self):
        node = self.head
        while node:
            yield node.value
            node = node.next

    def __repr__(self):
        return str([v for v in self])
</code>```

答:
I would tell you the short answer,
You are using copy library which has two options

Shallow copy

Deepcopy

copy.copy uses shallow copy which uses pass by reference and the changes done in the copied file will also affect the original.

copy.deepcopy creates a new structure where the changes in the new file would not affect
the original.

Title: Reversing a linked list issue

Body:
I am trying to reverse a linked and this is my implementation:

import copy
# ...

def reverse(linked_list):
    """
    Reverse the inputted linked list

    Args:
       linked_list(obj): Linked List to be reversed
    Returns:
       obj: Reveresed Linked List
    """

    if linked_list.head is None:
        return linked_list

    copy_list = copy.copy(linked_list)

    current = copy_list.head
    while current.next is not None:
        new_head = current.next
        tail = current.next.next
        new_head.next = copy_list.head
        current.next = tail
        copy_list.head = new_head

    return copy_list

Consider that the list is populated like this:

myList = LinkedList()
for value in [1, 2, 3, 4, 5]:
    myList.append(value)

# myList = [1, 2, 3, 4, 5]

so myList now contains: [1, 2, 3, 4, 5] - so far so good..

but then I reverse it:

reversed = reverse(myList)

# reversed = [5, 4, 3, 2, 1]
# myList = [1]

and the result is that reversed indeed contains a reversed list [5, 4, 3, 2, 1], but as a side effect this changes the contents of myList to: [1].

So it looks like whenever I am reversing the list, instead of working with a copy of it, I am changing the original list too.
Not sure why because I explicitly create a copy copy_list = copy.copy(linked_list) and then base my work on it.

Would appreciate if you could give me hint.

PS: I know that similar questions have been asked before, but I am not interested in a general solution, I am interested more in finding out what's wrong in my implementation.

Additional classes:

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            return

        node = self.head
        while node.next:
            node = node.next

        node.next = Node(value)

    def __iter__(self):
        node = self.head
        while node:
            yield node.value
            node = node.next

    def __repr__(self):
        return str([v for v in self])


问:
Android BottomNavigationView with child of Tabbed ViewPager
I'm using BottomNavigationView to navigate between two Fragments, on of these fragments has its own ViewPager with TabLayout as below:

This is what i'm trying to do:

```<code>MainActivity
 |--- HomeFragment
 |           |--- POPULAR
 |           |--- LATEST
 |           |--- TOP RATED
 |           |--- UPCOMING
 |--- FavoritesFragment
</code>```

it works fine while swiping the ViewPager, the problem occures when i'm in LATEST or TOP RATED and navigates the BottomNavigationView to  FavoritesFragment
and return back to HomeFragment, the ViewPager starts over from POPULAR not the fragment i was in before navigation.

How can i avoid this tricky navigation problem?

And what is the best solution to keep track of navigation in such situation?

答:
addToBackStack

Fragment Transactions

And what is the best solution to keep track of navigation in such
  situation?

I am obviously unaware of a best solution. A case like this involves fragment lifecycles as well which further complicate things.
If you want a very specific navigation behaviour - specially the ability to resume from any previous UI state - I would suggest using a log file to keep track of lifecycle and navigation changes. This has often paid off for me in the long run

Body:
I'm using BottomNavigationView to navigate between two Fragments, on of these fragments has its own ViewPager with TabLayout as below:

This is what i'm trying to do:

MainActivity
 |--- HomeFragment
 |           |--- POPULAR
 |           |--- LATEST
 |           |--- TOP RATED
 |           |--- UPCOMING
 |--- FavoritesFragment

it works fine while swiping the ViewPager, the problem occures when i'm in LATEST or TOP RATED and navigates the BottomNavigationView to  FavoritesFragment
and return back to HomeFragment, the ViewPager starts over from POPULAR not the fragment i was in before navigation.

How can i avoid this tricky navigation problem?

And what is the best solution to keep track of navigation in such situation?


问:
Why new created project is closed immediately in react-native?
I created new project in react-native but app doesnt open I dont know why ?

I installed these npms :

npm i react-navigation

npm i react-navigation-stack

npm i react-native-gesture-handler

npm i react-native-safe-area-context

npm install --save @react-native-community/masked-view

npm i react-native-screens

I didn't understand problem why app doesnt  run

this is my package.json:

this is my app.js:

答:
problem is with you createStackNavigator, i guess

also use "react-navigation": "^2.18.3"

import { createStackNavigator } from "react-navigation";
import Test from "./screens/test";

const navigate = createStackNavigator({
  Test: { screen: Test },
});

export default navigate;
```


问:
N-gram text categorization category size difference compensation
Lately I've been mucking about with text categorization and language classification based on Cavnar and Trenkle's article "N-Gram-Based Text Categorization" as well as other related sources.

For doing language classification I've found this method to be very reliable and useful. The size of the documents used to generate the N-gram frequency profiles is fairly unimportant as long as they are "long enough" since I'm just using the most common n N-grams from the documents.

On the other hand well-functioning text categorization eludes me. I've tried with both my own implementations of various variations of the algorithms at hand, with and without various tweaks such as idf weighting and other peoples' implementations. It works quite well as long as I can generate somewhat similarly-sized frequency profiles for the category reference documents but the moment they start to differ just a bit too much the whole thing falls apart and the category with the shortest profile ends up getting a disproportionate number of documents assigned to it.

Now, my question is. What is the preferred method of compensating for this effect? It's obviously happening because the algorithm assumes a maximum distance for any given N-gram that equals the length of the category frequency profile but for some reason I just can't wrap my head around how to fix it. One reason I'm interested in this fix is actually because I'm trying to automate the generation of category profiles based on documents with a known category which can vary in length (and even if they are the same length the profiles may end up being different lengths). Is there a "best practice" solution to this?

答:
As I know the task is to count probability of generation some text by language model M.

Recently i was working on measuring the readaiblity of texts using semantic, synctatic and lexical properties. It can be also measured by language model approach.

To answer properly you should consider these questions:

Are you using log-likelihood approach?

What levels of N-Grams are you using? unigrams digrams or higher level?

How big are language corpuses that you use?

Using only digrams and unigrams i managed to classify some documents with nice results. If your classification is weak consider creating bigger language corpuse or using n-grams of lower levels.

Also remember that classifying some text to invalid category may be an error depending on length of text (randomly there are few words appearing in another language models).

Just consider making your language corpuses bigger and know that analysing short texts have higher probability of missclasification


问:
@angular-cli install fails with deprecated request@2.88.2: request has been deprecated (mac)
After updating node.js and npm to current LTS:

```<code>node -v
v12.16.0
</code>```

```<code>npm -v
6.13.4
</code>```

When I'm trying to install @angular-cli following the steps in the documentation, running npm install -g @angular/cli
 in the terminal stops the installation and the console output is:

```<code>npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/user/.npm-global/bin/ng -> /USERS/USER/.npm-global/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.0.2 postinstall /USERS/USER/.npm-global/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.0.2
updated 1 package in 12.202s
</code>```

And in this case, ng new project-name yields -bash: ng: command not found. Any help would be very welcome as I have a big project coming up.
Thanks all.

答: The package request is now fully deprecated. So that will probably take a while to change. I think the solution would be for angular cli to release a new version that is not reliant upon request.</p>

Body:
After updating node.js and npm to current LTS:

node -v
v12.16.0

npm -v
6.13.4

When I'm trying to install @angular-cli following the steps in the documentation, running npm install -g @angular/cli
 in the terminal stops the installation and the console output is:

npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/user/.npm-global/bin/ng -> /USERS/USER/.npm-global/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.0.2 postinstall /USERS/USER/.npm-global/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.0.2
updated 1 package in 12.202s

And in this case, ng new project-name yields -bash: ng: command not found. Any help would be very welcome as I have a big project coming up.
Thanks all.


问:
Install Xamarin - VS Installer "Available" tab with not items
Hi I'm willing to install Xamarin as per MS youtube video,
I launched VS Installer but found nothing in "Available" tab.

I just updated Visual Studio 2019 Enterprise, 3 minutes ago and restarted it.

So I'm now stuck, can't install Xamarin.

答:
Issued fixed following the below links.

I just needed to click "Modify" in VS Installer.

https://learn.microsoft.com/en-us/xamarin/get-started/installation/windows

https://learn.microsoft.com/en-us/visualstudio/install/modify-visual-studio?view=vs-2019


问:
How to add additional paths to baseurl using Javascript
I have a base URL

```<code>url= 'www.baseUrl.com'
</code>```

I have an array of my paths Paths = [path1,path2,path3]

how do i create something like perhaps i need to do a loop?

```<code>www.baseUrl.com/path1
www.baseUrl.com/path2
www.baseUrl.com/path3
</code>```

答:
You can map one array to another:

```<code>const paths = ['path1','path2','path3'];
const url= 'www.baseUrl.com';

const fullPaths = paths.map(path => `${url}/${path}`);
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Body:
I have a base URL

url= 'www.baseUrl.com'

I have an array of my paths Paths = [path1,path2,path3]

how do i create something like perhaps i need to do a loop?

www.baseUrl.com/path1
www.baseUrl.com/path2
www.baseUrl.com/path3

Body:
You can map one array to another:

const paths = ['path1','path2','path3'];
const url= 'www.baseUrl.com';

const fullPaths = paths.map(path => `${url}/${path}`);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals


问:
How to split a String from a list in dart
I'm trying to sort some data in a List<String>. I want to split a long String of every other item and delete part of it. Data will be added to the list when the user performs an action.

Example of what could be in the list:

NOTE* These are not separate items in the list. Its all one String.

"Cat walked across the road"

What I want from this String is just:

"Cat"

Currently, I've initialised the list and split the String as shown below.

```<code>//Initialised List
 List<String> list = [];

//Method to split and delete String
String handleString(String items){

//Splits String
    items.split(" ").toString();

//TODO Delete String

}
</code>```

Output of this code looks like this:

Cat, walked, across, the, road

The code below gets a single item from the list using .text get method.

```<code>for(var txt in list){
     String sentenceInList  = txt.text
print(txt.text);

}
</code>```

Output :

Cat walked across the road

Im not sure how to remove everything except the first word of every other potential item in the list?

Im looking to start at item one so if the items were as shown below, it would look like this:

Item 1: "Cat walked across the road"

Output: Cat

Item 2: How are you today

How are you today

and so on...

If anyone is able to help with this, it would be most appreciated?

答:
If you need to split your list on your first space character you could just use substring together with indexOf:

var str = 'Cat walked across the road';
var index= str.indexOf(' ');

var cat = str.substring(0, index); // The substring before the space.
var walked = str.substring(index); // The substringafter the space (including it, add +1 to the index to exclude the space).
```

<p>or if you want to stick with <code>split</code> you can use <code>skip</code> to skip the first element:</p>

```var str = 'Cat walked across the road';
var split = str.split(' ');

var the = split.first; // The substring before the space.
var walked = split.skip(1).join(' '); // The substringafter the space.
```

Body:
I'm trying to sort some data in a List<String>. I want to split a long String of every other item and delete part of it. Data will be added to the list when the user performs an action.

Example of what could be in the list:

NOTE* These are not separate items in the list. Its all one String.

"Cat walked across the road"

What I want from this String is just:

"Cat"

Currently, I've initialised the list and split the String as shown below.

//Initialised List
 List<String> list = [];

//Method to split and delete String
String handleString(String items){

//Splits String
    items.split(" ").toString();

//TODO Delete String

}

Output of this code looks like this:

Cat, walked, across, the, road

The code below gets a single item from the list using .text get method.

for(var txt in list){
     String sentenceInList  = txt.text
print(txt.text);

}

Output :

Cat walked across the road

Im not sure how to remove everything except the first word of every other potential item in the list?

Im looking to start at item one so if the items were as shown below, it would look like this:

Item 1: "Cat walked across the road"

Output: Cat

Item 2: How are you today

How are you today

and so on...

If anyone is able to help with this, it would be most appreciated?

Body:
If you need to split your list on your first space character you could just use substring together with indexOf:

var str = 'Cat walked across the road';
var index= str.indexOf(' ');

var cat = str.substring(0, index); // The substring before the space.
var walked = str.substring(index); // The substringafter the space (including it, add +1 to the index to exclude the space).

or if you want to stick with split you can use skip to skip the first element:

var str = 'Cat walked across the road';
var split = str.split(' ');

var the = split.first; // The substring before the space.
var walked = split.skip(1).join(' '); // The substringafter the space.


问:
Trying to generate a 2-column table using PHP from JSON data
This should be a fairly simple problem, however I cannot for the life of me get it to work right.

I have JSON data in the form of an array like so and I am trying to generate a 2-column table where every 2 elements in the array take up a row.

```<code>[
    {
        "type": "Ground",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Water",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Sewer",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Tap",
        "field_location": "",
        "field_user": "",
    }
]

</code>```

I have overly simplified the code, however the function currently looks as follows.

```<code>function generateHtml($jsonDoc){
    $html = "";
    $html .= "<table>";
    $count = 0;

    foreach ($jsonDoc as $key => $value) {
        $count ++;

        if ($count % 2 == 0)
            $html .= "<tr>";

        $html .= "<td>";
        foreach ($value as $key => $val) {
            if(!empty($val))
                $html .= $key.":".$val."<br />";
        }
        $html .= "</td>";

        if ($count % 2 == 0)
            $html .= "</tr>";
        // $count ++;
    }
    $html .= "</table>";

    print($html);
}
</code>```

The resulting HTML output always seems to come out as follows and I cannot seem to understand what is missing.

```<code><table>
    <tr>
        <td>Ground</td>
    </tr>
    <tr>
        <td>Water</td>
    </tr>
    <tr>
        <td>Sewer</td>
    </tr>
    <tr>
        <td>Tap</td>
    </tr>
</table>
</code>```

as opposed to

```<code><table>
    <tr>
        <td>Ground</td>
        <td>Water</td>
    </tr>
    <tr>
        <td>Sewer</td>
        <td>Tap</td>
    </tr>
</table>
```
which is what I am looking for.
```

答:
Try this</p>

```<code>function generateHtml($jsonDoc){
    $html = "";
    $html .= "<table>";
    $count = 1;

    foreach ($jsonDoc as $key => $value) {
        //$count ++;

        if ($count % 2 != 0)
            $html .= "<tr>";

        $html .= "<td>";
        foreach ($value as $key => $val) {
            if(!empty($val))
                $html .= $key.":".$val."<br />";
        }
        $html .= "</td>";

        if ($count % 2 == 0)
            $html .= "</tr>";
        $count ++;
    }
    $html .= "</table>";

    print($html);
}
</code>```

Body:
This should be a fairly simple problem, however I cannot for the life of me get it to work right.

I have JSON data in the form of an array like so and I am trying to generate a 2-column table where every 2 elements in the array take up a row.

[
    {
        "type": "Ground",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Water",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Sewer",
        "field_location": "",
        "field_user": "",
    },
    {
        "type": "Tap",
        "field_location": "",
        "field_user": "",
    }
]

I have overly simplified the code, however the function currently looks as follows.

function generateHtml($jsonDoc){
    $html = "";
    $html .= "
";
    $count = 0;

    foreach ($jsonDoc as $key => $value) {
        $count ++;

        if ($count % 2 == 0)
            $html .= "
";

        $html .= "";
        foreach ($value as $key => $val) {
            if(!empty($val))
                $html .= $key.":".$val."
";
        }
        $html .= "	";

        if ($count % 2 == 0)
            $html .= "
";
        // $count ++;
    }
    $html .= "
";

    print($html);
}

The resulting HTML output always seems to come out as follows and I cannot seem to understand what is missing.

        Ground

        Water

        Sewer

        Tap

as opposed to

        Ground
        Water

        Sewer
        Tap

```
which is what I am looking for.

Body:
Try this

function generateHtml($jsonDoc){
    $html = "";
    $html .= "<table>";
    $count = 1;

    foreach ($jsonDoc as $key => $value) {
        //$count ++;

        if ($count % 2 != 0)
            $html .= "<tr>";

        $html .= "<td>";
        foreach ($value as $key => $val) {
            if(!empty($val))
                $html .= $key.":".$val."<br />";
        }
        $html .= "</td>";

        if ($count % 2 == 0)
            $html .= "</tr>";
        $count ++;
    }
    $html .= "</table>";

    print($html);
}


问:
How to implement localization in Swift UI
Can anybody help me? I can't find any description of the localization in Swift UI. Can anyone please give advice or better an example of how to localize for example Text()?

答:
To use Localazable in SwiftUI, you can perform this way:

import SwiftUI to use LocalizedStringKey in your files

```<code>//MARK: - File where you enum your keys to your Localized file
enum ButtonName: LocalizedStringKey {
case submit
case cancel
}

//MARK: - Your Localized file where are your translation
"submit" = "Submit is pressed";
"cancel" = "Cancel";

//MARK: - In your code
let submitButtonName = ButtonName.submit.rawValue
let cancelButtonName = ButtonName.cancel.rawValue

VStack {
Text(submitButtonName)
Text(cancelButtonName)
}
</code>```

Body:
To use Localazable in SwiftUI, you can perform this way:

import SwiftUI to use LocalizedStringKey in your files

//MARK: - File where you enum your keys to your Localized file
enum ButtonName: LocalizedStringKey {
case submit
case cancel
}

//MARK: - Your Localized file where are your translation
"submit" = "Submit is pressed";
"cancel" = "Cancel";

//MARK: - In your code
let submitButtonName = ButtonName.submit.rawValue
let cancelButtonName = ButtonName.cancel.rawValue

VStack {
Text(submitButtonName)
Text(cancelButtonName)
}


问:
Read-only file system when attempting mkdir /data/db on Mac
I am trying to create a new folder in the root directory.

I tried all kinds of examples.

sudo mkdir /data/db
```
<pre class="lang-bash prettyprint-override"><code>sudo mkdir -p /data/db
</code>```

I keep getting:

mkdir: /data: Read-only file system
```

答:
To make a permanent change of the path of mongod db folder.

Following these docs they say roughly this. If mongod is started with brew services:

```<code>$ brew services start mongodb-community@4.2
</code>```

It will use config file at path /usr/local/etc/mongod.conf

To fix this, edit the config file:

```<code>$ vim /usr/local/etc/mongod.conf
</code>```

And change the dbPath e.g. to your home directory like this:

```<code>systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /Users/<username>/data/db
net:
  bindIp: 127.0.0.1
</code>```

Save the file and restart mongod with brew:

```<code>$ brew services restart mongodb-community@4.2
</code>```

Body:
I am trying to create a new folder in the root directory.

I tried all kinds of examples.

sudo mkdir /data/db

sudo mkdir -p /data/db

I keep getting:

mkdir: /data: Read-only file system

Body:
To make a permanent change of the path of mongod db folder.

Following these docs they say roughly this. If mongod is started with brew services:

$ brew services start mongodb-community@4.2

It will use config file at path /usr/local/etc/mongod.conf

To fix this, edit the config file:

$ vim /usr/local/etc/mongod.conf

And change the dbPath e.g. to your home directory like this:

systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /Users/<username>/data/db
net:
  bindIp: 127.0.0.1

Save the file and restart mongod with brew:

$ brew services restart mongodb-community@4.2


问:
How to use strings as an ordering sequence?
I'd like to know how I can use a string like order = '8927391' (with 8 being largest and 1 being smallest) and print out an answer according to the order, for example:
Let's say if_no_is_higher(no1, no2) is a function that I have defined already to print yes if the first number is higher than the second, and no if the first number is smaller.

```<code>if_no_is_higher(8, 9)
</code>```

returns

```<code>yes
</code>```

because according to the order 8 is higher than 9

答:
Create a custom order and use the index of that collection to check for your condition:</p>

```<code>a = '8927391'
custom_order = [int(item) for item in a]
min(8, 9, key=custom_order.index)
</code>```

Body:
I'd like to know how I can use a string like order = '8927391' (with 8 being largest and 1 being smallest) and print out an answer according to the order, for example:
Let's say if_no_is_higher(no1, no2) is a function that I have defined already to print yes if the first number is higher than the second, and no if the first number is smaller.

if_no_is_higher(8, 9)

returns

yes

because according to the order 8 is higher than 9

Body:
Create a custom order and use the index of that collection to check for your condition:

a = '8927391'
custom_order = [int(item) for item in a]
min(8, 9, key=custom_order.index)


问:
How to efficiently sum over levels defined in another variable?
I am new to R. Now I have a function as follow:

```<code>funItemAverRating = function()
{
    itemRatingNum = array(0, itemNum);
    print("begin");
    apply(input, 1, function(x)
        {
            itemId = x[2]+1;
            itemAverRating[itemId] <<- itemAverRating[itemId] + x[3];
            itemRatingNum[itemId] <<- itemRatingNum[itemId] + 1;
        }
    );
}
</code>```

In this function input is a n*3 data frame, n is ~6*(10e+7), itemRatingNum is a vector of size ~3*(10e+5).

My question is why the apply function is so slow (it would take nearly an hour to finish)? Also, as the function runs, it uses more and more memory. But as you can see, the variables are all defined outside the apply function. Can anybody help me?

cheng

答:
Don't do that. You're following a logic that is completely not R-like. If I understand it right, you want to add to a certain itemAverRating vector a value from a third column in some input dataframe.

What itemRatingNum is doing, is rather obscure. It does not end up in the global environment, and it just becomes a vector filled with frequencies at the end of the loop. As you define itemRatingNum within the function, the <<- assignment will also assign it within the local environment of the function, and it will get destroyed when the function ends.

Next, you should give your function input, and get some output. Never assign to the global environment if it's not necessary. Your function is equivalent to the - rather a whole lot faster - following function, which takes input and gives output :

```<code>funItemAverRating = function(x,input){
    sums <- rowsum(input[,3],input[,2])
    sumid <- as.numeric(rownames(sums))+1
    x[sumid]+c(sums)
}
</code>```

FUNCTION EDITED PER MAREKS COMMENT

Which works like :

```<code># make data
itemNum <- 10
set.seed(12)
input <- data.frame(
    a1 = rep(1:10,itemNum),
    a2 = sample(9:0,itemNum*10,TRUE),
    a3 = rep(10:1,itemNum)
)
itemAverRating <- array(0, itemNum)
itemAverRating <- funItemAverRating(itemAverRating,input)
itemAverRating
 0  1  2  3  4  5  6  7  8  9
39 65 57 36 62 33 98 62 60 38
</code>```

If I try your code, I get :

```<code>> funItemAverRating()
[1] "begin"
...
> itemAverRating
 [1] 39 65 57 36 62 33 98 62 60 38
</code>```

Which is the same. If you want itemRatingNum, then just do :

```<code>> itemRatingNum <- table(input[,2])
 0  1  2  3  4  5  6  7  8  9
 6 11 11  8 10  6 18  9 13  8
</code>```

Body:
I am new to R. Now I have a function as follow:

funItemAverRating = function()
{
    itemRatingNum = array(0, itemNum);
    print("begin");
    apply(input, 1, function(x)
        {
            itemId = x[2]+1;
            itemAverRating[itemId] <<- itemAverRating[itemId] + x[3];
            itemRatingNum[itemId] <<- itemRatingNum[itemId] + 1;
        }
    );
}

In this function input is a n*3 data frame, n is ~6*(10e+7), itemRatingNum is a vector of size ~3*(10e+5).

My question is why the apply function is so slow (it would take nearly an hour to finish)? Also, as the function runs, it uses more and more memory. But as you can see, the variables are all defined outside the apply function. Can anybody help me?

cheng

Body:
Don't do that. You're following a logic that is completely not R-like. If I understand it right, you want to add to a certain itemAverRating vector a value from a third column in some input dataframe.

What itemRatingNum is doing, is rather obscure. It does not end up in the global environment, and it just becomes a vector filled with frequencies at the end of the loop. As you define itemRatingNum within the function, the <<- assignment will also assign it within the local environment of the function, and it will get destroyed when the function ends.

Next, you should give your function input, and get some output. Never assign to the global environment if it's not necessary. Your function is equivalent to the - rather a whole lot faster - following function, which takes input and gives output :

funItemAverRating = function(x,input){
    sums <- rowsum(input[,3],input[,2])
    sumid <- as.numeric(rownames(sums))+1
    x[sumid]+c(sums)
}

FUNCTION EDITED PER MAREKS COMMENT

Which works like :

# make data
itemNum <- 10
set.seed(12)
input <- data.frame(
    a1 = rep(1:10,itemNum),
    a2 = sample(9:0,itemNum*10,TRUE),
    a3 = rep(10:1,itemNum)
)
itemAverRating <- array(0, itemNum)
itemAverRating <- funItemAverRating(itemAverRating,input)
itemAverRating
 0  1  2  3  4  5  6  7  8  9
39 65 57 36 62 33 98 62 60 38

If I try your code, I get :

> funItemAverRating()
[1] "begin"
...
> itemAverRating
 [1] 39 65 57 36 62 33 98 62 60 38

Which is the same. If you want itemRatingNum, then just do :

> itemRatingNum <- table(input[,2])
 0  1  2  3  4  5  6  7  8  9
 6 11 11  8 10  6 18  9 13  8


问:
Parsing csv with changing timezone (due to daylight saving time) with pandas
I'm trying to parse a csv that looks like this

```<code>time                                val
28.10.2007 00:00:00.000 GMT+0100    1
28.10.2007 00:01:00.000 GMT+0100    2
28.10.2007 01:00:00.000 GMT-0000    3
28.10.2007 01:01:00.000 GMT-0000    4
</code>```

To do so, I use

```<code>pd.read_csv(f,
            parse_dates=[0],
            dayfirst=True,
            index_col=0)
</code>```

However, the result looks like this

```<code>                           val
time
2007-10-28 00:00:00-01:00    1
2007-10-28 00:01:00-01:00    2
2007-10-28 00:00:00-01:00    3
2007-10-28 00:01:00-01:00    4
</code>```

This cause the 3rd and 4th row to be duplicated values. Is there a way to ask pandas to convert this time to UTC and understand the change in TZ?

答:
I tried this and somehow it works but I don't know if this is something that you want.</p>

```<code>df = pd.read_csv('data.csv')

df['time'] = pd.to_datetime(df['time'], format='%d.%m.%Y %H:%M:%S.%f GMT%z')
df['time_'] = pd.to_datetime(df['time'], utc=True)
</code>```

Body:
I'm trying to parse a csv that looks like this

time                                val
28.10.2007 00:00:00.000 GMT+0100    1
28.10.2007 00:01:00.000 GMT+0100    2
28.10.2007 01:00:00.000 GMT-0000    3
28.10.2007 01:01:00.000 GMT-0000    4

To do so, I use

pd.read_csv(f,
            parse_dates=[0],
            dayfirst=True,
            index_col=0)

However, the result looks like this

                           val
time
2007-10-28 00:00:00-01:00    1
2007-10-28 00:01:00-01:00    2
2007-10-28 00:00:00-01:00    3
2007-10-28 00:01:00-01:00    4

This cause the 3rd and 4th row to be duplicated values. Is there a way to ask pandas to convert this time to UTC and understand the change in TZ?

Body:
I tried this and somehow it works but I don't know if this is something that you want.

df = pd.read_csv('data.csv')

df['time'] = pd.to_datetime(df['time'], format='%d.%m.%Y %H:%M:%S.%f GMT%z')
df['time_'] = pd.to_datetime(df['time'], utc=True)


问:
Extract either two or three words and exclude duplicates and accronyms
I have a group of names worded in a bizarre fashion. Here is a sample:

```<code>Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster
</code>```

My goal is to clean it so either first and last name show for names or just team names is returned for teams. Here is what have tried:

```<code>df$name <- sub("^(.*[a-z])[A-Z]", "\\1", "\\1", df$name)
</code>```

This is what I'm getting returned

```<code>Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster
</code>```

To be clear, goal would be to have this:

```<code>Sammy Watkins
Buffalo Bills
New England Patriots
Tre'Quan Smith
JuJu Smith-Schuster
</code>```

data

```<code>df <- data.frame(name = c(
  "Sammy WatkinsS. Watkins",
  "Buffalo BillsBUF",
  "New England PatriotsNE",
  "Tre'Quan SmithT. Smith",
  "JuJu Smith-SchusterJ. Smith-Schuster"),
  stringsAsFactors = FALSE)
</code>```

答:
I suggest

```<code>df$name <- sub("\\B[A-Z]+(?:\\.\\s+\\S+)*$", "", df$name)
</code>```

See the regex demo

Pattern details

\B - a non-word boundary (there must be a letter, digit or _ right before)

[A-Z]+ - 1+ ASCII uppercase letters (use \p{Lu} to match any Unicode uppercase letters)

(?:\.\s+\S+)* - 0 or more sequences of:

\. - a dot

\s+ - 1+ whitespaces

\S+ - 1+ non-whitespaces

$ - end of string.

Body:
I have a group of names worded in a bizarre fashion. Here is a sample:

Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster

My goal is to clean it so either first and last name show for names or just team names is returned for teams. Here is what have tried:

df$name <- sub("^(.*[a-z])[A-Z]", "\\1", "\\1", df$name)

This is what I'm getting returned

Sammy WatkinsS. Watkins
Buffalo BillsBUF
New England PatriotsNE
Tre'Quan SmithT. Smith
JuJu Smith-SchusterJ. Smith-Schuster

To be clear, goal would be to have this:

Sammy Watkins
Buffalo Bills
New England Patriots
Tre'Quan Smith
JuJu Smith-Schuster

data

df <- data.frame(name = c(
  "Sammy WatkinsS. Watkins",
  "Buffalo BillsBUF",
  "New England PatriotsNE",
  "Tre'Quan SmithT. Smith",
  "JuJu Smith-SchusterJ. Smith-Schuster"),
  stringsAsFactors = FALSE)

Body:
I suggest

df$name <- sub("\\B[A-Z]+(?:\\.\\s+\\S+)*$", "", df$name)

See the regex demo

Pattern details

\B - a non-word boundary (there must be a letter, digit or _ right before)

[A-Z]+ - 1+ ASCII uppercase letters (use \p{Lu} to match any Unicode uppercase letters)

(?:\.\s+\S+)* - 0 or more sequences of:

\. - a dot

\s+ - 1+ whitespaces

\S+ - 1+ non-whitespaces

$ - end of string.


问:
Solr: How to store data in lower case for specific field while importing by CSV?
I have fields in schema.xml as below

```<code><field name="Colour" type="string"/>
<field name="MerchantCampaignName" multiValued="false" type="string" indexed="true"/>
<field name="Name" type="text_general" indexed="true"/>
<field name="SKU" type="string" multiValued="false" indexed="true" required="true" stored="true"/>
<field name="Size" type="string" indexed="true"/>
</code>```

So while importing data from CSV, in the color field there are values like "red", "Red", "Reds".

In facet query on "Colour" field, it treated all three values as different.

SO is there any setting to save "Colour" field as lower case and also for singular and plural?

答:
Use the KeywordTokenizerFactory and LowerCaseFilterFactory for the same. You have create a custom field type using the above and apply the same to your field.

The keywordTokenizer is : This tokenizer treats the entire text field as a single token.

You can use the below field type for your field. The advantage would be it would help to search for words in all the case...UPPER and LOWER case both.

```<code><fieldType name="lowercaseExactMatch" class="solr.TextField" positionIncrementGap="100">
   <analyzer>
     <tokenizer class="solr.KeywordTokenizerFactory"/>
     <filter class="solr.LowerCaseFilterFactory" />
   </analyzer>
</fieldType>
</code>```

Here is your field defination would be :

```<code><field name="Colour" type="lowercaseExactMatch" indexed="true" stored="true"/>
</code>```

Body:
I have fields in schema.xml as below

<field name="Colour" type="string"/>
<field name="MerchantCampaignName" multiValued="false" type="string" indexed="true"/>
<field name="Name" type="text_general" indexed="true"/>
<field name="SKU" type="string" multiValued="false" indexed="true" required="true" stored="true"/>
<field name="Size" type="string" indexed="true"/>

So while importing data from CSV, in the color field there are values like "red", "Red", "Reds".

In facet query on "Colour" field, it treated all three values as different.

SO is there any setting to save "Colour" field as lower case and also for singular and plural?

Body:
Use the KeywordTokenizerFactory and LowerCaseFilterFactory for the same. You have create a custom field type using the above and apply the same to your field.

The keywordTokenizer is : This tokenizer treats the entire text field as a single token.

You can use the below field type for your field. The advantage would be it would help to search for words in all the case...UPPER and LOWER case both.

<fieldType name="lowercaseExactMatch" class="solr.TextField" positionIncrementGap="100">
   <analyzer>
     <tokenizer class="solr.KeywordTokenizerFactory"/>
     <filter class="solr.LowerCaseFilterFactory" />
   </analyzer>
</fieldType>

Here is your field defination would be :

<field name="Colour" type="lowercaseExactMatch" indexed="true" stored="true"/>


问:
is there an Application::onDestroy() equivalent for Android?
Hi I am using the Application::onCreate to put my initialisation code of my app, but when waiting some time and starting other apps, I noticed the instance of the Application class gets created again...

How to detect globally when Android is shuttting down my Application instance?

答:
I am not an experienced android developer. But as a beginner, I think you can use the onDestroy() method of the Activity.

It's a good idea for you to look into the Lifecycle of the Activity.

(Search for Lifecycle in the following link)
http://developer.android.com/guide/topics/fundamentals/activities.html


问:
mediawiki api search query with multiple expressions
I'd like to run a query for an artist's names. An artist could have a stage name, a full name (latin), korean name, nickname, etc.

I can't find how to seperate these names in a query URL.

```<code>https://commons.wikimedia.org/w/api.php?action=query&list=search&srnamespace=6&srlimit=500&format=json&srsearch=Taeyeon|Kim Tae-yeon|Taengoo|김태연
</code>```

If I run the query for only 1 name, it brings the results, but got nothing with more names.

答:
Use the keyword OR instead of |.

That means, run the following query:

```<code>https://commons.wikimedia.org/w/api.php?action=query&list=search&srnamespace=6&srlimit=500&format=json&srsearch=Taeyeon OR "Kim Tae-yeon" OR Taengoo OR 김태연
</code>```

Body:
I'd like to run a query for an artist's names. An artist could have a stage name, a full name (latin), korean name, nickname, etc.

I can't find how to seperate these names in a query URL.

https://commons.wikimedia.org/w/api.php?action=query&list=search&srnamespace=6&srlimit=500&format=json&srsearch=Taeyeon|Kim Tae-yeon|Taengoo|김태연

If I run the query for only 1 name, it brings the results, but got nothing with more names.

Body:
Use the keyword OR instead of |.

That means, run the following query:

https://commons.wikimedia.org/w/api.php?action=query&list=search&srnamespace=6&srlimit=500&format=json&srsearch=Taeyeon OR "Kim Tae-yeon" OR Taengoo OR 김태연


问:
jQuery animate background image on timeout up-down float effect
I have this element with background images:

```<code>background-image: url(../img/Icons/about-stars-bg2.svg),
  url(../img/about-planet-1.svg),
  url(../img/about-planet-2.svg),
  url(../img/about-planet-3.svg);
background-position: top 5px center, -115px 200px, left 1055px top 450px,
  right -45px top 350px;
background-repeat: no-repeat;
background-size: auto, auto, auto, 100px;
</code>```

Now I want the planets (every picture except the first one) to move a little bit up, then down. (Float effect).

In jQuery I created a setInterval so I have a loop every 2s. Inside I tried to change the background position. It works if I put

```<code>.css('background-position','top 5px center, -155px 200px, left 1255px top 250px, right -15px top 350px');
</code>```

But this just blinks the planets in 2 sec.

Then I tried:

```<code>$('.header').animate({backgroundPosition: '(0px -400px)'}, 1000 );// space here
</code>```

But nothing happened.

How can I achieve the hover effect up/down ?
Here is the jQuery:

```<code>// Move planets up down
$(document).ready(function(){
  var i = 0;
  setInterval(function(){

    //JUST BLINKS, CHANGES LOCATION
    //$('.header').css('background-position','top 5px center, -155px 200px, left 1255px top 250px, right -15px top 350px');

    //DOESN'T WORK
    $('.header').animate({backgroundPosition: '(0px -400px)'}, 1000 );

    i++;
  },2000);
});
</code>```

答:
#planets {
  height: 90vh;

  background-image:
    url(//placehold.it/40x40/f0b),
    url(//placehold.it/40x40/0bf),
    url(//placehold.it/40x40/bf0),
    url(//placehold.it/40x40/0fb);

  background-position:
    50% 15%,
    25% 35%,
    10% 19%,
    80% 60%;

  background-repeat: no-repeat;
  background-size:
    3%,
    4%,
    5%,
    6%;

  animation: planets 1s 0.5s ease-in-out alternate infinite;
}

@keyframes planets {
  to {
    background-position:
      50% 45%,
      25% 65%,
      10% 69%,
      80% 20%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="planets">

</div></code>```

Body:
I have this element with background images:

background-image: url(../img/Icons/about-stars-bg2.svg),
  url(../img/about-planet-1.svg),
  url(../img/about-planet-2.svg),
  url(../img/about-planet-3.svg);
background-position: top 5px center, -115px 200px, left 1055px top 450px,
  right -45px top 350px;
background-repeat: no-repeat;
background-size: auto, auto, auto, 100px;

Now I want the planets (every picture except the first one) to move a little bit up, then down. (Float effect).

In jQuery I created a setInterval so I have a loop every 2s. Inside I tried to change the background position. It works if I put

.css('background-position','top 5px center, -155px 200px, left 1255px top 250px, right -15px top 350px');

But this just blinks the planets in 2 sec.

Then I tried:

$('.header').animate({backgroundPosition: '(0px -400px)'}, 1000 );// space here

But nothing happened.

How can I achieve the hover effect up/down ?
Here is the jQuery:

// Move planets up down
$(document).ready(function(){
  var i = 0;
  setInterval(function(){

    //JUST BLINKS, CHANGES LOCATION
    //$('.header').css('background-position','top 5px center, -155px 200px, left 1255px top 250px, right -15px top 350px');

    //DOESN'T WORK
    $('.header').animate({backgroundPosition: '(0px -400px)'}, 1000 );

    i++;
  },2000);
});

Body:
#planets {
  height: 90vh;

  background-image:
    url(//placehold.it/40x40/f0b),
    url(//placehold.it/40x40/0bf),
    url(//placehold.it/40x40/bf0),
    url(//placehold.it/40x40/0fb);

  background-position:
    50% 15%,
    25% 35%,
    10% 19%,
    80% 60%;

  background-repeat: no-repeat;
  background-size:
    3%,
    4%,
    5%,
    6%;

  animation: planets 1s 0.5s ease-in-out alternate infinite;
}

@keyframes planets {
  to {
    background-position:
      50% 45%,
      25% 65%,
      10% 69%,
      80% 20%;
  }
}

<div id="planets">

</div>


问:
Fill numpy array by indexing with 2d array
I have a 2d numpy array of zeros subbins, and a 2d numpy array of indices into it combos. For example

```<code>p = 4
combos = np.asarray(list(itertools.combinations(range(p),3)))
subbins = np.zeros(shape=(len(combos),p))
</code>```

The arrays look like this

```<code>combos = [[0 1 2]
 [0 1 3]
 [0 2 3]
 [1 2 3]]
subbins = [[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
</code>```

How can I use combos to index into subbins and assign values without iterating - as pythonic as possible? I.e. the output I want is this:

```<code>output = [[1. 1. 1. 0.]
 [1. 1. 0. 1.]
 [1. 0. 1. 1.]
 [0. 1. 1. 1.]]
</code>```

Body:
I have a 2d numpy array of zeros subbins, and a 2d numpy array of indices into it combos. For example

p = 4
combos = np.asarray(list(itertools.combinations(range(p),3)))
subbins = np.zeros(shape=(len(combos),p))

The arrays look like this

combos = [[0 1 2]
 [0 1 3]
 [0 2 3]
 [1 2 3]]
subbins = [[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

How can I use combos to index into subbins and assign values without iterating - as pythonic as possible? I.e. the output I want is this:

output = [[1. 1. 1. 0.]
 [1. 1. 0. 1.]
 [1. 0. 1. 1.]
 [0. 1. 1. 1.]]

Body:
We can use np.put_along_axis:

np.put_along_axis(subbins, combos, 1, axis=1)

print(subbins)
array([[1., 1., 1., 0.],
       [1., 1., 0., 1.],
       [1., 0., 1., 1.],
       [0., 1., 1., 1.]])


问:
What are the differences between using self.add_error() and raising a ValidationError()?
You can throw a validation error in 2 ways. The first is with self.add_error() and the second with raise ValidationError().

I've read that when you use self.add_error('field1','description here') then field1 is also automatically removed from the cleaned_data list and i assume a ValidationError object is also added to the self.errors list, is this correct?

But what happens when you don't choose to use self.add_error and opt for using raise ValidationError  instead? Is this object also automatically added to the errors list behind the scenes? And how would you display this error message as caption under the correct invalid field?

Thank you

答:
If you raise an error, the control flow of that method, and callers of that method stops, until there is a method that has span a try-except over that, and catches the exception accordingly.

But sometimes a field might contain multiple errors. For example if you have a password, you might want to add errors because it is too short, does not contain a digit, a lowercase, and/or upppercase.

Then you thus can implement this with:

```<code>def clean_password(self):
    pwd = self.cleaned_data['password']
    if len(pwd) < 10:
        self.add_error('password', 'The password is too short.')
    if not any(c.isupper() for c in pwd):
        self.add_error('password', 'The password should contain an uppercase character.')
    if not any(c.islower() for c in pwd):
        self.add_error('password', 'The password should contain an lowercase character.')
    if not any(c.isdigit() for c in pwd):
        self.add_error('password', 'The password should contain an digit.')
    return pwd</code>```

If you would raise a ValidationError for one of these, it can not add mutliple problems that a password might have.

You can however pass a list of errors to a ValidationError data constructor, hence you can use the two interchangeable.

Body:
If you raise an error, the control flow of that method, and callers of that method stops, until there is a method that has span a try-except over that, and catches the exception accordingly.

But sometimes a field might contain multiple errors. For example if you have a password, you might want to add errors because it is too short, does not contain a digit, a lowercase, and/or upppercase.

Then you thus can implement this with:

def clean_password(self):
    pwd = self.cleaned_data['password']
    if len(pwd) < 10:
        self.add_error('password', 'The password is too short.')
    if not any(c.isupper() for c in pwd):
        self.add_error('password', 'The password should contain an uppercase character.')
    if not any(c.islower() for c in pwd):
        self.add_error('password', 'The password should contain an lowercase character.')
    if not any(c.isdigit() for c in pwd):
        self.add_error('password', 'The password should contain an digit.')
    return pwd

If you would raise a ValidationError for one of these, it can not add mutliple problems that a password might have.

You can however pass a list of errors to a ValidationError data constructor, hence you can use the two interchangeable.


问:
Java8 stream - combine the finding of sum, positive result and average result into single step
Is it possible to combine the below 3 steps into a single step?

First steps calculate the total price

The second step finds the non zero price count

The third step finds the average

private double calculateTotalBCMMatrixCost(SpecificationEntryRequest specificationEntryRequest) {

        // Finds the total BCM matrix cost
        double totalBcmMatrixCost = specificationEntryRequest.getComponentList().stream()
                .map(ComponentDetail::getStartingMaterialId)
                .map(this::calculateBCMMatrixCostForAnalyte)
                .collect(Collectors.summingDouble(Double::doubleValue));

        // Finds the non zero cost count
        long nonZeroPriceCount = specificationEntryRequest.getComponentList().stream()
                .map(ComponentDetail::getStartingMaterialId)
                .map(this::calculateBCMMatrixCostForAnalyte)
                .filter(price -> price > 0).count();

        // returns the average cost
        return totalBcmMatrixCost / nonZeroPriceCount;
    }
```

答:
Use DoubleSummaryStatistics:

```<code>DoubleSummaryStatistics stats = specificationEntryRequest.getComponentList().stream()
    .map(ComponentDetail::getStartingMaterialId)
    .mapToDouble(this::calculateBCMMatrixCostForAnalyte)
    .filter(price -> price > 0)
    .summaryStatistics();
double totalBcmMatrixCost = stats.gtSum ();
long nonZeroPriceCount = stats.getCount ();
double average = stats.getAverage ();
</code>```

Or course, if you only need the average (that's what your method is returning), you can use:

```<code>return specificationEntryRequest.getComponentList().stream()
    .map(ComponentDetail::getStartingMaterialId)
    .mapToDouble(this::calculateBCMMatrixCostForAnalyte)
    .filter(price -> price > 0)
    .average()
    .orElse(0.0);
</code>```

Body:
Use DoubleSummaryStatistics:

DoubleSummaryStatistics stats = specificationEntryRequest.getComponentList().stream()
    .map(ComponentDetail::getStartingMaterialId)
    .mapToDouble(this::calculateBCMMatrixCostForAnalyte)
    .filter(price -> price > 0)
    .summaryStatistics();
double totalBcmMatrixCost = stats.gtSum ();
long nonZeroPriceCount = stats.getCount ();
double average = stats.getAverage ();

Or course, if you only need the average (that's what your method is returning), you can use:

return specificationEntryRequest.getComponentList().stream()
    .map(ComponentDetail::getStartingMaterialId)
    .mapToDouble(this::calculateBCMMatrixCostForAnalyte)
    .filter(price -> price > 0)
    .average()
    .orElse(0.0);