问:
How to add extension in incognito mode when launched from selenium chrome webdriver with python
We are doing some testing using selenium python webdriver where we need to open one url in incognito mode and enable one extension already installed and then do some actions.

My findings:

loading of extension in incognito mode not working

extension getting loaded when icgnito mode turned off

Verified so many post on stack overflow, nothing worked.
tried below code"

```<code>path = os.path.dirname(r"C:\Users\ab\AppData\Local\Google\Chrome\User Data\Default\Extensions\jfpmbokkdeapjommajdfmmheiiakdlgo\0.1.7_0\manifest.json")
options = webdriver.ChromeOptions()
options.add_argument('--incognito')
options.add_argument("--load-extension={path}")
driver = webdriver.Chrome(chrome_options=options, executable_path='C:\chromedriver_win32\chromedriver.exe')
driver.maximize_window()
driver.get(xxxxxxxx)
</code>```

which throwing error cannot load manifest.json either missing or not readable. However i have made sure the path is correct.

any suggestion please how to load extension while opening chrome driver in incognito mode ?

答:
Rather you loading the required cookies/extension as part of your chrome options, other option is using the chrome profile. Check my answer in this post

To more on the profiles and how they work refer here

Here is the logic to turn on the extension in the incognito mode.

Python:

```<code># driver.get("chrome://extensions/?id=extion_name_goes_here"); # <=== general snippet see below example
# driver.get("chrome://extensions/?id=jfpmbokkdeapjommajdfmmheiiakdlgo")

# select allow in incognito mode checkbox
driver.execute_script("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()");
</code>```

Refer to my answer in this post for more information on the js used above.

Body:
We are doing some testing using selenium python webdriver where we need to open one url in incognito mode and enable one extension already installed and then do some actions.

My findings:

loading of extension in incognito mode not working

extension getting loaded when icgnito mode turned off

Verified so many post on stack overflow, nothing worked.
tried below code"

path = os.path.dirname(r"C:\Users\ab\AppData\Local\Google\Chrome\User Data\Default\Extensions\jfpmbokkdeapjommajdfmmheiiakdlgo\0.1.7_0\manifest.json")
options = webdriver.ChromeOptions()
options.add_argument('--incognito')
options.add_argument("--load-extension={path}")
driver = webdriver.Chrome(chrome_options=options, executable_path='C:\chromedriver_win32\chromedriver.exe')
driver.maximize_window()
driver.get(xxxxxxxx)

which throwing error cannot load manifest.json either missing or not readable. However i have made sure the path is correct.

any suggestion please how to load extension while opening chrome driver in incognito mode ?

Body:
Rather you loading the required cookies/extension as part of your chrome options, other option is using the chrome profile. Check my answer in this post

To more on the profiles and how they work refer here

Here is the logic to turn on the extension in the incognito mode.

Python:

# driver.get("chrome://extensions/?id=extion_name_goes_here"); # <=== general snippet see below example
# driver.get("chrome://extensions/?id=jfpmbokkdeapjommajdfmmheiiakdlgo")

# select allow in incognito mode checkbox
driver.execute_script("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()");

Refer to my answer in this post for more information on the js used above.


来源: stackexchange

问:
How to Convert all audio files in the same folder at the same time to another format
I have one folder full of audio samples in mp3 format and i want to format all of them in OGG format. So to save time i want to format all at the same time. what method do you suggest? </p>

答:
Using an audio file converter utility may be the best option for you. One very good option is NCH Switch. It's widely reviewed, and you get 30 days free use with no limitations. They allow you to batch convert, so you can add the whole folder, specify rename options (if you wish) and many other functions. It is quite simple and intuitive to use.
Another free and open source option is fre:ac.

ContentLicense: CC BY-SA 4.0


问:
How does an IP packet traverse back down the "tree"?
The path an IP packet takes up the network "tree" is pretty clear to me (or so I think):

Am I in the right network?

No: Forward to the gateway address.

Yes: Go to the final destination address.

Am I there yet?

No: Repeat step one.

Yes: Done!

This only really accounts for going up the network.  I'm not sure how to reconcile this with getting back down, say across the internet through all the gateways in between two personal computers.  I know about NAT, so a gateway can receive a packet intended for it, and forward it to a device on its network, but that's surely not the whole story - for example, what if is no NAT (perhaps with IPv6)?

It would seem routers would need tables to guide packets to the right branches, (alternative destination instead of another gateway), and that top level internet routers would need huge tables to reliably route packets.

答:
Well for the most part that is the case, you have huge routing tables that help route a packet from source to destination.

I'm not really sure what you meant by "going down the tree", but in the end of the day your private router at home get's a unique IP address from your ISP.

Your router probably doesn't have a specific route for a packet destined to facebook servers, but it also has a default gateway.

This means you'll keep getting through default gateways until your packet reaches a router that doe's know the specific router for a destination IP of a packet.

