问:
PDO MYSQL_ATTR_USE_BUFFERED_QUERY Not taking affect
I have the following rough code (full code is 146 lines, 90 of which are string parsing, can add if needed):

```<code>ini_set('memory_limit', '7G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2020-04-25', '2020-05-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
}
</code>```

during $stmt->execute(array('2020-04-25', '2020-05-25')); my memory consumption is as .34GB (using ps aux | grep 'php ' | awk '{$5=int(100 * $5/1024/1024)/100"GB";}{ print;}' to monitor consumption during select and show full processlist SQL side to verify). Once the script enters the while it jumps to +5 GB.

Testing the setattribute

```<code>var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));
</code>```

seems like it has taken affect:

```<code>bool(true)
</code>```

but the behavior doesn't change when I switch buffered or unbuffered.

```<code>$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)
</code>```

and

```<code>$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)
</code>```

Using echo $db->getAttribute(constant('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')); also shows the setting changes.

Moving the setting to the statement rather than connection as https://www.php.net/manual/en/ref.pdo-mysql.php suggested also didn't work.

```<code>$stmt = $db->prepare('select columns from stats where timestamp between ? and ?', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
</code>```

I've also tried moving the buffer setting to the connection with no affect:

```<code>$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
</code>```

Taking out the second connection seems to allow the unbuffered query to function as intended:

```<code>ini_set('memory_limit', '1G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
//$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
//$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2019-01-25', '2019-11-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      /*
     $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
     */
}
</code>```

This usage the memory_get_usage doesn't exceed 379999.

If I uncomment the second connection and make it unbuffered as well I receive:

```<code>Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
</code>```

The second connection buffered performs as initially described, large memory consumption on execution. If ini_set('memory_limit' is high it works if low it errors. Using a large memory_limit isn't a feasible solution.

Was using (Red Hat Enterprise Linux Server release 7.3 (Maipo)):

```<code>php71u-pdo.x86_64                  7.1.19-1.ius.centos7
</code>```

Moved script to a newer machine (Amazon Linux release 2 (Karoo)):

```<code>var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));
</code>```0

and have the same behavior.

答:
Can't you get rid of most of the code by simply running a single query:

```<code> INSERT IGNORE INTO newtable
     SELECT  ...,
             IF(..., 5, 4)
         FROM oldtable WHERE ...;
</code>```

With that, you could get rid of the 7G memory issue.

If that turns out to be doing too much at once, then break it into chunks.  See discussion here:  http://mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks  (That talks about DELETEs, but it can be adapted to other things, such as your SELECT.)

On another topic:  Why is select somedata from users limit 1 executed inside the loop?  It seems to get the same data every time.  Also, without an ORDER BY, you can't predict which limit 1 row you will get.

Body:
I have the following rough code (full code is 146 lines, 90 of which are string parsing, can add if needed):

ini_set('memory_limit', '7G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2020-04-25', '2020-05-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
}

during $stmt->execute(array('2020-04-25', '2020-05-25')); my memory consumption is as .34GB (using ps aux | grep 'php ' | awk '{$5=int(100 * $5/1024/1024)/100"GB";}{ print;}' to monitor consumption during select and show full processlist SQL side to verify). Once the script enters the while it jumps to +5 GB.

Testing the setattribute

var_dump($db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false));

seems like it has taken affect:

bool(true)

but the behavior doesn't change when I switch buffered or unbuffered.

$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false)

and

$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true)

Using echo $db->getAttribute(constant('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')); also shows the setting changes.

Moving the setting to the statement rather than connection as https://www.php.net/manual/en/ref.pdo-mysql.php suggested also didn't work.

$stmt = $db->prepare('select columns from stats where timestamp between ? and ?', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));

I've also tried moving the buffer setting to the connection with no affect:

$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));

Taking out the second connection seems to allow the unbuffered query to function as intended:

ini_set('memory_limit', '1G');
$db = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
//$db_ub = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass, array(PDO::ATTR_PERSISTENT => true));
//$db_ub->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$stmt = $db->prepare('select columns from stats where timestamp between ? and ?');
$stmt->execute(array('2019-01-25', '2019-11-25'));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo memory_get_usage() .PHP_EOL;
      echo $row['id'] . PHP_EOL;
      /*
     $stmt2 = $db_ub->prepare('select somedata from users limit 1');
      $stmt2->execute();
      $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
      $type = !empty($row2['somedate']) ? 5 : 4;
      $result = $db_ub->prepare('insert ignore into newtable (old, type) values (?, ?)');
      $result->execute(array($row['id'], $type));
     */
}

This usage the memory_get_usage doesn't exceed 379999.

If I uncomment the second connection and make it unbuffered as well I receive:

Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

The second connection buffered performs as initially described, large memory consumption on execution. If ini_set('memory_limit' is high it works if low it errors. Using a large memory_limit isn't a feasible solution.

Was using (Red Hat Enterprise Linux Server release 7.3 (Maipo)):

php71u-pdo.x86_64                  7.1.19-1.ius.centos7

Moved script to a newer machine (Amazon Linux release 2 (Karoo)):

php73-pdo.x86_64                   7.3.17-1.el7.ius

and have the same behavior.

Body:
Can't you get rid of most of the code by simply running a single query:

 INSERT IGNORE INTO newtable
     SELECT  ...,
             IF(..., 5, 4)
         FROM oldtable WHERE ...;

With that, you could get rid of the 7G memory issue.

If that turns out to be doing too much at once, then break it into chunks.  See discussion here:  http://mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks  (That talks about DELETEs, but it can be adapted to other things, such as your SELECT.)

On another topic:  Why is select somedata from users limit 1 executed inside the loop?  It seems to get the same data every time.  Also, without an ORDER BY, you can't predict which limit 1 row you will get.


来源: stackexchange

问:
java reflection issue
I have this code:

```<code>public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
            final Class<TypeVO> voClass, final String fieldName) {
        List<SelectItem> listSelectBox = null;
        final List<TypeVO> vosList = GenericEjbProxyFactory
                .getGenericTopValueObjectProxy(voClass)
                .getAllValueObjects(null);
        System.out.println("loaded vosList!!!!");
        if (vosList != null) {
            listSelectBox = new ArrayList<SelectItem>();
            for (final TypeVO currVo : vosList) {
                listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName()));
            }
        }
        return listSelectBox;
    }
</code>```

As you see here, I'm using currVo.getName because always, currVo has a name property.

I want to be able to use also other fields from this currVo which has type as voClass, but not all currVo classes will contain this field so I have to use reflection to identify these getField method, something like:

```<code>for (final TypeVO currVo : vosList) {
                for (final Method m : voClass.getMethods()) {
                    if (m.getName().contains(fieldName)) {
                        listSelectBox.add(new SelectItem(
                                currVo.getInternalId(), currVo.m));
                    }
                }
            }
</code>```

What I do not know is HOW I can use that specific method's value when I find it, exactly like currVo.getName (because, of course, currVo.m is wrong)?

Eg: If fieldName is "Age" I want to put in the list: currVo.getAge()... I am simply blocked here...

答:
You should use the invoke method from the Method class.

```<code>m.invoke(currVo, (Object[]) null);
</code>```

(Assuming the method takes no parameter.)

This will work for JDK versions 1.4 and later, since they state:

If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null

The one-parameter version of that call will not work on older JVMs.

ContentLicense: CC BY-SA 3.0

Title: java reflection issue

Body:
I have this code:

public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
            final Class<TypeVO> voClass, final String fieldName) {
        List<SelectItem> listSelectBox = null;
        final List<TypeVO> vosList = GenericEjbProxyFactory
                .getGenericTopValueObjectProxy(voClass)
                .getAllValueObjects(null);
        System.out.println("loaded vosList!!!!");
        if (vosList != null) {
            listSelectBox = new ArrayList<SelectItem>();
            for (final TypeVO currVo : vosList) {
                listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName()));
            }
        }
        return listSelectBox;
    }

As you see here, I'm using currVo.getName because always, currVo has a name property.

I want to be able to use also other fields from this currVo which has type as voClass, but not all currVo classes will contain this field so I have to use reflection to identify these getField method, something like:

for (final TypeVO currVo : vosList) {
                for (final Method m : voClass.getMethods()) {
                    if (m.getName().contains(fieldName)) {
                        listSelectBox.add(new SelectItem(
                                currVo.getInternalId(), currVo.m));
                    }
                }
            }

What I do not know is HOW I can use that specific method's value when I find it, exactly like currVo.getName (because, of course, currVo.m is wrong)?

Eg: If fieldName is "Age" I want to put in the list: currVo.getAge()... I am simply blocked here...

Body:
You should use the invoke method from the Method class.

m.invoke(currVo, (Object[]) null);

(Assuming the method takes no parameter.)

This will work for JDK versions 1.4 and later, since they state:

If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null

The one-parameter version of that call will not work on older JVMs.


问:
How to set large Request Body for fetch API call
I have a fetch POST that is sending a large JSON object:

const body = JSON.stringify(largeItem); // 80MB

const request = new Request(uri, {
    mode: 'cors',
    method: 'POST',
    headers: new Headers({ 'Content-Type': 'application/json' }),
    credentials: 'same-origin',
    body
});

