问:
SQL error "ORA-01722: invalid number"
A very easy one for someone,
The following insert is giving me the

ORA-01722: invalid number

why?

```<code>INSERT INTO CUSTOMER VALUES (1,'MALADY','Claire','27 Smith St Caulfield','0419 853 694');
INSERT INTO CUSTOMER VALUES (2,'GIBSON','Jake','27 Smith St Caulfield','0415 713 598');
INSERT INTO CUSTOMER VALUES (3,'LUU','Barry','5  Jones St Malvern','0413 591 341');
INSERT INTO CUSTOMER VALUES (4,'JONES','Michael','7  Smith St Caulfield','0419 853 694');
INSERT INTO CUSTOMER VALUES (5,'MALADY','Betty','27 Smith St Knox','0418 418 347');
</code>```

答:
Oracle does automatic String2number conversion, for String column values! However, for the textual comparisons in SQL, the input must be delimited as a String explicitly: The opposite conversion number2String is not performed automatically, not on the SQL-query level.

I had this query:

select max(acc_num) from ACCOUNTS where acc_num between 1001000 and 1001999;

That one presented a problem: Error: ORA-01722: invalid number

I have just surrounded the "numerical" values, to make them 'Strings', just making them explicitly delimited:

select max(acc_num) from ACCOUNTS where acc_num between '1001000' and '1001999';

...and voilà: It returns the expected result.

edit:
And indeed: the col acc_num in my table is defined as String. Although not numerical, the invalid number was reported. And the explicit delimiting of the string-numbers resolved the problem.

On the other hand, Oracle can treat Strings as numbers. So the numerical operations/functions can be applied on the Strings, and these queries work:

select max(string_column) from TABLE;

select string_column from TABLE where string_column between '2' and 'z';

select string_column from TABLE where string_column > '1';

select string_column from TABLE where string_column <= 'b';

Title: SQL error "ORA-01722: invalid number"

Body:
A very easy one for someone,
The following insert is giving me the

ORA-01722: invalid number

why?

INSERT INTO CUSTOMER VALUES (1,'MALADY','Claire','27 Smith St Caulfield','0419 853 694');
INSERT INTO CUSTOMER VALUES (2,'GIBSON','Jake','27 Smith St Caulfield','0415 713 598');
INSERT INTO CUSTOMER VALUES (3,'LUU','Barry','5  Jones St Malvern','0413 591 341');
INSERT INTO CUSTOMER VALUES (4,'JONES','Michael','7  Smith St Caulfield','0419 853 694');
INSERT INTO CUSTOMER VALUES (5,'MALADY','Betty','27 Smith St Knox','0418 418 347');

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Mysql Trigger with IF and IF ELSE conditions
i have table 'comments' with fields 'type','receiver_id' ,'confirm' and 'id'.
there are three types of object that each have comment section.
after comment confirm the trigger increase the number of objects in their respective table.

```<code>DB::unprepared('CREATE TRIGGER comment_confirm
        AFTER UPDATE ON comments FOR EACH ROW
        BEGIN
            IF OLD.confirm = 0 AND NEW.confirm = 1 THEN
                IF OLD.type = profile THEN
                    UPDATE profiles SET comments = comments + 1 WHERE user_id = OLD.reciever_id;
                ELSE IF OLD.type = blog THEN
                    UPDATE blogs SET comments = comments + 1 WHERE user_id = OLD.reciever_id;
                ELSE IF OLD.type = topic THEN
                    UPDATE topics SET comments = comments + 1 WHERE user_id = OLD.reciever_id;
                END IF;
            END IF;
        END
        ');
</code>```

the error for migration is:

```<code>[PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 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 '' at line 13
</code>```

答: Else if should be elseif (no space) IF OLD.type = profile doesn't look right should be in single quotes for a string comparison.</p>

ContentLicense: CC BY-SA 3.0

Body:
i have table 'comments' with fields 'type','receiver_id' ,'confirm' and 'id'.
there are three types of object that each have comment section.
after comment confirm the trigger increase the number of objects in their respective table.

DB::unprepared('CREATE TRIGGER comment_confirm
        AFTER UPDATE ON comments FOR EACH ROW
        BEGIN
            IF OLD.confirm = 0 AND NEW.confirm = 1 THEN
                IF OLD.type = profile THEN
                    UPDATE profiles SET comments = comments + 1 WHERE user_id = OLD.reciever_id;
                ELSE IF OLD.type = blog THEN
                    UPDATE blogs SET comments = comments + 1 WHERE user_id = OLD.reciever_id;
                ELSE IF OLD.type = topic THEN
                    UPDATE topics SET comments = comments + 1 WHERE user_id = OLD.reciever_id;
                END IF;
            END IF;
        END
        ');

the error for migration is:

[PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 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 '' at line 13


问:
Changing background colour subject to the value of the Name attribute
I've been experimenting with a Codepen and I'm looking to change the background color of a span subject to the value of the HTML's Name attribute.

The following codepen demonstrates where I am so far:

```<code><div class="card-body">
  <span id="community" class="card-community-tag" Name="test">Community 1</span>
  <span class="card-community-tag">Community 2</span>
</div>

document.load(function changeBackground() {
    var communityName = document.getElementById("community");
    if (communityName.getAttribute("Name") == "test") {
        communityName.style.backgroundColor = "red";
    }
});
</code>```

What am I doing wrong?

My end goal is for the JS to check the name attribute of a given  to determine what the background-color of that  should be.

答:
Use document.addEventListener('DOMContentLoaded', function() {}) (MDN) instead of document.load():

document.addEventListener('DOMContentLoaded', function() {
    var communityName = document.getElementById("community");
    if (communityName.getAttribute("Name") == "test") {
        communityName.style.backgroundColor = "red";
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card-body">
  <span id="community" class="card-community-tag" Name="test">Community 1</span>
  <span class="card-community-tag">Community 2</span>
</div></code>```

Body:
I've been experimenting with a Codepen and I'm looking to change the background color of a span subject to the value of the HTML's Name attribute.

The following codepen demonstrates where I am so far:

  Community 1
  Community 2

document.load(function changeBackground() {
    var communityName = document.getElementById("community");
    if (communityName.getAttribute("Name") == "test") {
        communityName.style.backgroundColor = "red";
    }
});

What am I doing wrong?

My end goal is for the JS to check the name attribute of a given  to determine what the background-color of that  should be.

Body:
Use document.addEventListener('DOMContentLoaded', function() {}) (MDN) instead of document.load():

document.addEventListener('DOMContentLoaded', function() {
    var communityName = document.getElementById("community");
    if (communityName.getAttribute("Name") == "test") {
        communityName.style.backgroundColor = "red";
    }
});

<div class="card-body">
  <span id="community" class="card-community-tag" Name="test">Community 1</span>
  <span class="card-community-tag">Community 2</span>
</div>


问:
How to change variables in a cfg.py file from another file?
I'm trying to create a config file to store some values that I'll be playing with in another file. But then I would like another main file to change the variables in the config file like so:

my config file:

```<code>#cfg.py
a = [2,3,4]
</code>```

my main file:

```<code>#main.py
import cfg
print(cfg.a)
cfg.a[1] = 10
print(cfg.a)
</code>```

It returns

```<code>[2,3,4]
[2,10,4]
</code>```

which is fine, but when I close everything and look at my cfg.py again, the value of a in the cfg.py file did not change. Am I missing something? Am I supposed to use some sort of save function to make sure that I'm writing new values into the file? Or am I going about this in the totally wrong way?

It seems like I'm changing an instance of cfg.a instead of the reference to a in the original cfg.py file.

答:
You could use "configobj" package with some minor adjustments.

The config file can be like this:

```<code>#cfg.py
a = 2,3,4
</code>```

Then in python:

```<code>import configobj
conf = configobj.ConfigObj("cfg.py")
conf["a"][1] = 10
conf.write()  # Actually writes changes to file
</code>```

Body:
I'm trying to create a config file to store some values that I'll be playing with in another file. But then I would like another main file to change the variables in the config file like so:

my config file:

#cfg.py
a = [2,3,4]

my main file:

#main.py
import cfg
print(cfg.a)
cfg.a[1] = 10
print(cfg.a)

It returns

[2,3,4]
[2,10,4]

which is fine, but when I close everything and look at my cfg.py again, the value of a in the cfg.py file did not change. Am I missing something? Am I supposed to use some sort of save function to make sure that I'm writing new values into the file? Or am I going about this in the totally wrong way?

It seems like I'm changing an instance of cfg.a instead of the reference to a in the original cfg.py file.

Body:
You could use "configobj" package with some minor adjustments.

The config file can be like this:

#cfg.py
a = 2,3,4

Then in python:

import configobj
conf = configobj.ConfigObj("cfg.py")
conf["a"][1] = 10
conf.write()  # Actually writes changes to file


问:
Calcite over MySql, tries to convert the id column to bigint
I'm trying to use Calcite to query MySql and Vertica in the same query:

MySql table: CREATE TABLE tableA (id INT(11), name VARCHAR(5), PRIMARY KEY(id));

Vertica table: CREATE TABLE tableB (id INTEGER NOT NULL, name VARCHAR(20), PRIMARY KEY (id));

When running the following query using Calcite:

```<code>statement.executeQuery(
            "SELECT a.\"name\", b.\"name\" " +
            "FROM \"mysqlschema\".\"tableA\" as a " +
            "INNER JOIN \"verticaschema\".\"tableB\" as b ON a.\"id\" = b.\"id\" " +
            "WHERE a.\"id\" = 1 "))
</code>```

I'm getting:

```<code>    Exception in thread "main" java.sql.SQLException: Error while executing SQL "SELECT a."name", b."name" FROM "mysqlschema"."tableA" as a INNER JOIN "verticaschema"."tableB" as b ON a."id" = b."id" WHERE a."id" = 1 ": while executing SQL [SELECT `id`, `name`, CAST(`id` AS BIGINT) AS `id0`
FROM `mysqlschema`.`tableA`
WHERE `id` = 1]
    at org.apache.calcite.avatica.Helper.createException(Helper.java:56)
    at org.apache.calcite.avatica.Helper.createException(Helper.java:41)
    at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:156)
    at org.apache.calcite.avatica.AvaticaStatement.executeQuery(AvaticaStatement.java:218)
    at com.test.TestCalcite.main(TestCalcite.java:73)
Caused by: java.lang.RuntimeException: while executing SQL [SELECT `id`, `name`, CAST(`id` AS BIGINT) AS `id0`
FROM `mysqlschema`.`tableA`
WHERE `id` = 1]
    at org.apache.calcite.runtime.ResultSetEnumerable.enumerator(ResultSetEnumerable.java:153)
    at org.apache.calcite.linq4j.EnumerableDefaults$10$1.<init>(EnumerableDefaults.java:1100)
    at org.apache.calcite.linq4j.EnumerableDefaults$10.enumerator(EnumerableDefaults.java:1099)
    at Baz$6$1.<init>(Unknown Source)
    at Baz$6.enumerator(Unknown Source)
    at org.apache.calcite.linq4j.AbstractEnumerable.iterator(AbstractEnumerable.java:33)
    at org.apache.calcite.avatica.MetaImpl.createCursor(MetaImpl.java:90)
    at org.apache.calcite.avatica.AvaticaResultSet.execute(AvaticaResultSet.java:206)
    at org.apache.calcite.jdbc.CalciteResultSet.execute(CalciteResultSet.java:67)
    at org.apache.calcite.jdbc.CalciteResultSet.execute(CalciteResultSet.java:44)
    at org.apache.calcite.avatica.AvaticaConnection$1.execute(AvaticaConnection.java:630)
    at org.apache.calcite.jdbc.CalciteMetaImpl.prepareAndExecute(CalciteMetaImpl.java:607)
    at org.apache.calcite.avatica.AvaticaConnection.prepareAndExecuteInternal(AvaticaConnection.java:638)
    at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:149)
    ... 2 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'BIGINT) AS `id0`
FROM `mysqlschema`.`tableA`
WHERE `id` = 1' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.Util.getInstance(Util.java:387)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2505)
    at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:840)
    at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:740)
    at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264)
    at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264)
    at org.apache.calcite.runtime.ResultSetEnumerable.enumerator(ResultSetEnumerable.java:143)
