问:
Why is for loop and if statement not working correctly for two lists in python?
I have some data to read and I don't know why my code is not working. I want to read multiple netcdf files and store them in a ds. Here my simplified input (I have ~400 entries in my lists names and file_paths, not 4):

```<code>names = ['a','b','c','d']
file_paths = ['file_path_a','file_path_b',file_path_c',file_path_d']
number_of_measurements = []

for a, b in zip(names, file_paths):
    a = xr.open_dataset(b, group='data')
    number_of_measurements.append(len(a.datetime))
</code>```

I want to remove the files_paths and the entries in the number_of_measurements when len(a.datetime) == 0 (this means that no measurements where done). I need the number_of_measurements to create a counter for an other function.

I tried this:

```<code>for i, j in zip(number_of_measurements, file_paths):
    if i == 0:
       file_paths.remove(j)
       number_of_measurements.remove(i)
</code>```

This seems to work but not always, before this for loop I had number_of_measurements.count(0) = 33 and after the for loop I had number_of_measurements = 4. When I did the for loop twice I had the wanted number_of_measurements.count(0) = 0. Why is it not working correctly for the first time?

I also tried this within the first for loop, but it is not working either and I don't know why:

```<code>for a, b in zip(names, file_paths):
    a = xr.open_dataset(b, group='data')
    if len(a.datetime) == 0:
        file_paths.remove(b)
    else:
        number_of_measurements.append(len(a.datetime))
</code>```

答:
It is generally not advisable to modify an sequence when iterating over itself.
For example:

```<code>li = [1, 2, 3]
for x in li:
    l.remove(x)
</code>```

One might expect li is now an empty list. However,

```<code>>>> li
>>> [2]
</code>```

This is due to how list iterator works. In the first iteration of the for loop, x is assigned the first element of the list 1. Then 1 is removed from the list. li now holds [2, 3]. When the for loop moves on to the second iteration, x is assigned the second element of the list. But the second element of the list is 3 now. Hence 2 is never removed from the list.

For your purpose, you can build a new list instead of modifying the original though.

```<code>number_of_measurements = []
file_paths_new = []
for b in file_paths:
    x = len(xr.open_dataset(b, group='data').datetime)
    if x != 0:
        number_of_measurements.append(x)
        file_paths_new.append(x)
file_paths = file_paths_new
</code>```

Body:
I have some data to read and I don't know why my code is not working. I want to read multiple netcdf files and store them in a ds. Here my simplified input (I have ~400 entries in my lists names and file_paths, not 4):

names = ['a','b','c','d']
file_paths = ['file_path_a','file_path_b',file_path_c',file_path_d']
number_of_measurements = []

for a, b in zip(names, file_paths):
    a = xr.open_dataset(b, group='data')
    number_of_measurements.append(len(a.datetime))

I want to remove the files_paths and the entries in the number_of_measurements when len(a.datetime) == 0 (this means that no measurements where done). I need the number_of_measurements to create a counter for an other function.

I tried this:

for i, j in zip(number_of_measurements, file_paths):
    if i == 0:
       file_paths.remove(j)
       number_of_measurements.remove(i)

This seems to work but not always, before this for loop I had number_of_measurements.count(0) = 33 and after the for loop I had number_of_measurements = 4. When I did the for loop twice I had the wanted number_of_measurements.count(0) = 0. Why is it not working correctly for the first time?

I also tried this within the first for loop, but it is not working either and I don't know why:

for a, b in zip(names, file_paths):
    a = xr.open_dataset(b, group='data')
    if len(a.datetime) == 0:
        file_paths.remove(b)
    else:
        number_of_measurements.append(len(a.datetime))

Body:
It is generally not advisable to modify an sequence when iterating over itself.
For example:

li = [1, 2, 3]
for x in li:
    l.remove(x)

One might expect li is now an empty list. However,

>>> li
>>> [2]

This is due to how list iterator works. In the first iteration of the for loop, x is assigned the first element of the list 1. Then 1 is removed from the list. li now holds [2, 3]. When the for loop moves on to the second iteration, x is assigned the second element of the list. But the second element of the list is 3 now. Hence 2 is never removed from the list.

For your purpose, you can build a new list instead of modifying the original though.

number_of_measurements = []
file_paths_new = []
for b in file_paths:
    x = len(xr.open_dataset(b, group='data').datetime)
    if x != 0:
        number_of_measurements.append(x)
        file_paths_new.append(x)
file_paths = file_paths_new


来源: stackexchange

问:
Error: Client does not support authentication protocol requested by server; consider upgrading MySQL client
While executing a JDBC program, I get the following error while connecting to database:

```<code>Exception in thread "main"
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does
not support authentication protocol requested by server; consider upgrading
MySQL client
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:885)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3421)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1247)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at main.java.MyFirstJdbcProgram.readDataBase(MyFirstJdbcProgram.java:23)
at main.java.Main.main(Main.java:6)
</code>```

When I researched this, I got to know that the below error is because I need to grant the privileges to the user, so follow

mysql -u root -p

then entered the password

then I ran

```<code>GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'mypassword';
</code>```

and also I used

```<code>UPDATE user SET authentication_string=password('mypassword') WHERE user='root';
</code>```

But I'm getting below error

ERROR 1064 (42000): You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near 'IDENTIFIED BY 'mypassword'' at line 1

答:
If you are installing Jasper server with MySQL-8.
And you're getting above error OR 'Access denied for user root@localhost' while running js-install-ce.bat / js-install-ce.bat test .

Run mysql query:
SELECT user,authentication_string,plugin,host FROM mysql.user;

Check the plugin column for ‘root’ user, it has to be ‘mysql_native_password’. If the plugin value is ‘caching_sha2_password’ then you need to run update query:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';

OR

Re-Install MySQL.
You just have to re-install MySQL-8 with Authentication Method as:
"Use Legacy Authentication Method(Retain MySQL 5.x Compatibility)", as given in snapshot:
enter image description here

ContentLicense: CC BY-SA 4.0

Body:
While executing a JDBC program, I get the following error while connecting to database:

Exception in thread "main"
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does
not support authentication protocol requested by server; consider upgrading
MySQL client
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:885)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3421)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1247)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at main.java.MyFirstJdbcProgram.readDataBase(MyFirstJdbcProgram.java:23)
at main.java.Main.main(Main.java:6)

When I researched this, I got to know that the below error is because I need to grant the privileges to the user, so follow

mysql -u root -p

then entered the password

then I ran

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'mypassword';

and also I used

UPDATE user SET authentication_string=password('mypassword') WHERE user='root';

But I'm getting below error

ERROR 1064 (42000): You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near 'IDENTIFIED BY 'mypassword'' at line 1


问:
Swift Execution Order ViewController UIKit
I'm new to swift and want to use the data from an api in form of a json file. I'm using the TableViewController but the execution order in it seems to be jumping around between the functions and not executing them fully. To see in which order the execution is happening I inserted some print statements.

```<code>
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var Info = Array<String>()

    override func viewDidLoad() {
        super.viewDidLoad()

            parse() { result in
                print("parse")
                if result != nil {
                    self.Info = result!
                    tableView.reloadData()
                }
                else {return}
            }

        print("viewDidLoad")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("numberOfRows")
        //
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("cellForRowAt")
        //
    }

}

</code>```

The result of executing it is:

viewDidLoad
numberOfRows
numberOfRows
parse

So my Question would be:

How do i get the jsonParse completionHandler to execute before numberofRows and why is cellForRowAt not executing ?

Thank you in advance.

答:
You can't because its the completion handler you are calling. But you can again call the tableview numberOfRows and another delegate after you parse data. Just add tableview.reloadData() like this</p>

```<code>parse() { result in

DispatchQueue.main.async {
               print("parse")
                    if  {
                        tableview.reloadData()
                    }
                    else {return}
                    }
                }
</code>```

Body:
I'm new to swift and want to use the data from an api in form of a json file. I'm using the TableViewController but the execution order in it seems to be jumping around between the functions and not executing them fully. To see in which order the execution is happening I inserted some print statements.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var Info = Array<String>()

    override func viewDidLoad() {
        super.viewDidLoad()

            parse() { result in
                print("parse")
                if result != nil {
                    self.Info = result!
                    tableView.reloadData()
                }
                else {return}
            }

        print("viewDidLoad")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("numberOfRows")
        //
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("cellForRowAt")
        //
    }

}

The result of executing it is:

viewDidLoad
numberOfRows
numberOfRows
parse

So my Question would be:

How do i get the jsonParse completionHandler to execute before numberofRows and why is cellForRowAt not executing ?

Thank you in advance.

Body:
You can't because its the completion handler you are calling. But you can again call the tableview numberOfRows and another delegate after you parse data. Just add tableview.reloadData() like this

parse() { result in

DispatchQueue.main.async {
               print("parse")
                    if  {
                        tableview.reloadData()
                    }
                    else {return}
                    }
                }


问:
Regular expression: the string must contains sequence of words
I have such code:

        String regexp = "[\\w\\W]*(London)[\\w\\W]*(Paris)[\\w\\W]*";

        String test1 = "London Paris";
        boolean t1 =  Pattern.matches(regexp, test1);
        System.out.println(t1);

        String test2 = "London to Paris";
        boolean t2 =  Pattern.matches(regexp, test2);
        System.out.println(t2);

        String test3 = "from London to Paris";
        boolean t3 =  Pattern.matches(regexp, test3);
        System.out.println(t3);

        String test4 = "from (London) -> (Paris)";
        boolean t4 =  Pattern.matches(regexp, test4);
        System.out.println(t4);