const response = await fetch(request);
```

This results in an error:

source-file.ts:72 Uncaught (in promise) TypeError: Failed to fetch

When I view this request in dev tools it looks incomplete - no request body and most of the request headers are missing. In addition it errors without a status code, instead the status is:

(failed) net::ERR_CONNECTION_RESET

Lots of other GET and POST requests to the same resource with the same credentials work fine. This code works fine with a smaller body.

How do I POST a request with a large (in this case 80MB) JSON body?

答:
I think your issue is related to http or the web server (or I guess the browser) Limits

Please read this answer to know what I'm talking about

Can HTTP POST be limitless?.

ContentLicense: CC BY-SA 4.0

Body:
I have a fetch POST that is sending a large JSON object:

const body = JSON.stringify(largeItem); // 80MB

const request = new Request(uri, {
    mode: 'cors',
    method: 'POST',
    headers: new Headers({ 'Content-Type': 'application/json' }),
    credentials: 'same-origin',
    body
});

const response = await fetch(request);

This results in an error:

source-file.ts:72 Uncaught (in promise) TypeError: Failed to fetch

When I view this request in dev tools it looks incomplete - no request body and most of the request headers are missing. In addition it errors without a status code, instead the status is:

(failed) net::ERR_CONNECTION_RESET

Lots of other GET and POST requests to the same resource with the same credentials work fine. This code works fine with a smaller body.

How do I POST a request with a large (in this case 80MB) JSON body?


问:
python3 sockets never stops trying to read data
i'm using a tcp socket to read data from a website, HTTP requests to be exact. I want to use sockets and not requests or pycurl so please do not suggest me any higher level library.

```<code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = wrap_socket(s)
response_bytes = b""
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.connect((website))
s.send(all of this works good)
#this is where my problems occur
while True:
    response_bytes+=s.recv(4096)
    if not response_bytes: break

</code>```

this solution should work perfectly according to multiple stack posts. I want to use the most efficient way without a timeout. If i use try/except and set a socket timeout it works fine but thats  not very good imo. This seems to make the code hang forever and make it try to read infinitely. Is there any reason it is doing this?

答:
```<code>s.send(all of this works good)
</code>```

Let me guess: this is doing a HTTP request with an explicit or implicit Connection: keep-alive. This header is implicit when doing a HTTP/1.1 request. Because of this the server decides to keep the TCP connection open because it is awaiting the next request of the client.

I want to use the most efficient way without a timeout.

The correct way is to properly understand the HTTP protocol, extract the size of the response body from the response header and read exactly as much data as specified by the size. The easy way is to just do a HTTP/1.0 request without enabling HTTP keep-alive. In this case the server will close the TCP connection immediately after the response was sent.

I want to use sockets and not requests or pycurl so please do not suggest me any higher level library.

It looks like you want to implement HTTP yourself. There is a standard you should read in this case which describes the fairly complex behavior of HTTP. Don't try to guess a protocol but read the actual specification.

Body:
i'm using a tcp socket to read data from a website, HTTP requests to be exact. I want to use sockets and not requests or pycurl so please do not suggest me any higher level library.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = wrap_socket(s)
response_bytes = b""
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.connect((website))
s.send(all of this works good)
#this is where my problems occur
while True:
    response_bytes+=s.recv(4096)
    if not response_bytes: break

this solution should work perfectly according to multiple stack posts. I want to use the most efficient way without a timeout. If i use try/except and set a socket timeout it works fine but thats  not very good imo. This seems to make the code hang forever and make it try to read infinitely. Is there any reason it is doing this?

Body:
s.send(all of this works good)

Let me guess: this is doing a HTTP request with an explicit or implicit Connection: keep-alive. This header is implicit when doing a HTTP/1.1 request. Because of this the server decides to keep the TCP connection open because it is awaiting the next request of the client.

I want to use the most efficient way without a timeout.

The correct way is to properly understand the HTTP protocol, extract the size of the response body from the response header and read exactly as much data as specified by the size. The easy way is to just do a HTTP/1.0 request without enabling HTTP keep-alive. In this case the server will close the TCP connection immediately after the response was sent.

I want to use sockets and not requests or pycurl so please do not suggest me any higher level library.

It looks like you want to implement HTTP yourself. There is a standard you should read in this case which describes the fairly complex behavior of HTTP. Don't try to guess a protocol but read the actual specification.


问:
Stopping ios 7 remote notification sound
In iOS 7, when a user swipes one of my notifications from the lockscreen and is taken to my app, the notification sound keeps playing (unlike iOS 6). Is there any way to programmatically stop that sound when my app launches in iOS 7?

NOTE: see the accepted answer for a shoddy workaround.

答:
For iOS 7, the accepted answer may be the only viable option. For developers who have come here that can support a minimum of iOS 10, this works.

You can remove all notifications from Notification Center by calling

```<code>UNUserNotificationCenter.current().removeAllDeliveredNotifications()
</code>```

This has a very similar affect as the accepted answer: the audio stops playing and all the notifications are removed from Notification Center.

An improved solution is to use

```<code>UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [String])
</code>```

This stops the audio for only the given notifications, and removes them from Notification Center.

To get the ids for all the delivered notifications, use

```<code>UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
  let ids = notifications.map { $0.request.identifier }
}
</code>```

Body:
For iOS 7, the accepted answer may be the only viable option. For developers who have come here that can support a minimum of iOS 10, this works.

You can remove all notifications from Notification Center by calling

UNUserNotificationCenter.current().removeAllDeliveredNotifications()

This has a very similar affect as the accepted answer: the audio stops playing and all the notifications are removed from Notification Center.

An improved solution is to use

UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [String])

This stops the audio for only the given notifications, and removes them from Notification Center.

To get the ids for all the delivered notifications, use

UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
  let ids = notifications.map { $0.request.identifier }
}


问:
How to know precisely where a NullPointerException comes from?
I'm writing some code in Java.
I've got tons of classes that have subclasses that have subclasses ... You get it.
At some point, when running my code, I have a NullPointerException.
Eclipse tells me that it comes from a line of code that looks like :

```<code>Something1.Something2.Something3.Something4.Something5...
</code>```

Where Something(n+1) is a field of Something(n).

My question is, do I have a way to know where is the NullPointerException exactly ?
I mean, any of the Something(n) could be null and cause the Exception when I try accessing one of its fields.

Thank you by advance,

Kal8578

答:
You can get detailed info on NullPointerException only on JDK 14+.

See JEP 358 Helpful
NullPointerException

List of features included in
JDK14

Body:
I'm writing some code in Java.
I've got tons of classes that have subclasses that have subclasses ... You get it.
At some point, when running my code, I have a NullPointerException.
Eclipse tells me that it comes from a line of code that looks like :

Something1.Something2.Something3.Something4.Something5...

Where Something(n+1) is a field of Something(n).

My question is, do I have a way to know where is the NullPointerException exactly ?
I mean, any of the Something(n) could be null and cause the Exception when I try accessing one of its fields.

Thank you by advance,

Kal8578


问:
How to use cpio to modify or creat ramdisk?
This question contain 2 parts.New is at line 29.

I use cygwin cpio command to creat ramdisk.But i find it cant used in android becouse file tree is E:\xx\xx.
I need ramdisk content is \xx.How to do?

```<code>set "bin=E:\cygwin64\bin"
set "PATH=E:"
"%bin%"\find "%PATH%"\ramdisk -depth -print0 | "%bin%"\cpio --null -ov >e:\ramdisknew
</code>```

when i use cpio -t the output like this.

```<code>E:\ramdisk/acct
E:\ramdisk/bugreports
E:\ramdisk/cache
E:\ramdisk/charger
E:\ramdisk/config
E:\ramdisk/d
E:\ramdisk/data
</code>```

I need -t putput like this.

```<code>"E:\cygwin64\bin"\cpio -t "E:"\ramdisk0
acct
bugreports
cache
charger
config
d
</code>```

    data

I found in windows the file or dirctory Owner is 1000 not root maybe thats the problem.

So i changed Fedora 31.

The origin file ramdisk0 properties Kind=CPIO archive.

Use cpio -idv < /ramdisk0 then -ov to ramdisknew.Replace origin ramdisk0 to run android

It DONT work.

I find two problem

1.Output sequence become reverse not [acct bugreports cache d]

```<code>selinux_version
sepolicy
init.environ.rc
init.zygote32.rc
etc
config
</code>```

2.ramdisknew hex content differ from ramdisk0
Origin ramdisk0 includ lot of '07070100049...' but ramdisknew have none
The only string 'acct' is a dir still in format

[070701000493e0000041ed0000000000000000000000010000000000000000000000000000000000000000000000000000000500000000acct]

but in ramdisknew the format is[...Õ^Gð....acct]

origin ramdisk hex [part]

```<code>...
30 30 00 00  30 37 30 37  30 31 30 30  30 34 39 33 | 00..070701000493
65 31 30 30  30 30 61 31  61 34 30 30  30 30 30 30 | e10000a1a4000000
30 30 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 0000000000000000
30 31 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 0100000000000000
33 32 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 3200000000000000
30 30 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 0000000000000000
30 30 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 000000000b000000
30 30 62 75  67 72 65 70  6F 72 74 73  00 00 00 00 | 00bugreports....
2F 64 61 74  61 2F 75 73  65 72 5F 64  65 2F 30 2F | /data/user_de/0/com
...
</code>```

new ramdisknew hex [part]

```<code>D5 5E 47 F0  0B 00 00 00  32 00 62 75  67 72 65 70 | Õ^Gð....2. bugrep
6F 72 74 73  00 00 2F 64  61 74 61 2F  75 73 65 72 | orts../data/user_de/0/com
</code>```

How to fix it?

答:
I believe something like this might work:

```<code>pushd "%PATH%"\ramdisk
"%bin%"\find . -depth -printf "%P\0" | "%bin%"\cpio --null -ov >e:\ramdisknew
popd
</code>```

Cpio here apparently stores the full path as passed by Find.  The pushd and popd commands temporarily change the working directory to where the files are stored.  The find command is modified to look into the current directory (but that change isn't strictly necessary) and to print only the relative path (the %P); null character separators are retained (the \0 part).

Body:
This question contain 2 parts.New is at line 29.

I use cygwin cpio command to creat ramdisk.But i find it cant used in android becouse file tree is E:\xx\xx.
I need ramdisk content is \xx.How to do?

set "bin=E:\cygwin64\bin"
set "PATH=E:"
"%bin%"\find "%PATH%"\ramdisk -depth -print0 | "%bin%"\cpio --null -ov >e:\ramdisknew

when i use cpio -t the output like this.

E:\ramdisk/acct
E:\ramdisk/bugreports
E:\ramdisk/cache
E:\ramdisk/charger
E:\ramdisk/config
E:\ramdisk/d
E:\ramdisk/data

I need -t putput like this.

"E:\cygwin64\bin"\cpio -t "E:"\ramdisk0
acct
bugreports
cache
charger
config
d

    data

I found in windows the file or dirctory Owner is 1000 not root maybe thats the problem.

So i changed Fedora 31.

The origin file ramdisk0 properties Kind=CPIO archive.

Use cpio -idv < /ramdisk0 then -ov to ramdisknew.Replace origin ramdisk0 to run android

It DONT work.

I find two problem

1.Output sequence become reverse not [acct bugreports cache d]

selinux_version
sepolicy
init.environ.rc
init.zygote32.rc
etc
config

2.ramdisknew hex content differ from ramdisk0
Origin ramdisk0 includ lot of '07070100049...' but ramdisknew have none
The only string 'acct' is a dir still in format

[070701000493e0000041ed0000000000000000000000010000000000000000000000000000000000000000000000000000000500000000acct]

but in ramdisknew the format is[...Õ^Gð....acct]

origin ramdisk hex [part]

...
30 30 00 00  30 37 30 37  30 31 30 30  30 34 39 33 | 00..070701000493
65 31 30 30  30 30 61 31  61 34 30 30  30 30 30 30 | e10000a1a4000000
30 30 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 0000000000000000
30 31 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 0100000000000000
33 32 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 3200000000000000
30 30 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 0000000000000000
30 30 30 30  30 30 30 30  30 30 30 30  30 30 30 30 | 000000000b000000
30 30 62 75  67 72 65 70  6F 72 74 73  00 00 00 00 | 00bugreports....
2F 64 61 74  61 2F 75 73  65 72 5F 64  65 2F 30 2F | /data/user_de/0/com
...

new ramdisknew hex [part]

D5 5E 47 F0  0B 00 00 00  32 00 62 75  67 72 65 70 | Õ^Gð....2. bugrep
6F 72 74 73  00 00 2F 64  61 74 61 2F  75 73 65 72 | orts../data/user_de/0/com

How to fix it?

Body:
I believe something like this might work:

pushd "%PATH%"\ramdisk
"%bin%"\find . -depth -printf "%P\0" | "%bin%"\cpio --null -ov >e:\ramdisknew
popd

Cpio here apparently stores the full path as passed by Find.  The pushd and popd commands temporarily change the working directory to where the files are stored.  The find command is modified to look into the current directory (but that change isn't strictly necessary) and to print only the relative path (the %P); null character separators are retained (the \0 part).


问:
Laravel MSSQL Server Connection not working
Laravel version:7.13, SqlServer:2019

```<code> SQLSTATE[08001]: [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider:
 An existing connection was forcibly closed by the remote host (SQL: select * from [users]).
</code>```

Above is error message what I got.

I tried with core php and it works well.

Below is php code.

```<code><?php

$serverName = "MYPCNAME";
$connectionInfo = array( "Database"=>"DBNAME", "UID"=>"sa", "PWD"=>'MyPassword');
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
     echo "Connection established.<br />";

     if(($result = sqlsrv_query($conn,"SELECT * FROM users")) !== false){
        while( $obj = sqlsrv_fetch_object( $result )) {
              echo $obj->name.'<br />';
        }
    }

}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}