When the packet (let's say from facebook servers) get's back, the destination would be the unique IPv4 address (or IPv6, but we'll focus on 4) of your router.

Again it would go through all the default gateways, until reaching some router that knows what to do with the destination IP.

To help with routing, there are few predefined rules/ranges of addresses for each country/organization, and that helps route packets to/from them over the internet.

Btw, between the same organization. a lot of times they use tunneling - which i recommend reading on since it might help you get an even better understanding on the topic.


问:
React Js Updating a value inside a array with onChange to a child component
I have a list with opening_hours that I map inside my render function. I map them to a child component. I want to change the value of each object inside my parent state when the child component state is changed. Only problem is that my values don't change in the child component nor the parent state. I have passed the onChange method to each child component, but the problem lies in my onChange function in the parent state.

I have tried to pass the onChange to my child component and update the state with [e.target.name] : e.target.value. But that didn't work. So I tried to copy the arrayList and update the state based on the index of the mapped arrayList. That also didn't work.

```<code>    handleOnChange =  (index) => {
        let newData = [...this.state.opening_hours];
        this.setState(
            newData.map((barbershop, j) => {
                if (j === index) {
                    return barbershop;
                    console.log(barbershop)
                }
            return {
                newData,
            };
        }));
        console.log(newData)
    };

    render() {
        return (
            <>
                <div className="container mb-2">
                    <h4>Opening hours </h4>
                    <Form>
                        {this.state.opening_hours.map((barbershop, index) => (
                            <Day
                                key={barbershop.id}
                                day={barbershop.day}
                                open_time={barbershop.open_time}
                                close_time={barbershop.close_time}
                                index = {index}
                                onChange={() => this.handleOnChange(index)}/>
                        ))}
                    </Form>

                    <Button onClick={this.handleSubmit} variant="primary" type="submit">
                        Update opening hours
                    </Button>
                </div>
            </>
        );
    }
}
</code>```

My child component looks like this

```<code>class Day extends Component {

    constructor(props) {
        super(props);
        this.state = {
            day: this.props.day,
            open_time: this.props.open_time,
            close_time: this.props.close_time,
        };
        console.log(this.state)
    }

    handleChange = () => {
        this.props.onChange(this.props.index)
    }

    render() {
        return (
                <Form.Group as={Row}>
                <Form.Label column sm="3">
                    {ENUM[this.state.day]}
                </Form.Label>
                <Col sm="3">
                    <Form.Control
                        name="open_time"
                        value={this.state.open_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
                <Col sm="3">
                    <Form.Control
                        name="close_time"
                        value={this.state.close_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
            </Form.Group>
        );
    }
}

</code>```

EDIT:

答:
You're passing a function that calls this.handleChange(index), but you should really be passing that method as a prop to your <Day /> component and call it in there. You're already passing in the index (although I would use barbershop.id instead)

So in your parent component, I would do this instead:

```<code><Day
  key={barbershop.id}
  day={barbershop.day}
  open_time={barbershop.open_time}
  close_time={barbershop.close_time}
  index = {barbershop.id}
  handleChange={this.handleOnChange}
/>
</code>```

Then in your this.handleChange method in the parent component, if you're just trying to get this.state.opening_hours for a specific barbershop, I would do something like this instead:

```<code>handleChange = (id) => {
  this.setState(() => ({
    opening_hours: this.state.opening_hours.filter((barbershop) => {
      return barbershop.id === id;
    })
  }))
}
</code>```

Body:
I have a list with opening_hours that I map inside my render function. I map them to a child component. I want to change the value of each object inside my parent state when the child component state is changed. Only problem is that my values don't change in the child component nor the parent state. I have passed the onChange method to each child component, but the problem lies in my onChange function in the parent state.

I have tried to pass the onChange to my child component and update the state with [e.target.name] : e.target.value. But that didn't work. So I tried to copy the arrayList and update the state based on the index of the mapped arrayList. That also didn't work.

    handleOnChange =  (index) => {
        let newData = [...this.state.opening_hours];
        this.setState(
            newData.map((barbershop, j) => {
                if (j === index) {
                    return barbershop;
                    console.log(barbershop)
                }
            return {
                newData,
            };
        }));
        console.log(newData)
    };

    render() {
        return (
            <>

Opening hours

                    <Form>
                        {this.state.opening_hours.map((barbershop, index) => (
                            <Day
                                key={barbershop.id}
                                day={barbershop.day}
                                open_time={barbershop.open_time}
                                close_time={barbershop.close_time}
                                index = {index}
                                onChange={() => this.handleOnChange(index)}/>
                        ))}
                    </Form>

                    <Button onClick={this.handleSubmit} variant="primary" type="submit">
                        Update opening hours
                    </Button>

            </>
        );
    }
}

My child component looks like this

class Day extends Component {

    constructor(props) {
        super(props);
        this.state = {
            day: this.props.day,
            open_time: this.props.open_time,
            close_time: this.props.close_time,
        };
        console.log(this.state)
    }

    handleChange = () => {
        this.props.onChange(this.props.index)
    }

    render() {
        return (
                <Form.Group as={Row}>
                <Form.Label column sm="3">
                    {ENUM[this.state.day]}
                </Form.Label>
                <Col sm="3">
                    <Form.Control
                        name="open_time"
                        value={this.state.open_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
                <Col sm="3">
                    <Form.Control
                        name="close_time"
                        value={this.state.close_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
            </Form.Group>
        );
    }
}

EDIT:

Body:
You're passing a function that calls this.handleChange(index), but you should really be passing that method as a prop to your <Day /> component and call it in there. You're already passing in the index (although I would use barbershop.id instead)

So in your parent component, I would do this instead:

<Day
  key={barbershop.id}
  day={barbershop.day}
  open_time={barbershop.open_time}
  close_time={barbershop.close_time}
  index = {barbershop.id}
  handleChange={this.handleOnChange}
/>

Then in your this.handleChange method in the parent component, if you're just trying to get this.state.opening_hours for a specific barbershop, I would do something like this instead:

handleChange = (id) => {
  this.setState(() => ({
    opening_hours: this.state.opening_hours.filter((barbershop) => {
      return barbershop.id === id;
    })
  }))
}


问:
How to set up trade chests with command blocks in minecraft 1.14?
I am currently trying to trade certain items in my inventory for other items, using command blocks in minecraft 1.14. For example, trading in 32x charcoal for 1x diamond, as if using a machine to compress the carbon. The only problem is that the guides/vids I find use /testfor.</p>

答:
/testfor has been removed in 1.13 as it has been replaced by /execute which is much more useful. In the old days, you would have to take a comparator output from /testfor or /testforblock to see if the thing that was tested for was True. So basically you could only have boolean data. With execute, you can do everything like that but also store entity targets right away in the same command. Especially the new 1.13 system has made execute so powerful. Check out some videos on 1.13 command system brigadier.

As for this system, you could do something like this on a repeat command block. There are still problems with this clearly. You could improve it by just checking for more things.

```<code>/execute positioned <chest location> if data block ~ ~ ~ {Items:[{id:"minecraft:coal",Count:32b}]} run data merge block ~ ~ ~ {Items:[{id:"minecraft:diamond",Count:1b}]}
</code>```

Body:
/testfor has been removed in 1.13 as it has been replaced by /execute which is much more useful. In the old days, you would have to take a comparator output from /testfor or /testforblock to see if the thing that was tested for was True. So basically you could only have boolean data. With execute, you can do everything like that but also store entity targets right away in the same command. Especially the new 1.13 system has made execute so powerful. Check out some videos on 1.13 command system brigadier.

As for this system, you could do something like this on a repeat command block. There are still problems with this clearly. You could improve it by just checking for more things.

/execute positioned <chest location> if data block ~ ~ ~ {Items:[{id:"minecraft:coal",Count:32b}]} run data merge block ~ ~ ~ {Items:[{id:"minecraft:diamond",Count:1b}]}


问:
The variables I updated in my forEach, return to their original value
I am trying to query, that would get all of the earning and withdrawal amount and sum, but somehow after the forEach loop is done and exits, all of the updated values I placed in a variable return to their original values.</p>

```<code>  var withdrawbalance = 0;
  var totalearning = 0;

  userplans.forEach((up) => {
    DepositEarning.findOne({deposit: up.deposit._id})
      .then(depositearning => {
        withdrawbalance += parseInt(depositearning.WithdrawableBalance, 10);
      });
    Earning.findOne({deposit: up.deposit._id})
      .then(earnings => {
        totalearning += parseInt(earnings.Earning, 10);
    });
  })

  console.log(withdrawbalance);
  console.log(totalearning);
</code>```

答:
Just to add my two cents,

As other answers have stated, your foreach loop is using asynchronous code. It is making use of some API which is not a part of Js.

The call is pushed to call stack and then it is removed from the call stack. Because the work will be handled by the API now. the call to

console.log(withdrawbalance);
  console.log(totalearning);

is added to the call stack and what is the value right now? 0 0.

The API, when it is done with the work, will add the function in the task queue and from that, event loop will check if the call stack is empty. Since it is empty right now, will add the function in the call stack.

And it is then run. And then you will be having the real values of withdrawbalance and
 totalearning values.

Body:
I am trying to query, that would get all of the earning and withdrawal amount and sum, but somehow after the forEach loop is done and exits, all of the updated values I placed in a variable return to their original values.

  var withdrawbalance = 0;
  var totalearning = 0;

  userplans.forEach((up) => {
    DepositEarning.findOne({deposit: up.deposit._id})
      .then(depositearning => {
        withdrawbalance += parseInt(depositearning.WithdrawableBalance, 10);
      });
    Earning.findOne({deposit: up.deposit._id})
      .then(earnings => {
        totalearning += parseInt(earnings.Earning, 10);
    });
  })

  console.log(withdrawbalance);
  console.log(totalearning);


问:
Request re-input from user if input is not integer
```<code>While True:
    n=turtle.textinput(“”,”write your grade”)
    grade = int(n)

    while int(n) != grade :
        n=turtle.textinput(“”,”use only number”)
        grade = int(n)

    If grade <=100 and grade>=95 :
        print(“A+“)
    else :
        print(“F”)
</code>```

I'm getting value error.

I want to get situation <- if users gives me literal answer, I want to say "only number".

答:
I think you meant to try this

def enforce_int(x):
    try:
        _ = int(x)
        return True
    except ValueError as _:
        return False

While True: # why is this here though?
    n=turtle.textinput(“”,”write your grade”)

    while not enforce_int(n):
        n=turtle.textinput(“”,”use only number”)

    grade = int(n)
    If grade <=100 and grade>=95 :
        print(“A+“)
    else :
        print(“F”)
```

Body:
While True:
    n=turtle.textinput(“”,”write your grade”)
    grade = int(n)

    while int(n) != grade :
        n=turtle.textinput(“”,”use only number”)
        grade = int(n)

    If grade <=100 and grade>=95 :
        print(“A+“)
    else :
        print(“F”)

I'm getting value error.

I want to get situation <- if users gives me literal answer, I want to say "only number".


答:
Next time please format your code in ASCII.</p>

```<code>while True:
    n = input("write your grade: ")
    while True:
        try:
            grade = int(n)
            break
        except:
            n=input("use only number: ")

    if grade <=100 and grade>=95 :
        print("A+")
    else :
        print("F")
</code>```

Title: Request re-input from user if input is not integer

Body:
Next time please format your code in ASCII.

while True:
    n = input("write your grade: ")
    while True:
        try:
            grade = int(n)
            break
        except:
            n=input("use only number: ")

    if grade <=100 and grade>=95 :
        print("A+")
    else :
        print("F")


问:
Sticky footer at the bottom in Angular 2
I'm building a project in Angular 2, and I need a sticky footer which always must be at the bottom of the page, not fixed. Example: http://codepen.io/chriscoyier/pen/uwJjr

The structure of 'app' component is like this:

```<code><header-main></header-main>
<router-outlet></router-outlet>
<footer>...</footer>
</code>```

Probably, the problem is not connected with Angular itself, but with only CSS. However, I tried implementing it like this:

```<code>app {
   min-height: 100%;
   position: relative;
}

footer {
   position: absolute;
   bottom: 0;
   left: 0;
   width: 100%;
   height: 271px;
}
</code>```

The result is awful:

The interesting thing is that if I turn off a position of footer in inspector, and turn on again, the footer becomes OK:

SOLUTION:

```<code>app {
  min-height: 100%;
  width: 100%;
  margin-bottom: -271px;
  display: table;
}

header-main,
router-outlet,
footer{
  display: table-row;
}

header-main {
 height: 60px;
}

router-outlet {
  position: absolute;
}

footer {
  height: 271px;
}
</code>```

答:
this is the first time I write here :D
I'm currently learning angular 7 and I had the same problem...
So I created my own solution (probably not the best but I think it can help some1).

HTML:

```<code><div class="main-root">
    <header></header>
    <router-outlet></router-outlet>
    <footer></footer>
</div>
</code>```

CSS:

```<code>html,
body {
    height: 100%;
    margin: 0;
}

.main-root {
    height: 100%;
    display: flex;
    flex-direction: column;
}

footer {
    margin-top: auto;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm building a project in Angular 2, and I need a sticky footer which always must be at the bottom of the page, not fixed. Example: http://codepen.io/chriscoyier/pen/uwJjr

The structure of 'app' component is like this:

<router-outlet></router-outlet>
...

Probably, the problem is not connected with Angular itself, but with only CSS. However, I tried implementing it like this:

app {
   min-height: 100%;
   position: relative;
}

footer {
   position: absolute;
   bottom: 0;
   left: 0;
   width: 100%;
   height: 271px;
}

The result is awful:

The interesting thing is that if I turn off a position of footer in inspector, and turn on again, the footer becomes OK:

SOLUTION:

app {
  min-height: 100%;
  width: 100%;
  margin-bottom: -271px;
  display: table;
}

header-main,
router-outlet,
footer{
  display: table-row;
}

header-main {
 height: 60px;
}

router-outlet {
  position: absolute;
}

footer {
  height: 271px;
}

Body:
this is the first time I write here :D
I'm currently learning angular 7 and I had the same problem...
So I created my own solution (probably not the best but I think it can help some1).

HTML:

<div class="main-root">
    <header></header>
    <router-outlet></router-outlet>
    <footer></footer>
</div>

CSS:

html,
body {
    height: 100%;
    margin: 0;
}

.main-root {
    height: 100%;
    display: flex;
    flex-direction: column;
}

footer {
    margin-top: auto;
}


问:
NoClassDefFoundError after exporting jar
I am trying to work with MongoDB in my Java projects.

After exporting my project to a file I get a no class defined error for the MongoClient.

I get no errors while exporting.

I use Maven to import the different dependencies and all jars are being exported properly

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

public class MongoDB {

    private static MongoClient client;

    public static void init() {
        try {
            client = MongoClients.create("mongodb://localhost:27017/xenoncraft");
            System.out.println("[XenonSuite] Successfully connected to MongoDB");
        } catch(Exception e) {
            System.out.println("[XenonSuite] Following errors were catched while connecting to MongoDB");
            e.printStackTrace();
        }
    }
```

答:
This is how I solved your issue:

Checkout project from Github source code:

unzip, build, test

OR

1. Created a maven project

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

Update pom.xml with following, added mongo client code from OP and printing collection names

Execute
mvn clean package

Execute
java -jar test.jar
output I got is:

```<code>INFO: Opened connection [connectionId{localValue:1, serverValue:9}] to localhost:27017
Jun 01, 2019 8:17:22 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 5]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2249770}
Jun 01, 2019 8:17:22 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:10}] to localhost:27017
admin
config
local
test
[XenonSuite] Successfully connected to MongoDB
</code>```

pom.xml(ignore package names)

Check shade plugin configuration

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>test</name>

  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <mainClass>test.App</mainClass>
  </properties>

  <packaging>jar</packaging>

  <dependencies>

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.10.2</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <version>3.2.1</version>
          <executions>
            <execution>
              <phase>package</phase>
              <goals>
                <goal>shade</goal>
              </goals>
              <configuration>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <transformers>
                  <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <mainClass>test.App</mainClass>
                  </transformer>
                </transformers>
                <finalName>test</finalName>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
  </build>
</project>

```

There are multiple ways to solve this problem
Ref: https://www.baeldung.com/executable-jar-with-maven

Body:
This is how I solved your issue:

Checkout project from Github source code:

unzip, build, test

OR

1. Created a maven project

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

Update pom.xml with following, added mongo client code from OP and printing collection names

Execute
mvn clean package

Execute
java -jar test.jar
output I got is:

INFO: Opened connection [connectionId{localValue:1, serverValue:9}] to localhost:27017
Jun 01, 2019 8:17:22 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 5]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2249770}
Jun 01, 2019 8:17:22 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:10}] to localhost:27017
admin
config
local
test
[XenonSuite] Successfully connected to MongoDB