```

I need all boolean to be true. Now, this condition is met, but the regex seems to me not too effective. How can I change this?

答:
You may want to use word boundaries as well. Like this regex:

```<code>.*\b(London)\b.*(Paris)\b.*
</code>```

The reason is that you current regex will also match LondonaParis or aLondona   Parisaaa. Not sure if you want that.

If you keep a word boundary around the specific names you are looking for, these strings won't pass.

However, I second @Ali Ben Zarrouk's point of not needing regexes for this.

Body:
I have such code:

        String regexp = "[\\w\\W]*(London)[\\w\\W]*(Paris)[\\w\\W]*";

        String test1 = "London Paris";
        boolean t1 =  Pattern.matches(regexp, test1);
        System.out.println(t1);

        String test2 = "London to Paris";
        boolean t2 =  Pattern.matches(regexp, test2);
        System.out.println(t2);

        String test3 = "from London to Paris";
        boolean t3 =  Pattern.matches(regexp, test3);
        System.out.println(t3);

        String test4 = "from (London) -> (Paris)";
        boolean t4 =  Pattern.matches(regexp, test4);
        System.out.println(t4);

I need all boolean to be true. Now, this condition is met, but the regex seems to me not too effective. How can I change this?

Body:
You may want to use word boundaries as well. Like this regex:

.*\b(London)\b.*(Paris)\b.*

The reason is that you current regex will also match LondonaParis or aLondona   Parisaaa. Not sure if you want that.

If you keep a word boundary around the specific names you are looking for, these strings won't pass.

However, I second @Ali Ben Zarrouk's point of not needing regexes for this.


问:
Define and plot constant function in python
I am trying to plot a constant function in python (this is not what I am actually trying to do but if I solve this it might be a first step).

```<code>import matplotlib.pyplot as plt
import numpy as np

def constant_function(x):
    return 2

t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1,constant_function(t1))
</code>```

However I get the error

```<code>ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)
</code>```

答:
One option is to vectorize your function:

```<code>import matplotlib.pyplot as plt
import numpy as np

@np.vectorize
def constant_function(x):
    return 2

t1 = np.arange(0.0, 1.0, 0.1)
plt.plot(t1, constant_function(t1))
plt.show()
</code>```

this way constant_function(t1) will return [2 2 2 2 2 2 2 2 2 2] (i.e. [f(x[0]), f(x[1]), f(x[2]), ...]) instead of just 2 and the dimensions will match.

Body:
I am trying to plot a constant function in python (this is not what I am actually trying to do but if I solve this it might be a first step).

import matplotlib.pyplot as plt
import numpy as np

def constant_function(x):
    return 2

t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1,constant_function(t1))

However I get the error

ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)

Body:
One option is to vectorize your function:

import matplotlib.pyplot as plt
import numpy as np

@np.vectorize
def constant_function(x):
    return 2

t1 = np.arange(0.0, 1.0, 0.1)
plt.plot(t1, constant_function(t1))
plt.show()

this way constant_function(t1) will return [2 2 2 2 2 2 2 2 2 2] (i.e. [f(x[0]), f(x[1]), f(x[2]), ...]) instead of just 2 and the dimensions will match.


问:
Initializer Element is not a constant->Objective C
I am getting "Initializer Element is not a constant" error for the following declaration.</p>

```<code>struct EBD_HEADER
{
    char   x;
    int Key;
    char Number;
    int ID;
    int Version;
}EBD_HEAD;

struct EBD_TRAILER
{
    int Crc_0;
    int Crc_1;
    int  Etx;
}EBD_TRAIL;

static const int EBD_HEADER_SIZE  = sizeof(EBD_HEAD);

static const int EBD_TRAILER_SIZE = sizeof(EBD_TRAIL);

static const int RMH_ENCODED_MSG_OVERHEAD = EBD_HEADER_SIZE +
EBD_TRAILER_SIZE; //**error:Intializer Element is not a constant**
</code>```

答:
Use macros instead.

```<code>#define EBD_HEADER_SIZE sizeof(EBD_HEAD)
#define EBD_TRAILER_SIZE sizeof(EBD_TRAIL)
#define RMH_ENCODED_MSG_OVERHEAD (EBD_HEADER_SIZE + EBD_TRAILER_SIZE)
</code>```

Feels scary? Read this and remember this is C (which Objective-C is based on) and not C++

ContentLicense: CC BY-SA 3.0

Body:
I am getting "Initializer Element is not a constant" error for the following declaration.

struct EBD_HEADER
{
    char   x;
    int Key;
    char Number;
    int ID;
    int Version;
}EBD_HEAD;

struct EBD_TRAILER
{
    int Crc_0;
    int Crc_1;
    int  Etx;
}EBD_TRAIL;

static const int EBD_HEADER_SIZE  = sizeof(EBD_HEAD);

static const int EBD_TRAILER_SIZE = sizeof(EBD_TRAIL);

static const int RMH_ENCODED_MSG_OVERHEAD = EBD_HEADER_SIZE +
EBD_TRAILER_SIZE; //**error:Intializer Element is not a constant**

Body:
Use macros instead.

#define EBD_HEADER_SIZE sizeof(EBD_HEAD)
#define EBD_TRAILER_SIZE sizeof(EBD_TRAIL)
#define RMH_ENCODED_MSG_OVERHEAD (EBD_HEADER_SIZE + EBD_TRAILER_SIZE)

Feels scary? Read this and remember this is C (which Objective-C is based on) and not C++


问:
Is there a way in QML to change a buttons color on multiple events?
I am new to Qml and I am a little bit lost. I want to set multiple states for an Image, or a color of a button. One simpler part is, that if the button is pressed, it should change color or image. This can be achieved by the following:

```<code>Button {
    width: 50
    height: 50

    background: Rectangle {
        color: parent.pressed ? "red" : "blue"
    }
}
</code>```

In Addtion I have also the states: clicked, enabled, enabled clicked and many more.

So first: Can I do just catch the parent.pressed without an else statement, something like:

```<code>if (parent.pressed)
    color = "red"
elseif (onClicked)
    color = "blue"