?>
</code>```

I think SQL Server configuration is correct. I installed php_sqlsrv, php_pdo_sqlsrv extensions and they are displayed as installed in phpinfo()

Here is my Laravel configuration.

```<code>DB_CONNECTION=sqlsrv
DB_HOST=MYPCNAME
DB_PORT=1433
DB_DATABASE=DBNAME
DB_USERNAME=sa
DB_PASSWORD=MyPassword
</code>```

Following is database config file.

```<code> 'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST'),
            'port' => env('DB_PORT'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],
</code>```

I tried to change DB_HOST with 127.0.0.1 too but there was same issue.
I was going to get users from users table.

My thought: I changed server name with 127.0.0.1 in core php and it displayed exact same error with laravel.

Can anyone help me?
Thanks

答:
Ok, I sovled issue.

When I set DB_PORT=null it worked.

However, I didn't find the exact answer yet.

Here is post url about it.

PHP Sqlsrv connection not working when specify port, instance

I think the main reason is above.
Anyway If I set DB_PORT=null, it worked successfully.

Body:
Laravel version:7.13, SqlServer:2019

 SQLSTATE[08001]: [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider:
 An existing connection was forcibly closed by the remote host (SQL: select * from [users]).

Above is error message what I got.

I tried with core php and it works well.

Below is php code.

<?php

$serverName = "MYPCNAME";
$connectionInfo = array( "Database"=>"DBNAME", "UID"=>"sa", "PWD"=>'MyPassword');
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
     echo "Connection established.
";

     if(($result = sqlsrv_query($conn,"SELECT * FROM users")) !== false){
        while( $obj = sqlsrv_fetch_object( $result )) {
              echo $obj->name.'
';
        }
    }

}else{
     echo "Connection could not be established.
";
     die( print_r( sqlsrv_errors(), true));
}

?>

I think SQL Server configuration is correct. I installed php_sqlsrv, php_pdo_sqlsrv extensions and they are displayed as installed in phpinfo()

Here is my Laravel configuration.

DB_CONNECTION=sqlsrv
DB_HOST=MYPCNAME
DB_PORT=1433
DB_DATABASE=DBNAME
DB_USERNAME=sa
DB_PASSWORD=MyPassword

Following is database config file.

 'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST'),
            'port' => env('DB_PORT'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

I tried to change DB_HOST with 127.0.0.1 too but there was same issue.
I was going to get users from users table.

My thought: I changed server name with 127.0.0.1 in core php and it displayed exact same error with laravel.

Can anyone help me?
Thanks


问:
center the dots of the unorder list in html
I have tried to fix this, but the bullets are staying to the left, but text is formatting correctly. I used
text-align: center , but that only formats the text, and not the bullets. Here is my code:

<!DOCTYPE html>

Header Label

first

second

three

```
</div>
</div>
</p>

<p>It should look like below (here * represents bullets):</p>

```                                * first
                                * second
                                * third
```

答:
Way 1:

```<code>.toolbar {
    width: fit-content;
    margin-left: auto;
    margin-right: auto;
}
</code>```