pom.xml(ignore package names)

Check shade plugin configuration

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>test</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <mainClass>test.App</mainClass>
  </properties>

  <packaging>jar</packaging>

  <dependencies>

  <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.10.2</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <version>3.2.1</version>
          <executions>
            <execution>
              <phase>package</phase>
              <goals>
                <goal>shade</goal>
              </goals>
              <configuration>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <transformers>
                  <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <mainClass>test.App</mainClass>
                  </transformer>
                </transformers>
                <finalName>test</finalName>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
  </build>
</project>

There are multiple ways to solve this problem
Ref: https://www.baeldung.com/executable-jar-with-maven


问:
Why is it that setting TextInput focus equal to True, makes TextInput not respond to keyboard input?

Background:

I have a button that adds TextInput widgets to a GridLayout with focus: True.  If a TextInput is already present in the layout with focus = True, the previous TextInput is firstly unfocused then a new TextInput is added with focus = True.

Problem:

Once a TextInput is added I cannot type even though the cursor is focused on the added TextInput.
Secondary problem is when an user clicks on another widget the TextInput stays focused.  Meaning an unfocus event cannot be fired.

Tried:

I removed setting the focus explicitly, but then the desired result to start typing after adding a TextInput is lost.
Secondary I tried setting unfocus_on_touch = True, but the TextInput stayed focused even after user left the TextInput.

Code:

```<code>import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
from kivy.uix.textinput import TextInput
from kivy.uix.bubble import Bubble
from kivy.lang import Builder

Builder.load_string('''
#: import Window kivy.core.window.Window
<Button>:
    background_normal: ''
<Label>:
    canvas.before:
        Color:
            rgba: (0,0.59,0.36,1)
        Rectangle:
            pos: self.pos
            size: self.size
<TextInput>:
    hint_text: 'Nuwe nota'
    font_size: self.height / 4.5 if self.focus else self.height / 3
    background_normal: ''
    background_active: ''
    focus: True
    foreground_color: (0,0.61,0.36,1) if self.focus else (0.71,0.75,0.71,1)
    canvas.after:
        Color:
            rgb: (0,0,0,1)
        Line:
            points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1]
    size_hint_y: None
    height: Window.height / 6 if self.focus else Window.height / 12
<ChoiceBubble>:
    orientation: 'horizontal'
    size_hint: (None, None)
    size: (160, 120)
    pos_hint: {'top': 0.2, 'right': 0.8}
    arrow_pos: 'top_left'
    BubbleButton:
        text: 'Save'
    BubbleButton:
        text: 'Encrypt..'
    BubbleButton:
        text: 'Delete'
        on_release: root.del_txt_input()
<Notation>:
    canvas:
        Color:
            rgba: (0,0.43,0.37,1)
        Rectangle:
            pos: self.pos
            size: self.size
    Label:
        pos_hint: {'top': 1, 'right': 0.8}
        size_hint: [0.8, None]
        height: Window.height / 15
    Button:
        text: 'Set'
        color: (0,0,0,1)
        pos_hint: {'top': 1, 'right': 0.9}
        size_hint: [0.1, None]
        height: Window.height / 15

    Button:
        text: '+ Plus'
        color: (0,0,0,1)
        pos_hint: {'top': 1, 'right': 1}
        size_hint: [0.1, None]
        height: Window.height / 15
        on_release: root.add_input()
    ScrollView:
        size_hint_y: None
        size: Window.width, Window.height
        pos_hint: {'top': 0.92, 'right': 1}
        GridLayout:
            id: text_holder
            cols: 1
            pos_hint: {'top': 0.92, 'right': 1}
            padding: 4
            size_hint_x: 1
            size_hint_y: None
            height: self.minimum_height

''')
class ChoiceBubble(Bubble):
    pass
class Notation(FloatLayout):
    which_txt = ObjectProperty(None)
    new_txt = ObjectProperty(None)
    def add_input(self):
        txt_hld = self.ids.text_holder
        if self.new_txt == None:
            self.new_txt = TextInput()
            txt_hld.add_widget(self.new_txt)
        else:
            self.new_txt.focus = False
            print(self.new_txt.focus)
            self.new_txt = TextInput(focus = True)
            print(self.new_txt.focus)
            txt_hld.add_widget(self.new_txt)
    def que_txt_input(self, instance):
        self.which_txt = instance
        print(instance)
    def del_txt_input(self):
        print(self.which_txt)

class theNoteApp(App):
    title = 'My Notes'
    def build(self):
        return Notation()

if __name__ == '__main__':
    theNoteApp().run()

</code>```

Desired Result:

I want to start typing after adding a new TextInput and after clicking in another widget I want the TextInput to loose focus and fire a unfocus_on_touch event?

答:
I had the same problem some time ago and I opened an issue at kivy's github page.
There is no solution yet, but there is a workaround.
You have to add these lines to your TextInput rule:

```<code>keyboard_mode: 'managed'
keyboard_on_key_down: self.show_keyboard()
</code>```

After that, its working, but with the way you add the widgets you keep focus to all of them all the time, so you have to fix this independently.

The only focus that you need is at your TextInput rule, nowhere else..

Body:
Background:

I have a button that adds TextInput widgets to a GridLayout with focus: True.  If a TextInput is already present in the layout with focus = True, the previous TextInput is firstly unfocused then a new TextInput is added with focus = True.