....
</code>```

and maybe setting additional states, which I can ask for and change my color, when my backend is disabling or enabling any of my GUI elements.

So basically I have two problems: how to catch a event in an if statement and how to catch multiple events and not using that if else statement like:

```<code> parent.pressed ? "red" : "blue"
</code>```

I got further, it is possible to add states.

```<code>Button {
width: 50
height: 50
id: btn
onClicked: state="clicked"
onPressed: state="pressed"

background: Rectangle
{
    anchors.fill: parent
}

states: [
    State {
        name: "clicked"
        PropertyChanges { target: btn; background: color= "red" }
    },
    State {
        name: "pressed"
        PropertyChanges { target: btn; background: color= "blue" }
    }
]
</code>```

}

But this won't change the color of my button, but the rest of the UI.

答:
I guess you have syntax error in your code.
Actually it should be something like the following:

Button {
    id: btn
    text: "Click me"
    property color bgColor
    anchors.centerIn: parent
    state: pressed ? "pressed" : "regular"
    background: Rectangle {
        color: btn.bgColor
    }

    states: [
        State {
            name: "regular"
            PropertyChanges {
                target: btn
                bgColor: "orange"

            }
        },
        State {
            name: "pressed"
            PropertyChanges {
                target: btn
                bgColor: "green"
            }
        }
    ]
}
```

<p>or you can play with the <code>Rectangle</code>:</p>

<pre class="lang-js prettyprint-override"><code>background: Rectangle {
    id: bg
}

states: [
    State {
        name: "regular"
        PropertyChanges {
            target: bg
            color: "orange"

        }
    },
    State {
        name: "pressed"
        PropertyChanges {
            target: bg
            color: "green"
        }
    }
]
</code>```

Body:
I am new to Qml and I am a little bit lost. I want to set multiple states for an Image, or a color of a button. One simpler part is, that if the button is pressed, it should change color or image. This can be achieved by the following:

Button {
    width: 50
    height: 50

    background: Rectangle {
        color: parent.pressed ? "red" : "blue"
    }
}

In Addtion I have also the states: clicked, enabled, enabled clicked and many more.

So first: Can I do just catch the parent.pressed without an else statement, something like:

if (parent.pressed)
    color = "red"
elseif (onClicked)
    color = "blue"
....

and maybe setting additional states, which I can ask for and change my color, when my backend is disabling or enabling any of my GUI elements.

So basically I have two problems: how to catch a event in an if statement and how to catch multiple events and not using that if else statement like:

 parent.pressed ? "red" : "blue"

I got further, it is possible to add states.

Button {
width: 50
height: 50
id: btn
onClicked: state="clicked"
onPressed: state="pressed"

background: Rectangle
{
    anchors.fill: parent
}

states: [
    State {
        name: "clicked"
        PropertyChanges { target: btn; background: color= "red" }
    },
    State {
        name: "pressed"
        PropertyChanges { target: btn; background: color= "blue" }
    }
]

}

But this won't change the color of my button, but the rest of the UI.

Body:
I guess you have syntax error in your code.
Actually it should be something like the following:

Button {
    id: btn
    text: "Click me"
    property color bgColor
    anchors.centerIn: parent
    state: pressed ? "pressed" : "regular"
    background: Rectangle {
        color: btn.bgColor
    }

    states: [
        State {
            name: "regular"
            PropertyChanges {
                target: btn
                bgColor: "orange"

            }
        },
        State {
            name: "pressed"
            PropertyChanges {
                target: btn
                bgColor: "green"
            }
        }
    ]
}

or you can play with the Rectangle:

background: Rectangle {
    id: bg
}

states: [
    State {
        name: "regular"
        PropertyChanges {
            target: bg
            color: "orange"

        }
    },
    State {
        name: "pressed"
        PropertyChanges {
            target: bg
            color: "green"
        }
    }
]


问:
Firebase simple query gives error: "Converting circular structure to JSON at JSON.stringify"
I'm trying to loop through a /users path and join it to my auth().listUsers result however this code:

https://github.com/QuantumInformation/svelte-fullstack-starter/blob/master/firebase_specific/functions/src/users.ts#L32

export async function getSomeUsers(amount: number) {
    try {
        const listUsersResult = await admin.auth().listUsers(amount)
        const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map(async user => {
            console.log("try read_______________" + user.uid)
            let userProfileSnapshot = await admin
                .database()
                .ref("users/" + user.uid)
                .once("value")

            console.log("end try read_______________" + user.uid)
            return { ...user, userProfileSnapshot }
        })

        return parsedUsers
    } catch (error) {
        console.error("Error listing users:", error)
        throw new Error("Error users" + error)
    }
}

```

<p>gives this error</p>

<blockquote>
  <p>Converting circular structure to JSON at JSON.stringify () at stringify </p>
</blockquote>

<p>but this code works fine</p>

<pre class="lang-js prettyprint-override"><code>export async function getSomeUsers(amount: number) {
    try {
        const listUsersResult = await admin.auth().listUsers(amount)

        const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map( user => {

            return 1
        })

        return parsedUsers
    } catch (error) {
        console.error("Error listing users:", error)
        throw new Error("Error users" + error)
    }
}
</code>```

答:
Based on your 2nd code snippet, i think there is an issue in async call.
Did you try whether the async inside the map is working as expected ?.
Try like this and check. </p>

```<code>    let parsedUsers = [];
    const userList = listUsersResult.users.map(stripUserSensitiveInfo);
    for (const user of userList) {
      try {
        let userProfileSnapshot = await admin
            .database()
            .ref("users/" + user.uid)
            .once("value")
        parsedUsers.push({...user, userProfileSnapshot});
      } catch (error) {
        console.error('Error on API', error);
      }
    }
</code>```

Body:
I'm trying to loop through a /users path and join it to my auth().listUsers result however this code:

https://github.com/QuantumInformation/svelte-fullstack-starter/blob/master/firebase_specific/functions/src/users.ts#L32

export async function getSomeUsers(amount: number) {
    try {
        const listUsersResult = await admin.auth().listUsers(amount)
        const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map(async user => {
            console.log("try read_______________" + user.uid)
            let userProfileSnapshot = await admin
                .database()
                .ref("users/" + user.uid)
                .once("value")

            console.log("end try read_______________" + user.uid)
            return { ...user, userProfileSnapshot }
        })

        return parsedUsers
    } catch (error) {
        console.error("Error listing users:", error)
        throw new Error("Error users" + error)
    }
}

gives this error

Converting circular structure to JSON at JSON.stringify () at stringify

but this code works fine

export async function getSomeUsers(amount: number) {
    try {
        const listUsersResult = await admin.auth().listUsers(amount)

        const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map( user => {

            return 1
        })

        return parsedUsers
    } catch (error) {
        console.error("Error listing users:", error)
        throw new Error("Error users" + error)
    }
}

Body:
Based on your 2nd code snippet, i think there is an issue in async call.
Did you try whether the async inside the map is working as expected ?.
Try like this and check.

    let parsedUsers = [];
    const userList = listUsersResult.users.map(stripUserSensitiveInfo);
    for (const user of userList) {
      try {
        let userProfileSnapshot = await admin
            .database()
            .ref("users/" + user.uid)
            .once("value")
        parsedUsers.push({...user, userProfileSnapshot});
      } catch (error) {
        console.error('Error on API', error);
      }
    }


问:
Response.Redirect in Session_Start doesn't work
I have a simple Session_Start code that looks like this:

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
    Dim sid = Session.SessionID
    Response.Redirect("~/Blog.aspx")
    dim dummy=4/0
End Sub
```

It does not work as expected. Usually in my whole site, whenever Response.Redirect() is called, it also terminates the code execution. Whereas here, even if the page eventually redirects, the dim dummy=4/0 line is also executed.

This is causing me problems in other code called from Session_Start() where I built on the assumption that the redirect is an exit point.

I also tried setting endResponse in the Response.Redirect(url, endResponse) overloaded method as true or false but this doesn't work either.

答:
http://msdn.microsoft.com/en-us/library/a8wa7sdt%28v=vs.80%29.aspx

```<code>public void Redirect (
    string url,
    bool endResponse
)
</code>```

url  -  The target location.

endResponse  -  Indicates whether execution of the current page should terminate.

Body:
I have a simple Session_Start code that looks like this:

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
    Dim sid = Session.SessionID
    Response.Redirect("~/Blog.aspx")
    dim dummy=4/0
End Sub

It does not work as expected. Usually in my whole site, whenever Response.Redirect() is called, it also terminates the code execution. Whereas here, even if the page eventually redirects, the dim dummy=4/0 line is also executed.

This is causing me problems in other code called from Session_Start() where I built on the assumption that the redirect is an exit point.

I also tried setting endResponse in the Response.Redirect(url, endResponse) overloaded method as true or false but this doesn't work either.

Body:
http://msdn.microsoft.com/en-us/library/a8wa7sdt%28v=vs.80%29.aspx

public void Redirect (
    string url,
    bool endResponse
)

url  -  The target location.

endResponse  -  Indicates whether execution of the current page should terminate.


问:
refactoring passport.js authentication code
We have a passport.js file like this:

const axios = require('axios')
const uuid = require('uuid/v4')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const session = require('express-session')
const mongoStore = require('connect-mongo')(session)

module.exports = (app) => {
    const users = [
        {
            id: '2f24vvg',
            email: 'test@test.com',
            password: 'password'
        }
    ]

    const mongoSessionStore = new mongoStore({
        url: 'mongodb://localhost/test-app',
        ttl: 30 * 60 // 30 min
    })

    let sess = {
        genid: (req) => {
            console.log('Inside the session middleware')
            console.log(req.sessionID)
            return uuid()
        },
        store: mongoSessionStore,
        secret: 'keyboard cat', // password from environment
        resave: false,
        rolling: true,
        saveUninitialized: true,
        unset: 'destroy', // removes the session from the server when end() is called
        cookie: {
            HttpOnly: true,
            maxAge: 30 * 60 * 1000 // 30 minutes
        }
    }

    app.use(session(sess))

    passport.use(new LocalStrategy(
        { usernameField: 'email' },
        (email, password, done) => {
            axios.get(`http://localhost:5000/users?email=${email}`)
                .then(res => {
                    const user = res.data[0]
                    if (!user) {
                        return done(null, false, { message: 'Invalid credentials.\n' })
                    }
                    if (password != user.password) {
                        return done(null, false, { message: 'Invalid password.\n' })
                    }
                    return done(null, user)
                })
                .catch(error => done(error))
        }
    ))

    passport.serializeUser((user, done) => {
        console.log('Inside serializeUser callback. User id is saved to the session store')
        done(null, user.id)
    })
    passport.deserializeUser((id, done) => {
        axios.get(`http://localhost:5000/users/${id}`)
            .then(res => done(null, res.data))
            .catch(error => done(error, false))
    })

    app.use(passport.initialize())
    app.use(passport.session())
}

```

<p>We have multiple router files that contain the same function <code>isAuthorized</code>:</p>

<pre class="lang-js prettyprint-override"><code>function isAuthorized(req, res, next) {
    if (req.isAuthenticated()) {
        console.log('Is allowed')
        next()
    }
    else {
        console.log('Is not allowed')
        res.sendStatus(401)
        // res.redirect('/')
    }
}
// Example in use:
router.get('/secure', isAuthorized, (req, res) => {
    res.format({
        html: () => {
            res.render('secure')
        },

        json: () => {
            res.send({ message: 'you reached the secure endpoint' })
        }
    })
})

</code>```

To avoid having the function isAuthorized in every routes.js file we're trying to move it to a module. For this I thought it would be sufficient to add it to the end of passport.js as following:

module.exports = function isAuthorized(req, res, next) {
    if (req.isAuthenticated()) {
        console.log('Is allowed')
        next()
    }
    else {
        console.log('Is not allowed')
        res.sendStatus(401)
        // res.redirect('/')
    }
}
```

However, when we then try to use it  in the route.js files we get the error:

TypeError: req.isAuthenticated is not a function

How can this function be separate from the routes and still be used? Thank you for the help.

答:
This is what your middleware function should look like

```<code> module.exports = (req, res, next) => {

        if (req.Authenticated()) {
            return next();

        } else {

            res.status(401);
        }
    }
</code>```

and this is how you use your middleware in other(i.e server.js) files

```<code>    const theMiddleWare = "/middlewareDir";
    app.use("/routes",theMiddleWare(),"routeDir");
// before doing this you have to add the passport middleware
</code>```

Body:
We have a passport.js file like this:

const axios = require('axios')
const uuid = require('uuid/v4')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const session = require('express-session')
const mongoStore = require('connect-mongo')(session)

module.exports = (app) => {
    const users = [
        {
            id: '2f24vvg',
            email: 'test@test.com',
            password: 'password'
        }
    ]

    const mongoSessionStore = new mongoStore({
        url: 'mongodb://localhost/test-app',
        ttl: 30 * 60 // 30 min
    })

    let sess = {
        genid: (req) => {
            console.log('Inside the session middleware')
            console.log(req.sessionID)
            return uuid()
        },
        store: mongoSessionStore,
        secret: 'keyboard cat', // password from environment
        resave: false,
        rolling: true,
        saveUninitialized: true,
        unset: 'destroy', // removes the session from the server when end() is called
        cookie: {
            HttpOnly: true,
            maxAge: 30 * 60 * 1000 // 30 minutes
        }
    }

    app.use(session(sess))

    passport.use(new LocalStrategy(
        { usernameField: 'email' },
        (email, password, done) => {
            axios.get(`http://localhost:5000/users?email=${email}`)
                .then(res => {
                    const user = res.data[0]
                    if (!user) {
                        return done(null, false, { message: 'Invalid credentials.\n' })
                    }
                    if (password != user.password) {
                        return done(null, false, { message: 'Invalid password.\n' })
                    }
                    return done(null, user)
                })
                .catch(error => done(error))
        }
    ))

    passport.serializeUser((user, done) => {
        console.log('Inside serializeUser callback. User id is saved to the session store')
        done(null, user.id)
    })
    passport.deserializeUser((id, done) => {
        axios.get(`http://localhost:5000/users/${id}`)
            .then(res => done(null, res.data))
            .catch(error => done(error, false))
    })

    app.use(passport.initialize())
    app.use(passport.session())
}