.toolbar {
      width: fit-content;
      margin-left: auto;
      margin-right: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toolbar">
    <h1>Header Label</h1>
    <ul>
      <li>first</li>
      <li>second</li>
      <li>three</li>
    </ul>
</div></code>```

Way 2:

h1 {
   text-align: center;
}

ul {
      width: fit-content;
      margin-left: auto;
      margin-right: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toolbar">
    <h1>Header Label</h1>
    <ul>
      <li>first</li>
      <li>second</li>
      <li>three</li>
    </ul>
</div></code>```

Body:
I have tried to fix this, but the bullets are staying to the left, but text is formatting correctly. I used
text-align: center , but that only formats the text, and not the bullets. Here is my code:

<!DOCTYPE html>

Header Label

first

second

three

It should look like below (here * represents bullets):

                                * first
                                * second
                                * third

Body:
Way 1:

.toolbar {
    width: fit-content;
    margin-left: auto;
    margin-right: auto;
}

.toolbar {
      width: fit-content;
      margin-left: auto;
      margin-right: auto;
}

<div class="toolbar">
    <h1>Header Label</h1>
    <ul>
      <li>first</li>
      <li>second</li>
      <li>three</li>
    </ul>
</div>

Way 2:

h1 {
   text-align: center;
}

ul {
      width: fit-content;
      margin-left: auto;
      margin-right: auto;
}

<div class="toolbar">
    <h1>Header Label</h1>
    <ul>
      <li>first</li>
      <li>second</li>
      <li>three</li>
    </ul>
</div>


问:
sql server 2005 Permissions with Windows Authentication
I  installed SQL Server 2005 Management Studio Express. When I login to the Database server  using Windows Authentication.

I am unable to create tables or create databases. How do I grant the permissions for the users logged in as Windows Authentication to be able to create tables / databases?

答:
In the Object Explorer look for the Security Folder at the top level.

Then under logins right click and choose properties of the user in question.

Grant them further access.


问:
Docker build can't find docker to run tests
I have a NodeJS application that is using ioredis to connect to redis and publish data and other redisy things.

I am trying to write a component test against redis and was able to create a setup/teardown script via jest that runs redis via docker on a random port and tears it down when the tests are done via docker run -d -p 6379 --rm redis and docker stop {containerId}.

This works great locally, but we have the tests running in a multi-stage build in our Dockerfile:
RUN yarn test

which I try to build via docker build . it goes great until it gets to the tests and then complains with the following error - /bin/sh: docker: not found

Hence, Docker is unavailable to the docker-build process to run the tests?

Is there a way to run docker-build to give it the ability to spin up sibling processes during the process?

答:
In my practice, tests shouldn't be concerned with initializing the database, they should only be concerned about how to connect to the database, so you just pass your db connection data via environment variables.

The way you are doing it it won't scale, imagine that you need a lot more services for your application, it will be difficult and not practical to start them via tests.

When you are developing locally, it's your responsibility to have the services running before doing the tests.

You can have docker compose scripts in your repository that create and start all the services you need when you start developing.

And when you are using CI in the cloud, you would still use docker containers and run tests in them( node container with your tests, redis container, mysql container, etc...) and again just pass the appropriate connection data via environment variables.


问:
Python Paramiko download multiple files to window client over SSH
I would like to download multiple files under linux server to my window clients, i have many files under desktop

test_file1_20200601_0001.csv
test_file1_20200601_0002.csv
test_file1_20200601_0003.csv
test_file1_20200601_0004.csv
test_file1_20200601_0004.csv
.
.
test_file1_20200601_0400.csv

Here is my code

```<code>dt_today  = datetime.strftime(datetime.now() - timedelta(0), '%Y%m%d')
dt_yesday = datetime.strftime(datetime.now() - timedelta(1), '%Y%m%d')

Destination = os.path.join(os.sep,str(Path.home()),'Template and Raw','Raw')
ssh = paramiko.SSHClient()
ssh.connect('192.168.1.1', username="server1", password="server1@123")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sftp = ssh.open_sftp()

for filename in sftp.listdir('/home/server1/Desktop/test/'+ dt_yesday):
    if fnmatch.fnmatch(filename, 'test_file1_'+dt_yesday+'*.csv'):
        sftp.get(filename, Destination)
sftp.close()
</code>```

And i got this Error

PermissionError: [Errno 13] Permission denied: 'C:\Users\YouKnowWho\Template and Raw\Raw'

May i know how can i fix this

答:
Paramiko source shows that the get method opens localpath for writing.
You're passing a folder to .get.

```<code>    def get(self, remotepath, localpath, callback=None):
        """
        Copy a remote file (``remotepath``) from the SFTP server to the local
        host as ``localpath``.  Any exception raised by operations will be
        passed through.  This method is primarily provided as a convenience.

        :param str remotepath: the remote file to copy
        :param str localpath: the destination path on the local host
        :param callable callback:
            optional callback function (form: ``func(int, int)``) that accepts
            the bytes transferred so far and the total bytes to be transferred

        .. versionadded:: 1.4
        .. versionchanged:: 1.7.4
            Added the ``callback`` param
        """
        with open(localpath, "wb") as fl:
            size = self.getfo(remotepath, fl, callback)
        s = os.stat(localpath)
        if s.st_size != size:
            raise IOError(
                "size mismatch in get!  {} != {}".format(s.st_size, size)
            )

</code>```

Body:
I would like to download multiple files under linux server to my window clients, i have many files under desktop

test_file1_20200601_0001.csv
test_file1_20200601_0002.csv
test_file1_20200601_0003.csv
test_file1_20200601_0004.csv
test_file1_20200601_0004.csv
.
.
test_file1_20200601_0400.csv

Here is my code

dt_today  = datetime.strftime(datetime.now() - timedelta(0), '%Y%m%d')
dt_yesday = datetime.strftime(datetime.now() - timedelta(1), '%Y%m%d')

Destination = os.path.join(os.sep,str(Path.home()),'Template and Raw','Raw')
ssh = paramiko.SSHClient()
ssh.connect('192.168.1.1', username="server1", password="server1@123")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sftp = ssh.open_sftp()

for filename in sftp.listdir('/home/server1/Desktop/test/'+ dt_yesday):
    if fnmatch.fnmatch(filename, 'test_file1_'+dt_yesday+'*.csv'):
        sftp.get(filename, Destination)
sftp.close()

And i got this Error

PermissionError: [Errno 13] Permission denied: 'C:\Users\YouKnowWho\Template and Raw\Raw'

May i know how can i fix this

Body:
Paramiko source shows that the get method opens localpath for writing.
You're passing a folder to .get.

    def get(self, remotepath, localpath, callback=None):
        """
        Copy a remote file (``remotepath``) from the SFTP server to the local
        host as ``localpath``.  Any exception raised by operations will be
        passed through.  This method is primarily provided as a convenience.

        :param str remotepath: the remote file to copy
        :param str localpath: the destination path on the local host
        :param callable callback:
            optional callback function (form: ``func(int, int)``) that accepts
            the bytes transferred so far and the total bytes to be transferred

        .. versionadded:: 1.4
        .. versionchanged:: 1.7.4
            Added the ``callback`` param
        """
        with open(localpath, "wb") as fl:
            size = self.getfo(remotepath, fl, callback)
        s = os.stat(localpath)
        if s.st_size != size:
            raise IOError(
                "size mismatch in get!  {} != {}".format(s.st_size, size)
            )


问:
Function return map with 0 elements in Typescript/Angular
I am new to Angular and working on a sample app, which accepts a property file as input from html, process the files and stores the values in a map using typescript. I am able to store the value in the map but not able to access the map from another component.

File-reader-component.ts

```<code>export class FileReaderComponent {
    static readFileAsMap(file: File): Map<string, string> {
        let map :Map<string, string>= new Map<string, string>();

        let fileReader = new FileReader();
        fileReader.onloadend = (e) => {
            // By lines
            let lines = fileReader.result.toString().split('\n');
            for(let line = 0; line < lines.length; line++){
                if(lines[line].startsWith('#') ||
                    lines[line].startsWith('//') ||
                    ! lines[line].includes('=') ) {
                    // invalid line - ignoring it
                    continue;
                }
                let lineArr = lines[line].split('=');
                let key = lineArr[0].trim();
                let value = lineArr[1].trim();

                map.set(key, value);
                // not checking duplicate keys to let override the config
            }
        };

        fileReader.readAsText(file);
        console.log(map);
        return map;
    }
}
</code>```

In the above file, console.log(map) works fine. But when we call this method in another component(as below) it returns map with 0 elements.

```<code>let config: Map<string, string> = FileReaderComponent.readFileAsMap(configFile);
</code>```

答:
The map variable is assigned values asynchronously. You could try to return an observable (using for eg. RxJS Subject) from the function. Try the following

static readFileAsMap(file: File): Observable<Map<string, string>> {
  const result = new Subject<Map<string, string>>();

  let fileReader = new FileReader();
  fileReader.onloadend = (e) => {
      // By lines
      let map: Map<string, string> = new Map<string, string>();
      let lines = fileReader.result.toString().split('\n');
      for(let line = 0; line < lines.length; line++){
          if(lines[line].startsWith('#') ||
              lines[line].startsWith('//') ||
              ! lines[line].includes('=') ) {
              // invalid line - ignoring it
              continue;
          }
          let lineArr = lines[line].split('=');
          let key = lineArr[0].trim();
          let value = lineArr[1].trim();

          map.set(key, value);
          // not checking duplicate keys to let override the config
      }
      result.next(map);          // <-- push value here
  };

  fileReader.readAsText(file);
  console.log(map);
  return result.asObservable();  // <-- return an observable
}
```

<p>Now you need to subscribe to the function <code>readFileAsMap()</code> to obtain the values.</p>

<pre class="lang-js prettyprint-override"><code>let config: Map<string, string>;

FileReaderComponent.readFileAsMap(configFile).subscribe(
  value => { config = value; }
);
</code>```

Body:
I am new to Angular and working on a sample app, which accepts a property file as input from html, process the files and stores the values in a map using typescript. I am able to store the value in the map but not able to access the map from another component.

File-reader-component.ts

export class FileReaderComponent {
    static readFileAsMap(file: File): Map<string, string> {
        let map :Map<string, string>= new Map<string, string>();

        let fileReader = new FileReader();
        fileReader.onloadend = (e) => {
            // By lines
            let lines = fileReader.result.toString().split('\n');
            for(let line = 0; line < lines.length; line++){
                if(lines[line].startsWith('#') ||
                    lines[line].startsWith('//') ||
                    ! lines[line].includes('=') ) {
                    // invalid line - ignoring it
                    continue;
                }
                let lineArr = lines[line].split('=');
                let key = lineArr[0].trim();
                let value = lineArr[1].trim();

                map.set(key, value);
                // not checking duplicate keys to let override the config
            }
        };

        fileReader.readAsText(file);
        console.log(map);
        return map;
    }
}

In the above file, console.log(map) works fine. But when we call this method in another component(as below) it returns map with 0 elements.

let config: Map<string, string> = FileReaderComponent.readFileAsMap(configFile);

Body:
The map variable is assigned values asynchronously. You could try to return an observable (using for eg. RxJS Subject) from the function. Try the following

static readFileAsMap(file: File): Observable<Map<string, string>> {
  const result = new Subject<Map<string, string>>();

  let fileReader = new FileReader();
  fileReader.onloadend = (e) => {
      // By lines
      let map: Map<string, string> = new Map<string, string>();
      let lines = fileReader.result.toString().split('\n');
      for(let line = 0; line < lines.length; line++){
          if(lines[line].startsWith('#') ||
              lines[line].startsWith('//') ||
              ! lines[line].includes('=') ) {
              // invalid line - ignoring it
              continue;
          }
          let lineArr = lines[line].split('=');
          let key = lineArr[0].trim();
          let value = lineArr[1].trim();

          map.set(key, value);
          // not checking duplicate keys to let override the config
      }
      result.next(map);          // <-- push value here
  };

  fileReader.readAsText(file);
  console.log(map);
  return result.asObservable();  // <-- return an observable
}

Now you need to subscribe to the function readFileAsMap() to obtain the values.

let config: Map<string, string>;

FileReaderComponent.readFileAsMap(configFile).subscribe(
  value => { config = value; }
);


答:
Do I understand it correctly that you want to invoke the method m on your object currVo?  Then it's simply

```<code>m.invoke(currVo);
</code>```

Title: java reflection issue

Body:
Do I understand it correctly that you want to invoke the method m on your object currVo?  Then it's simply

m.invoke(currVo);


问:
Using clustermq R package as a parallel backend for foreach
I've started using the clustermq package as a parallel backend for a drake pipeline, and have been very impressed over the performance improvements that I've observed.  I'm interested in evaluating the use of clustermq / rzmq in settings outside of drake, but seemingly can't get the example using foreach listed in the User Guide (in the subsection titled "As parallel foreach backend") to work.  What am I missing here?

In the example below on my 4-core machine, I would expect the following code to run in close to 5 seconds, yet it runs in close to 20 seconds.  When I use similar code to run some heavy processing, I'm only observing one core doing significant work.

library(foreach)
(n_cores <- parallel::detectCores())
#> [1] 4
clustermq::register_dopar_cmq(n_jobs = n_cores)
system.time(foreach(i = seq_len(n_cores)) %dopar% Sys.sleep(5))
#> Submitting 4 worker jobs (ID: 6856) ...
#>    user  system elapsed
#>   0.118   0.022  20.187
```

答:
The good news is,
the R-console reported the work-units got dispatched to the 4 worker jobs (ID: 6856) ...

To see how the acounting of CPU-usage works ( as in unix.time() ), test this ( the online R-code execution were not able to load either the library(foreach) nor the library(doParallel) to show the differences live, online, yet the code ought be clear on how to do that on a properly configured localhost R system :

```<code>factor = function( x ) {
         if (      x < 3 ) return( x )
         else              return( x * factor( x - 1 ) )
}

load   = function( n ) {
         for ( l in 1:n ) {
               base <- factor( 1078 )
               for ( k in 2:1111 ){
                     base <- ( base + factor( k ) ) / factor( k )
               }
         }
}

op <- options( digits.secs = 6 )

Sys.time()
system.time(                                           load( 100 ) )
Sys.time()
system.time( foreach( i = seq_len( n_cores ) ) %dopar% load( 100 ) )

Sys.time()

# ___________________________________________________________________
# tio.run
# ___________________________________________________________________
#
# factor(   78 )                                                     user: 0.016 system: 0.001 elapsed: 0.018
# factor(  178 )                                                     user: 0.016 system: 0.002 elapsed: 0.018 Real: 0.271 User: 0.180 Sys.: 0.059 CPU share: 88.04 %
# factor( 1078 )                                                     user: 0.017 system: 0.005 elapsed: 0.021 Real: 0.236 User: 0.188 Sys.: 0.047 CPU share: 99.94 %
# factor( 2178 )                                  Timing stopped at: user: 0.017 system: 0.005 elapsed: 0.023 Error: C stack usage  7972624 is too close to the limit : Execution halted
#
# load(   4 )                                                        user: 2.230 system: 0.005 elapsed: 2.253 Real: 2.483 User: 2.398 Sys.: 0.048 CPU share: 98.25 %
# load(   8 )                                                        user: 4.435 system: 0.013 elapsed: 4.481 Real: 4.753 User: 4.614 Sys.: 0.067 CPU share: 98.49 %
# load(  16 )                                                        user: 8.620 system: 0.009 elapsed: 8.693 Real: 8.932 User: 8.775 Sys.: 0.059 CPU share: 98.91 %
# load(  32 )                                                        user:20.522 system: 0.018 elapsed:20.892 Real:21.167 User:20.699 Sys.: 0.077 CPU share: 98.15 %
# load(  64 )                                                        user:35.212 system: 0.007 elapsed:35.611 Real:35.861 User:35.374 Sys.: 0.053 CPU share: 98.78 %
# load( 100 )                                                        user:54.721 system: 0.009 elapsed:55.128 Real:55.377 User:54.875 Sys.: 0.065 CPU share: 99.21 %
# load( 104 )                                                        user:57.087 system: 0.012 elapsed:57.532 Real:57.743 User:57.245 Sys.: 0.060 CPU share: 99.24 %
#
# ___________________________________________________________________
# https://www.jdoodle.com/execute-r-online/
# ___________________________________________________________________
#
# factor(   78 ) CPU Time: 0.27 sec(s), Mem: 52532 kB(s)             user: 0.028 system: 0.000 elapsed: 0.030
# factor(  178 ) CPU Time: 0.28 sec(s), Mem: 53212 kB(s)             user: 0.024 system: 0.004 elapsed: 0.028
# factor( 1078 ) CPU Time: 0.27 sec(s), Mem: 56884 kB(s)             user: 0.024 system: 0.008 elapsed: 0.037
# factor( 2178 ) CPU Time: 0.28 sec(s), Mem: 60768 kB(s) stopped at: user: 0.028 system: 0.004 elapsed: 0.032 Error: C stack usage  7971588 is too close to the limit : Execution halted
#
#
# load(  2 ) executed in  4.025 sec(s)                               user: 2.584 system: 0.008 elapsed: 2.630
# load(  4 ) executed in  6.005 sec(s)                               user: 4.704 system: 0.016 elapsed: 4.791
# load(  8 ) executed in 11.036 sec(s)                               user: 9.372 system: 0.028 elapsed: 9.572
# load( 16 ) executed in 20.085 sec(s)                               user:18.388 system: 0.068 elapsed:18.789
# load( 32 ) executed in 39.093 sec(s)                               user:37.664 system: 0.060 elapsed:37.974

# library(foreach)
# (n_cores <- parallel::detectCores())
## > [1] 4
# clustermq::register_dopar_cmq( n_jobs = n_cores ) ############################ REGISTER a parallel-backend
# system.time( foreach( i = seq_len( n_cores ) ) %dopar% load( 200 ) )
## > Submitting 4 worker jobs (ID: 6856) ...
## >    user  system elapsed
## >   0.118   0.022  20.187
</code>```

Body:
The good news is,
the R-console reported the work-units got dispatched to the 4 worker jobs (ID: 6856) ...

To see how the acounting of CPU-usage works ( as in unix.time() ), test this ( the online R-code execution were not able to load either the library(foreach) nor the library(doParallel) to show the differences live, online, yet the <a href="https://tio.run/##tVdNb@M2EL37VwwQBJDbmhYpiR/CtoemQbGHAkWyORWFIUtMrI1sOZKMJFjsb0@HkmyJcmLE65Qn2iTnvXkczmiKl5fbKK7yAn6F280qrtJ85cATjOHbCLYjvQWnmT3BJ/BwsdDVpmg2dtt0VmqwRrftJ2hgzHwCFE2MR99HoyyPEtzXx17Z2LdIzYEM0hXQcLDWjHmEsJ8mOwDqCtmn1bdzb@ywkOKA8Z4l257TzH7eGb43rGHa/z208H3Um6J/@dpYytfGtdKBJL1Lq5KUOi7RZ47nR9fPJanSpXbGo/K5rPSy@QVGGeOLW0v15jZ0S0fxwoEUDZb6YZZpo@Esxv/Lmu95kq@j4vyAwdEZ2DZb/xg1QuLmM5idPtAKqkCKzeqj7KGdLVWAmuqPjE2pixBc4lLeylD/cinGc7QuddIsyj4a/XA0NkCDKx1lZs4EhZv2EJUumHur9wQKLv6@gXIRFToEKYnrw3mPZPMMTiQpLJKBRZLRjqTHeyRlR9IXfZJKEWWTZO9U8ku6TFd3UFb5eq0TiKrwvSQ9uCyKHHde4Okovsdz0R2mKaEE48yHtIQqzyHOcnzrVQ7VQkOGaBWEcPmk4415urCIskondcg17wjA/0Fxd/oylM19izouBl6rLyO@9Fp9GfFUX19p6SvxVK3vlqQ8laRPfC/ok6ReRxIX5TYIfCKCLUmfcOp3JLkYkPRVnyS@hBNJSsKZraTqSOKi2iopifJYS1ISIYK3nhOSVLRPEo@dRpK5JGDMUlLuSOKiVKwhySihqNhNe4gr1ZEUQyWpdd381Jj0AsKoRdIVO5K4yGl73TiXvE1MOPdE77oxDGyS@MQ7kk0BOoVkgKGGuef16w4CQlmbPQNDrFUSD8n@dfNgkJgYtUieqmQgiCutxES7FI@LgddeN86F3z4cnDO/T9Idkqyz54fV40VVrctwOn18fCRfkzxPMk3ifDnVdd7Tk2KSr7J0paf/X8U2/mFy102pwy@Y2CnHv8BfRrSAGZXuf8d/Xi9PeNH9KHCtzO@5@xXbQpMDNM@E/iE030Lz7Toj90vvQd@4lP4RaNL2TezX0EO@cVdw2aK9WkMHStq@4SW8WUNpgOX@2BraZSyTVdtoS8ynOZYOF0tYQ/6dVTSQb0rFCK/DoEXzh2i8LrpHoGHqcS00LF69cigU7dDkAI1SlJIfg6Ywf1nZmPV8UyQQrMtYfICGpcOVx/hGJfGkFQa8Q6Mmi6sdmje8N08RF6vs@9E8QTi3lOTd88VFJfyRaUyydF5ExbPT9jmmF3G23Q12VtjZRFmmszBMdKXj6sIsOGPcdga/wT/0X/DxRJxtEKZYPoRhoe9SM5/VXdEsXj6YbulrPjcNWdc2nR0YcHX55@frL5dXEO3wJ3N8FnqV7LVSR7ZnrG3PavrXmzm@ocp8@PrwmBf3uoCaqfP5D3zTMuBjIIQ0m1thocXfagnbVfwwxw8OqKOIgQkPKsXLy38" rel="nofollow noreferrer">code ought be clear on how to do that on a properly configured localhost R system :

factor = function( x ) {
         if (      x < 3 ) return( x )
         else              return( x * factor( x - 1 ) )
}

load   = function( n ) {
         for ( l in 1:n ) {
               base <- factor( 1078 )
               for ( k in 2:1111 ){
                     base <- ( base + factor( k ) ) / factor( k )
               }
         }
}

op <- options( digits.secs = 6 )

Sys.time()
system.time(                                           load( 100 ) )
Sys.time()
system.time( foreach( i = seq_len( n_cores ) ) %dopar% load( 100 ) )

Sys.time()

# ___________________________________________________________________
# tio.run
# ___________________________________________________________________
#
# factor(   78 )                                                     user: 0.016 system: 0.001 elapsed: 0.018
# factor(  178 )                                                     user: 0.016 system: 0.002 elapsed: 0.018 Real: 0.271 User: 0.180 Sys.: 0.059 CPU share: 88.04 %
# factor( 1078 )                                                     user: 0.017 system: 0.005 elapsed: 0.021 Real: 0.236 User: 0.188 Sys.: 0.047 CPU share: 99.94 %
# factor( 2178 )                                  Timing stopped at: user: 0.017 system: 0.005 elapsed: 0.023 Error: C stack usage  7972624 is too close to the limit : Execution halted
#
# load(   4 )                                                        user: 2.230 system: 0.005 elapsed: 2.253 Real: 2.483 User: 2.398 Sys.: 0.048 CPU share: 98.25 %
# load(   8 )                                                        user: 4.435 system: 0.013 elapsed: 4.481 Real: 4.753 User: 4.614 Sys.: 0.067 CPU share: 98.49 %
# load(  16 )                                                        user: 8.620 system: 0.009 elapsed: 8.693 Real: 8.932 User: 8.775 Sys.: 0.059 CPU share: 98.91 %
# load(  32 )                                                        user:20.522 system: 0.018 elapsed:20.892 Real:21.167 User:20.699 Sys.: 0.077 CPU share: 98.15 %
# load(  64 )                                                        user:35.212 system: 0.007 elapsed:35.611 Real:35.861 User:35.374 Sys.: 0.053 CPU share: 98.78 %
# load( 100 )                                                        user:54.721 system: 0.009 elapsed:55.128 Real:55.377 User:54.875 Sys.: 0.065 CPU share: 99.21 %
# load( 104 )                                                        user:57.087 system: 0.012 elapsed:57.532 Real:57.743 User:57.245 Sys.: 0.060 CPU share: 99.24 %
#
# ___________________________________________________________________
# https://www.jdoodle.com/execute-r-online/
# ___________________________________________________________________
#
# factor(   78 ) CPU Time: 0.27 sec(s), Mem: 52532 kB(s)             user: 0.028 system: 0.000 elapsed: 0.030
# factor(  178 ) CPU Time: 0.28 sec(s), Mem: 53212 kB(s)             user: 0.024 system: 0.004 elapsed: 0.028
# factor( 1078 ) CPU Time: 0.27 sec(s), Mem: 56884 kB(s)             user: 0.024 system: 0.008 elapsed: 0.037
# factor( 2178 ) CPU Time: 0.28 sec(s), Mem: 60768 kB(s) stopped at: user: 0.028 system: 0.004 elapsed: 0.032 Error: C stack usage  7971588 is too close to the limit : Execution halted
#
#
# load(  2 ) executed in  4.025 sec(s)                               user: 2.584 system: 0.008 elapsed: 2.630
# load(  4 ) executed in  6.005 sec(s)                               user: 4.704 system: 0.016 elapsed: 4.791
# load(  8 ) executed in 11.036 sec(s)                               user: 9.372 system: 0.028 elapsed: 9.572
# load( 16 ) executed in 20.085 sec(s)                               user:18.388 system: 0.068 elapsed:18.789
# load( 32 ) executed in 39.093 sec(s)                               user:37.664 system: 0.060 elapsed:37.974

# library(foreach)
# (n_cores <- parallel::detectCores())
## > [1] 4
# clustermq::register_dopar_cmq( n_jobs = n_cores ) ############################ REGISTER a parallel-backend
# system.time( foreach( i = seq_len( n_cores ) ) %dopar% load( 200 ) )
## > Submitting 4 worker jobs (ID: 6856) ...
## >    user  system elapsed
## >   0.118   0.022  20.187


问:
Get Google Colab autocomplete in Jupyter Notebook
I recently started using Google Colab and absolutely love the autocomplete UI. I usually code in Jupyter Notebook and hence am used to an autocomplete which only returns the single methods and takes a second or two to load. Google Colab on the other hand is instant, returns the method and also tells you the expected arguments and a description of what a method does. I love it, it reminds me of my old days in eclipse.

Therefore I wanted to ask if there is a module/plugin for Jupyter Notebook to have this UI. Otherwise, is there a different IDE like Jupyter (with these code snippets) with the advanced autocomplete functions? Possibly open source. Thanks.

答:
You can try to use the Hinterland, it's an extension that enable code autocompletion menu for every keypress in a code cell, instead of only calling it with tab.

You can lean how to enable an extension in here, and read more about Hinterland in here.

I hope it helped you


问:
SQL Get current month
I have table1 with data

```<code>file  Startdate
A     2020-05-01
B     2020-06-01
</code>```

We have today is 2020-06-01 and I could use Select and where startdate ='2020-06-01'

But I try this query and not get 2020-06-01

```<code>select file from table1
where
 startdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
         and startdate < datefromparts(year(getdate()), month(getdate()), 1)
</code>```

Please correct me. Thank you

答:
You're looking for

```<code>select [file] from table1
where
 startdate = datefromparts(year(getdate()), month(getdate()), 1)
</code>```

This'll returns

```<code>file  Startdate
B     2020-06-01
</code>```

UPDATE:

I mean not just 2020-06-01 but if I add 2020-06-02 then should get 2 records for 2020-06-01 and 2020-06-02

```<code>SELECT [File]
FROM Table1
WHERE StartDate >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)
      AND
      StartDate <= EOMONTH(GETDATE());