</code>```

Converting the id column in the MySql table solves it but I can't convert as I'm dealing with existing tables which cannot be changed.

Any thoughts on how to work around this?

Thanks

答:
Solved by casting the id in B:</p>

```<code>ON a."id" = CAST(b."b" AS INT)
</code>```

Body:
I'm trying to use Calcite to query MySql and Vertica in the same query:

MySql table: CREATE TABLE tableA (id INT(11), name VARCHAR(5), PRIMARY KEY(id));

Vertica table: CREATE TABLE tableB (id INTEGER NOT NULL, name VARCHAR(20), PRIMARY KEY (id));

When running the following query using Calcite:

statement.executeQuery(
            "SELECT a.\"name\", b.\"name\" " +
            "FROM \"mysqlschema\".\"tableA\" as a " +
            "INNER JOIN \"verticaschema\".\"tableB\" as b ON a.\"id\" = b.\"id\" " +
            "WHERE a.\"id\" = 1 "))

I'm getting:

    Exception in thread "main" java.sql.SQLException: Error while executing SQL "SELECT a."name", b."name" FROM "mysqlschema"."tableA" as a INNER JOIN "verticaschema"."tableB" as b ON a."id" = b."id" WHERE a."id" = 1 ": while executing SQL [SELECT `id`, `name`, CAST(`id` AS BIGINT) AS `id0`
FROM `mysqlschema`.`tableA`
WHERE `id` = 1]
    at org.apache.calcite.avatica.Helper.createException(Helper.java:56)
    at org.apache.calcite.avatica.Helper.createException(Helper.java:41)
    at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:156)
    at org.apache.calcite.avatica.AvaticaStatement.executeQuery(AvaticaStatement.java:218)
    at com.test.TestCalcite.main(TestCalcite.java:73)
Caused by: java.lang.RuntimeException: while executing SQL [SELECT `id`, `name`, CAST(`id` AS BIGINT) AS `id0`
FROM `mysqlschema`.`tableA`
WHERE `id` = 1]
    at org.apache.calcite.runtime.ResultSetEnumerable.enumerator(ResultSetEnumerable.java:153)
    at org.apache.calcite.linq4j.EnumerableDefaults$10$1.<init>(EnumerableDefaults.java:1100)
    at org.apache.calcite.linq4j.EnumerableDefaults$10.enumerator(EnumerableDefaults.java:1099)
    at Baz$6$1.<init>(Unknown Source)
    at Baz$6.enumerator(Unknown Source)
    at org.apache.calcite.linq4j.AbstractEnumerable.iterator(AbstractEnumerable.java:33)
    at org.apache.calcite.avatica.MetaImpl.createCursor(MetaImpl.java:90)
    at org.apache.calcite.avatica.AvaticaResultSet.execute(AvaticaResultSet.java:206)
    at org.apache.calcite.jdbc.CalciteResultSet.execute(CalciteResultSet.java:67)
    at org.apache.calcite.jdbc.CalciteResultSet.execute(CalciteResultSet.java:44)
    at org.apache.calcite.avatica.AvaticaConnection$1.execute(AvaticaConnection.java:630)
    at org.apache.calcite.jdbc.CalciteMetaImpl.prepareAndExecute(CalciteMetaImpl.java:607)
    at org.apache.calcite.avatica.AvaticaConnection.prepareAndExecuteInternal(AvaticaConnection.java:638)
    at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:149)
    ... 2 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'BIGINT) AS `id0`
FROM `mysqlschema`.`tableA`
WHERE `id` = 1' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.Util.getInstance(Util.java:387)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2505)
    at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:840)
    at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:740)
    at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264)
    at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264)
    at org.apache.calcite.runtime.ResultSetEnumerable.enumerator(ResultSetEnumerable.java:143)

Converting the id column in the MySql table solves it but I can't convert as I'm dealing with existing tables which cannot be changed.

Any thoughts on how to work around this?

Thanks

Body:
Solved by casting the id in B:

ON a."id" = CAST(b."b" AS INT)


问:
Conditioning on the length of values in two columns to assign a value
I have a data frame with two columns.

```<code>C1  C2
A  T
T  T
T  G
TTG T
G  GTGA
AAT A
</code>```

I want to go through the dataset, and turn column C1 into either a "D" if the length of it's value is less than C2, or to an "I" if the length is greater than C2

Desired output:

```<code>C1  C2
A  T
T  T
T  G
I  T
D GTGA
I  A
</code>```

答:
We can use case_when to do this

```<code>library(dplyr)
df1 %>%
    mutate(C1 = case_when(nchar(C1) < nchar(C2) ~ 'D',
                          nchar(C1) > nchar(C2) ~ 'I',
                          TRUE ~ C1))
#   C1   C2
#1  A    T
#2  T    T
#3  T    G
#4  I    T
#5  D GTGA
#6  I    A
</code>```

Body:
I have a data frame with two columns.

C1  C2
A  T
T  T
T  G
TTG T
G  GTGA
AAT A

I want to go through the dataset, and turn column C1 into either a "D" if the length of it's value is less than C2, or to an "I" if the length is greater than C2

Desired output:

C1  C2
A  T
T  T
T  G
I  T
D GTGA
I  A

Body:
We can use case_when to do this

library(dplyr)
df1 %>%
    mutate(C1 = case_when(nchar(C1) < nchar(C2) ~ 'D',
                          nchar(C1) > nchar(C2) ~ 'I',
                          TRUE ~ C1))
#   C1   C2
#1  A    T
#2  T    T
#3  T    G
#4  I    T
#5  D GTGA
#6  I    A


问:
Remove commas in list and make a sentence with list items
So basically I have a list with 4 items.

```<code>list = ['My', 'name', 'is', 'mike']
</code>```

What I want to do is to remove the commas that split the items and make one string. The removed commas should be replaced with space. What I have seen so far is the replace method for string's. I have been wondering if there is something similar for lists.

答:
Use</p>

```<code>>>> ' '.join(list)
'My name is mike'
</code>```

Body:
So basically I have a list with 4 items.

list = ['My', 'name', 'is', 'mike']

What I want to do is to remove the commas that split the items and make one string. The removed commas should be replaced with space. What I have seen so far is the replace method for string's. I have been wondering if there is something similar for lists.

Body:
Use

>>> ' '.join(list)
'My name is mike'


问:
How can I check if a given member_descriptor object holds a value for a reference instance
I'm working on an advanced interface that works mildly similar to Blender's property definitions.

what I'm doing to handle data is overwriting a member_descriptor object with a property that keeps reference of the member_descriptor's methods internally.

```<code>class Object(object):
    """an example"""
    __slots__ = ['item']
    def __init__(obj):
        obj.item = static_object() # stored in the descriptor and updated