We have multiple router files that contain the same function isAuthorized:

function isAuthorized(req, res, next) {
    if (req.isAuthenticated()) {
        console.log('Is allowed')
        next()
    }
    else {
        console.log('Is not allowed')
        res.sendStatus(401)
        // res.redirect('/')
    }
}
// Example in use:
router.get('/secure', isAuthorized, (req, res) => {
    res.format({
        html: () => {
            res.render('secure')
        },

        json: () => {
            res.send({ message: 'you reached the secure endpoint' })
        }
    })
})

To avoid having the function isAuthorized in every routes.js file we're trying to move it to a module. For this I thought it would be sufficient to add it to the end of passport.js as following:

module.exports = function isAuthorized(req, res, next) {
    if (req.isAuthenticated()) {
        console.log('Is allowed')
        next()
    }
    else {
        console.log('Is not allowed')
        res.sendStatus(401)
        // res.redirect('/')
    }
}

However, when we then try to use it  in the route.js files we get the error:

TypeError: req.isAuthenticated is not a function

How can this function be separate from the routes and still be used? Thank you for the help.

Body:
This is what your middleware function should look like

 module.exports = (req, res, next) => {

        if (req.Authenticated()) {
            return next();

        } else {

            res.status(401);
        }
    }

and this is how you use your middleware in other(i.e server.js) files

    const theMiddleWare = "/middlewareDir";
    app.use("/routes",theMiddleWare(),"routeDir");
// before doing this you have to add the passport middleware


问:
Self injecting prototype bean - cyclic reference
I need to self-inject prototype bean.
As I know, it is possible if bean scope="singleton", but in this case I get message from spring : "The dependencies of some of the beans in the application context form a cycle: postMan2"

My bean:

```<code>@Service
@Scope("prototype")
public class PostMan2 implements PostMans2 {

    private PostMans2 postman;

    @Async
    public Future<String> deliverLetter(String message, int i) {
        postman.test();
        String res = "result!";
        return new AsyncResult<String>(res);
    }

    @Override
    public void test() {
        System.out.println("Self injection example thread name="+name);
    }

    @PostConstruct
    private void init() {
        postman = ctx.getBean(PostMans2.class);
    }

}
</code>```

Invoking:

```<code>@Service
public class PostOffice implements PostOffices {

    @Autowired
    ApplicationContext ctx;

    @Override
    public void creatingPostmans() {
        PostMans2 thr = ctx.getBean(PostMans2.class);
        Future<String> fut = thr.deliverLetter("Some letter", 100);
        while (!fut.isDone()) {
           Thread.sleep(1000);
        }
        System.out.println("ending of PostMan's jobs...");

    }

}
</code>```

How to improve my code?

答:
Why do you need to go through Spring to get instance of this?

Looks like what you want to do it this:

```<code>@PostConstruct
private void init() {
    postman = this;
}
</code>```

Body:
I need to self-inject prototype bean.
As I know, it is possible if bean scope="singleton", but in this case I get message from spring : "The dependencies of some of the beans in the application context form a cycle: postMan2"

My bean:

@Service
@Scope("prototype")
public class PostMan2 implements PostMans2 {

    private PostMans2 postman;

    @Async
    public Future<String> deliverLetter(String message, int i) {
        postman.test();
        String res = "result!";
        return new AsyncResult<String>(res);
    }

    @Override
    public void test() {
        System.out.println("Self injection example thread name="+name);
    }

    @PostConstruct
    private void init() {
        postman = ctx.getBean(PostMans2.class);
    }

}

Invoking:

@Service
public class PostOffice implements PostOffices {

    @Autowired
    ApplicationContext ctx;

    @Override
    public void creatingPostmans() {
        PostMans2 thr = ctx.getBean(PostMans2.class);
        Future<String> fut = thr.deliverLetter("Some letter", 100);
        while (!fut.isDone()) {
           Thread.sleep(1000);
        }
        System.out.println("ending of PostMan's jobs...");

    }

}

How to improve my code?

Body:
Why do you need to go through Spring to get instance of this?

Looks like what you want to do it this:

@PostConstruct
private void init() {
    postman = this;
}


问:
Griddb Nosql - Error when make Makefile:382 all-recursive
I implemented with the guideline from https://github.com/griddb/griddb_nosql

I had already run below command
./bootstrap.sh
./configure

But when I ran make command, I encounter the following error:

```<code>$ make
Making all in 3rd_party/MessagePack
make[1]: Entering directory '/home/conglb/Documents/github/griddb_nosql/3rd_party/MessagePack'
make[1]: Nothing to be done for 'all'.
make[1]: Leaving directory '/home/conglb/Documents/github/griddb_nosql/3rd_party/MessagePack'
Making all in utility
make[1]: Entering directory '/home/conglb/Documents/github/griddb_nosql/utility'
source='./util/allocator.cpp' object='libutil_a-allocator.o' libtool=no \
DEPDIR=.deps depmode=none /bin/bash ../depcomp \
g++ -DPACKAGE_NAME=\"GridDB_NoSQL\" -DPACKAGE_TARNAME=\"griddb_nosql\" -DPACKAGE_VERSION=\"4.3.0\" -DPACKAGE_STRING=\"GridDB_NoSQL\ 4.3.0\" -DPACKAGE_BUGREPORT=\"\" -DPACKAGE_URL=\"\" -DPACKAGE=\"griddb_nosql\" -DVERSION=\"4.3.0\" -I.  -I../utility   -Wall -finput-charset=UTF-8 -Wpointer-arith -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unused-function -std=gnu++0x -O3 -fno-tree-vectorize -DNDEBUG -c -o libutil_a-allocator.o `test -f './util/allocator.cpp' || echo './'`./util/allocator.cpp
../depcomp: line 772: exec: g++: not found
Makefile:382: recipe for target 'libutil_a-allocator.o' failed
make[1]: *** [libutil_a-allocator.o] Error 127
make[1]: Leaving directory '/home/conglb/Documents/github/griddb_nosql/utility'
Makefile:386: recipe for target 'all-recursive' failed
make: *** [all-recursive] Error 1
</code>```

Can anybody say what did I miss?

答:
Your error is ../depcomp: line 772: exec: g++: not found.

It causes by your environment which don't have g++ compiler.

I checked on GridDB repository in Github. Compiler required is CentOS 7.6 (gcc 4.8.5), Ubuntu 18.04 (gcc 4.8.5) and openSUSE Leap 15.1 (gcc 4.8.5).

You need to install g++ compiler version 4.8.5.

Body:
I implemented with the guideline from https://github.com/griddb/griddb_nosql

I had already run below command
./bootstrap.sh
./configure

But when I ran make command, I encounter the following error:

$ make
Making all in 3rd_party/MessagePack
make[1]: Entering directory '/home/conglb/Documents/github/griddb_nosql/3rd_party/MessagePack'
make[1]: Nothing to be done for 'all'.
make[1]: Leaving directory '/home/conglb/Documents/github/griddb_nosql/3rd_party/MessagePack'
Making all in utility
make[1]: Entering directory '/home/conglb/Documents/github/griddb_nosql/utility'
source='./util/allocator.cpp' object='libutil_a-allocator.o' libtool=no \
DEPDIR=.deps depmode=none /bin/bash ../depcomp \
g++ -DPACKAGE_NAME=\"GridDB_NoSQL\" -DPACKAGE_TARNAME=\"griddb_nosql\" -DPACKAGE_VERSION=\"4.3.0\" -DPACKAGE_STRING=\"GridDB_NoSQL\ 4.3.0\" -DPACKAGE_BUGREPORT=\"\" -DPACKAGE_URL=\"\" -DPACKAGE=\"griddb_nosql\" -DVERSION=\"4.3.0\" -I.  -I../utility   -Wall -finput-charset=UTF-8 -Wpointer-arith -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unused-function -std=gnu++0x -O3 -fno-tree-vectorize -DNDEBUG -c -o libutil_a-allocator.o `test -f './util/allocator.cpp' || echo './'`./util/allocator.cpp
../depcomp: line 772: exec: g++: not found
Makefile:382: recipe for target 'libutil_a-allocator.o' failed
make[1]: *** [libutil_a-allocator.o] Error 127
make[1]: Leaving directory '/home/conglb/Documents/github/griddb_nosql/utility'
Makefile:386: recipe for target 'all-recursive' failed
make: *** [all-recursive] Error 1

Can anybody say what did I miss?


问:
What code should I surround with run(){}?
I finished a 2000-line Swing + SQL program and I'd like to add to it a login window before everything is initialized. The login window is a JFrame class, instanced from the main program.

So my main app needs to implement Runnable. All I want with the thread I'm creating out of it is waiting -with wait()- until the login thread finishes -and uses notify()-.

My program consist of dozens of visual components, methods, main(), constructor, initializer, etc. What's the minimum amount of code I should surround with run(){}?

This is an example of what I want to do. It's not by any means correct (I suppose) but you'll get it:

```<code>private void initialize() { // Called from main()

    this.setBounds(100, 200, 1024, 576);
    this.setTitle("Main app");
    this.setVisible(false);

    Runnable runnable = new Visual_Login();
    Thread login_thread = new Thread(runnable);

    login_thread.run();
    main_thread.wait();

    this.setVisible(true);
    this.setContentPane(getJContentPane());

}
</code>```