</code>```

Title: SQL Get current month

Body:
I have table1 with data

file  Startdate
A     2020-05-01
B     2020-06-01

We have today is 2020-06-01 and I could use Select and where startdate ='2020-06-01'

But I try this query and not get 2020-06-01

select file from table1
where
 startdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
         and startdate < datefromparts(year(getdate()), month(getdate()), 1)

Please correct me. Thank you

Body:
You're looking for

select [file] from table1
where
 startdate = datefromparts(year(getdate()), month(getdate()), 1)

This'll returns

file  Startdate
B     2020-06-01

UPDATE:

I mean not just 2020-06-01 but if I add 2020-06-02 then should get 2 records for 2020-06-01 and 2020-06-02

SELECT [File]
FROM Table1
WHERE StartDate >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)
      AND
      StartDate <= EOMONTH(GETDATE());


问:
Selecting only non null fields from the filter rows django
I have this query which are getting the required rows which i want but the problem is most fields/columns have null values I just want to get only those fields from these rows which have non null values

```<code>queryset = User.objects.filter(email__exact=email)
</code>```

Here, is my model

```<code>class User(models.Model):
    email = models.CharField(max_length=50, null=True, blank=True)
    password = models.CharField(db_index=True, max_length=40, null=True)
    source = models.CharField(default='unknown', max_length=150, null=True)
    domain = models.CharField(max_length=50, null=True, blank=True)
    before_at = models.CharField(max_length=255, null=True, blank=True)
    username = models.CharField(db_index=True, max_length=150, null=True, blank=True)
    hash = models.CharField(max_length=255, null=True, blank=True)
    ipaddress = models.CharField(max_length=50, null=True, blank=True)
    phonenumber = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        if self.email != None:
            return self.email
        elif self.username != None:
            return self.username