Problem:

Once a TextInput is added I cannot type even though the cursor is focused on the added TextInput.
Secondary problem is when an user clicks on another widget the TextInput stays focused.  Meaning an unfocus event cannot be fired.

Tried:

I removed setting the focus explicitly, but then the desired result to start typing after adding a TextInput is lost.
Secondary I tried setting unfocus_on_touch = True, but the TextInput stayed focused even after user left the TextInput.

Code:

import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
from kivy.uix.textinput import TextInput
from kivy.uix.bubble import Bubble
from kivy.lang import Builder

Builder.load_string('''
#: import Window kivy.core.window.Window
<Button>:
    background_normal: ''
:
    canvas.before:
        Color:
            rgba: (0,0.59,0.36,1)
        Rectangle:
            pos: self.pos
            size: self.size
<TextInput>:
    hint_text: 'Nuwe nota'
    font_size: self.height / 4.5 if self.focus else self.height / 3
    background_normal: ''
    background_active: ''
    focus: True
    foreground_color: (0,0.61,0.36,1) if self.focus else (0.71,0.75,0.71,1)
    canvas.after:
        Color:
            rgb: (0,0,0,1)
        Line:
            points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1]
    size_hint_y: None
    height: Window.height / 6 if self.focus else Window.height / 12
<ChoiceBubble>:
    orientation: 'horizontal'
    size_hint: (None, None)
    size: (160, 120)
    pos_hint: {'top': 0.2, 'right': 0.8}
    arrow_pos: 'top_left'
    BubbleButton:
        text: 'Save'
    BubbleButton:
        text: 'Encrypt..'
    BubbleButton:
        text: 'Delete'
        on_release: root.del_txt_input()
<Notation>:
    canvas:
        Color:
            rgba: (0,0.43,0.37,1)
        Rectangle:
            pos: self.pos
            size: self.size
    Label:
        pos_hint: {'top': 1, 'right': 0.8}
        size_hint: [0.8, None]
        height: Window.height / 15
    Button:
        text: 'Set'
        color: (0,0,0,1)
        pos_hint: {'top': 1, 'right': 0.9}
        size_hint: [0.1, None]
        height: Window.height / 15

    Button:
        text: '+ Plus'
        color: (0,0,0,1)
        pos_hint: {'top': 1, 'right': 1}
        size_hint: [0.1, None]
        height: Window.height / 15
        on_release: root.add_input()
    ScrollView:
        size_hint_y: None
        size: Window.width, Window.height
        pos_hint: {'top': 0.92, 'right': 1}
        GridLayout:
            id: text_holder
            cols: 1
            pos_hint: {'top': 0.92, 'right': 1}
            padding: 4
            size_hint_x: 1
            size_hint_y: None
            height: self.minimum_height

''')
class ChoiceBubble(Bubble):
    pass
class Notation(FloatLayout):
    which_txt = ObjectProperty(None)
    new_txt = ObjectProperty(None)
    def add_input(self):
        txt_hld = self.ids.text_holder
        if self.new_txt == None:
            self.new_txt = TextInput()
            txt_hld.add_widget(self.new_txt)
        else:
            self.new_txt.focus = False
            print(self.new_txt.focus)
            self.new_txt = TextInput(focus = True)
            print(self.new_txt.focus)
            txt_hld.add_widget(self.new_txt)
    def que_txt_input(self, instance):
        self.which_txt = instance
        print(instance)
    def del_txt_input(self):
        print(self.which_txt)

class theNoteApp(App):
    title = 'My Notes'
    def build(self):
        return Notation()

if __name__ == '__main__':
    theNoteApp().run()

Desired Result:

I want to start typing after adding a new TextInput and after clicking in another widget I want the TextInput to loose focus and fire a unfocus_on_touch event?

Body:
I had the same problem some time ago and I opened an issue at kivy's github page.
There is no solution yet, but there is a workaround.
You have to add these lines to your TextInput rule:

keyboard_mode: 'managed'
keyboard_on_key_down: self.show_keyboard()

After that, its working, but with the way you add the widgets you keep focus to all of them all the time, so you have to fix this independently.

The only focus that you need is at your TextInput rule, nowhere else..


问:
Difference between subarray, subset & subsequence
I'm a bit confused between subarray, subsequence & subset

if I have {1,2,3,4}

then

subsequence can be {1,2,4} OR {2,4} etc. So basically I can omit some elements but keep the order.

subarray would be( say subarray of size 3)

```<code>{1,2,3}
{2,3,4}
</code>```

Then what would be the subset?

I'm  bit confused between these 3.

答:
Per my understanding, for example, we have a list say [3,5,7,8,9]. here

subset doesn’t need to maintain order and has non-contiguous behavior. For example, [9,3] is a subset

subsequence maintain order and has non-contiguous behavior. For example, [5,8,9] is a subsequence

subarray maintains order and has contiguous behavior. For example, [8,9] is a subarray

Body:
I'm a bit confused between subarray, subsequence & subset

if I have {1,2,3,4}

then

subsequence can be {1,2,4} OR {2,4} etc. So basically I can omit some elements but keep the order.

subarray would be( say subarray of size 3)

{1,2,3}
{2,3,4}

Then what would be the subset?

I'm  bit confused between these 3.


问:
Debug running Tizen Web Application...?
Tizen Studio has a way to run a Web App in debug mode, which is very handy, but as soon as application is closed, the console gets disconnected as well.

I wonder if it is possible to remotely connect to already running application and debug it?

答:
Yes this is possible if the application was started in debug mode and you know the debug port. Samsung is just using Chrome DevTools. The Chrome DevTools can connect to a remote debugging session provided you know the IP and port to connect to.

Drop me a comment if you'd like more details. All the details I have are on another machine but the comment will remind me to get them for you.

Title: Debug running Tizen Web Application...?


问:
How to change cell background after content edited?
I'm importing some csv columns into a html table. I need to do some validation: if one or more than one cells for a specific column are empty then I don't allow the importing of data to my database and I highlight the empty cell with a background colour. It is a editable table; can someone explain how I can change the background colour when the empty cell has been edited and is not empty anymore?

This is what my javascript looks like so far:

function NoneEmpty(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === "") return false;
  }
  return true;
}

$(document).on('click', '#import_data', function(e) {

  if (NoneEmpty(interno) == false) {

    $('.beta tr').each(function(i) {
      var column2cell = $($(this).children('td')[2]);
      if (column2cell.text() == "") {
        column2cell.css('background-color', 'red');
      }
    });

    return;

  }

});

//This is how I build the html table after uploading the csv file