def reassign():
    dscget = Object.item.__get__
    dscset = Object.item.__set__

    def setter(obj, val):
        """my problem lies here"""
        if hasattr(Object, 'item'): # this will create an infinite recursion loop
            dscget(obj,Object).update(val)
        elif val.__class__ is static_object: dscset(obj,val)
        else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )

    Object.item = property( dscget, setter )
</code>```

so since hasattr checks the property, which checks the property, and so on, what would be a more efficient and performative way of checking if the descriptor holds the required item??

I don't want to use try because except AttributeError is super slow...

for example:

```<code>    def setter(obj, val):
        """the slow method"""
        try: dscget(obj,Object).update(val)
        except AttributeError: # because the descriptor holds nothing.
            if val.__class__ is static_object: dscset(obj,val)
            else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )
</code>```

is there an alternate method, or is this poop the best I got??

答:
You can use the type function. For example: </p>

```<code>if(type(YourObjectInstance) is YourObject)
if(type(5) is int)
</code>```

Body:
I'm working on an advanced interface that works mildly similar to Blender's property definitions.

what I'm doing to handle data is overwriting a member_descriptor object with a property that keeps reference of the member_descriptor's methods internally.

class Object(object):
    """an example"""
    __slots__ = ['item']
    def __init__(obj):
        obj.item = static_object() # stored in the descriptor and updated

def reassign():
    dscget = Object.item.__get__
    dscset = Object.item.__set__

    def setter(obj, val):
        """my problem lies here"""
        if hasattr(Object, 'item'): # this will create an infinite recursion loop
            dscget(obj,Object).update(val)
        elif val.__class__ is static_object: dscset(obj,val)
        else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )

    Object.item = property( dscget, setter )

so since hasattr checks the property, which checks the property, and so on, what would be a more efficient and performative way of checking if the descriptor holds the required item??

I don't want to use try because except AttributeError is super slow...

for example:

    def setter(obj, val):
        """the slow method"""
        try: dscget(obj,Object).update(val)
        except AttributeError: # because the descriptor holds nothing.
            if val.__class__ is static_object: dscset(obj,val)
            else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )

is there an alternate method, or is this poop the best I got??

Body:
You can use the type function. For example:

if(type(YourObjectInstance) is YourObject)
if(type(5) is int)


问:
bind function parameters to thread
I tried calling a function with parameters, using boost, but it does not work. the code is this

```<code>void Simulate::cr_number_threaded(lint nodes) {
    for(lint i = 0; i < trials_per_thread; i++) {
        // code
    }

}

void Simulate::run_cr_number() {
    vec_cr_number.clear();
    boost::thread t[threads];

    for(int i = 0; i < n_s.size(); i++) {
        // n_s[i] is the current number of nodes
        for(int t_idx = 0; t_idx < threads; t_idx++)
            t[t_idx] = boost::thread(cr_number_threaded, n_s[i]);
        // etc...
    }

}
</code>```

the error I get is the following:

Simulate.cpp: In member function 'void
  Simulate::run_cr_number()':
  Simulate.cpp:27: error: no matching
  function for call to
  'boost::thread::thread(, long int&)'

UPDATE:
I followed the suggestions. Using the first solution I get

Simulate.cpp: In member function 'void
  Simulate::run_cr_number()':
  Simulate.cpp:28: error: no matching
  function for call to 'bind(, long int&)'
  ../../boost_1_44_0/boost/bind/bind.hpp:1472:
  note: candidates are:
  boost::_bi::bind_t::type>
  boost::bind(F, A1) [with F = void
  (Simulate::*)(lint), A1 = long int]
  ../../boost_1_44_0/boost/bind/bind.hpp:1728:
  note:

  boost::_bi::bind_t::type, boost::_mfi::dm,
  typename
  boost::_bi::list_av_1::type>
  boost::bind(M T::*, A1) [with A1 =
  long int, M = void ()(lint), T =
  Simulate]

using the second one I get this instead

Simulate.cpp: In member function 'void
  Simulate::run_cr_number()':
  Simulate.cpp:28: error: no matching
  function for call to
  'boost::thread::swap(boost::_bi::bind_t,
  boost::_bi::list2,
  boost::_bi::value > >)'
  ../../boost_1_44_0/boost/thread/detail/thread.hpp:310: note: candidates are: void
  boost::thread::swap(boost::thread&)

答:
1) boost::thread is not copyable but swappable

2) you need to specify member function and pass an instance

something like this:

```<code>t[t_idx].swap(boost::thread(&Simulate::cr_number_threaded, this, n_s[i]));
</code>```

in this case you need to be sure that this will live longer than threads.

ContentLicense: CC BY-SA 2.5

Title: bind function parameters to thread

Body:
I tried calling a function with parameters, using boost, but it does not work. the code is this

void Simulate::cr_number_threaded(lint nodes) {
    for(lint i = 0; i < trials_per_thread; i++) {
        // code
    }

}

void Simulate::run_cr_number() {
    vec_cr_number.clear();
    boost::thread t[threads];

    for(int i = 0; i < n_s.size(); i++) {
        // n_s[i] is the current number of nodes
        for(int t_idx = 0; t_idx < threads; t_idx++)
            t[t_idx] = boost::thread(cr_number_threaded, n_s[i]);
        // etc...
    }

}

the error I get is the following:

Simulate.cpp: In member function 'void
  Simulate::run_cr_number()':
  Simulate.cpp:27: error: no matching
  function for call to
  'boost::thread::thread(, long int&)'

UPDATE:
I followed the suggestions. Using the first solution I get

Simulate.cpp: In member function 'void
  Simulate::run_cr_number()':
  Simulate.cpp:28: error: no matching
  function for call to 'bind(, long int&)'
  ../../boost_1_44_0/boost/bind/bind.hpp:1472:
  note: candidates are:
  boost::_bi::bind_t::type>
  boost::bind(F, A1) [with F = void
  (Simulate::*)(lint), A1 = long int]
  ../../boost_1_44_0/boost/bind/bind.hpp:1728:
  note:

  boost::_bi::bind_t::type, boost::_mfi::dm,
  typename
  boost::_bi::list_av_1::type>
  boost::bind(M T::*, A1) [with A1 =
  long int, M = void ()(lint), T =
  Simulate]

using the second one I get this instead

Simulate.cpp: In member function 'void
  Simulate::run_cr_number()':
  Simulate.cpp:28: error: no matching
  function for call to
  'boost::thread::swap(boost::_bi::bind_t,
  boost::_bi::list2,
  boost::_bi::value > >)'
  ../../boost_1_44_0/boost/thread/detail/thread.hpp:310: note: candidates are: void
  boost::thread::swap(boost::thread&)

Body:
1) boost::thread is not copyable but swappable

2) you need to specify member function and pass an instance

something like this:

t[t_idx].swap(boost::thread(&Simulate::cr_number_threaded, this, n_s[i]));

in this case you need to be sure that this will live longer than threads.


问:
How to remove scripts tags inside another code by regex
I'm trying to remove script tags from the source code using regular expression.

```<code>/<\s*script[^>]*[^\/]>(.*?)<\s*\/\s*script\s*>/is
</code>```

But I ran into the problem when I need to remove the code inside another code.

Please see this screenshot

I'm tested in https://regex101.com/r/R6XaUT/1

How do I correctly create a regular expression so that it can cover all the code?

答:
Simply use the PHP function strip_tags. See

http://php.net/manual/de/function.strip-tags.php

```<code>$string = "<div>hello</div>";
echo strip_tags($string);
</code>```

Will output

```<code>hello
</code>```

You also can provide a list of tags to keep.

==

Another approach is this:

```<code>// Load a file into $html
$html = file_get_contents('scratch.html');
$matches = [];
preg_match_all("/<\/*([^\s>]*)>/", $html, $matches);

// Have a list of all Tags only once
$tags = array_unique($matches[1]);

// Find the script index and remove it
$scriptTagIndex = array_search("script", $tags);
if($scriptTagIndex !== false) unset($tags[$scriptTagIndex]);

// Taglist must be a string containing <tagname1><tagename2>...
$allowedTags = array_map(function ($s) { return "<$s>"; }, $tags);

// Stript the HTML and keep all Tags except for removed ones (script)
$noScript = strip_tags($html,join("", $allowedTags));

echo $noScript;
</code>```

Body:
I'm trying to remove script tags from the source code using regular expression.

/<\s*script[^>]*[^\/]>(.*?)<\s*\/\s*script\s*>/is

But I ran into the problem when I need to remove the code inside another code.

Please see this screenshot

I'm tested in https://regex101.com/r/R6XaUT/1

How do I correctly create a regular expression so that it can cover all the code?

Body:
Simply use the PHP function strip_tags. See

http://php.net/manual/de/function.strip-tags.php

$string = "<div>hello</div>";
echo strip_tags($string);

Will output

hello

You also can provide a list of tags to keep.

==

Another approach is this:

// Load a file into $html
$html = file_get_contents('scratch.html');
$matches = [];
preg_match_all("/<\/*([^\s>]*)>/", $html, $matches);

// Have a list of all Tags only once
$tags = array_unique($matches[1]);

// Find the script index and remove it
$scriptTagIndex = array_search("script", $tags);
if($scriptTagIndex !== false) unset($tags[$scriptTagIndex]);

// Taglist must be a string containing <tagname1><tagename2>...
$allowedTags = array_map(function ($s) { return "<$s>"; }, $tags);

// Stript the HTML and keep all Tags except for removed ones (script)
$noScript = strip_tags($html,join("", $allowedTags));

echo $noScript;


问:
I don't understand why it doesn't let me check 'contains' on switch cases
I was trying to do the following:

```<code>var stringwithcharactherTofind = "booboo$booboo"