</code>```

答:
Alternatively, You can use this:

```<code>  for q in queryset:
    if q.email == None or q.username == None:
      queryset = queryset.exclude(email=q.email)
</code>```

I hope that this would solve your problem.

Body:
I have this query which are getting the required rows which i want but the problem is most fields/columns have null values I just want to get only those fields from these rows which have non null values

queryset = User.objects.filter(email__exact=email)

Here, is my model

class User(models.Model):
    email = models.CharField(max_length=50, null=True, blank=True)
    password = models.CharField(db_index=True, max_length=40, null=True)
    source = models.CharField(default='unknown', max_length=150, null=True)
    domain = models.CharField(max_length=50, null=True, blank=True)
    before_at = models.CharField(max_length=255, null=True, blank=True)
    username = models.CharField(db_index=True, max_length=150, null=True, blank=True)
    hash = models.CharField(max_length=255, null=True, blank=True)
    ipaddress = models.CharField(max_length=50, null=True, blank=True)
    phonenumber = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        if self.email != None:
            return self.email
        elif self.username != None:
            return self.username

Body:
Alternatively, You can use this:

  for q in queryset:
    if q.email == None or q.username == None:
      queryset = queryset.exclude(email=q.email)

I hope that this would solve your problem.


问:
Adding Search Path For #include
I have tried to understand: (Manipulating the search path for include files), but I am having troubles. Note that I am new.

I have tried putting the following in the #include with brackets: #include "boost/1.73.0/include/boost/math/tools/promotion.hpp" where "= bracket.

I have tried to add the search path to the options file in make. I used: -I/boost/1.73.0/include/boost/math/tools and #include "promotion.hpp"

The person that created the original OpenFoam solver had nothing in the options file, and had #include "boost/math/tools/promotion.hpp" where "= bracket.

I am not compiling one file, I am using Allwmake to compile an OpenFoam solver. In some cases, the file path has changed since the solver was written for an older version. So, I am updating.

A Computational Fluid Dynamics site suggested I install boost under home directory. The boost path is not recognized.

I ask for "complete" explanation because I have tried a lot. I am lost.

Each gave me the compilation errors that the file or directory does not exist.

I need help. I have read a lot, I am ignorant still, and I need a complete explanation.

Thanks!

答:
You need to add the directory to the compiler's include search path. For g++ and clang it's done via -I option. In your case that would be

g++ -I/boost/1.73.0/include.

Never fixup your include directories in the source code. This would tie the source code to your specific configuration. It would simply make the code non-compilable on any other machine.

Title: Adding Search Path For #include


问:
How to properly use TypeScript types with a Styled Component canvas on React
I am creating a React component on Gatsby using TypeScript and have defined a canvas Styled Component this way:

```<code>const Background = styled.canvas`
  position: fixed;
  width: 100%;
  height: 100%;
`;
</code>```

And to use it I am assigning types to it this way:

```<code>const canvas: HTMLCanvasElement = Background,
  context = Background.getContext('2d');