$('#upload').click(function(e) {

  // Prevent form to be submitted again after page refresh
  e.preventDefault();

  var formData = new FormData();
  formData.append('csv_file', $('#csv_file')[0].files[0]);
  // Append ajax action to formData so I can process the model from the controller
  formData.append('ajax_action', 'kmg_admin_fetch_csv_building_unit');

  $.ajax({

    method: "POST",
    data: formData,
    dataType: 'json',
    contentType: false,
    // cache:false,
    processData: false,

    success: function(data) {

      if (data.notice_code == KM_ERROR_CODE) {

        alert('err');

        $('#csv_file_data').html("
" + data.notice_message + "
");

      } else {

        var html = '
';

        if (data.column) {
          html += '
';
          for (var count = 0; count < data.column.length; count++) {
            html += '' + data.column[count] + '	';
          }
          html += '
';
        }

        if (data.row_data) {
          for (var count = 0; count < data.row_data.length; count++) {
            html += '
';
            html += '' + data.row_data[count].scala + '	';
            html += '' + data.row_data[count].piano + '	';
            html += '' + data.row_data[count].interno + '	';
            html += '' + data.row_data[count].mq + '	';
            html += '' + data.row_data[count].foglio + '	';
            html += '' + data.row_data[count].particella + '	';
            html += '' + data.row_data[count].sub + '
';

          }
        }

        html += '
';
        html += '
<button type="button" id="import_data" class="btn btn-success">Importa unità immobilari</button>
';

        $('#csv_file_data').html(html);
        $('#upload_csv')[0].reset();

      }

    }
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<form id="upload_csv" method="post" enctype="multipart/form-data">
  <div class="row">
    <div class="col-md-5">
      <div class="form-group">
        <div class="fileinput fileinput-new" data-provides="fileinput">
          <div class="input-group input-large">
            <div class="form-control uneditable-input input-fixed input-medium" data-trigger="fileinput">
              <span class="fileinput-filename"> </span>
            </div>
            <span class="input-group-addon btn default btn-file">
                                                                            <span class="fileinput-new"> Seleziona documento </span>
            <span class="fileinput-exists"> Modifica </span>
            <input type="file" name="csv_file" id="csv_file" accept=".csv">
            </span>
             Rimuovi
          </div>
        </div>
      </div>
    </div>

    {#
    <div class="col-md-1"> #}
      <button type="submit" id="upload" name="upload" class="btn blue" value="Upload"><i class="fa fa-cloud-upload"></i> Carica file csv</button> {# </div> #}
  </div>
</form>

<div class="clearfix margin-bottom-10"> </div>
<div id="csv_file_data"></div></code>```

答:
You can attach an input event listener to your rows. So each time a row's text is an empty string make it's background red, if it's not empty make it a different color.

$('.beta tr').each(function(i) {
  var column2cell = $($(this).children('td')[2]);

  if (column2cell.text() == "") {
    column2cell.css('background-color', 'red');
  }
  column2cell.on('input', function() {
    if ($(this).text() != "") {
      column2cell.css('background-color', '#dddddd');
    } else {
      column2cell.css('background-color', 'red');
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr {
  background-color: #dddddd;
}</code>```

    Company
    Contact
    Country

    Company A
    Person A

    Company B
    Person B
    Country B

    Company C
    Person C
    Country C

```

Body:
I'm importing some csv columns into a html table. I need to do some validation: if one or more than one cells for a specific column are empty then I don't allow the importing of data to my database and I highlight the empty cell with a background colour. It is a editable table; can someone explain how I can change the background colour when the empty cell has been edited and is not empty anymore?

This is what my javascript looks like so far:

function NoneEmpty(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === "") return false;
  }
  return true;
}

$(document).on('click', '#import_data', function(e) {

  if (NoneEmpty(interno) == false) {

    $('.beta tr').each(function(i) {
      var column2cell = $($(this).children('td')[2]);
      if (column2cell.text() == "") {
        column2cell.css('background-color', 'red');
      }
    });

    return;

  }

});

//This is how I build the html table after uploading the csv file

$('#upload').click(function(e) {

  // Prevent form to be submitted again after page refresh
  e.preventDefault();

  var formData = new FormData();
  formData.append('csv_file', $('#csv_file')[0].files[0]);
  // Append ajax action to formData so I can process the model from the controller
  formData.append('ajax_action', 'kmg_admin_fetch_csv_building_unit');

  $.ajax({

    method: "POST",
    data: formData,
    dataType: 'json',
    contentType: false,
    // cache:false,
    processData: false,

    success: function(data) {

      if (data.notice_code == KM_ERROR_CODE) {

        alert('err');

        $('#csv_file_data').html("
" + data.notice_message + "
");

      } else {

        var html = '
';

        if (data.column) {
          html += '
';
          for (var count = 0; count < data.column.length; count++) {
            html += '' + data.column[count] + '	';
          }
          html += '
';
        }

        if (data.row_data) {
          for (var count = 0; count < data.row_data.length; count++) {
            html += '
';
            html += '' + data.row_data[count].scala + '	';
            html += '' + data.row_data[count].piano + '	';
            html += '' + data.row_data[count].interno + '	';
            html += '' + data.row_data[count].mq + '	';
            html += '' + data.row_data[count].foglio + '	';
            html += '' + data.row_data[count].particella + '	';
            html += '' + data.row_data[count].sub + '
';

          }
        }

        html += '
';
        html += '
<button type="button" id="import_data" class="btn btn-success">Importa unità immobilari</button>
';

        $('#csv_file_data').html(html);
        $('#upload_csv')[0].reset();

      }

    }
  });

});

<form id="upload_csv" method="post" enctype="multipart/form-data">

                                                                             Seleziona documento
             Modifica
            <input type="file" name="csv_file" id="csv_file" accept=".csv">

             Rimuovi

    {#

 #}
      <button type="submit" id="upload" name="upload" class="btn blue" value="Upload"> Carica file csv</button> {#
 #}

</form>

Body:
You can attach an input event listener to your rows. So each time a row's text is an empty string make it's background red, if it's not empty make it a different color.

$('.beta tr').each(function(i) {
  var column2cell = $($(this).children('td')[2]);

  if (column2cell.text() == "") {
    column2cell.css('background-color', 'red');
  }
  column2cell.on('input', function() {
    if ($(this).text() != "") {
      column2cell.css('background-color', '#dddddd');
    } else {
      column2cell.css('background-color', 'red');
    }
  });
});

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr {
  background-color: #dddddd;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="beta">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td contentEditable="true">Company A</td>
    <td contentEditable="true">Person A</td>
    <td contentEditable="true"></td>
  </tr>
  <tr>
    <td contentEditable="true">Company B</td>
    <td contentEditable="true">Person B</td>
    <td contentEditable="true">Country B</td>
  </tr>
  <tr>
    <td contentEditable="true">Company C</td>
    <td contentEditable="true">Person C</td>
    <td contentEditable="true">Country C</td>
  </tr>
</table>


问:
Iphone get coords in background
Can I make iphone app that get coords from gps in 2 seconds and save them in file. In the end of the day I should send via mail?</p>

答: You cannot tell the Core Location framework to alert your app every 2 seconds with GPS information.  Your app can use the Significant-Change Location Service.  So if the device is in a car on the highway, that could well be every 2 seconds.  But if the device is traveling by foot, then that depends on how fast the user is walking.  Then you can use a Local Notification to alert the user and bring the app from the background at the end of the day.</p>

Title: Iphone get coords in background


问:
I need to change my wordpress theme's add on to my desired design
This is my first topic here. I need help with my WordPress theme. This is my site I need the help with, https://assetbangla.com/

Here there is an advanced search option at the beginning of the site. Like this. https://i.imgur.com/gjLwRgt.jpg

Now I want this to look like this in both desktop and laptop. https://i.imgur.com/kgyBOMi.jpg

And on the mobile, I need to fix this. Right now it’s showing distorted…
https://i.imgur.com/xUxlX7v.jpg

Please help me with this. It will be a world to me. Thanks so much.

答:
Given the class name "wppb-builder-container" it looks like the plugin "Profile Builder" by Cozmolabs was used to create this form. In that case you should find a "Profile Builder" section in your admin area:

Screenshot of Profile Builder in Wordpress admin area

You can find the documentation for the plugin here:
https://www.cozmoslabs.com/docs/profile-builder-2/

And you can reach the support of Cozmolabs here:
https://www.cozmoslabs.com/support/open-ticket/


问:
Should return empty list [] 200/204 or 404 in a Restful API design?
For example, there's a restful API GET http://luexu.com/users/{page} to list the users in Nth page. Suppose there're 20 users in each page. There're 100 users total in the database. GET http://luexu.com/users/5 returns the 80th to 100th users.

So how about query GET http://luexu.com/users/10? it's out of the total users. Which is a better design to return an empty list, empty array [] or 404?

200?

```<code>{
    "code": 200,
    "msg": "OK",
    "data": []
}
</code>```

or 204?

```<code>{
    "code": 204,
    "msg": "OK",
    "data": []
}
</code>```

or 404?

```<code>{
    "code": 404,
    "msg": "Not Found",
    "data": null
}
</code>```

答:
Returning 404 won't fit cases where you have partial page(e.g you have 85 users), so i'd go with an empty list, 404 suites better when you have a binary question, resource found or not.

I would take a look in the following similar question:
Rest service returns 404

Body:
For example, there's a restful API GET http://luexu.com/users/{page} to list the users in Nth page. Suppose there're 20 users in each page. There're 100 users total in the database. GET http://luexu.com/users/5 returns the 80th to 100th users.

So how about query GET http://luexu.com/users/10? it's out of the total users. Which is a better design to return an empty list, empty array [] or 404?

200?

{
    "code": 200,
    "msg": "OK",
    "data": []
}

or 204?

{
    "code": 204,
    "msg": "OK",
    "data": []
}

or 404?

{
    "code": 404,
    "msg": "Not Found",
    "data": null
}


问:
Change key of entries in PHP array
I'm currently trying to build a complex function to re-order the positions of some sections (div's) which are defined in a PHP array.

So for example I've this array here:

```<code>$sections = array(
    0 => 'section_one',
    1 => 'section_two',
    2 => 'section_three',
    3 => 'section_four',
    4 => 'section_five',
    5 => 'section_six',
    6 => 'section_seven'
);
</code>```

Which turns out like this:

```<code>array(7) { [0]=> string(11) "section_one" [1]=> string(11) "section_two" [2]=> string(13) "section_three" [3]=> string(12) "section_four" [4]=> string(12) "section_five" [5]=> string(11) "section_six" [6]=> string(13) "section_seven" }
</code>```

When the user moves now the section six before section two on my website, I need to change the key of section six to 1 and move every key one number up after the moved section. So section_two becomes the key 2 and so on...

Any idea how I can do this? I know that I can replace keys this way:

```<code>$arr[ $newkey ] = $arr[ $oldkey ];
unset( $arr[ $oldkey ] );
</code>```

When the user finished a move of an element, I know the name like section_six and the new position of the element.

After re-ordering / re-placing the keys, the array must look like this:

```<code>$sections_a = array(
    0 => 'section_one',
    1 => 'section_six',
    2 => 'section_two',
    3 => 'section_three',
    4 => 'section_four',
    5 => 'section_five',
    6 => 'section_seven'
);
</code>```

答:
One option is to copy the array and use array_splice

```<code>$sections = array(
    0 => 'section_one',
    1 => 'section_two',
    2 => 'section_three',
    3 => 'section_four',
    4 => 'section_five',
    5 => 'section_six',
    6 => 'section_seven'
);

$oldkey = 5;
$newkey = 1;

$sections_a = $sections;
array_splice( $sections_a, $newkey, 0, array_splice( $sections_a, $oldkey, 1) );
</code>```

This will result to:

```<code>Array
(
    [0] => section_one
    [1] => section_six
    [2] => section_two
    [3] => section_three
    [4] => section_four
    [5] => section_five
    [6] => section_seven
)
</code>```

Title: Change key of entries in PHP array

Body:
I'm currently trying to build a complex function to re-order the positions of some sections (div's) which are defined in a PHP array.

So for example I've this array here:

$sections = array(
    0 => 'section_one',
    1 => 'section_two',
    2 => 'section_three',
    3 => 'section_four',
    4 => 'section_five',
    5 => 'section_six',
    6 => 'section_seven'
);

Which turns out like this:

array(7) { [0]=> string(11) "section_one" [1]=> string(11) "section_two" [2]=> string(13) "section_three" [3]=> string(12) "section_four" [4]=> string(12) "section_five" [5]=> string(11) "section_six" [6]=> string(13) "section_seven" }

When the user moves now the section six before section two on my website, I need to change the key of section six to 1 and move every key one number up after the moved section. So section_two becomes the key 2 and so on...

Any idea how I can do this? I know that I can replace keys this way:

$arr[ $newkey ] = $arr[ $oldkey ];
unset( $arr[ $oldkey ] );

When the user finished a move of an element, I know the name like section_six and the new position of the element.

After re-ordering / re-placing the keys, the array must look like this:

$sections_a = array(
    0 => 'section_one',
    1 => 'section_six',
    2 => 'section_two',
    3 => 'section_three',
    4 => 'section_four',
    5 => 'section_five',
    6 => 'section_seven'
);

Body:
One option is to copy the array and use array_splice

$sections = array(
    0 => 'section_one',
    1 => 'section_two',
    2 => 'section_three',
    3 => 'section_four',
    4 => 'section_five',
    5 => 'section_six',
    6 => 'section_seven'
);

$oldkey = 5;
$newkey = 1;

$sections_a = $sections;
array_splice( $sections_a, $newkey, 0, array_splice( $sections_a, $oldkey, 1) );

This will result to:

Array
(
    [0] => section_one
    [1] => section_six
    [2] => section_two
    [3] => section_three
    [4] => section_four
    [5] => section_five
    [6] => section_seven
)


问:
Filter pandas DataFrame by substring criteria
I have a pandas DataFrame with a column of string values. I need to select rows based on partial string matches.

Something like this idiom:

```<code>re.search(pattern, cell_in_question)
</code>```

returning a boolean. I am familiar with the syntax of df[df['A'] == "hello world"] but can't seem to find a way to do the same with a partial string match, say 'hello'.

答:
There are answers before this which accomplish the asked feature, anyway I would like to show the most generally way:

```<code>df.filter(regex=".*STRING_YOU_LOOK_FOR.*")
</code>```

This way let's you get the column you look for whatever the way is wrote.

( Obviusly, you have to write the proper regex expression for each case )

Body:
I have a pandas DataFrame with a column of string values. I need to select rows based on partial string matches.

Something like this idiom:

re.search(pattern, cell_in_question)

returning a boolean. I am familiar with the syntax of df[df['A'] == "hello world"] but can't seem to find a way to do the same with a partial string match, say 'hello'.

Body:
There are answers before this which accomplish the asked feature, anyway I would like to show the most generally way:

df.filter(regex=".*STRING_YOU_LOOK_FOR.*")

This way let's you get the column you look for whatever the way is wrote.

( Obviusly, you have to write the proper regex expression for each case )


问:
How do I draw android.graphics.drawable.Icon on canvas?
I'm startled.
I was sure Icon will behave an any other drawable. But I don't see any draw or setBounds methods. I can't find any examples of outputting Icon(lot of them for creating one from bitmap). How do I draw something I have as  android.graphics.drawable.Icon on canvas in specific place?</p>

答:
you can use loadDrawable(Context context) method to get a Drawable object as mentioned in the official documentation

Returns a Drawable that can be used to draw the image inside this Icon, constructing it if necessary. Depending on the type of image, this may not be something you want to do on the UI thread, so consider using loadDrawableAsync instead.

Context: Context in which to load the drawable; used to access Resources, for example.

Returns : A fresh instance of a drawable for this image, yours to keep.


问:
Can I prevent my custom class from being sympified?
I am building my custom class, which is a subclass of object. (No other superclass is in option because of __r(operator)__ priority.)

Since this class is not sympy class, it is sympified whenever I try to apply it to sympy functions, and this is causing troubles.

Is there any way to make it return itself when it is sympified? For example, just like sympify(sin(x)) returns sin(x), I want the instance of my class to behave in such way: sympify(instance) to return instance.

答: Try adding a def for _sympy_ in your class: def _sympy_(self): return self or maybe Basic(self)...but then SymPy won't be able to work with such expressions. Can you give an example of what you are trying to do? There is the CantSympify mixin available, too, but that will prevent the object from being sympified at all.


问:
AttributeError: module 'datetime' has no attribute 'today' error while executing tests using Selenium GeckoDriver and Firefox through Python
The code using Selenium webdriver shows me error after setup.

I tried to setup different ways: for Google web driver, for Firefox.

I tried with and without showing the path to the driver (Chrome driver and gecko driver that we can find on Stack Overflow)

I tried to show the path with and without raw before the path to the file

I tried to find similar issues on Internet but didn't found.

Here is the code:

```<code>from selenium import webdriver as wd

driver = wd.Firefox(executable_path=r'C:\Users\User\Downloads\geckodriver-v0.24.0-win64')
driver.get('https://youtube.com')
</code>```

I was expecting the code lauching Firefox then go on YouTube it shows me this:

```<code>   (most recent call last):
  File "C:/Users/User/.PyCharmCE2018.3/config/scratches/tringseln.py", line 1, in <module>
    from selenium import webdriver as wd
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\selenium\webdriver\__init__.py", line 18, in <module>
    from .firefox.webdriver import WebDriver as Firefox  # noqa
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 29, in <module>
    from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 27, in <module>
    from .remote_connection import RemoteConnection
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 24, in <module>
    import urllib3
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\__init__.py", line 7, in <module>
    from .connectionpool import (
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\connectionpool.py", line 11, in <module>
    from .exceptions import (
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\exceptions.py", line 2, in <module>
    from .packages.six.moves.http_client import (
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 668, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 638, in _load_backward_compatible
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\packages\six.py", line 203, in load_module
    mod = mod._resolve()
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\packages\six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module
    __import__(name)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 71, in <module>
    import email.parser
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\email\parser.py", line 12, in <module>
    from email.feedparser import FeedParser, BytesFeedParser
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\email\feedparser.py", line 27, in <module>
    from email._policybase import compat32
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\email\_policybase.py", line 9, in <module>
    from email.utils import _has_surrogates
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\email\utils.py", line 30, in <module>
    import datetime
  File "C:\Users\User\.PyCharmCE2018.3\config\scratches\datetime.py", line 2, in <module>
    tday = datetime.datetime.today()
AttributeError: module 'datetime' has no attribute 'today'
</code>```

If someone helps me would be really great. Thanks for your time.

答:
This error is from the line of code in your script.

```<code>tday = datetime.datetime.today()  # <===== there is no today method `today` for datetime
</code>```

Check  this error message in trackback AttributeError: module 'datetime' has no attribute 'today'

Body:
The code using Selenium webdriver shows me error after setup.

I tried to setup different ways: for Google web driver, for Firefox.

I tried with and without showing the path to the driver (Chrome driver and gecko driver that we can find on Stack Overflow)

I tried to show the path with and without raw before the path to the file

I tried to find similar issues on Internet but didn't found.

Here is the code:

from selenium import webdriver as wd

driver = wd.Firefox(executable_path=r'C:\Users\User\Downloads\geckodriver-v0.24.0-win64')
driver.get('https://youtube.com')

I was expecting the code lauching Firefox then go on YouTube it shows me this:

   (most recent call last):
  File "C:/Users/User/.PyCharmCE2018.3/config/scratches/tringseln.py", line 1, in <module>
    from selenium import webdriver as wd
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\selenium\webdriver\__init__.py", line 18, in <module>
    from .firefox.webdriver import WebDriver as Firefox  # noqa
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 29, in <module>
    from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 27, in <module>
    from .remote_connection import RemoteConnection
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 24, in <module>
    import urllib3
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\__init__.py", line 7, in <module>
    from .connectionpool import (
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\connectionpool.py", line 11, in <module>
    from .exceptions import (
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\exceptions.py", line 2, in <module>
    from .packages.six.moves.http_client import (
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 668, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 638, in _load_backward_compatible
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\packages\six.py", line 203, in load_module
    mod = mod._resolve()
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\packages\six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "C:\Users\User\PycharmProjects\instasubs and generators\venv\lib\site-packages\urllib3\packages\six.py", line 82, in _import_module
    __import__(name)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 71, in <module>
    import email.parser
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\email\parser.py", line 12, in <module>
    from email.feedparser import FeedParser, BytesFeedParser
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\email\feedparser.py", line 27, in <module>
    from email._policybase import compat32
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\email\_policybase.py", line 9, in <module>
    from email.utils import _has_surrogates
  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\email\utils.py", line 30, in <module>
    import datetime
  File "C:\Users\User\.PyCharmCE2018.3\config\scratches\datetime.py", line 2, in <module>
    tday = datetime.datetime.today()
AttributeError: module 'datetime' has no attribute 'today'

If someone helps me would be really great. Thanks for your time.

Body:
This error is from the line of code in your script.

tday = datetime.datetime.today()  # <===== there is no today method `today` for datetime

Check  this error message in trackback AttributeError: module 'datetime' has no attribute 'today'


问:
Cannot read property 'ScrollView' of undefined on React-Native and React-Navigation 3.x
When I follow the instruction from https://reactnavigation.org/docs/en/getting-started.html

and run the application, I have this error

Requiring module "node_modules/react-native-gesture-handler/index.js", which threw an exception: TypeError:

  "dependencies": {
    "react": "^16.8.6",
    "react-art": "^16.6.3",
    "react-dom": "16.8.6",
    "react-native": "^0.59.8",
    "react-native-gesture-handler": "^1.2.2",
    "react-native-modal-selector": "^1.0.3",
    "react-native-vector-icons": "^6.1.0",
    "react-native-web": "0.11.2",
    "react-navigation": "^3.0.0"
  },
  "resolutions": {
    "uglify-es": "3.2.2"
  },
  "devDependencies": {
    "@types/jest": "24.0.12",
    "@types/node": "^10.12.12",
    "@types/react": "16.8.15",
    "@types/react-dom": "^16.0.11",
    "@types/react-native": "^0.57.60",
    "@types/react-navigation": "^3.0.7",
    "@types/react-test-renderer": "16.8.1",
    "babel-jest": "24.7.1",
    "jest": "24.7.1",
    "metro-react-native-babel-preset": "0.50.0",
    "prettier": "1.17.0",
    "react-art": "16.8.6",
    "react-native-typescript-transformer": "^1.2.10",
    "react-scripts": "3.0.0",
    "react-scripts-ts": "^3.1.0",
    "react-test-renderer": "16.8.6",
    "ts-jest": "24.0.2",
    "tslint": "5.16.0",
    "tslint-config-prettier": "1.18.0",
    "typescript": "3.4.5"
  },```

答:
You need to install react-native-gesture-handler package to make it works   npm install --save react-native-gesture-handler and link it.

Complete installation guide can be found here: https://kmagiera.github.io/react-native-gesture-handler/docs/getting-started.html


问:
Immutable vs Observable collections in Flutter
When using Flutter with realtime databases, such as Firebase Database, it is beneficial to know not just that a collection has been updated, but where exactly. Such as to show a pretty list animation, or trigger some additional events based on which item has updated. Dart already has an amazing infrastructure for delivering events.

A canonical example is to use a FirebaseAnimatedList, but it's glued to Firebase and doesn't support filtering and ordering (outside of very basic Firebase model). I am looking for a more generic solution, which would allow to inject some logic between database (that notifies of item change/insert/delete), and aforementioned AnimatedList, which expects the same events.

Most recent tendency seems to be in favor of immutable collections, such as built_value, which makes a lot of sense in Dart, as object creation is very cheap. However, immutable collections do not have a way of telling which item has changed, they simply deliver a new collection. This approach also makes it difficult to attach some local information to an item, such as "selected" bit when user multi-selects items, or custom ordering. Because, well, items are immutable, and their reference (aka pointer, aka object ID) keeps changing.

One alternative solution is to implement a kind of observable list, such as what package:observable offers, but it seems that its authors are not convinced of its popularity anymore. So what is the approach you take to create animated, filtered, sorted, selection-supporting lists in Flutter, backed by a realtime database?

答:
However, immutable collections do not have a way of telling which item has changed, they simply deliver a new collection.

Some pseudo code: (old collection) - (new collection) = (what changed) - works the other way around too.

This approach also makes it difficult to attach some local information to an item, such as "selected" bit when user multi-selects items, or custom ordering.

Extend said 'item' and add a property selected (or order, or any other info you want available), then just construct the new list with these properties properly set.

There are a lot of state-management-with-Flutter-related questions around these days, so to avoid repeating myself, I would rather link you to an answer of mine from earlier today.

Edit:

I just want to insert a practical example regarding (old collection) - (new collection) = (what changed):

Basically this is how to see what changed when comparing 2 lists, containing closely related elements.

List currentState = [...];
List nextState = [...];

List addedItems = nextState.where((e) => !currentState.contains(e)).toList(),
List removedItems = currentState.where((e) => !nextState.contains(e)).toList();

doSomethingWith(addedItems);
doSomethingElseWith(removedItems);
```

Of course you should keep in mind that the Lists should be deeply comparable, i.e. for Dart's specific case you can use built_value or equatable packages.

I have also uploaded a repository, with a pure Dart project example. You're more than welcome to do whatever you want with the code.

Body:
However, immutable collections do not have a way of telling which item has changed, they simply deliver a new collection.

Some pseudo code: (old collection) - (new collection) = (what changed) - works the other way around too.

This approach also makes it difficult to attach some local information to an item, such as "selected" bit when user multi-selects items, or custom ordering.

Extend said 'item' and add a property selected (or order, or any other info you want available), then just construct the new list with these properties properly set.

There are a lot of state-management-with-Flutter-related questions around these days, so to avoid repeating myself, I would rather link you to an answer of mine from earlier today.

Edit:

I just want to insert a practical example regarding (old collection) - (new collection) = (what changed):

Basically this is how to see what changed when comparing 2 lists, containing closely related elements.

List currentState = [...];
List nextState = [...];

List addedItems = nextState.where((e) => !currentState.contains(e)).toList(),
List removedItems = currentState.where((e) => !nextState.contains(e)).toList();

doSomethingWith(addedItems);
doSomethingElseWith(removedItems);

Of course you should keep in mind that the Lists should be deeply comparable, i.e. for Dart's specific case you can use built_value or equatable packages.

I have also uploaded a repository, with a pure Dart project example. You're more than welcome to do whatever you want with the code.


问:
Randomly Cant connect to local MySQL?
This might be related to another problem i am having. But in this case my app was idling and i had a crash in my GetConnection() on conn.open().

Since i was idling i figure it had comething to do with my queue in the background and possibly garbage collection? I took a look at netstat and found 16 connections.

Does mysql only accept 16 connections by default? is it because i am opening too many connections? this IS because of not closing/disposing connections? might commands have something to do with it or is that completely not the problem and is a MySqlConnection issue?

```<code>  TCP    127.0.0.1:7919          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7920          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7921          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7922          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7923          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7924          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7926          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8782          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8783          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8784          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8785          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8786          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8787          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8788          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8791          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8792          Adam-PC:3306          ESTABLISHED
</code>```

答: I've encountered this when using the MySQL connector. The work around I use is to manually turn off connection pooling in the connection string by adding "pooling=false;" to the end of the connection string. It will hurt your scalability but allow your application to run.</p>

ContentLicense: CC BY-SA 2.5

Title: Randomly Cant connect to local MySQL?

Body:
This might be related to another problem i am having. But in this case my app was idling and i had a crash in my GetConnection() on conn.open().

Since i was idling i figure it had comething to do with my queue in the background and possibly garbage collection? I took a look at netstat and found 16 connections.

Does mysql only accept 16 connections by default? is it because i am opening too many connections? this IS because of not closing/disposing connections? might commands have something to do with it or is that completely not the problem and is a MySqlConnection issue?

  TCP    127.0.0.1:7919          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7920          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7921          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7922          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7923          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7924          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:7926          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8782          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8783          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8784          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8785          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8786          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8787          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8788          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8791          Adam-PC:3306          ESTABLISHED
  TCP    127.0.0.1:8792          Adam-PC:3306          ESTABLISHED


问:
re.search().TypeError: cannot use a string pattern on a bytes-like object
```<code>import urllib.request
import re

f = urllib.request.urlopen('http://www.geekynu.cn/')
html = f.read()

title = re.search('<title>(.*?)</title>', html)
print(title)
#print(title.decode('utf-8')) //I had try to solve by this code.
</code>```

[python 3.5] when I use re.search()to read the Web title,the error is hapen"TypeError: cannot use a string pattern on a bytes-like object", what should I do? THX!

答: If you could add html=html.decode('utf-8'), I think it will be ok.

Body:
import urllib.request
import re

f = urllib.request.urlopen('http://www.geekynu.cn/')
html = f.read()

title = re.search('<title>(.*?)</title>', html)
print(title)
#print(title.decode('utf-8')) //I had try to solve by this code.

[python 3.5] when I use re.search()to read the Web title,the error is hapen"TypeError: cannot use a string pattern on a bytes-like object", what should I do? THX!


问:
how can I retrieve data from my backend in a table with reactjs?
I want to retrieve all usernames from my django backend using axios. The users where shown in a console, but all the details data:(username email...) ,headers, token ....
 So I want to restrict that to just get the data or just show the data in the console
 After that I want to know how can i put the usernames in a table or a list

This is my retrieve function :

```<code> const RetrievUsers=()=>{
      axios.get('http://127.0.0.1:8000/user/list')
      .then(data =>
      console.log(data)
     )

    .catch(err=>console.log(err))

    }
</code>```

The data in my back-end looks like this:

```<code>"username": "pol",
        "password": "**********************",
        "nom": "a",
        "prenom": "a",
        "email": "a@gmail.com",
        "residence": "po",
        "phone": "po"
</code>```

console :

```<code>{data: Array(2), status: code, statusText: " ", headers: {…}, config: {…}, …}config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, @@@}

/I need only this part
data:Array(2)
0: email: "a@gmail.com"nom:"a "password: "***pbkd g=" phone: "po"
prenom: "a"residence: "po"username: "pol"__proto__: Object
1: email: "a@gmail.com" nom: "a" password: "*****A4=" phone: "a"
prenom: "a"residence: "pass"username: "a"__proto__: Object
//
length: 2__proto__: Array(0)headers: { }request: XMLHttpRequest {onreadystatechange:   …}status:
</code>```

答:
for filtering the username just try consoling like this

```<code>console.log(data.data[0].username);
</code>```

for looping through the data try this

```<code>data.data.forEach(function(element) {
  console.log(element.username);
});
</code>```

Body:
I want to retrieve all usernames from my django backend using axios. The users where shown in a console, but all the details data:(username email...) ,headers, token ....
 So I want to restrict that to just get the data or just show the data in the console
 After that I want to know how can i put the usernames in a table or a list

This is my retrieve function :

 const RetrievUsers=()=>{
      axios.get('http://127.0.0.1:8000/user/list')
      .then(data =>
      console.log(data)
     )

    .catch(err=>console.log(err))

    }

The data in my back-end looks like this:

"username": "pol",
        "password": "**********************",
        "nom": "a",
        "prenom": "a",
        "email": "a@gmail.com",
        "residence": "po",
        "phone": "po"

console :

{data: Array(2), status: code, statusText: " ", headers: {…}, config: {…}, …}config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, @@@}

/I need only this part
data:Array(2)
0: email: "a@gmail.com"nom:"a "password: "***pbkd g=" phone: "po"
prenom: "a"residence: "po"username: "pol"__proto__: Object
1: email: "a@gmail.com" nom: "a" password: "*****A4=" phone: "a"
prenom: "a"residence: "pass"username: "a"__proto__: Object
//
length: 2__proto__: Array(0)headers: { }request: XMLHttpRequest {onreadystatechange:   …}status:

Body:
for filtering the username just try consoling like this

console.log(data.data[0].username);

for looping through the data try this

data.data.forEach(function(element) {
  console.log(element.username);
});


问:
How to fix the position of main panel in r shiny
I have the following ui function for which I want to make mainpanel map fixed so when I scroll the sidebarPanel it shouldn't scroll along with that.

Also how can I remove the whitespace between sidebar and main panel.

```<code>ui <- fluidPage(

    sidebarLayout(position="right", fluid=TRUE,

    # Sidebar panel for inputs ----
    sidebarPanel(

      #h3("Airbnb Explorer"),

      selectInput("nhd","Select Neighbourhood", choices=unique(airbnb_Data$neighbourhood), selected = NULL, multiple = FALSE,selectize = TRUE, width = NULL, size = NULL),
      uiOutput("selYear"),
      uiOutput("selRoomType"),

      plotlyOutput("ListingsPlot", height = 200), #%>% withSpinner(),
      br(),
      plotlyOutput("ListingsAvailPlot", height = 200), # %>% withSpinner(),
      br(),
      plotlyOutput("AvailPiePlot", height = 200), # %>% withSpinner(),
      br(),
      plotlyOutput("ListingsPerHost", height = 200) # %>% withSpinner()

    ),

    # Main panel for displaying outputs ----
    mainPanel(
      # Output: Histogram ----
      leafletOutput("nhdMap",width = "100%", height = "650px") #, width = "100%", height = "100%") %>% withSpinner()
    )

  )
)
</code>```

答:
An option:

```<code>library(shiny)

ui <- fluidPage(

  div(
    style = "display:flex; align-items:flex-start",
    wellPanel( #~~ Sidebar ~~#
      style = "overflow-y: auto; position:fixed; width:300px; top:0; bottom:0",
      sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins2", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins3", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins4", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins5", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins6", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins7", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins8", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins9", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins10", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins11", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins12", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins13", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins14", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins15", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins16", "Number of bins:", min = 1, max = 50, value = 30)
    ),
    div( #~~ Main panel ~~#
      titlePanel("Old Faithful Geyser Data"),
      style = "flex-grow:1; resize:horizontal; overflow: hidden; position:relative; margin-left: 310px",
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })
}

shinyApp(ui = ui, server = server)
</code>```

If you want the sidebar at right, swap the two elements of the flexbox and set right:0 for the sidebar:

```<code>ui <- fluidPage(

  div(
    style = "display:flex; align-items:flex-start",
    div( #~~ Main panel ~~#
      titlePanel("Old Faithful Geyser Data"),
      style = "flex-grow:1; resize:horizontal; overflow: hidden; position:relative; margin-right: 310px",
      plotOutput("distPlot")
    ),
    wellPanel( #~~ Sidebar ~~#
      style = "overflow-y: auto; position:fixed; width:300px; top:0; bottom:0;; right:0",
      sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins2", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins3", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins4", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins5", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins6", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins7", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins8", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins9", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins10", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins11", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins12", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins13", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins14", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins15", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins16", "Number of bins:", min = 1, max = 50, value = 30)
    )
  )
)
</code>```

Body:
I have the following ui function for which I want to make mainpanel map fixed so when I scroll the sidebarPanel it shouldn't scroll along with that.

Also how can I remove the whitespace between sidebar and main panel.

ui <- fluidPage(

    sidebarLayout(position="right", fluid=TRUE,

    # Sidebar panel for inputs ----
    sidebarPanel(

      #h3("Airbnb Explorer"),

      selectInput("nhd","Select Neighbourhood", choices=unique(airbnb_Data$neighbourhood), selected = NULL, multiple = FALSE,selectize = TRUE, width = NULL, size = NULL),
      uiOutput("selYear"),
      uiOutput("selRoomType"),

      plotlyOutput("ListingsPlot", height = 200), #%>% withSpinner(),
      br(),
      plotlyOutput("ListingsAvailPlot", height = 200), # %>% withSpinner(),
      br(),
      plotlyOutput("AvailPiePlot", height = 200), # %>% withSpinner(),
      br(),
      plotlyOutput("ListingsPerHost", height = 200) # %>% withSpinner()

    ),

    # Main panel for displaying outputs ----
    mainPanel(
      # Output: Histogram ----
      leafletOutput("nhdMap",width = "100%", height = "650px") #, width = "100%", height = "100%") %>% withSpinner()
    )

  )
)

Body:
An option:

library(shiny)

ui <- fluidPage(

  div(
    style = "display:flex; align-items:flex-start",
    wellPanel( #~~ Sidebar ~~#
      style = "overflow-y: auto; position:fixed; width:300px; top:0; bottom:0",
      sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins2", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins3", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins4", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins5", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins6", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins7", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins8", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins9", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins10", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins11", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins12", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins13", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins14", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins15", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins16", "Number of bins:", min = 1, max = 50, value = 30)
    ),
    div( #~~ Main panel ~~#
      titlePanel("Old Faithful Geyser Data"),
      style = "flex-grow:1; resize:horizontal; overflow: hidden; position:relative; margin-left: 310px",
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })
}

shinyApp(ui = ui, server = server)

If you want the sidebar at right, swap the two elements of the flexbox and set right:0 for the sidebar:

ui <- fluidPage(

  div(
    style = "display:flex; align-items:flex-start",
    div( #~~ Main panel ~~#
      titlePanel("Old Faithful Geyser Data"),
      style = "flex-grow:1; resize:horizontal; overflow: hidden; position:relative; margin-right: 310px",
      plotOutput("distPlot")
    ),
    wellPanel( #~~ Sidebar ~~#
      style = "overflow-y: auto; position:fixed; width:300px; top:0; bottom:0;; right:0",
      sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins2", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins3", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins4", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins5", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins6", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins7", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins8", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins9", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins10", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins11", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins12", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins13", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins14", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins15", "Number of bins:", min = 1, max = 50, value = 30),
      br(),
      sliderInput("bins16", "Number of bins:", min = 1, max = 50, value = 30)
    )
  )
)