switch stringwithcharactherTofind{
  case stringwithcharactherTofind.ifhasprefix("$"):
  stringwithcharactherTofind = "done"
  default:
  break
}
</code>```

Is it possible to do this?

At all

答:
The switch statement matches the given value against the given patterns.
stringwithcharactherTofind.hasprefix("$") is a boolean expression
and not a pattern that a string can be matched against.

You could (ab)use the where clause in combination with the
wildcard pattern:

```<code>let str = "FooBar"

switch str {
case _ where str.hasPrefix("Foo"):
    print("prefix")
case _ where str.contains("Foo"):
    print("contains")
default:
    print("nope")
}
</code>```

You could even define a pattern match operator which allows to
match a value against a boolean predicate (also demonstrated
here):

```<code>func ~=<T>(lhs: (T) -> Bool, rhs: T) -> Bool {
    return lhs(rhs)
}

let str = "FooBar"

switch str {
case { $0.hasPrefix("Foo") }:
    print("prefix")
case { $0.contains("Foo") }:
    print("contains")
default:
    print("nope")
}
</code>```

But why make it so complicated? A if/else if/else statement
does exactly what you need:

```<code>if str.hasPrefix("Foo") {
    print("prefix")
} else if str.contains("Foo") {
    print("contains")
} else {
    print("nope")
}
</code>```

Body:
I was trying to do the following:

var stringwithcharactherTofind = "booboo$booboo"

switch stringwithcharactherTofind{
  case stringwithcharactherTofind.ifhasprefix("$"):
  stringwithcharactherTofind = "done"
  default:
  break
}

Is it possible to do this?

At all

Body:
The switch statement matches the given value against the given patterns.
stringwithcharactherTofind.hasprefix("$") is a boolean expression
and not a pattern that a string can be matched against.

You could (ab)use the where clause in combination with the
wildcard pattern:

let str = "FooBar"

switch str {
case _ where str.hasPrefix("Foo"):
    print("prefix")
case _ where str.contains("Foo"):
    print("contains")
default:
    print("nope")
}

You could even define a pattern match operator which allows to
match a value against a boolean predicate (also demonstrated
here):

func ~=<T>(lhs: (T) -> Bool, rhs: T) -> Bool {
    return lhs(rhs)
}

let str = "FooBar"

switch str {
case { $0.hasPrefix("Foo") }:
    print("prefix")
case { $0.contains("Foo") }:
    print("contains")
default:
    print("nope")
}

But why make it so complicated? A if/else if/else statement
does exactly what you need:

if str.hasPrefix("Foo") {
    print("prefix")
} else if str.contains("Foo") {
    print("contains")
} else {
    print("nope")
}


问:
SQL get latest row in one to many relationship using where clause only
I have two tables in which (roll_no) is same in both tables.
I have a table (student) having columns name and roll_no. e.g

```<code>roll_no    name
----------------
123        John
</code>```

It has relation with another table (student_changed). Which has columns name, roll_no and LastEditTime. e.g.

```<code>roll_no    name     LastEditTime
--------------------------------------
123        Johny    2017-11-09 06:00:00
123        John     2017-11-08 07:00:00
</code>```

What I want to ask is, how can I get the join having the most recent LastEditTime.
There are many similar questions but my limitation is that I can only use/modify where clause.
e.g.
I cannot modify the select query as well.
Consider it like this

```<code>select * from student, student_changed <-- *this part cannot be changed*
where <-- This can be modified
</code>```

答:
Thanks for all the answers but I managed to get it working by the following where clause.</p>

```<code>where student.roll_no = student_changed.roll_no
and LASTEDITTIME in(select max(LASTEDITTIME) from student_changed where student.roll_no = student_changed.roll_no)
</code>```

Body:
I have two tables in which (roll_no) is same in both tables.
I have a table (student) having columns name and roll_no. e.g

roll_no    name
----------------
123        John

It has relation with another table (student_changed). Which has columns name, roll_no and LastEditTime. e.g.

roll_no    name     LastEditTime
--------------------------------------
123        Johny    2017-11-09 06:00:00
123        John     2017-11-08 07:00:00

What I want to ask is, how can I get the join having the most recent LastEditTime.
There are many similar questions but my limitation is that I can only use/modify where clause.
e.g.
I cannot modify the select query as well.
Consider it like this

select * from student, student_changed <-- *this part cannot be changed*
where <-- This can be modified

Body:
Thanks for all the answers but I managed to get it working by the following where clause.

where student.roll_no = student_changed.roll_no
and LASTEDITTIME in(select max(LASTEDITTIME) from student_changed where student.roll_no = student_changed.roll_no)


问:
Async support not enabled even though it should be by default
I have a application built with spring boot and google app engine. I've tried implementing sever sent events by following this https://golb.hplar.ch/p/Server-Sent-Events-with-Spring tutorial.
When I build and try to access the endpoint that creates the sse-emitter I get the following error

```<code>   java.lang.IllegalStateException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml.
</code>```

Which is weird because spring-boot should have async support enabled by default https://github.com/spring-projects/spring-boot/issues/1665 as it says in this issue.

I've tried adding the following code that was suggested on some stackoverflow threads but still the same issue. Is there a way around this error?

```<code>@Bean
public ServletRegistrationBean dispatcherServlet() {
    ServletRegistrationBean registration = new
    ServletRegistrationBean(new DispatcherServlet(), "/");
    registration.setAsyncSupported(true);
    return registration;
}
</code>```

It's worth adding that I had the same problem when trying to implement websockets which I later gave up on in favour of server sent events.
Here's the code:

pom.xml

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- Exclude Tomcat so that it doesn't conflict w/ Jetty server -->
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.google.appengine</groupId>
        <artifactId>appengine-api-1.0-sdk</artifactId>
        <version>1.9.54</version>
    </dependency>
    <dependency>                        <!-- Google Core Libraries for Java -->
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>  <!-- https://github.com/google/guava/wiki -->
        <!-- Guava v21.0 doesn't support Java7 -->
        <version>20.0</version>
        <scope>compile</scope>
    </dependency>
    <dependency>                        <!-- Google Cloud Client Library for Java -->
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-storage</artifactId>
        <version>1.3.1</version>
    </dependency>
    <!-- Exclude any jul-to-slf4j -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jul-to-slf4j</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- Include Servlet API -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-datastore</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.1</version>
     </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <version>1.5.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.social</groupId>
        <artifactId>spring-social-core</artifactId>
        <version>1.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session</artifactId>
        <version>1.3.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.18</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.webjars.bower</groupId>
        <artifactId>jquery</artifactId>
        <version>2.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.1</version>
    </dependency>
</dependencies>
</code>```

The Java code:

```<code>@SpringBootApplication
@EnableOAuth2Sso
public class SpringBootExampleApplication extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
                .authorizeRequests()
                    .anyRequest() // This is just temporary. Otherwise only "/" is permited
                        .permitAll();
    }
    public static void main(String[] args) {
        SpringApplication.run(SpringBootExampleApplication.class, args);
    }
}
</code>```

The controller:

```<code>@Controller
public class SSEController {
    private final CopyOnWriteArrayList<SseEmitter> emitters = new CopyOnWriteArrayList<>();
    @GetMapping("/memory")
    public SseEmitter handle() {
        SseEmitter emitter = new SseEmitter();
        // SseEmitter emitter = new SseEmitter(180_000L);
        this.emitters.add(emitter);
        emitter.onCompletion(() -> this.emitters.remove(emitter));
        emitter.onTimeout(() -> this.emitters.remove(emitter));
        return emitter;
    }
    @EventListener
    public void onMemoryInfo(MemoryInfo memoryInfo) {
        List<SseEmitter> deadEmitters = new ArrayList<>();
        this.emitters.forEach(emitter -> {
            try {
                emitter.send(memoryInfo);
            }
            catch (Exception e) {
                deadEmitters.add(emitter);
            }
        });
        this.emitters.removeAll(deadEmitters);
    }
}
</code>```

The scheduled service:

```<code>@Service
public class MemoryObserverJob {
  public final ApplicationEventPublisher eventPublisher;
  public MemoryObserverJob(ApplicationEventPublisher eventPublisher) {
    this.eventPublisher = eventPublisher;
  }
  @Scheduled(fixedRate = 1000)
  public void doSomething() {
    MemoryInfo mi = new MemoryInfo(123L, 123L);
    this.eventPublisher.publishEvent(mi);
  }
}
</code>```

Template for the message:

```<code>public class MemoryInfo {
    private final long heap;
    private final long nonHeap;
    private final long ts;
    public MemoryInfo(long heap, long nonHeap) {
        this.ts = System.currentTimeMillis();
        this.heap = heap;
        this.nonHeap = nonHeap;
    }
    public long getHeap() {
        return this.heap;
    }
    public long getNonHeap() {
        return this.nonHeap;
    }
    public long getTs() {
        return this.ts;
    }
}
</code>```

答:
Annotate your BootApplication with @EnableAsync

```<code>@SpringBootApplication
@EnableAsync
@EnableOAuth2Sso
public class SpringBootExampleApplication
</code>```

then add another to your methods that you want to async.

```<code>@Async
public void methodToAsync(){...}
</code>```

Body:
I have a application built with spring boot and google app engine. I've tried implementing sever sent events by following this https://golb.hplar.ch/p/Server-Sent-Events-with-Spring tutorial.
When I build and try to access the endpoint that creates the sse-emitter I get the following error

   java.lang.IllegalStateException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml.