</code>```

But I am getting this error with the canvas type:

```<code>Type 'String & StyledComponentBase<"canvas", any, {}, never> & NonReactStatics<never, {}>' is missing the following properties from type 'HTMLCanvasElement': height, width, getContext, toBlob, and 238 more.
</code>```

I am also getting an error on the .getContext() method:

```<code>This expression is not callable.
Type 'never' has no call signatures.
</code>```

I have been searching for a solution but can not find a proper one for this specific problem.
Could someone please explain to me the best way to use Styled Component canvas with TypeScript?

答:
The answer from @101arrowz was almost right but had a problem with the context that gave me this error.

```<code>Object is possibly 'null'.
</code>```

But it helped me to find a different approach with the styles being inline and solve the problem this way:

```<code>const Component: React.FC = () => {
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const [context, setContext] = React.useState<CanvasRenderingContext2D | null>(
    null
  );

  React.useEffect(() => {
    if (canvasRef.current) {
      const renderCtx = canvasRef.current.getContext('2d');

      if (renderCtx) {
        setContext(renderCtx);
      }
    }
  }, [context]);

  return (
    <div>
      <canvas
        id="canvas"
        ref={canvasRef}
        style={{
          position: 'fixed',
          width: '100%',
          height: '100%'
        }}
      ></canvas>
    </div>
  );

</code>```

Body:
I am creating a React component on Gatsby using TypeScript and have defined a canvas Styled Component this way:

const Background = styled.canvas`
  position: fixed;
  width: 100%;
  height: 100%;
`;

And to use it I am assigning types to it this way:

const canvas: HTMLCanvasElement = Background,
  context = Background.getContext('2d');

But I am getting this error with the canvas type:

Type 'String & StyledComponentBase<"canvas", any, {}, never> & NonReactStatics<never, {}>' is missing the following properties from type 'HTMLCanvasElement': height, width, getContext, toBlob, and 238 more.

I am also getting an error on the .getContext() method:

This expression is not callable.
Type 'never' has no call signatures.

I have been searching for a solution but can not find a proper one for this specific problem.
Could someone please explain to me the best way to use Styled Component canvas with TypeScript?

Body:
The answer from @101arrowz was almost right but had a problem with the context that gave me this error.

Object is possibly 'null'.

But it helped me to find a different approach with the styles being inline and solve the problem this way:

const Component: React.FC = () => {
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const [context, setContext] = React.useState<CanvasRenderingContext2D | null>(
    null
  );

  React.useEffect(() => {
    if (canvasRef.current) {
      const renderCtx = canvasRef.current.getContext('2d');

      if (renderCtx) {
        setContext(renderCtx);
      }
    }
  }, [context]);

  return (
    <div>
      <canvas
        id="canvas"
        ref={canvasRef}
        style={{
          position: 'fixed',
          width: '100%',
          height: '100%'
        }}
      ></canvas>
    </div>
  );


问:
Finding the calculation that generates a NaN
I have a moderately large piece (a few thousand lines) of Python/Numpy/Scipy code that is throwing up NaNs with certain inputs. I've looked for, and found, some of the usual suspects (log(0) and the like), but none of the obvious ones seem to be the culprits in this case.

Is there a relatively painless way (i.e., apart from putting exception handling code around each potential culprit), to find out where these NaNs are coming from?

答: You can use numpy.seterr to set floating point error handling behaviour globally for all numpy routines. That should let you pinpoint where in the code they are arising from (or a least where numpy see them for the first time).


问:
how can i print a clikible link on command in spigot api
hi I'm making a plugin for Minecraft spigot and want to have it so you can type the command

/shop

and it while answer whit

https://vattenfallet.tebex.io witch is the site for the shop

答:
you could use Minecrafts TextComponents to send the message. Just use them like this: </p>

```<code>TextComponent textComponent = new TextComponent(broadcast);
textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
player.sendMessage(textComponent);
</code>```

Body:
you could use Minecrafts TextComponents to send the message. Just use them like this:

TextComponent textComponent = new TextComponent(broadcast);
textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
player.sendMessage(textComponent);


问:
Java: prevent another thread getting control until a specific command in the first thread is executed
I have a simple concurrent code that increments a shared variable.

Two threads increment the counter 10,000,000 times each and print the result.

It works alright (race condition is resolved with synchronized inside the increment method).

However after thread A is done incrementing, thread B starts incrementing before thread A has a chance to prints its result (should be 10,000,000). I can resolve it by getting thread B to sleep 3 seconds before starting its own increment:

```<code>public class DogLatch {
    private static Counter counter = new Counter();

    public static void main(String[] args) throws Exception {
        Thread a = new Thread(new A());
        Thread b = new Thread(new B());

        a.start();
        b.start();

        a.join();
        b.join();

        System.out.printf("counter: %,d", counter.getValue());
    }

    static class Counter  {
        private int i;

        public void increment()  {
            synchronized (this)  {
                i++;
            }
        }

        public int getValue()  {return i;}

        public void setValue(int i ) {this.i = i;}
    }

    static class A implements Runnable  {
        @Override
        public void run()  {
            for (int i = 0; i < 10_000_000; i++) {
                counter.increment();
            }

            System.out.println("A done: " + counter.getValue());
        }
    }

    static class B implements Runnable  {
        @Override
        public void run()  {
            System.out.println("Go to school");
            System.out.println("Walk dog");

            try  {
                Thread.sleep(5000);
            }
            catch (Exception e) {
                e.printStackTrace();
            }

            for (int i = 0; i < 10_000_000; i++) {
                counter.increment();
            }

            System.out.println("B done: " + counter.getValue());
        }
    }
}
</code>```

would print

```<code>Go to school
Walk dog
A done: 10000000
B done: 20000000
counter: 20,000,000
</code>```

However if I repalce B with:

```<code>static class B implements Runnable  {
        @Override
        public void run()  {
            System.out.println("Go to school");
            System.out.println("Walk dog");

            for (int i = 0; i < 10_000_000; i++) {
                counter.increment();
            }

            System.out.println("B done: " + counter.getValue());
        }
    }
</code>```

I get

```<code>Go to school
Walk dog
A done: 17368068
B done: 20000000
counter: 20,000,000
</code>```

output. Is there a way to achieve the correct output where A done: 10000000 and B done: 10000000 is displayed, without resorting to Thread.sleep() in B?

答:
Actually, your program is not really doing much concurrent processing.  You wait 5 seconds in thread B while thread A increments up to 10,000,000 and then B wakes up and continues.

This would be the result if you just started them one after the other in a single thread.

But you know it's working fine since the the end result is always 20,000,000 without the sleep statement.

If you force alternation you will loose the benefit of using threads.  The fact that A prints out different values but the final tally is 20,000,000 is indicative of it working perfectly!

Body:
I have a simple concurrent code that increments a shared variable.

Two threads increment the counter 10,000,000 times each and print the result.

It works alright (race condition is resolved with synchronized inside the increment method).

However after thread A is done incrementing, thread B starts incrementing before thread A has a chance to prints its result (should be 10,000,000). I can resolve it by getting thread B to sleep 3 seconds before starting its own increment:

public class DogLatch {
    private static Counter counter = new Counter();

    public static void main(String[] args) throws Exception {
        Thread a = new Thread(new A());
        Thread b = new Thread(new B());

        a.start();
        b.start();

        a.join();
        b.join();

        System.out.printf("counter: %,d", counter.getValue());
    }

    static class Counter  {
        private int i;

        public void increment()  {
            synchronized (this)  {
                i++;
            }
        }

        public int getValue()  {return i;}

        public void setValue(int i ) {this.i = i;}
    }

    static class A implements Runnable  {
        @Override
        public void run()  {
            for (int i = 0; i < 10_000_000; i++) {
                counter.increment();
            }

            System.out.println("A done: " + counter.getValue());
        }
    }

    static class B implements Runnable  {
        @Override
        public void run()  {
            System.out.println("Go to school");
            System.out.println("Walk dog");

            try  {
                Thread.sleep(5000);
            }
            catch (Exception e) {
                e.printStackTrace();
            }

            for (int i = 0; i < 10_000_000; i++) {
                counter.increment();
            }

            System.out.println("B done: " + counter.getValue());
        }
    }
}

would print

Go to school
Walk dog
A done: 10000000
B done: 20000000
counter: 20,000,000

However if I repalce B with:

static class B implements Runnable  {
        @Override
        public void run()  {
            System.out.println("Go to school");
            System.out.println("Walk dog");

            for (int i = 0; i < 10_000_000; i++) {
                counter.increment();
            }

            System.out.println("B done: " + counter.getValue());
        }
    }

I get

Go to school
Walk dog
A done: 17368068
B done: 20000000
counter: 20,000,000

output. Is there a way to achieve the correct output where A done: 10000000 and B done: 10000000 is displayed, without resorting to Thread.sleep() in B?


问:
How to display button opposite of level in React?
How to display button opposite of its status. Suppose its showing open then the button should appear Withdraw and if the status is appearing Withdraw button should appear Open in Reactjs.

I have a Json object which carries the necessary information.

Here is code is what I have had tried..

```<code>const initial = {
  description: [
    {
      name: 'Alex',
      level: 'open',
    },
    {
      name: 'Sycus',
      level: 'open',
    },
    {
      name: 'Rasku',
      level: 'Withdraw',
    }
  ]
}

export default function App() {

  const [state, setState] = React.useState(initial)
  const [show , setshow] = React.useState(true)

  const handleClick = () => {
    return
  }

  const butFunction = () => {
      return state.description.map(sub => {
          const { level } = sub
          return (
            if(level === 'open'){
              <button>Withdraw</button>
            }
            else{
              <button>Open</buton>
            }
          )
      })
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        <table>
          <tbody>
            {
              state.description.map(desc => (
                <tr>
                  <td>
                  {desc.name}
                  </td>
                  <td>
                  {desc.level}
                  </td>
                <td>

                { show && butFunction()}
                </td>
                </tr>
              ))
              }
          </tbody>
        </table>
      </div>
    </div>
  );
}
</code>```

答:
I don't think you need the map inside the butFunction. That would print 3 buttons for every entry. Instead, pass the function a parameter telling it which level it is.

Example below:

export default function App() {
  const [state, setState] = React.useState(initial)
  const [show , setshow] = React.useState(true)

  // Use the level passed in
  const butFunction = (level) => {
    if(level === 'open'){
      return <button>Withdraw</button>;
    } else {
      return <button>Open</button>;
    }
  }

  return (

Hello CodeSandbox

            {state.description.map(desc => (

                  {desc.name}

                  {desc.level}

                  {show && butFunction(desc.level)} // <- Pass it here

            ))}

  );
}
```

Not it will only return one button per entry.

Body:
How to display button opposite of its status. Suppose its showing open then the button should appear Withdraw and if the status is appearing Withdraw button should appear Open in Reactjs.

I have a Json object which carries the necessary information.

Here is code is what I have had tried..

const initial = {
  description: [
    {
      name: 'Alex',
      level: 'open',
    },
    {
      name: 'Sycus',
      level: 'open',
    },
    {
      name: 'Rasku',
      level: 'Withdraw',
    }
  ]
}

export default function App() {

  const [state, setState] = React.useState(initial)
  const [show , setshow] = React.useState(true)

  const handleClick = () => {
    return
  }

  const butFunction = () => {
      return state.description.map(sub => {
          const { level } = sub
          return (
            if(level === 'open'){
              <button>Withdraw</button>
            }
            else{
              <button>Open</buton>
            }
          )
      })
  }

  return (

Hello CodeSandbox

            {
              state.description.map(desc => (

                  {desc.name}

                  {desc.level}

                { show && butFunction()}

              ))
              }

  );
}

Body:
I don't think you need the map inside the butFunction. That would print 3 buttons for every entry. Instead, pass the function a parameter telling it which level it is.

Example below:

export default function App() {
  const [state, setState] = React.useState(initial)
  const [show , setshow] = React.useState(true)

  // Use the level passed in
  const butFunction = (level) => {
    if(level === 'open'){
      return <button>Withdraw</button>;
    } else {
      return <button>Open</button>;
    }
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        <table>
          <tbody>
            {state.description.map(desc => (
              <tr>
                <td>
                  {desc.name}
                </td>
                <td>
                  {desc.level}
                </td>
                <td>
                  {show && butFunction(desc.level)} // <- Pass it here
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Not it will only return one button per entry.


问:
android SELECT MAX not work
I have tested this select in SQLite and it works but, when I use this in Android, it returns 0.

Where am I going wrong?

Thanks!!

```<code>final String idauto = bundle.getString("idtabella");

DatabaseHelper databaseHelper = new DatabaseHelper(this);

final SQLiteDatabase db = databaseHelper.getReadableDatabase();
final Cursor cursordati = db.rawQuery("SELECT MAX('in_auto') AS in_auto "
    + "FROM inout WHERE id_auto ='" + idauto + "'", null);

final int  Ingressi = cursordati.getColumnIndex("in_auto");
if(cursordati.moveToFirst()){
    TextV.append("iprova: "+ Ingressi);
    do {
        TextV.append("dprova: "+ Ingressi);
    } while (cursordati.moveToNext());
    TextV.append("wprova: "+ Ingressi);
}
</code>```

答:
I'm not sure why you thing you have a problem. You're asking for the column index for a query with exactly one column. Since the index is zero-based, you will get zero.

If you want to get the actual value of max(in_auto) instead of its index, you should probably try:

```<code>final int  Ingressi = cursordati.getInt(cursordati.getColumnIndex("in_auto"));
</code>```

or probably just:

```<code>final int  Ingressi = cursordati.getInt(0);
</code>```

would be fine, as long as you remember to check and possibly change it if you ever modify the query.

Title: android SELECT MAX not work

Body:
I have tested this select in SQLite and it works but, when I use this in Android, it returns 0.

Where am I going wrong?

Thanks!!

final String idauto = bundle.getString("idtabella");

DatabaseHelper databaseHelper = new DatabaseHelper(this);

final SQLiteDatabase db = databaseHelper.getReadableDatabase();
final Cursor cursordati = db.rawQuery("SELECT MAX('in_auto') AS in_auto "
    + "FROM inout WHERE id_auto ='" + idauto + "'", null);

final int  Ingressi = cursordati.getColumnIndex("in_auto");
if(cursordati.moveToFirst()){
    TextV.append("iprova: "+ Ingressi);
    do {
        TextV.append("dprova: "+ Ingressi);
    } while (cursordati.moveToNext());
    TextV.append("wprova: "+ Ingressi);
}

Body:
I'm not sure why you thing you have a problem. You're asking for the column index for a query with exactly one column. Since the index is zero-based, you will get zero.

If you want to get the actual value of max(in_auto) instead of its index, you should probably try:

final int  Ingressi = cursordati.getInt(cursordati.getColumnIndex("in_auto"));

or probably just:

final int  Ingressi = cursordati.getInt(0);

would be fine, as long as you remember to check and possibly change it if you ever modify the query.


问:
Even or odd. If the number is equal to 0, the program must stop
I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.

```<code>Input
1
2
3
0
Output
odd
even
odd
</code>```

My code:

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int num;
        for (; ; ) {
            Scanner reader = new Scanner(System.in);
            num = reader.nextInt();
            if (num % 2 == 0) {
                System.out.println("even");
            }
            else if(num == 0){
                break;
            }
            else{
                System.out.println("odd");
            }
        }
    }
}
</code>```

答:
```<code>int num;
Scanner reader = new Scanner(System.in);
for ( ; ; ) {
    num = reader.nextInt();
    if (num == 0) {
        break;
    } else if (num % 2== 0) {
        System.out.println("even");
    } else {
        System.out.println("odd");
    }
}
</code>```

Your problem is the sequence of your if/else conditions. If the first input is 0, 0 % 2 returns true - so it will never break.

Also, you do not need a new Scanner every time. You can take it out of the loop and reuse it.

Body:
I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.

Input
1
2
3
0
Output
odd
even
odd

My code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int num;
        for (; ; ) {
            Scanner reader = new Scanner(System.in);
            num = reader.nextInt();
            if (num % 2 == 0) {
                System.out.println("even");
            }
            else if(num == 0){
                break;
            }
            else{
                System.out.println("odd");
            }
        }
    }
}

Body:
int num;
Scanner reader = new Scanner(System.in);
for ( ; ; ) {
    num = reader.nextInt();
    if (num == 0) {
        break;
    } else if (num % 2== 0) {
        System.out.println("even");
    } else {
        System.out.println("odd");
    }
}

Your problem is the sequence of your if/else conditions. If the first input is 0, 0 % 2 returns true - so it will never break.

Also, you do not need a new Scanner every time. You can take it out of the loop and reuse it.


问:
preprocessing tweets, remove @ and # , eliminate stop words and remove user from list of list in python
i wrote the code below but now I want to p reprocess, so I transformed to lower, I wrote some word to eliminate stop words but it does not work, and I want to remove @ and # and also remove user , can you help me?  </p>

```<code>

! pip install wget
import wget
url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/tweets_en.txt'
wget.download(url, 'tweets_en.txt')
tweets = [line.strip() for line in open('tweets_en.txt', encoding='utf8')]

import spacy
from collections import Counter
# your code here
import itertools
nlp = spacy.load('en')

#Creates a list of lists of tokens
tokens = [[token.text for token in nlp(sentence)] for sentence in tweets[:200]]
print(tokens)

#to lower
token_l=[[w.lower() for w in line] for line in tokens]
token_l[:1]

#remove #

#remove stop word

#remove user

#remove @

from nltk.corpus import stopwords

# filtered_words = [[w for w in line] for line in tokens if w not in # stopwords.words('english')]

</code>```

答:
Always try to organise your code into functions: they are reusable, readable, and loopable.

```<code>from nltk.corpus import stopwords
import spacy, re

nlp = spacy.load('en')

stop_words = [w.lower() for w in stopwords.words()]

def sanitize(input_string):
    """ Sanitize one string """

    # normalize to lowercase
    string = input_string.lower()

    # spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # in case the string is empty
    if not string_split:
        return ''

    # remove user
    # assuming user is the first word and contains an @
    if '@' in string_split[0]:
        del string_split[0]

    # join back to string
    string = ' '.join(string_split)

    #remove # and @
    for punc in '@#':
       string = string.replace(punc, '')

    # remove 't.co/' links
    string = re.sub(r't.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # removing stop words
    string = ' '.join([w for w in string.split() if w not in stop_words])

    return string

list = ['@Jeff_Atwood Thank you for #stackoverflow', 'All hail @Joel_Spolsky t.co/Gsb7V1oVLU #stackoverflow' ]

list_sanitized = [sanitize(string) for string in list]
</code>```

Ouput:

```<code>['thank stackoverflow', 'hail joel_spolsky stackoverflow']
</code>```

Body:
i wrote the code below but now I want to p reprocess, so I transformed to lower, I wrote some word to eliminate stop words but it does not work, and I want to remove @ and # and also remove user , can you help me?

! pip install wget
import wget
url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/tweets_en.txt'
wget.download(url, 'tweets_en.txt')
tweets = [line.strip() for line in open('tweets_en.txt', encoding='utf8')]

import spacy
from collections import Counter
# your code here
import itertools
nlp = spacy.load('en')

#Creates a list of lists of tokens
tokens = [[token.text for token in nlp(sentence)] for sentence in tweets[:200]]
print(tokens)

#to lower
token_l=[[w.lower() for w in line] for line in tokens]
token_l[:1]

#remove #

#remove stop word

#remove user

#remove @

from nltk.corpus import stopwords

# filtered_words = [[w for w in line] for line in tokens if w not in # stopwords.words('english')]

Body:
Always try to organise your code into functions: they are reusable, readable, and loopable.

from nltk.corpus import stopwords
import spacy, re

nlp = spacy.load('en')

stop_words = [w.lower() for w in stopwords.words()]

def sanitize(input_string):
    """ Sanitize one string """

    # normalize to lowercase
    string = input_string.lower()

    # spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # in case the string is empty
    if not string_split:
        return ''

    # remove user
    # assuming user is the first word and contains an @
    if '@' in string_split[0]:
        del string_split[0]

    # join back to string
    string = ' '.join(string_split)

    #remove # and @
    for punc in '@#':
       string = string.replace(punc, '')

    # remove 't.co/' links
    string = re.sub(r't.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # removing stop words
    string = ' '.join([w for w in string.split() if w not in stop_words])

    return string

list = ['@Jeff_Atwood Thank you for #stackoverflow', 'All hail @Joel_Spolsky t.co/Gsb7V1oVLU #stackoverflow' ]

list_sanitized = [sanitize(string) for string in list]

Ouput:

['thank stackoverflow', 'hail joel_spolsky stackoverflow']