(...I hope I'm understanding concurrency well)

Thank you in advance.

答:
You start a thread with the start() method and not the run() method. The Thread class will call the run method when it has properly configured itself.

In your case it should be:

```<code>Runnable runnable = new Visual_Login();
Thread login_thread = new Thread(runnable);
login_thread.start();
// run() will be called later.

wait();
// waits for another thread to do notify or notifyAll.
// it should be around here where the runnable thread will "run()"
</code>```

Other than that if you're planning to block the application anyway then why do you need to start another thread?

Body:
I finished a 2000-line Swing + SQL program and I'd like to add to it a login window before everything is initialized. The login window is a JFrame class, instanced from the main program.

So my main app needs to implement Runnable. All I want with the thread I'm creating out of it is waiting -with wait()- until the login thread finishes -and uses notify()-.

My program consist of dozens of visual components, methods, main(), constructor, initializer, etc. What's the minimum amount of code I should surround with run(){}?

This is an example of what I want to do. It's not by any means correct (I suppose) but you'll get it:

private void initialize() { // Called from main()

    this.setBounds(100, 200, 1024, 576);
    this.setTitle("Main app");
    this.setVisible(false);

    Runnable runnable = new Visual_Login();
    Thread login_thread = new Thread(runnable);

    login_thread.run();
    main_thread.wait();

    this.setVisible(true);
    this.setContentPane(getJContentPane());

}

(...I hope I'm understanding concurrency well)

Thank you in advance.

Body:
You start a thread with the start() method and not the run() method. The Thread class will call the run method when it has properly configured itself.

In your case it should be:

Runnable runnable = new Visual_Login();
Thread login_thread = new Thread(runnable);
login_thread.start();
// run() will be called later.

wait();
// waits for another thread to do notify or notifyAll.
// it should be around here where the runnable thread will "run()"

Other than that if you're planning to block the application anyway then why do you need to start another thread?


问:
Inner spacing inside rounded checkbox
I'm trying to achieve this:

I've also managed to get the result, but I cannot add the spacing between the grey border and blue circle:

```<code>input {
  line-height: normal;
  &[type="checkbox"],
  &[type="radio"] {
    width: 1.3em;
    height: 1.3em;
    background-color: white;
    border-radius: 50%;
    vertical-align: middle;
    border: 1px solid #ddd;
    border-width: thick;
    -webkit-appearance: none;
    outline: none;
    cursor: pointer;
  }
}
</code>```

答:
Use border: 2px solid white; for the white ring, and box-shadow: 0 0 0 2px #ddd; for the outer grey ring.

Then you can set background-color to white for unchecked or #73c0ec for checked.

input[type="radio"] {
  width: 1.3em;
  height: 1.3em;
  background-color: white;
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 0 0 2px #ddd;
  -webkit-appearance: none;
  cursor: pointer;
}
input[type="radio"]:checked {
  background-color: #73c0ec;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" name="group-1"><br>
<input type="radio" name="group-1"><br>
<input type="radio" name="group-1"></code>```

Title: Inner spacing inside rounded checkbox

Body:
I'm trying to achieve this:

I've also managed to get the result, but I cannot add the spacing between the grey border and blue circle:

input {
  line-height: normal;
  &[type="checkbox"],
  &[type="radio"] {
    width: 1.3em;
    height: 1.3em;
    background-color: white;
    border-radius: 50%;
    vertical-align: middle;
    border: 1px solid #ddd;
    border-width: thick;
    -webkit-appearance: none;
    outline: none;
    cursor: pointer;
  }
}

Body:
Use border: 2px solid white; for the white ring, and box-shadow: 0 0 0 2px #ddd; for the outer grey ring.

Then you can set background-color to white for unchecked or #73c0ec for checked.

input[type="radio"] {
  width: 1.3em;
  height: 1.3em;
  background-color: white;
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 0 0 2px #ddd;
  -webkit-appearance: none;
  cursor: pointer;
}
input[type="radio"]:checked {
  background-color: #73c0ec;
}

<input type="radio" name="group-1"><br>
<input type="radio" name="group-1"><br>
<input type="radio" name="group-1">


问:
Version control of packages in Unity 2019
I'm managing my Unity 2019.3 project in git and I have a directory called Packages in the root of my project. In here there is a file called manifest.json. Is this the only file that matters in the folder or are there other configuration files that could be generated and need tracking?

In other words, is it safe to put the following lines in my .gitignore

```<code>/[Pp]ackages/*
!/[Pp]ackages/manifest.json
</code>```

This is very similar to this question but it doesn't explicitly answer what I want to know.

Edit

To clarify, I am asking if manifest.json will always be enough to regenerate the content of Packages or if there may be other files that are stored in there and required for configuration. I.e. files that won't be the same if left for automatic regeneration by Unity.

The use of this is I have an asset that adds files to that Packages folder and they do not need tracking. They are automatically added back in by the asset when needed. So I want to exclude all but the necessary files from that folder. If the necessary files could change and there is no way for me to know what configuration files could be generated, then I will not do this. If manifest.json is going to always be the only file of importance in that folder, I will leave my .gitignore as it is.

答: Revisiting this a few months later. I still have found no documentation to confirm manifest.json is the only file that matters in the Packages directory, however, I have not had any issues with adding those two lines to several different Unity projects that use several different packages. It seems pretty safe to add.

Body:
I'm managing my Unity 2019.3 project in git and I have a directory called Packages in the root of my project. In here there is a file called manifest.json. Is this the only file that matters in the folder or are there other configuration files that could be generated and need tracking?

In other words, is it safe to put the following lines in my .gitignore

/[Pp]ackages/*
!/[Pp]ackages/manifest.json

This is very similar to this question but it doesn't explicitly answer what I want to know.

Edit

To clarify, I am asking if manifest.json will always be enough to regenerate the content of Packages or if there may be other files that are stored in there and required for configuration. I.e. files that won't be the same if left for automatic regeneration by Unity.

The use of this is I have an asset that adds files to that Packages folder and they do not need tracking. They are automatically added back in by the asset when needed. So I want to exclude all but the necessary files from that folder. If the necessary files could change and there is no way for me to know what configuration files could be generated, then I will not do this. If manifest.json is going to always be the only file of importance in that folder, I will leave my .gitignore as it is.


问:
Need to add some conditions before service get called RXJS
I am new to Angular and I am using primeng Datatable to show a grid in my application, now I have integrated pagination for the grid as well, I need to an add loading / spinner symbol to the grid when the user searches or clicks on page number.
 Below, serviceloading is set to true at the start of method but service wasn't called at a particular instance which makes to show loading always, actually I do hide the loading only when I get the response. So is there any way where I can set loading to true at the start of API call so that I could hide after I get response.

Thanks in Advance

```<code>private TransactionSearch: Subject<void> = new Subject();
loadTerritories(event:LazyLoadEvent)
{
    this.serviceloading = true;
    this.params = event.filters.TerritoryName;
    this.TransactionSearch.next();
    this.TransactionSearch.pipe(
      distinctUntilChanged(),
      debounceTime(1000),
      switchMap(() => {
            return this.TransService.getSalesTerritory(this.params);
      })).
      subscribe(res =>{
        this.totalcount = res.Total;
        this.salesTerritoryList =  res.Data;
        this.serviceloading = false;
      });
  }
</code>```

HTML Content

```<code><p-table
   #dt
   [value]="salesTerritoryList"
   [autoLayout]="true"
   [totalRecords]="totalcount"
   [paginator]="true"
   [rows]="15"
   [lazy]="true"
   [loading]="serviceloading"
   (onLazyLoad)="loadSalesTerritories($event)"
>
</p-table>
</code>```

答:
You may be able to add tap to your pipe below the switchMap.  Please see below.  I hope this helps.</p>

```<code>this.TransactionSearch.pipe(
  distinctUntilChanged(),
  debounceTime(1000),
  tap(() => {
    this.serviceloading = true;
  }),
  switchMap(() => { return this.TransService.getSalesTerritory(this.params);})).
  subscribe(res =>{
    this.totalcount = res.Total;
    this.salesTerritoryList =  res.Data;
    this.serviceloading = false;
  });
</code>```

Body:
I am new to Angular and I am using primeng Datatable to show a grid in my application, now I have integrated pagination for the grid as well, I need to an add loading / spinner symbol to the grid when the user searches or clicks on page number.
 Below, serviceloading is set to true at the start of method but service wasn't called at a particular instance which makes to show loading always, actually I do hide the loading only when I get the response. So is there any way where I can set loading to true at the start of API call so that I could hide after I get response.

Thanks in Advance

private TransactionSearch: Subject<void> = new Subject();
loadTerritories(event:LazyLoadEvent)
{
    this.serviceloading = true;
    this.params = event.filters.TerritoryName;
    this.TransactionSearch.next();
    this.TransactionSearch.pipe(
      distinctUntilChanged(),
      debounceTime(1000),
      switchMap(() => {
            return this.TransService.getSalesTerritory(this.params);
      })).
      subscribe(res =>{
        this.totalcount = res.Total;
        this.salesTerritoryList =  res.Data;
        this.serviceloading = false;
      });
  }

HTML Content

Body:
You may be able to add tap to your pipe below the switchMap.  Please see below.  I hope this helps.

this.TransactionSearch.pipe(
  distinctUntilChanged(),
  debounceTime(1000),
  tap(() => {
    this.serviceloading = true;
  }),
  switchMap(() => { return this.TransService.getSalesTerritory(this.params);})).
  subscribe(res =>{
    this.totalcount = res.Total;
    this.salesTerritoryList =  res.Data;
    this.serviceloading = false;
  });


问:
Replace multiple OR operators with a single IN or ANY operator
I would like to query a list of cities that end in vowels and I would like each city in the list to be distinct. The code noted below works fine but I would like to achieve the same thing using the IN or ANY operators.I have attached a picture of the description of the table I'm working with. Thank you!

```<code>SELECT DISTINCT City FROM Station
WHERE City LIKE '%a'
OR City LIKE '%e'
OR City LIKE '%i'
OR City LIKE '%o'
OR City LIKE '%u';
</code>```

Table description

答:
You can use regexp_like

```<code>SELECT distinct CITY
  FROM station
 WHERE regexp_like(CITY, '[aeiou]$', 'i');
</code>```

Demo

Body:
I would like to query a list of cities that end in vowels and I would like each city in the list to be distinct. The code noted below works fine but I would like to achieve the same thing using the IN or ANY operators.I have attached a picture of the description of the table I'm working with. Thank you!

SELECT DISTINCT City FROM Station
WHERE City LIKE '%a'
OR City LIKE '%e'
OR City LIKE '%i'
OR City LIKE '%o'
OR City LIKE '%u';

Table description

Body:
You can use regexp_like

SELECT distinct CITY
  FROM station
 WHERE regexp_like(CITY, '[aeiou]$', 'i');

Demo


问:
AttributeError: 'NoneType' object has no attribute 'data' - when I'm writing a function to insert an element into sorted linked list
I'm writing a function to implement insertion into a sorted singly linked list.

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

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

    def isListEmpty(self):
        if self.head is None:
            return True
        return False

    def listLength(self):
        length = 0
        currentNode = self.head
        while currentNode is not None:
            length += 1
            currentNode = currentNode.next
        return length

    def insertAt(self, newNode, position):
        if position < 0 or position > self.listLength():
            print("Invalid Position")
            return
        elif position == 0:
            self.insertHead(newNode)
        else:
            currentPosition = 0
            currentNode = self.head
            while currentPosition is not position:
                currentPosition += 1
                previousNode = currentNode
                currentNode = currentNode.next
            newNode.next = currentNode
            previousNode.next = newNode

    def insertSort(self, newNode):
        if self.isListEmpty():
            self.insertEnd(newNode)
        else:
            currentPosition = 0
            currentNode = self.head
            while True:
                currentData = currentNode.data  # line with error
                if currentData <= newNode.data:
                    currentPosition += 1
                    currentNode = currentNode.next
            self.insertAt(newNode, currentPosition)

firstNode = Node(10)
link = LinkedList()
link.insertEnd(firstNode)
fifthNode = Node(25)
link.insertSort(fifthNode)
</code>```

Currently getting the error:

```<code>     currentData = currentNode.data
AttributeError: 'NoneType' object has no attribute 'data'
</code>```

I can't even guess what's the problem with the code.
I tried to print the node data with print(currentNode.data) but it shows no error, it comes error only during the condition check.

答:
```<code>while True:
currentData = currentNode.data  # line with error
if currentData <= newNode.data:
    currentPosition += 1
    currentNode = currentNode.next
self.insertAt(newNode, currentPosition)
</code>```

Here you never exited the while loop.
So, final currentNode will contain None. Check if you reached to the end of the LinkedList and exit.

I would like to add one more thing.

```<code>while currentPosition is not position:
            currentPosition += 1
            previousNode = currentNode
            currentNode = currentNode.next
        newNode.next = currentNode
        previousNode.next = newNode
</code>```

This loop in InsertAt function you need to know whether the position mentioned is correct or not. Let's say the total number of positions were 25 and the entered position was 30. Now your loop will fail as it would never reach to 30. So you need to add one exit loop in while condition itself saying:

```<code>while ((currentPosition is not position) and (currentNode is not None))
</code>```

Now the code will never fail.

Body:
I'm writing a function to implement insertion into a sorted singly linked list.

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

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

    def isListEmpty(self):
        if self.head is None:
            return True
        return False

    def listLength(self):
        length = 0
        currentNode = self.head
        while currentNode is not None:
            length += 1
            currentNode = currentNode.next
        return length

    def insertAt(self, newNode, position):
        if position < 0 or position > self.listLength():
            print("Invalid Position")
            return
        elif position == 0:
            self.insertHead(newNode)
        else:
            currentPosition = 0
            currentNode = self.head
            while currentPosition is not position:
                currentPosition += 1
                previousNode = currentNode
                currentNode = currentNode.next
            newNode.next = currentNode
            previousNode.next = newNode

    def insertSort(self, newNode):
        if self.isListEmpty():
            self.insertEnd(newNode)
        else:
            currentPosition = 0
            currentNode = self.head
            while True:
                currentData = currentNode.data  # line with error
                if currentData <= newNode.data:
                    currentPosition += 1
                    currentNode = currentNode.next
            self.insertAt(newNode, currentPosition)

firstNode = Node(10)
link = LinkedList()
link.insertEnd(firstNode)
fifthNode = Node(25)
link.insertSort(fifthNode)

Currently getting the error:

     currentData = currentNode.data
AttributeError: 'NoneType' object has no attribute 'data'

I can't even guess what's the problem with the code.
I tried to print the node data with print(currentNode.data) but it shows no error, it comes error only during the condition check.

Body:
while True:
currentData = currentNode.data  # line with error
if currentData <= newNode.data:
    currentPosition += 1
    currentNode = currentNode.next
self.insertAt(newNode, currentPosition)

Here you never exited the while loop.
So, final currentNode will contain None. Check if you reached to the end of the LinkedList and exit.

I would like to add one more thing.

while currentPosition is not position:
            currentPosition += 1
            previousNode = currentNode
            currentNode = currentNode.next
        newNode.next = currentNode
        previousNode.next = newNode

This loop in InsertAt function you need to know whether the position mentioned is correct or not. Let's say the total number of positions were 25 and the entered position was 30. Now your loop will fail as it would never reach to 30. So you need to add one exit loop in while condition itself saying:

while ((currentPosition is not position) and (currentNode is not None))

Now the code will never fail.


问:
In JDeveloper, how do I specify which class's 'main' to use?
When I first set up my JDev project, it used the main method from the first class I had created - so when I hit run, it would use that as the starting point.

I then imported my project onto another computer, including a dozen classes, and when I first hit 'run', JDeveloper asked me which 'main' to start from - but I clicked on the wrong one. At the time I just left it, but I now can't find out how to specify the other class as the correct 'starting point'.

Specifically, I want to do this from within JDeveloper so it works when I hit 'run' on the IDE, I don't want to specify it in the command window when running it, etc.

答:
You can define Jdeveloper run target as follow :

Run > Choose active Run configuration > Manage Run configuration

Edit Default run configuration > Browse > Choose your Default run target


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

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

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

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

export default Update;

</code>```

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

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

答:
The useEffect hook will also run on mount. So you need to prevent the hook from setting the color on the first render.

You can do this by using useRef hook.

```<code>const mountRef = useRef(false);

useEffect(() => {
  if (mountRef.current) {
    setLikeColor("green");
  }
  else {
   mountRef.current = true;
  }
}, like);
</code>```

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

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

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

  return (

Username

08:30am

Reading a good book!

          Likes:
          **
{like}
**

          Dislikes:

{dislike}

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

  );
}

export default Update;

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

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

Body:
The useEffect hook will also run on mount. So you need to prevent the hook from setting the color on the first render.

You can do this by using useRef hook.

const mountRef = useRef(false);

useEffect(() => {
  if (mountRef.current) {
    setLikeColor("green");
  }
  else {
   mountRef.current = true;
  }
}, like);


问:
'module' object has no attribute 'svc'
```<code>import pandas as pd
from sklearn import svm

### Read the CSV ###
df = pd.read_csv('C:/Users/anagha/Documents/Python Scripts/sampleData.csv')
df

from sklearn.cross_validation import train_test_split
train, test = train_test_split(df, train_size = 0.8)
train
test

x_column=['Userid','day_of_week','hour_of_day','minute_of_hour']
y_column = ['thermostat']

svc = svm.SVC()
model = svm.svc(kernel='linear', c=1, gamma=1)
</code>```

I'm getting an error AttributeError: 'module' object has no attribute 'svc'. Tried many techniques, but none of them are working. I'm new to python, and would really appreciate the help

答:
You can try

```<code>from sklearn.svm import SVC
</code>```

then

```<code>model = SVC(kernel='linear', c=1, gamma=1)
</code>```

worked fine for me

Title: 'module' object has no attribute 'svc'

Body:
import pandas as pd
from sklearn import svm

### Read the CSV ###
df = pd.read_csv('C:/Users/anagha/Documents/Python Scripts/sampleData.csv')
df

from sklearn.cross_validation import train_test_split
train, test = train_test_split(df, train_size = 0.8)
train
test

x_column=['Userid','day_of_week','hour_of_day','minute_of_hour']
y_column = ['thermostat']

svc = svm.SVC()
model = svm.svc(kernel='linear', c=1, gamma=1)

I'm getting an error AttributeError: 'module' object has no attribute 'svc'. Tried many techniques, but none of them are working. I'm new to python, and would really appreciate the help

Body:
You can try

from sklearn.svm import SVC

then

model = SVC(kernel='linear', c=1, gamma=1)

worked fine for me


问:
No item in queue but there should be python threading
I am working on a project that is a gui with a separate thread. When the user clicks a button a function is fired that sends data to the queue and launches the other thread. The other thread then gets the data from the queue and adds new data to it. Where the gui will then get that data and do something. But it gets stuck saying the queue is empty? Why is this and how can I fix it?

```<code>def click():
            if self.uN.get() and self.pW.get():
                self.q.put("LOGIN")
                self.q.put(self.uN.get() + "," + self.pW.get())
            else:
                self.q.put("eFi")

            con = Connect(self.q)
            con.setDaemon(True)
            con.start()

            time.sleep(1)

            while True:
                root.update()
                try:
                    data = self.q.get(False)
                except queue.Empty:
                    pass
                else:
                    print(data + "+")
                    if data == "Fcon":
                        tkMessageBox.showerror("ERROR!", "Failed to connect to the server!")
                    elif data == "nCre":
                        tkMessageBox.showerror("ERROR!", "A text field is empty!")
                    elif data == "Gcon":
                        for item in root.winfo_children():
                            item.destroy()

                        self.mScreen()
                    else:
                        print("?")

                    print('!')
                    break
</code>```

Here is the other threads code:

```<code>class Connect(Thread):
    def __init__(self, q):
        Thread.__init__(self)
        self.s = socket.socket()
        self.q = q

    def run(self):
        while True:
            try:
                data = self.q.get()
            except Exception as e:
                pass
            else:
                if data == "LOGIN":
                    self.login()
                elif data == "eFi":
                    self.q.put("nCre")
                    print("??????")

    def login(self):
        info = self.q.get().split(",")

        self.q.put("Gcon")
        print("GOD")
</code>```

答: The problem was being caused by having two threads access the same queue one thread would grab the information before the proper thread was able to access it. To solve the problem I made two queues one for each thread.</p>

Body:
I am working on a project that is a gui with a separate thread. When the user clicks a button a function is fired that sends data to the queue and launches the other thread. The other thread then gets the data from the queue and adds new data to it. Where the gui will then get that data and do something. But it gets stuck saying the queue is empty? Why is this and how can I fix it?

def click():
            if self.uN.get() and self.pW.get():
                self.q.put("LOGIN")
                self.q.put(self.uN.get() + "," + self.pW.get())
            else:
                self.q.put("eFi")

            con = Connect(self.q)
            con.setDaemon(True)
            con.start()

            time.sleep(1)

            while True:
                root.update()
                try:
                    data = self.q.get(False)
                except queue.Empty:
                    pass
                else:
                    print(data + "+")
                    if data == "Fcon":
                        tkMessageBox.showerror("ERROR!", "Failed to connect to the server!")
                    elif data == "nCre":
                        tkMessageBox.showerror("ERROR!", "A text field is empty!")
                    elif data == "Gcon":
                        for item in root.winfo_children():
                            item.destroy()

                        self.mScreen()
                    else:
                        print("?")

                    print('!')
                    break

Here is the other threads code:

class Connect(Thread):
    def __init__(self, q):
        Thread.__init__(self)
        self.s = socket.socket()
        self.q = q

    def run(self):
        while True:
            try:
                data = self.q.get()
            except Exception as e:
                pass
            else:
                if data == "LOGIN":
                    self.login()
                elif data == "eFi":
                    self.q.put("nCre")
                    print("??????")

    def login(self):
        info = self.q.get().split(",")

        self.q.put("Gcon")
        print("GOD")


问:
How to move the main body content further down the page when it swaps to mobile design?
When my website goes to 850px it swaps to mobile design, the issue is that I have a button that appears on both desktop and mobile mode but when it's at the beginning of mobile design which is 850 px the button is hidden under the header banner.  I want to push the whole website's main body content down.  I can do this in desktop mode with the CSS property as - margin-top: 200px and I am wondering if there is any @media or any other type of code that can change this just for the mobile design.

I have found that if I put the code of
 it does change it but surely there is a better way than just having a few
 in the button code and even that will just change it for desktop design.

Sorry if my explanation doesn't make much sense.

I will show my button code if this helps and if any other code is required to help can anyone just let me know.

    CLICK HERE FOR A NO OBLIGATION INSTANT QUOTE!</button>

```

Once again thank you for any help!

Screenshot of Desktop mode:

Screenshot of Mobile Mode with the button that is hidden under the top banner:

答:
Well, just put that top margin for your content wrapper into a media query below the other CSS rules, similar to this:</p>

```<code>@media screen and (max-width: 850px) {
  .yourcontentdiv {
    margin-top: 200px;
  }
}
</code>```

Body:
When my website goes to 850px it swaps to mobile design, the issue is that I have a button that appears on both desktop and mobile mode but when it's at the beginning of mobile design which is 850 px the button is hidden under the header banner.  I want to push the whole website's main body content down.  I can do this in desktop mode with the CSS property as - margin-top: 200px and I am wondering if there is any @media or any other type of code that can change this just for the mobile design.

I have found that if I put the code of
 it does change it but surely there is a better way than just having a few
 in the button code and even that will just change it for desktop design.

Sorry if my explanation doesn't make much sense.

I will show my button code if this helps and if any other code is required to help can anyone just let me know.

    <a href="products.asp" <button class="button" style="vertical-align:middle">CLICK HERE FOR A NO OBLIGATION INSTANT QUOTE!</button>

Once again thank you for any help!

Screenshot of Desktop mode:

Screenshot of Mobile Mode with the button that is hidden under the top banner:

Body:
Well, just put that top margin for your content wrapper into a media query below the other CSS rules, similar to this:

@media screen and (max-width: 850px) {
  .yourcontentdiv {
    margin-top: 200px;
  }
}


答:
Use regexp</p>

```<code>select DISTINCT
City   FROM Station
WHERE  regexp_like(city,'[aeiou]$')
</code>```

Title: Replace multiple OR operators with a single IN or ANY operator

Body:
Use regexp

select DISTINCT
City   FROM Station
WHERE  regexp_like(city,'[aeiou]$')


问:
Check API response data with interface in Typescript Angular
I have an app that when the user logs in he received some data as a response, but if the response is not what I expect, the app crashes.

Let me show you the following:

I created an interface to tell Typescript the data I expect.

export interface AuthResponseData {
  token: string;
  expires: string;
  role: number;
}
```

<p>Then I created a method to send the login data to the server.</p>

<pre class="lang-js prettyprint-override"><code>login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    catchError(this.handleError),
    tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
  );
}
</code>```

I was expecting that if the response from the server didn't match the interface then the Angular would redirect to catchError. But doesn't happen.

Now my question is: Is there any way to check if an API response is equal to the interface and throw an error if is not. Or what I'm asking isn't possible?

UPDATE:

After searching I discover that the interfaces disappear on run time, so there is no way to compare the api response with the interface (to the best of my knowledge). But I keep searching for a way to check the api response in a dynamic way. I think it is not really secure depending on api response to be always right. So I should check the API response. How can I do that?

Hope you can help me, thanks :)

答:
To check if an API response is valid, use a class instead of an interface and give it an isValid function, and/or check the data in the constructor.

e.g.

interface IAuthResponseData {
  token: string;
  expires: string;
  role: string;
}

class AuthResponseData implements IAuthResponseData {
  public token: string;
  public expires: string;
  private __expires: Date;
  public role: string;

  public constructor(data: IAuthResponseData) {
    this.token = data.token;
    this.expires = data.expires;
    this.__expires = new Date(data.expires);
    this.role = data.role;
    if (!this.isValid()) {
      throw new Error("Invalid Parameters")
    }
  }

  public isValid(): boolean {
    // simple equals check against null is also true when the value is undefined
    for (let member in this) {
      if (this[member] == null) {
        return false;
      }
    }
    return true;
  }
}
```

Remember to catch the error and act on it, or leave the check out of the constructor and instead check after you created the object and then act on it.

Body:
I have an app that when the user logs in he received some data as a response, but if the response is not what I expect, the app crashes.

Let me show you the following:

I created an interface to tell Typescript the data I expect.

export interface AuthResponseData {
  token: string;
  expires: string;
  role: number;
}

Then I created a method to send the login data to the server.

login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    catchError(this.handleError),
    tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
  );
}

I was expecting that if the response from the server didn't match the interface then the Angular would redirect to catchError. But doesn't happen.

Now my question is: Is there any way to check if an API response is equal to the interface and throw an error if is not. Or what I'm asking isn't possible?

UPDATE:

After searching I discover that the interfaces disappear on run time, so there is no way to compare the api response with the interface (to the best of my knowledge). But I keep searching for a way to check the api response in a dynamic way. I think it is not really secure depending on api response to be always right. So I should check the API response. How can I do that?

Hope you can help me, thanks :)

Body:
To check if an API response is valid, use a class instead of an interface and give it an isValid function, and/or check the data in the constructor.

e.g.

interface IAuthResponseData {
  token: string;
  expires: string;
  role: string;
}

class AuthResponseData implements IAuthResponseData {
  public token: string;
  public expires: string;
  private __expires: Date;
  public role: string;

  public constructor(data: IAuthResponseData) {
    this.token = data.token;
    this.expires = data.expires;
    this.__expires = new Date(data.expires);
    this.role = data.role;
    if (!this.isValid()) {
      throw new Error("Invalid Parameters")
    }
  }

  public isValid(): boolean {
    // simple equals check against null is also true when the value is undefined
    for (let member in this) {
      if (this[member] == null) {
        return false;
      }
    }
    return true;
  }
}

Remember to catch the error and act on it, or leave the check out of the constructor and instead check after you created the object and then act on it.


问:
Change actionbar color programmatically more than once
I am using

```<code>getSherlockActivity().getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xff00ACED));
</code>```

To change the color of my action bar in a fragment and it works. But if i open this fragment then open another fragment that calls this method with a different color the actionbar doesn't change to the desired color. Instead it turns to a white color instead of the color I set it to.

答:
((AppCompatActivity) getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorPrimary)));

In the fragment and Java

Body:
I am using

getSherlockActivity().getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xff00ACED));

To change the color of my action bar in a fragment and it works. But if i open this fragment then open another fragment that calls this method with a different color the actionbar doesn't change to the desired color. Instead it turns to a white color instead of the color I set it to.


答:
You could use Oracle's REGEXP_LIKE here:

```<code>SELECT DISTINCT City
FROM Station
WHERE REGEXP_LIKE(City, '^.*[aeiou]$', 'i');
</code>```

The regex pattern ^.*[aeiou]$ will match any city name which ends in a vowel.  The third i parameter passed to REGEXP_LIKE tells Oracle to do the match in case insensitive mode, in case that would matter.

Body:
You could use Oracle's REGEXP_LIKE here:

SELECT DISTINCT City
FROM Station
WHERE REGEXP_LIKE(City, '^.*[aeiou]$', 'i');

The regex pattern ^.*[aeiou]$ will match any city name which ends in a vowel.  The third i parameter passed to REGEXP_LIKE tells Oracle to do the match in case insensitive mode, in case that would matter.


问:
Swapping characters using TRegEx in Delphi
I need to swap character dot with comma and vice versa simultaneously.

```<code>function TformMain.SwapString(input, fromSymbol, toSymbol: String): String;
begin
  Result := AnsiReplaceStr(input, fromSymbol, '_');  //100,200_00
  Result := AnsiReplaceStr(Result, toSymbol, fromSymbol); //100.200_00
  Result := AnsiReplaceStr(Result, '_', toSymbol); //100.200,00
end;
</code>```

How to do this using TRegEx in Delphi Rio?

答:
Although this is not an answer to your question (how to do this using regular expressions), I'd like to point out that this task can be performed with much greater runtime performance using a simple loop:

```<code>function SwapPeriodComma(const S: string): string;
var
  i: Integer;
begin
  Result := S;
  for i := 1 to S.Length do
    case S[i] of
      '.':
        Result[i] := ',';
      ',':
        Result[i] := '.';
    end;
end;
</code>```

This is much faster than both the AnsiReplaceStr approach and the regular expression approach.

Generalised to any two characters:

```<code>function SwapChars(const S: string; C1, C2: Char): string;
var
  i: Integer;
begin
  Result := S;
  for i := 1 to S.Length do
    if S[i] = C1 then
      Result[i] := C2
    else if S[i] = C2 then
      Result[i] := C1;
end;
</code>```

(If you are OK with a procedure instead of a function, you can do this in-place and save memory and gain speed. But most likely you don't need such optimisations.)

Body:
I need to swap character dot with comma and vice versa simultaneously.

function TformMain.SwapString(input, fromSymbol, toSymbol: String): String;
begin
  Result := AnsiReplaceStr(input, fromSymbol, '_');  //100,200_00
  Result := AnsiReplaceStr(Result, toSymbol, fromSymbol); //100.200_00
  Result := AnsiReplaceStr(Result, '_', toSymbol); //100.200,00
end;

How to do this using TRegEx in Delphi Rio?

Body:
Although this is not an answer to your question (how to do this using regular expressions), I'd like to point out that this task can be performed with much greater runtime performance using a simple loop:

function SwapPeriodComma(const S: string): string;
var
  i: Integer;
begin
  Result := S;
  for i := 1 to S.Length do
    case S[i] of
      '.':
        Result[i] := ',';
      ',':
        Result[i] := '.';
    end;
end;

This is much faster than both the AnsiReplaceStr approach and the regular expression approach.

Generalised to any two characters:

function SwapChars(const S: string; C1, C2: Char): string;
var
  i: Integer;
begin
  Result := S;
  for i := 1 to S.Length do
    if S[i] = C1 then
      Result[i] := C2
    else if S[i] = C2 then
      Result[i] := C1;
end;

(If you are OK with a procedure instead of a function, you can do this in-place and save memory and gain speed. But most likely you don't need such optimisations.)


问:
Problem with EOF when determining stream end
When I try to determine end of file with function feof(FILE *), I find it does not work as I expected: an extra read is required even if the stream does end. E.g., feof(FILE*) will not return true if invoked on a file with 10 bytes data just after reading 10 bytes out. I need an extra read operation which of course returns 0. Then feof(FILE *) will say "OK, now you reach the end."

Why is one more read required and how can I determine end of file or how can I know how many bytes are left in a file stream if I don't want the feof-style?

答:
Do not use feof() or any variants—it is as simple as that. You want it to somehow predict the next read will fail, but that's not what it does - it tells you what the result of the previous read was. The correct way to read a file is (in pseudocode):

while(read(file, buffer)) {
   // Do something with buffer
}
```

In other words, you need to test the result of the read operation. This is true for both C streams and C++ iostreams.

Body:
Do not use feof() or any variants—it is as simple as that. You want it to somehow predict the next read will fail, but that's not what it does - it tells you what the result of the previous read was. The correct way to read a file is (in pseudocode):

while(read(file, buffer)) {
   // Do something with buffer
}

In other words, you need to test the result of the read operation. This is true for both C streams and C++ iostreams.


问:
Remove Duplicate object from Array Deep Check
I have a array of objects, like:

```<code>[{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
}]
</code>```

I want this array to be unique on the basis of offerId. If offerId is the same, then I want to remove that object from the array.

答:
You can create an object which would have objectId as its key, like this:

```<code>var target = {};
for (let item of myArray) {
    if (target[item.objectId] === undefined) {
        target[item.objectId] = item;
    }
}
</code>```

and then, when you attempt to add to this array, you just check whether the item with the certain key already exists.

Body:
I have a array of objects, like:

[{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    }
  }
}]

I want this array to be unique on the basis of offerId. If offerId is the same, then I want to remove that object from the array.

Body:
You can create an object which would have objectId as its key, like this:

var target = {};
for (let item of myArray) {
    if (target[item.objectId] === undefined) {
        target[item.objectId] = item;
    }
}

and then, when you attempt to add to this array, you just check whether the item with the certain key already exists.


答:
I think you are looking for custom radio style like this

 .radio-custom {
    opacity: 0;
    position: absolute;
}

 .radio-custom, .radio-custom-label {
    display: inline-block;
    vertical-align: middle;
    margin: 5px;
    cursor: pointer;
}

.radio-custom-label {
    position: relative;
}

.radio-custom + .radio-custom-label:before {
    content: '';
    background: #fff;
    border: 2px solid #ddd;
    display: inline-block;
    vertical-align: middle;
    width: 20px;
    height: 20px;
    padding: 2px;
    margin-right: 10px;
    text-align: center;
}

.radio-custom + .radio-custom-label:before {
    border-radius: 50%;
}

.radio-custom:checked + .radio-custom-label:before {
    background: #ccc;
    box-shadow: inset 0px 0px 0px 4px #fff;
}

.radio-custom:focus + .radio-custom-label {
  outline: 1px solid #ddd; /* focus style */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <form>
        <h2>Radio Buttons</h2>
        <div>
            <input id="radio-1" class="radio-custom" name="radio-group" type="radio" checked>
            <label for="radio-1" class="radio-custom-label">First Choice</label>
        </div>
        <div>
            <input id="radio-2" class="radio-custom"name="radio-group" type="radio">
            <label for="radio-2" class="radio-custom-label">Second Choice</label>
        </div>
        <div>
            <input id="radio-3" class="radio-custom" name="radio-group" type="radio">
            <label for="radio-3" class="radio-custom-label">Third Choice</label>
        </div>
    </form></code>```

Title: Inner spacing inside rounded checkbox

Body:
I'm trying to achieve this:

I've also managed to get the result, but I cannot add the spacing between the grey border and blue circle:

input {
  line-height: normal;
  &[type="checkbox"],
  &[type="radio"] {
    width: 1.3em;
    height: 1.3em;
    background-color: white;
    border-radius: 50%;
    vertical-align: middle;
    border: 1px solid #ddd;
    border-width: thick;
    -webkit-appearance: none;
    outline: none;
    cursor: pointer;
  }
}

Body:
I think you are looking for custom radio style like this

 .radio-custom {
    opacity: 0;
    position: absolute;
}

 .radio-custom, .radio-custom-label {
    display: inline-block;
    vertical-align: middle;
    margin: 5px;
    cursor: pointer;
}

.radio-custom-label {
    position: relative;
}

.radio-custom + .radio-custom-label:before {
    content: '';
    background: #fff;
    border: 2px solid #ddd;
    display: inline-block;
    vertical-align: middle;
    width: 20px;
    height: 20px;
    padding: 2px;
    margin-right: 10px;
    text-align: center;
}

.radio-custom + .radio-custom-label:before {
    border-radius: 50%;
}

.radio-custom:checked + .radio-custom-label:before {
    background: #ccc;
    box-shadow: inset 0px 0px 0px 4px #fff;
}

.radio-custom:focus + .radio-custom-label {
  outline: 1px solid #ddd; /* focus style */
}

    <form>
        <h2>Radio Buttons</h2>
        <div>
            <input id="radio-1" class="radio-custom" name="radio-group" type="radio" checked>
            <label for="radio-1" class="radio-custom-label">First Choice</label>
        </div>
        <div>
            <input id="radio-2" class="radio-custom"name="radio-group" type="radio">
            <label for="radio-2" class="radio-custom-label">Second Choice</label>
        </div>
        <div>
            <input id="radio-3" class="radio-custom" name="radio-group" type="radio">
            <label for="radio-3" class="radio-custom-label">Third Choice</label>
        </div>
    </form>


问:
Conditional logic vs duplication in MVVM
We have a module with its Views, ViewModels and Models and a requirement came in to have an exact copy of the module, but part of the functionality has to be read-only.
The read-only mode should be turned on by a configuration parameter. The Model part is the same - it will use the same data sources.

I see two possible solutions to this problem:

Change the existing Views and ViewModels, by manipulating controls' interactivity based on the param.
Downsides of this approach is additional conditional logic. We're worried that if we do this, another requirement might come in, where we have to add more conditional logic. Upside - no duplication.

Another way is to split the existing view's into multiple components and assemble the regular module version and the read-only version using those components. We could disable interactivity on the View level in read-only versions and inherit from the ViewModel of the View which we're splitting from and override needed behaviour. The upside would be modularity. Downside - duplication, multiple places to maintain when new components are added in the future.

What's the preferred approach to solve problems like this?

答:
This is a little simpler than you think.

The most elegant approach is to have a flag or value contained within the viewmodel which represents the editable state of the data (this could simply be a true/false flag, but I've also seen cases where it can be represented as an enum because there are multiple conditions or states).

Then within the view you can bind the control's IsEnabled or IsReadOnly properties to that value (using a converter if necessary to change the value to a boolean).


问:
Visual Studio 2010 - Debug Breakpoint
Ive just created a new web site project , added a few lines of code in my .cs file set a break point, and nada, website works, but debug point is not hit.
Any ideas?

Im starting the project with Debugging, running on windows 7 64bit

thanks

答: Are you running VS as Administrator? If not Try Run As Administrator option.</p>

Title: Visual Studio 2010 - Debug Breakpoint