Which is weird because spring-boot should have async support enabled by default https://github.com/spring-projects/spring-boot/issues/1665 as it says in this issue.

I've tried adding the following code that was suggested on some stackoverflow threads but still the same issue. Is there a way around this error?

@Bean
public ServletRegistrationBean dispatcherServlet() {
    ServletRegistrationBean registration = new
    ServletRegistrationBean(new DispatcherServlet(), "/");
    registration.setAsyncSupported(true);
    return registration;
}

It's worth adding that I had the same problem when trying to implement websockets which I later gave up on in favour of server sent events.
Here's the code:

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>

        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.google.appengine</groupId>
        <artifactId>appengine-api-1.0-sdk</artifactId>
        <version>1.9.54</version>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>

        <version>20.0</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-storage</artifactId>
        <version>1.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jul-to-slf4j</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-datastore</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.1</version>
     </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <version>1.5.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.social</groupId>
        <artifactId>spring-social-core</artifactId>
        <version>1.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session</artifactId>
        <version>1.3.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.18</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.webjars.bower</groupId>
        <artifactId>jquery</artifactId>
        <version>2.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.1</version>
    </dependency>
</dependencies>

The Java code:

@SpringBootApplication
@EnableOAuth2Sso
public class SpringBootExampleApplication extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
                .authorizeRequests()
                    .anyRequest() // This is just temporary. Otherwise only "/" is permited
                        .permitAll();
    }
    public static void main(String[] args) {
        SpringApplication.run(SpringBootExampleApplication.class, args);
    }
}

The controller:

@Controller
public class SSEController {
    private final CopyOnWriteArrayList<SseEmitter> emitters = new CopyOnWriteArrayList<>();
    @GetMapping("/memory")
    public SseEmitter handle() {
        SseEmitter emitter = new SseEmitter();
        // SseEmitter emitter = new SseEmitter(180_000L);
        this.emitters.add(emitter);
        emitter.onCompletion(() -> this.emitters.remove(emitter));
        emitter.onTimeout(() -> this.emitters.remove(emitter));
        return emitter;
    }
    @EventListener
    public void onMemoryInfo(MemoryInfo memoryInfo) {
        List<SseEmitter> deadEmitters = new ArrayList<>();
        this.emitters.forEach(emitter -> {
            try {
                emitter.send(memoryInfo);
            }
            catch (Exception e) {
                deadEmitters.add(emitter);
            }
        });
        this.emitters.removeAll(deadEmitters);
    }
}

The scheduled service:

@Service
public class MemoryObserverJob {
  public final ApplicationEventPublisher eventPublisher;
  public MemoryObserverJob(ApplicationEventPublisher eventPublisher) {
    this.eventPublisher = eventPublisher;
  }
  @Scheduled(fixedRate = 1000)
  public void doSomething() {
    MemoryInfo mi = new MemoryInfo(123L, 123L);
    this.eventPublisher.publishEvent(mi);
  }
}

Template for the message:

public class MemoryInfo {
    private final long heap;
    private final long nonHeap;
    private final long ts;
    public MemoryInfo(long heap, long nonHeap) {
        this.ts = System.currentTimeMillis();
        this.heap = heap;
        this.nonHeap = nonHeap;
    }
    public long getHeap() {
        return this.heap;
    }
    public long getNonHeap() {
        return this.nonHeap;
    }
    public long getTs() {
        return this.ts;
    }
}

Body:
Annotate your BootApplication with @EnableAsync

@SpringBootApplication
@EnableAsync
@EnableOAuth2Sso
public class SpringBootExampleApplication

then add another to your methods that you want to async.

@Async
public void methodToAsync(){...}


答:
Your problem is this line

```<code>document.load(function changeBackground() {
</code>```

load or onload are no longer supported by browsers now change it handle DOMContentLoaded event (updated pen)

```<code>document.addEventListener("DOMContentLoaded", function () {
</code>```

Title: Changing background colour subject to the value of the Name attribute

Body:
I've been experimenting with a Codepen and I'm looking to change the background color of a span subject to the value of the HTML's Name attribute.

The following codepen demonstrates where I am so far:

  Community 1
  Community 2

document.load(function changeBackground() {
    var communityName = document.getElementById("community");
    if (communityName.getAttribute("Name") == "test") {
        communityName.style.backgroundColor = "red";
    }
});

What am I doing wrong?

My end goal is for the JS to check the name attribute of a given  to determine what the background-color of that  should be.

Body:
Your problem is this line

document.load(function changeBackground() {

load or onload are no longer supported by browsers now change it handle DOMContentLoaded event (updated pen)

document.addEventListener("DOMContentLoaded", function () {


问:
PlaceAutoCompleteFragment NullPointerException when accessing via findFragmentById
The following XML shows I do have the fragment added.
It is a lot, but you can find the fragment at the bottom. The other UI elements are irrelevant, I just included them for the sake of completeness.

```<code><?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginRight="5dp"
    android:layout_marginLeft="5dp"
    android:columnCount="2"
    android:rowCount="7">
    <EditText
        android:layout_gravity="fill_horizontal"
        android:id="@+id/title"
        android:layout_row="0"
        android:layout_column="0"
        android:layout_width="0dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:hint="Event name"
        android:textSize="35dp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center" />

    <LinearLayout
        android:layout_row="2"
        android:layout_column="0"
        android:layout_gravity="fill_horizontal"
        android:layout_width="0dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="4">
        <TextView
            android:id="@+id/fromLabel"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="From:"
            android:textSize="30dp"
            android:layout_centerVertical="true"
            />

        <EditText
            android:id="@+id/fromDate"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="2017.01.01"
            android:textSize="20dp"
            android:gravity="center"
            android:clickable="true"
            android:focusable="false"
            />
        <EditText
            android:text="00:00"
            android:layout_weight="1"
            android:textSize="20dp"
            android:id="@+id/fromTime"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:clickable="true"
            android:focusable="false"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_gravity="fill_horizontal"
        android:layout_row="3"
        android:layout_column="0"
        android:layout_width="0dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="4">
        <TextView
            android:id="@+id/toLabel"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="To:"
            android:textSize="30dp"
            android:layout_centerVertical="true"
            />

        <EditText
            android:id="@+id/toDate"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="2017.01.01"
            android:textSize="20dp"
            android:gravity="center"
            android:clickable="true"
            android:focusable="false"
            />
        <EditText
            android:text="00:00"
            android:layout_weight="1"
            android:textSize="20dp"
            android:id="@+id/toTime"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:clickable="true"
            android:focusable="false"
            />
    </LinearLayout>
    <EditText
        android:layout_gravity="fill_horizontal"
        android:id="@+id/description"
        android:layout_row="4"
        android:layout_column="0"
        android:layout_width="0dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:hint="Description"
        android:textSize="20sp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center" />
    <Button
        android:id="@+id/submitEvent"
        android:layout_gravity="fill_horizontal"
        android:layout_row="5"
        android:layout_column="0"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="Submit event"/>
    <FrameLayout
        android:layout_gravity="fill"
        android:layout_row="6"
        android:layout_rowSpan="1"
        android:layout_column="0"
        android:id="@+id/friendsList"
        android:layout_width="0dp"
        android:layout_columnWeight="0.6"
        android:layout_height="0dp"
        >
    </FrameLayout>
    <fragment
        android:id="@+id/place_autocomplete_fragment"
        android:layout_gravity="fill"
        android:layout_row="0"
        android:layout_rowSpan="7"
        android:layout_column="1"
        android:layout_width="0dp"
        android:layout_columnWeight="1.6"
        android:layout_height="0dp"
            android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
    />
</GridLayout>
</code>```

And I have the Activity file, whose onCreare contains this code AFTER the setContentView(R.layout.activity_event);

```<code>PlaceAutocompleteFragment autocompleteFragment =
            (PlaceAutocompleteFragment) getFragmentManager()
                    .findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
   @Override
   public void onPlaceSelected(Place place) {
       Log.i("PLACE",  place.getName().toString());
   }

   @Override
   public void onError(Status status) {
       Log.i("PLACE", "ERROR WHEN AUTO COMPLETE PLACE");
   }
});
</code>```

The problem is, the setOnPlaceSelectedListener gives me the NullPointerException all the time, and says I'm trying to set the listener to a null object. I need to use the Google Places in a fragment.

Note, for smaller screens the Activity version starts alright. The problem is only with this one.

答:
You need to create class which extends fragment, override onCreateView method and inflate your fragment layout (place_autocomplete_fragment) in that method. Then create object of that class and only then you can set listener.

```<code>class FragmentClass extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.place_autocomplete_fragment, container, false);
        return view;
    }
}
</code>```

then create FragmentClass object and set desired listeners.

Body:
The following XML shows I do have the fragment added.
It is a lot, but you can find the fragment at the bottom. The other UI elements are irrelevant, I just included them for the sake of completeness.

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginRight="5dp"
    android:layout_marginLeft="5dp"
    android:columnCount="2"
    android:rowCount="7">
    <EditText
        android:layout_gravity="fill_horizontal"
        android:id="@+id/title"
        android:layout_row="0"
        android:layout_column="0"
        android:layout_width="0dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:hint="Event name"
        android:textSize="35dp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center" />

    <LinearLayout
        android:layout_row="2"
        android:layout_column="0"
        android:layout_gravity="fill_horizontal"
        android:layout_width="0dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="4">
        <TextView
            android:id="@+id/fromLabel"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="From:"
            android:textSize="30dp"
            android:layout_centerVertical="true"
            />

        <EditText
            android:id="@+id/fromDate"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="2017.01.01"
            android:textSize="20dp"
            android:gravity="center"
            android:clickable="true"
            android:focusable="false"
            />
        <EditText
            android:text="00:00"
            android:layout_weight="1"
            android:textSize="20dp"
            android:id="@+id/fromTime"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:clickable="true"
            android:focusable="false"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_gravity="fill_horizontal"
        android:layout_row="3"
        android:layout_column="0"
        android:layout_width="0dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="4">
        <TextView
            android:id="@+id/toLabel"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="To:"
            android:textSize="30dp"
            android:layout_centerVertical="true"
            />

        <EditText
            android:id="@+id/toDate"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="2017.01.01"
            android:textSize="20dp"
            android:gravity="center"
            android:clickable="true"
            android:focusable="false"
            />
        <EditText
            android:text="00:00"
            android:layout_weight="1"
            android:textSize="20dp"
            android:id="@+id/toTime"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:clickable="true"
            android:focusable="false"
            />
    </LinearLayout>
    <EditText
        android:layout_gravity="fill_horizontal"
        android:id="@+id/description"
        android:layout_row="4"
        android:layout_column="0"
        android:layout_width="0dp"
        android:layout_columnWeight="1"
        android:layout_height="wrap_content"
        android:hint="Description"
        android:textSize="20sp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center" />
    <Button
        android:id="@+id/submitEvent"
        android:layout_gravity="fill_horizontal"
        android:layout_row="5"
        android:layout_column="0"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="Submit event"/>
    <FrameLayout
        android:layout_gravity="fill"
        android:layout_row="6"
        android:layout_rowSpan="1"
        android:layout_column="0"
        android:id="@+id/friendsList"
        android:layout_width="0dp"
        android:layout_columnWeight="0.6"
        android:layout_height="0dp"
        >
    </FrameLayout>
    <fragment
        android:id="@+id/place_autocomplete_fragment"
        android:layout_gravity="fill"
        android:layout_row="0"
        android:layout_rowSpan="7"
        android:layout_column="1"
        android:layout_width="0dp"
        android:layout_columnWeight="1.6"
        android:layout_height="0dp"
            android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
    />
</GridLayout>

And I have the Activity file, whose onCreare contains this code AFTER the setContentView(R.layout.activity_event);

PlaceAutocompleteFragment autocompleteFragment =
            (PlaceAutocompleteFragment) getFragmentManager()
                    .findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
   @Override
   public void onPlaceSelected(Place place) {
       Log.i("PLACE",  place.getName().toString());
   }

   @Override
   public void onError(Status status) {
       Log.i("PLACE", "ERROR WHEN AUTO COMPLETE PLACE");
   }
});

The problem is, the setOnPlaceSelectedListener gives me the NullPointerException all the time, and says I'm trying to set the listener to a null object. I need to use the Google Places in a fragment.

Note, for smaller screens the Activity version starts alright. The problem is only with this one.

Body:
You need to create class which extends fragment, override onCreateView method and inflate your fragment layout (place_autocomplete_fragment) in that method. Then create object of that class and only then you can set listener.

class FragmentClass extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.place_autocomplete_fragment, container, false);
        return view;
    }
}

then create FragmentClass object and set desired listeners.


答:
You try to call load, but you're looking for onload.

```<code>function changeBackground() {
  var communityName = document.getElementById("community");
  if (communityName.getAttribute("Name") == "test") {
    communityName.style.backgroundColor = "red";
  }
}

document.onload = changeBackground();
</code>```

Note: Better than change CSS directly in JS is change CSS classname.

```<code>communityName.className += ' red';
</code>```

Body:
You try to call load, but you're looking for onload.

function changeBackground() {
  var communityName = document.getElementById("community");
  if (communityName.getAttribute("Name") == "test") {
    communityName.style.backgroundColor = "red";
  }
}

document.onload = changeBackground();

Note: Better than change CSS directly in JS is change CSS classname.

communityName.className += ' red';


问:
How to block user from entering URLs in text box in Angular
I am using Angular 2 and I want to restrict the user from entering URLs and links in the text box.
Can we use regular expression for this ?</p>

答:
You can use a directive to monitor the input in your textbox. The directive can use a Regular Expression to check if the current input is a URL or not. Here's an example

```<code>import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
  selector: '[appUrlBlocker]'
})
export class UrlBlockerDirective {
  constructor(private el: ElementRef) {}

  expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
  regex = new RegExp(this.expression);

  @HostListener('keyup') check() {
    if (this.el.nativeElement.value.match(this.regex)) {
      alert('You have entered a URL!');
      // Remove entered content
      this.el.nativeElement.value = '';
    } else {
      console.log('Does not match');
    }
  }
}
</code>```

And then use it on your input like so

```<code><input appUrlBlocker type="text" placeholder="No URLs allowed" />
</code>```

Working demo

Body:
You can use a directive to monitor the input in your textbox. The directive can use a Regular Expression to check if the current input is a URL or not. Here's an example

import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
  selector: '[appUrlBlocker]'
})
export class UrlBlockerDirective {
  constructor(private el: ElementRef) {}

  expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
  regex = new RegExp(this.expression);

  @HostListener('keyup') check() {
    if (this.el.nativeElement.value.match(this.regex)) {
      alert('You have entered a URL!');
      // Remove entered content
      this.el.nativeElement.value = '';
    } else {
      console.log('Does not match');
    }
  }
}

And then use it on your input like so

<input appUrlBlocker type="text" placeholder="No URLs allowed" />

Working demo


问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
This is because the compiler is smart enough to figure out that >= null will always be false and replaces your expression with a constant value of false.

Check out this example:

```<code>using System;

class Example
{
    static void Main()
    {
        int? i = null;

        Console.WriteLine(i >= null);
        Console.WriteLine(i == null);
    }
}
</code>```

This compiles down to the following code:

```<code>class Example
{
    private static void Main()
    {
        int? i = new int?();
        Console.WriteLine(false);
        Console.WriteLine(!i.HasValue);
    }
}
</code>```

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

Body:
This is because the compiler is smart enough to figure out that >= null will always be false and replaces your expression with a constant value of false.

Check out this example:

using System;

class Example
{
    static void Main()
    {
        int? i = null;

        Console.WriteLine(i >= null);
        Console.WriteLine(i == null);
    }
}

This compiles down to the following code:

class Example
{
    private static void Main()
    {
        int? i = new int?();
        Console.WriteLine(false);
        Console.WriteLine(!i.HasValue);
    }
}


问:
Bootstrap row with two columns and textareas fill up page
I'm trying to make a simple page that have a header on a row, then a row with two columns. Each column will include a textarea. I want the columns and the textareas to fill up the rest of the page. I have been searching but i can't solve this. I'm using boostrap v4.0.0-beta.2.

Here is my snippet:

  label { font-weight: bold; }
            html, body, .container-fluid {
                height: 100%;
                min-height: 100%;
            }
            textarea.form-control {
                height: 100%;
                width: 100%;
                min-height: 100%;
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid" style="background: #DDDDDD">
   <div class="row">
       <div class="col-lg-12 jumbotron text-center">
           <h1>Formatter</h1>
           <p>Enter raw input to see output</p>
       </div>
   </div>
   <div class="row" style="background: #CCCCCC;">
       <div class="col-lg-6">
           <label for="input">Input:</label>
           <textarea class="form-control" id="input">
           </textarea>
       </div>
       <div class="col-lg-6">
           <label for="output">Output:</label>
           <textarea readonly class="form-control" id="output"></textarea>
        </div>
    </div>
</div></code>```

答:
In your code you set Height of text area to 100%. But it depend on its parent div. 100% means 100% of its parent div.

So either you have to change all of its parent divs styles or if you are ok with CSS3 you can use viewport percentage units like  width: 100vw and height: 100vh(it means 100% of the viewport/ window size).

```<code>textarea.form-control {
     height: 100vh;
     width: 100vw;
}
</code>```

Body:
I'm trying to make a simple page that have a header on a row, then a row with two columns. Each column will include a textarea. I want the columns and the textareas to fill up the rest of the page. I have been searching but i can't solve this. I'm using boostrap v4.0.0-beta.2.

Here is my snippet:

  label { font-weight: bold; }
            html, body, .container-fluid {
                height: 100%;
                min-height: 100%;
            }
            textarea.form-control {
                height: 100%;
                width: 100%;
                min-height: 100%;
            }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Formatter

Enter raw input to see output

           Input:
           <textarea class="form-control" id="input">
           </textarea>

           Output:
           <textarea readonly class="form-control" id="output"></textarea>

Body:
In your code you set Height of text area to 100%. But it depend on its parent div. 100% means 100% of its parent div.

So either you have to change all of its parent divs styles or if you are ok with CSS3 you can use viewport percentage units like  width: 100vw and height: 100vh(it means 100% of the viewport/ window size).

textarea.form-control {
     height: 100vh;
     width: 100vw;
}


问:
Wordpress: Using post__not_in to exclude custom taxonomy category
I'm trying to exclude the items within a custom taxonomy category (slug: private-case-study, ID: 5) from a loop. I'm using the following code, does anyone have suggestions or ideas why it's not working? Thanks in advance!</p>

```

    // Get the current page ID
        $this_post = $post->ID;
        $private_case_study = get_term_by('slug', 'private-case-study', 'mgt_portfolio_filter');

        // Show items from specific category
        if($category_name == '') {
            $wp_query = new WP_Query(array(
                'post_type' => 'mgt_portfolio',
                'posts_per_page' => $posts_per_page,
                'orderby'    => $orderby,
                'order' => $order,
                'post__not_in' => array($this_post, $private_case_study)
            ));
        } else {
            $wp_query = new WP_Query(array(
                'post_type' => 'mgt_portfolio',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'mgt_portfolio_filter',
                        'field'    => 'slug',
                        'terms'    => $category_name,
                    ),
                ),
                'posts_per_page' => $posts_per_page,
                'orderby'    => $orderby,
                'post__not_in' => array($this_post, $private_case_study),
                'order' => $order
            ));
        }

```

答:
//Get the current page ID
        $this_post = $post->ID;
        $private_case_study = get_term_by('slug', 'private-case-study', 'mgt_portfolio_filter');</p>

```<code>    // Show items from specific category
    if($category_name == '') {
        $wp_query = new WP_Query(array(
            'post_type' => 'mgt_portfolio',
            'posts_per_page' => $posts_per_page,
            'orderby'    => $orderby,
            'order' => $order,
            'post__not_in' => array($this_post)
        ));
    } else {
        $wp_query = new WP_Query(array(
            'post_type' => 'mgt_portfolio',
            'tax_query' => array(
                array(
                    'taxonomy' => 'mgt_portfolio_filter',
                    'field'    => 'slug',
                    'terms'    => $category_name,
                ),
            ),
            'posts_per_page' => $posts_per_page,
            'orderby'    => $orderby,
            'post__not_in' => array($this_post),
            'order' => $order
        ));
    }
</code>```

Body:
I'm trying to exclude the items within a custom taxonomy category (slug: private-case-study, ID: 5) from a loop. I'm using the following code, does anyone have suggestions or ideas why it's not working? Thanks in advance!

    // Get the current page ID
        $this_post = $post->ID;
        $private_case_study = get_term_by('slug', 'private-case-study', 'mgt_portfolio_filter');

        // Show items from specific category
        if($category_name == '') {
            $wp_query = new WP_Query(array(
                'post_type' => 'mgt_portfolio',
                'posts_per_page' => $posts_per_page,
                'orderby'    => $orderby,
                'order' => $order,
                'post__not_in' => array($this_post, $private_case_study)
            ));
        } else {
            $wp_query = new WP_Query(array(
                'post_type' => 'mgt_portfolio',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'mgt_portfolio_filter',
                        'field'    => 'slug',
                        'terms'    => $category_name,
                    ),
                ),
                'posts_per_page' => $posts_per_page,
                'orderby'    => $orderby,
                'post__not_in' => array($this_post, $private_case_study),
                'order' => $order
            ));
        }

Body:
//Get the current page ID
        $this_post = $post->ID;
        $private_case_study = get_term_by('slug', 'private-case-study', 'mgt_portfolio_filter');

    // Show items from specific category
    if($category_name == '') {
        $wp_query = new WP_Query(array(
            'post_type' => 'mgt_portfolio',
            'posts_per_page' => $posts_per_page,
            'orderby'    => $orderby,
            'order' => $order,
            'post__not_in' => array($this_post)
        ));
    } else {
        $wp_query = new WP_Query(array(
            'post_type' => 'mgt_portfolio',
            'tax_query' => array(
                array(
                    'taxonomy' => 'mgt_portfolio_filter',
                    'field'    => 'slug',
                    'terms'    => $category_name,
                ),
            ),
            'posts_per_page' => $posts_per_page,
            'orderby'    => $orderby,
            'post__not_in' => array($this_post),
            'order' => $order
        ));
    }


问:
C# Textbox: Bind object to suggestion list
I am currently working at a project where I need to manage cities and their zip codes. Therefore, I created the fallowing object:

```<code>class Place
{
   Guid Id { get; set; }
   string Name { get; set; }
   int ZipCode { get; set; }

   ... further fields
}
</code>```

and filled a List<Place> with a number of Place. Now I have a Textbox where I can enter the name of the city or its zip code. I both cases I would like to get a suggestion list which match with the entered input like this

Example: input = "1234" or "City"

12341 CityOne

12342 CityTwo

12343 CityThree

...

If I than choose an item from this suggestion list I would like to get the related Place as a return value. How can I implement this feature in C# with a WindowsFormsApplication?

答:
What you've asked isn't a simple or single question. I think you can have a hidden ListBox below the TextBox where the user will enter text.

Now TextBox has an event called OnTextChanged. This event is fired every time there is a change in the text. This means that this event is fired overtime a user adds or deletes a character in the corresponding TextBox.

You can use this event to filter the list to display in your ListBox.

Something like this

```<code>//Imagine the TextBox ID as CityZipTextBox and ListBox ID as CityZipSuggestionsListBox
protected override void OnTextChanged(EventArgs e)
{
    string txtCityZip = CityZipTextBox.Text;
    List<Place> suggestedPlaces = filterCode;//Code to filter the full list using the TextBox content
    CityZipSuggestionsListBox.DataSource = suggestedPlaces;
 }
</code>```

Does this help?

Body:
I am currently working at a project where I need to manage cities and their zip codes. Therefore, I created the fallowing object:

class Place
{
   Guid Id { get; set; }
   string Name { get; set; }
   int ZipCode { get; set; }

   ... further fields
}

and filled a List<Place> with a number of Place. Now I have a Textbox where I can enter the name of the city or its zip code. I both cases I would like to get a suggestion list which match with the entered input like this

Example: input = "1234" or "City"

12341 CityOne

12342 CityTwo

12343 CityThree

...

If I than choose an item from this suggestion list I would like to get the related Place as a return value. How can I implement this feature in C# with a WindowsFormsApplication?

Body:
What you've asked isn't a simple or single question. I think you can have a hidden ListBox below the TextBox where the user will enter text.

Now TextBox has an event called OnTextChanged. This event is fired every time there is a change in the text. This means that this event is fired overtime a user adds or deletes a character in the corresponding TextBox.

You can use this event to filter the list to display in your ListBox.

Something like this

//Imagine the TextBox ID as CityZipTextBox and ListBox ID as CityZipSuggestionsListBox
protected override void OnTextChanged(EventArgs e)
{
    string txtCityZip = CityZipTextBox.Text;
    List<Place> suggestedPlaces = filterCode;//Code to filter the full list using the TextBox content
    CityZipSuggestionsListBox.DataSource = suggestedPlaces;
 }

Does this help?


问:
Angular2 - How module is different from component?
In the below code from ../src/app/app.module.ts,

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
</code>```

Component consists:

view(../src/app/app.component.html)

logic(../src/app/app.component.ts)

style(../src/app/app.component.css)

Angular application is a tree of components. Good components have high cohesion, i.e. each component contains only elements with related functionality. They are also well encapsulated and loosely coupled.

How modules are different from components?

答:
A component is just a class with the @Component() annotation. Note that .html and .css files might be referenced by the component, certainly not mandatory. The component template might very well be 'inlined' directly in the component configuration, or there simply might not be any html template at all for a given component.

A module is a structural element of an Angular application (and maybe other classes and interfaces). It is also "just a class" with the @NgModule() annotation.

It acts as a logical 'container' for your components, directives, services, pipes, etc... to help you structure your overall source code better.

You can have a look at this existing question : What's the difference between an Angular component and module

Body:
In the below code from ../src/app/app.module.ts,

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';

Component consists:

view(../src/app/app.component.html)

logic(../src/app/app.component.ts)

style(../src/app/app.component.css)

Angular application is a tree of components. Good components have high cohesion, i.e. each component contains only elements with related functionality. They are also well encapsulated and loosely coupled.

How modules are different from components?


问:
How to add Mouse listener to an ImageIcon embedded in a JLabel?
I want to have a clickable icon (an ImageIcon object) inside a JLabel. How can I add a MouseListener or any ActionListener just to that Icon. Is there any other way to know if the icon has been clicked? I use the setIcon() method for the JLabel to set its icon.

Thanks.

答: You could have two separate JLabel inside a container, the first with text, the second with just the icon, and add a mouse listener to the icon JLabel.</p>


问:
Javascript arrays with email address and password
I work with PHP and I am more familiar with it. I have tried an array in Javascript but keep getting a syntax error and I am not sure why. I have Googled arrays and I do not seem to get the answer.

Here is my array of Users in Javascript:

```<code>var users = [
    [
      emailAddress: 'david@email.com',
      password: 'secretCat';
    ],
    [
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    ],

    [
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    ],

    [
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    ],

];
</code>```

Am I supposed to do it differently in Javascript?

答:
PHP supports associative arrays. But in JavaScript you can use object to reflect the behavior of associative array. Like this:

var users = [
    {
      emailAddress: 'david@email.com',
      password: 'secretCat'
    },
    {
      emailAddress: 'john@email.com',
      password: 'secretCatTwo'
    },

    {
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree'
    },

    {
       emailAddress: 'susan@email.com',
       password: 'secretCatFour'
    }

     ];

    console.log('SrNo.\tEmail\t\tPassword');
    users.forEach((item,index)=>{
    console.log(index+1+'\t'+item.emailAddress+'\t'+item.password)
    })```

Body:
I work with PHP and I am more familiar with it. I have tried an array in Javascript but keep getting a syntax error and I am not sure why. I have Googled arrays and I do not seem to get the answer.

Here is my array of Users in Javascript:

var users = [
    [
      emailAddress: 'david@email.com',
      password: 'secretCat';
    ],
    [
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    ],

    [
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    ],

    [
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    ],

];

Am I supposed to do it differently in Javascript?


问:
res.end(result) doesn't display the result on my web page
Calling res.end(result) doesn't display the result on my web page, it is just displayed on the console when I call console.log('result ' + result).

this is my nodejs code:

```<code> const express = require('express')
    const app = express()
    var url = require('url');
    var Web3 = require('web3');

app.get('/', function(req, res) {
            res.writeHead(200, {
                'Content-Type': 'text/html'
            });

            if (typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider);
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://54.00.00.00:3010"));
            }

            if (web3.isConnected()) {

                var abi = JSON.parse('[{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getData","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"uint256"},{"name":"","type":"bytes32"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"Achats","outputs":[{"name":"aName","type":"bytes32"},{"name":"aId","type":"uint256"},{"name":"aDate","type":"bytes32"},{"name":"aValue","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"name","type":"bytes32"},{"name":"iid","type":"uint256"},{"name":"date","type":"bytes32"},{"name":"value","type":"uint256"}],"name":"setData","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]');
                TestContract = web3.eth.contract(abi);
                contractInstance = TestContract.at('0xc08f46fff9fcf082a0d1cebbcc464ca141d2b7d7');

                if (q.opt == 'get' && typeof q.index != "undefined") {
                    contractInstance.getData.call(parseInt(q.index), {
                        from: '0x3e10889Ef5066C1428ECaf8580aD4EFd50F8Cf7B'
                    }, function(error, result) {
                        console.log('error ' + error);
                        console.log('result ' + result);
                        res.end(result);
                    });
                }
            }
        }
        app.listen(3000, function() {
            console.log('Yep... on 3000 !')
        })
</code>```

i have been trying "res.end(result)" inside and outside of the function 'getData' but the same problem, nothing displayed on the web page

答:
could you try the following thing:

```<code>    res.write(result);
    res.end()
</code>```

res is a stream so you need to write your result in res and then end it

have a nice day !

Body:
Calling res.end(result) doesn't display the result on my web page, it is just displayed on the console when I call console.log('result ' + result).

this is my nodejs code:

 const express = require('express')
    const app = express()
    var url = require('url');
    var Web3 = require('web3');

app.get('/', function(req, res) {
            res.writeHead(200, {
                'Content-Type': 'text/html'
            });

            if (typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider);
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://54.00.00.00:3010"));
            }

            if (web3.isConnected()) {

                var abi = JSON.parse('[{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getData","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"uint256"},{"name":"","type":"bytes32"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"Achats","outputs":[{"name":"aName","type":"bytes32"},{"name":"aId","type":"uint256"},{"name":"aDate","type":"bytes32"},{"name":"aValue","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"name","type":"bytes32"},{"name":"iid","type":"uint256"},{"name":"date","type":"bytes32"},{"name":"value","type":"uint256"}],"name":"setData","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]');
                TestContract = web3.eth.contract(abi);
                contractInstance = TestContract.at('0xc08f46fff9fcf082a0d1cebbcc464ca141d2b7d7');

                if (q.opt == 'get' && typeof q.index != "undefined") {
                    contractInstance.getData.call(parseInt(q.index), {
                        from: '0x3e10889Ef5066C1428ECaf8580aD4EFd50F8Cf7B'
                    }, function(error, result) {
                        console.log('error ' + error);
                        console.log('result ' + result);
                        res.end(result);
                    });
                }
            }
        }
        app.listen(3000, function() {
            console.log('Yep... on 3000 !')
        })

i have been trying "res.end(result)" inside and outside of the function 'getData' but the same problem, nothing displayed on the web page

Body:
could you try the following thing:

    res.write(result);
    res.end()

res is a stream so you need to write your result in res and then end it

have a nice day !


问:
Trying to use a number with percentage as value
Hi there I am trying to run a loop that changes the value of all cells containing 0% to value "N/A". I wrote the following code: </p>

```<code>Dim Fail As Integer
Fail = "0%"
ThisWorkbook.Sheets("Summary").Activate
LastRow = Cells(Rows.Count, "G").End(xlUp).Row
    For X = 22 To LastRow

    If Range("G" & X).Value = Fail Then Range("G" & X).Value = "N/A"
Next X
</code>```

<p>but all it does is that it replaces all the values in column G with "N/A". Where did I go wrong? </p>

答:
The character "%" can't exist within an integer. You can only use whole numbers when dimming an integer. Source

Your problem lies within Fail = "0%", excel automatically changes the formatting of all cells containing % to percentage. So what you need to do is to change Fail = "0%" to Fail = "0".

See the final code below:

```<code>Dim Fail As Integer
Fail = "0"
ThisWorkbook.Sheets("Summary").Activate
LastRow = Cells(Rows.Count, "G").End(xlUp).Row
    For X = 22 To LastRow

    If Range("G" & X).Value = Fail Then Range("G" & X).Value = "N/A"
Next X
</code>```

Body:
Hi there I am trying to run a loop that changes the value of all cells containing 0% to value "N/A". I wrote the following code:

Dim Fail As Integer
Fail = "0%"
ThisWorkbook.Sheets("Summary").Activate
LastRow = Cells(Rows.Count, "G").End(xlUp).Row
    For X = 22 To LastRow

    If Range("G" & X).Value = Fail Then Range("G" & X).Value = "N/A"
Next X

but all it does is that it replaces all the values in column G with "N/A". Where did I go wrong?

Body:
The character "%" can't exist within an integer. You can only use whole numbers when dimming an integer. Source

Your problem lies within Fail = "0%", excel automatically changes the formatting of all cells containing % to percentage. So what you need to do is to change Fail = "0%" to Fail = "0".

See the final code below:

Dim Fail As Integer
Fail = "0"
ThisWorkbook.Sheets("Summary").Activate
LastRow = Cells(Rows.Count, "G").End(xlUp).Row
    For X = 22 To LastRow

    If Range("G" & X).Value = Fail Then Range("G" & X).Value = "N/A"
Next X


问:
Maximum call stack size exceeded in angularjs using ng-view
I am new to angular and using routing in my code.  In index file i have a menu bar in which i am using concept of routing.

```<code>    <div class="menuBar">
        <a href="#!home" class="menuBarItems">Home</a> <a href="#!about"
            class="menuBarItems">About</a> <a href="#!services"
            class="menuBarItems">Services</a> <a href="#!contact"
            class="menuBarItems">Contact Us</a>
    </div>
    <div ng-view></div>
<script>
        var app = angular.module("myApp", [ "ngRoute" ]);
        app.config(function($routeProvider) {
            $routeProvider.when("/home", {
                templateUrl : "home.html"
            }).when("/about", {
                templateUrl : "about.html"
            }).when("/services", {
                templateUrl : "services.html"
            }).when("/contact", {
                templateUrl : "contactus.html"
            });
        });
    </script>
</code>```

From this i am routing to four different html pages, but with in the home page i want nested routing. Code for home.html is as follows:

```<code>    <div>
        <section class="section1">
            <div class="section1Element"
                style="border-bottom: 2px solid rgba(0, 0, 0, 0.16);">
                <a href="#!london" class="link">London</a><br>
            </div>
            <div class="section1Element">
                <a href="#!paris" class="link">Paris</a>
            </div>
        </section>
        <section class="section2" ng-view></section>
    </div>
</div>

<script>
    var app = angular.module("myHome", [ "ngRoute" ]);
    app.config(function($routeProvider) {
        $routeProvider.when("/london", {
            templateUrl : "london.html"
        }).when("/paris", {
            templateUrl : "paris.html"
        });
    });
</script>
</code>```

Here when I am using ng-view in section element it is showing an error of maximum call stack exceeded. I don't know how to fix it. Can anyone help me out in this please?

答:
Hey you are doing it somewhat wrong way, you should not have 2 routes defined, you need to work on nested routes, as far i can infer from your above example. so your code must be modified in a way like this

```<code><script>
        var app = angular.module("myApp", [ "ngRoute" ]);
        app.config(function($routeProvider) {
            $routeProvider.when("/home", {
                templateUrl : "home.html"
            }).when("/home/london", {
                templateUrl : "london.html"
            }).when("/home/paris", {
                templateUrl : "paris.html"
            }).when("/about", {
                templateUrl : "about.html"
            }).when("/services", {
                templateUrl : "services.html"
            }).when("/contact", {
                templateUrl : "contactus.html"
            });
        });
    </script>
</code>```

and then things will work as expected.

Body:
I am new to angular and using routing in my code.  In index file i have a menu bar in which i am using concept of routing.

        Home About Services Contact Us

From this i am routing to four different html pages, but with in the home page i want nested routing. Code for home.html is as follows:

                London

                Paris

Here when I am using ng-view in section element it is showing an error of maximum call stack exceeded. I don't know how to fix it. Can anyone help me out in this please?

Body:
Hey you are doing it somewhat wrong way, you should not have 2 routes defined, you need to work on nested routes, as far i can infer from your above example. so your code must be modified in a way like this

<script>
        var app = angular.module("myApp", [ "ngRoute" ]);
        app.config(function($routeProvider) {
            $routeProvider.when("/home", {
                templateUrl : "home.html"
            }).when("/home/london", {
                templateUrl : "london.html"
            }).when("/home/paris", {
                templateUrl : "paris.html"
            }).when("/about", {
                templateUrl : "about.html"
            }).when("/services", {
                templateUrl : "services.html"
            }).when("/contact", {
                templateUrl : "contactus.html"
            });
        });
    </script>

and then things will work as expected.