问:
Jackson parse exception while using Guava's RateLimiter
I am using Guava's RateLimiter so I don't hit the max requests per second (I'ts 5..) at the API. It works fine, I never hit the rate limit now but I have a strange problem now. For some reason it gives 1 out of 5 times running the app an exception for one of the 6 calls:</p>

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.fasterxml.jackson.databind.JavaType.equals(java.lang.Object)' on a null object reference
                                               at com.fasterxml.jackson.databind.type.ResolvedRecursiveType.equals(ResolvedRecursiveType.java:103)
                                               at com.fasterxml.jackson.databind.type.TypeBindings$AsKey.equals(TypeBindings.java:458)
                                               at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1014)
                                               at java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1522)
                                               at com.fasterxml.jackson.databind.util.LRUMap.putIfAbsent(LRUMap.java:64)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1274)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(TypeFactory.java:1384)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1154)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._resolveSuperInterfaces(TypeFactory.java:1298)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1247)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1150)
                                               at com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeFactory.java:618)
                                               at com.fasterxml.jackson.databind.cfg.MapperConfig.constructType(MapperConfig.java:290)
                                               at com.fasterxml.jackson.databind.cfg.MapperConfig.introspectClassAnnotations(MapperConfig.java:320)
                                               at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findTypeDeserializer(BasicDeserializerFactory.java:1338)
                                               at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:481)
                                               at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3890)
                                               at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3756)
                                               at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:2198)
                                               at dk.nykredit.jackson.dataformat.hal.deser.HALBeanDeserializer.deserialize(HALBeanDeserializer.java:27)
                                               at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
                                               at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2913)
                                               at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:179)
                                               at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:174)
                                               at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:89)
                                               at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:738)
                                               at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:723)
                                               at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:544)
                                               at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506)
                                               at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:455)
                                               at nl.app.App.API.RestClient_.getAdviseurs(RestClient_.java:117)
                                               at nl.app.App.Services.AdviseurService.getAdviseur(AdviseurService.java:60)
                                               at nl.app.App.Services.AdviseurService.getAdviseurAsync(AdviseurService.java:49)
                                               at nl.app.App.Services.AdviseurService_.access$101(AdviseurService_.java:19)
                                               at nl.app.App.Services.AdviseurService_$2.execute(AdviseurService_.java:66)
                                               at org.androidannotations.api.BackgroundExecutor$Task.run(BackgroundExecutor.java:405)
                                               at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                               at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                               at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
                                               at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
</code>```

答:
That exception does not appear to have anything to do with RateLimiter. The stack trace is saying that Spring and/or Jackson tried to call .equals() via reflection on a null reference. My guess would be you're passing null to something you shouldn't be - perhaps you're returning null if the rate limiter doesn't have enough permits?

Without seeing the code in question it's hard to say exactly what's causing this error. Try making an MCVE that replicates the error - it's likely simply creating the MCVE will be enough for you to find the issue.

Body:
I am using Guava's RateLimiter so I don't hit the max requests per second (I'ts 5..) at the API. It works fine, I never hit the rate limit now but I have a strange problem now. For some reason it gives 1 out of 5 times running the app an exception for one of the 6 calls:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.fasterxml.jackson.databind.JavaType.equals(java.lang.Object)' on a null object reference
                                               at com.fasterxml.jackson.databind.type.ResolvedRecursiveType.equals(ResolvedRecursiveType.java:103)
                                               at com.fasterxml.jackson.databind.type.TypeBindings$AsKey.equals(TypeBindings.java:458)
                                               at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1014)
                                               at java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1522)
                                               at com.fasterxml.jackson.databind.util.LRUMap.putIfAbsent(LRUMap.java:64)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1274)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(TypeFactory.java:1384)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1154)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._resolveSuperInterfaces(TypeFactory.java:1298)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1247)
                                               at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1150)
                                               at com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeFactory.java:618)
                                               at com.fasterxml.jackson.databind.cfg.MapperConfig.constructType(MapperConfig.java:290)
                                               at com.fasterxml.jackson.databind.cfg.MapperConfig.introspectClassAnnotations(MapperConfig.java:320)
                                               at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findTypeDeserializer(BasicDeserializerFactory.java:1338)
                                               at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:481)
                                               at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3890)
                                               at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3756)
                                               at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:2198)
                                               at dk.nykredit.jackson.dataformat.hal.deser.HALBeanDeserializer.deserialize(HALBeanDeserializer.java:27)
                                               at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
                                               at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2913)
                                               at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:179)
                                               at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:174)
                                               at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:89)
                                               at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:738)
                                               at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:723)
                                               at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:544)
                                               at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506)
                                               at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:455)
                                               at nl.app.App.API.RestClient_.getAdviseurs(RestClient_.java:117)
                                               at nl.app.App.Services.AdviseurService.getAdviseur(AdviseurService.java:60)
                                               at nl.app.App.Services.AdviseurService.getAdviseurAsync(AdviseurService.java:49)
                                               at nl.app.App.Services.AdviseurService_.access$101(AdviseurService_.java:19)
                                               at nl.app.App.Services.AdviseurService_$2.execute(AdviseurService_.java:66)
                                               at org.androidannotations.api.BackgroundExecutor$Task.run(BackgroundExecutor.java:405)
                                               at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                               at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                               at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
                                               at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)


来源: stackexchange

问:
how to use multiple query in sql
I want to show count and row table in one query, but when I run this it shows 0 rows and it does not show the count.</p>

```<code>   <?php

   include "connect_db.php";
   $query = "SELECT COUNT(*) AS numberOfRows FROM wp_cf7_data, wp_cf7_data_entry WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
   UNION
   SELECT * FROM wp_cf7_data, wp_cf7_data_entry WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
   ";

   $result = mysqli_query($conn, $query);

   if (mysqli_num_rows($result) > 0) {
       // output data of each row
       while($row = mysqli_fetch_assoc($result)) {
         echo $row['numberOfRows'];
           echo "id: " . $row["id"]. " - Name: " . $row["cf7_id"]. " " . $row["name"]. "<br>";

       }
   } else {
       echo "0 results";
   }

   mysqli_close($conn);
   ?>
</code>```

答:
My guess is that you're getting an error from MySQL, which you're not capturing (that's something that you should check on because your code in general should be written to handle errors.

The problem here is that you're trying to UNION two result sets that don't have the same columns. COUNT(*) is a single integer column, while SELECT * is going to return you multiple columns.

Instead, just use your second query after the UNION (remove the entire SELECT COUNT(*)) then check the count from the resultset that you get back using mysql_num_rows. I don't program in php, but I'm sure that you can find examples of how to use this with a quick Google search.

Some other quick notes:

Never use SELECT *. ALWAYS list out the column list that you're hoping to return. If you use SELECT * then not only is your code not clear, but if the table design changes at any point it will suddenly break all of your code.

Also, use explicit JOINs (INNER or OUTER as appropriate). Don't just put your tables in the FROM clause.

ContentLicense: CC BY-SA 3.0

Title: how to use multiple query in sql

Body:
I want to show count and row table in one query, but when I run this it shows 0 rows and it does not show the count.

   <?php

   include "connect_db.php";
   $query = "SELECT COUNT(*) AS numberOfRows FROM wp_cf7_data, wp_cf7_data_entry WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
   UNION
   SELECT * FROM wp_cf7_data, wp_cf7_data_entry WHERE wp_cf7_data.id=wp_cf7_data_entry.data_id and cf7_id = 1470 AND name = \"your-name\" and wp_cf7_data.created BETWEEN '2017-11-27 08:54:39' and '2017-12-03 08:54:39'
   ";

   $result = mysqli_query($conn, $query);

   if (mysqli_num_rows($result) > 0) {
       // output data of each row
       while($row = mysqli_fetch_assoc($result)) {
         echo $row['numberOfRows'];
           echo "id: " . $row["id"]. " - Name: " . $row["cf7_id"]. " " . $row["name"]. "
";

       }
   } else {
       echo "0 results";
   }

   mysqli_close($conn);
   ?>


问:
select dropdown value matching to be case insensitive when prefilled
In Html template

```<code><select [(ngModel)]="modelName">
  <option *ngFor="let ele of elements" [value]="element">{{ele}}</option>
</select>
</code>```

In .ts file

```<code>this.elements = ['ABCd', 'mnOp'];
this.modelName = 'Abcd';
</code>```

I Expect the value of the modelName 'ABCd' to be preselected from the list.

Currently nothing is displayed in the Select box though the modelName contains value 'Abcd'

答:
Like teddy said, the strings compared between the 'select' value and the 'element' values are case-sensitive. You can either copy the value from the first element manually or, since you already conveniently have the array in your code, assign the first element of the array directly to your model. This way if for some reason the array is created dynamically you won't have to worry about finding the value;

HTML

```<code><select [(ngModel)]="modelName">
    <option *ngFor="let ele of elements" [value]="ele">{{ele}}</option>
</select>
</code>```

TS

```<code>this.elements = ['ABCd', 'mnOp'];
this.modelName = this.elements[0];
</code>```

EDIT

Based on what you've said I believe the best solution for you is indeed to change the case of the variables. Angular provides a couple pipes to do so. This method requires that you split the two-way binding up, and create two different fields for property binding and event binding. See below:

HTML

```<code><select
    [ngModel]="modelName | uppercase"
    (change)="modelName = $event" >
    <option *ngFor="let ele of elements" [value]="ele | uppercase">
        {{ele}}
    </option>
</select>
</code>```

Hope this helps someone. Good Luck!

Body:
In Html template

<select [(ngModel)]="modelName">
  <option *ngFor="let ele of elements" [value]="element">{{ele}}</option>
</select>

In .ts file

this.elements = ['ABCd', 'mnOp'];
this.modelName = 'Abcd';

I Expect the value of the modelName 'ABCd' to be preselected from the list.

Currently nothing is displayed in the Select box though the modelName contains value 'Abcd'

Body:
Like teddy said, the strings compared between the 'select' value and the 'element' values are case-sensitive. You can either copy the value from the first element manually or, since you already conveniently have the array in your code, assign the first element of the array directly to your model. This way if for some reason the array is created dynamically you won't have to worry about finding the value;

HTML

<select [(ngModel)]="modelName">
    <option *ngFor="let ele of elements" [value]="ele">{{ele}}</option>
</select>

TS

this.elements = ['ABCd', 'mnOp'];
this.modelName = this.elements[0];

EDIT

Based on what you've said I believe the best solution for you is indeed to change the case of the variables. Angular provides a couple pipes to do so. This method requires that you split the two-way binding up, and create two different fields for property binding and event binding. See below:

HTML

<select
    [ngModel]="modelName | uppercase"
    (change)="modelName = $event" >
    <option *ngFor="let ele of elements" [value]="ele | uppercase">
        {{ele}}
    </option>
</select>

Hope this helps someone. Good Luck!


问:
Neo4j cypher: Find all paths till node of certain type
In Neo4j I have stored data with nodes of type A and B. Between 2 nodes A there could be many nodes of type B. I would like to fetch first node of type A for each path outgoing from a given node A. I post example structure below.

```<code>  /->A2->A3
A1-->A4->A5
  \->B1->A6
</code>```

For input: A1, I would like my query to return only A2, A4 and A6.

Query that I'm using right now is below:

```<code> MATCH p=(source:Node ) - [:relation*] -> (target:Node) WHERE
 source.name = "A1" AND target.type = "A" RETURN target
</code>```

However it returns nodes A3 and A5 which I want to get rid of.

答:
I have used this sample data set to reproduce your scenario:

```<code>create (root:Node {name : "A1", type: "A"})-[:LINKED_TO]->(:Node{name : "A2", type: "A"})-[:LINKED_TO]->(:Node{name : "A3", type: "A"}),
(root)-[:LINKED_TO]->(:Node{name : "A4", type: "A"})-[:LINKED_TO]->(:Node{name : "A5", type: "A"}),
(root)-[:LINKED_TO]->(:Node{name : "B1", type: "B"})-[:LINKED_TO]->(:Node{name : "A6", type: "A"})
</code>```

Then, this query, using filter() function:

```<code>// MATCH all paths between source and target, starting from 2 hops.
// target node should be the last node of the path.
MATCH p=(source:Node)-[:LINKED_TO*]->(target:Node)
WHERE source.name = "A1" AND target.type = "A" AND NOT (target)-->()
// grouping by path, I have filtered the nodes of each path, getting only ones that have type = "A"
// then I get the first one by index (index [0])
WITH p, filter(node IN nodes(p)[1..] WHERE node.type = "A")[0] as firstA
// return the firstA node
RETURN firstA
</code>```

The output:

```<code>╒════════════════════════╕
│"firstA"                │
╞════════════════════════╡
│{"name":"A6","type":"A"}│
├────────────────────────┤
│{"name":"A4","type":"A"}│
├────────────────────────┤
│{"name":"A2","type":"A"}│
└────────────────────────┘
</code>```

Tip: instead of a property named type you can add another label for each node denoting your type, like :A and :B. Remember that labels are ideal for grouping nodes into sets. Also, a node can have more than one label.

Body:
In Neo4j I have stored data with nodes of type A and B. Between 2 nodes A there could be many nodes of type B. I would like to fetch first node of type A for each path outgoing from a given node A. I post example structure below.

  /->A2->A3
A1-->A4->A5
  \->B1->A6

For input: A1, I would like my query to return only A2, A4 and A6.

Query that I'm using right now is below:

 MATCH p=(source:Node ) - [:relation*] -> (target:Node) WHERE
 source.name = "A1" AND target.type = "A" RETURN target

However it returns nodes A3 and A5 which I want to get rid of.

Body:
I have used this sample data set to reproduce your scenario:

create (root:Node {name : "A1", type: "A"})-[:LINKED_TO]->(:Node{name : "A2", type: "A"})-[:LINKED_TO]->(:Node{name : "A3", type: "A"}),
(root)-[:LINKED_TO]->(:Node{name : "A4", type: "A"})-[:LINKED_TO]->(:Node{name : "A5", type: "A"}),
(root)-[:LINKED_TO]->(:Node{name : "B1", type: "B"})-[:LINKED_TO]->(:Node{name : "A6", type: "A"})

Then, this query, using filter() function:

// MATCH all paths between source and target, starting from 2 hops.
// target node should be the last node of the path.
MATCH p=(source:Node)-[:LINKED_TO*]->(target:Node)
WHERE source.name = "A1" AND target.type = "A" AND NOT (target)-->()
// grouping by path, I have filtered the nodes of each path, getting only ones that have type = "A"
// then I get the first one by index (index [0])
WITH p, filter(node IN nodes(p)[1..] WHERE node.type = "A")[0] as firstA
// return the firstA node
RETURN firstA

The output:

╒════════════════════════╕
│"firstA"                │
╞════════════════════════╡
│{"name":"A6","type":"A"}│
├────────────────────────┤
│{"name":"A4","type":"A"}│
├────────────────────────┤
│{"name":"A2","type":"A"}│
└────────────────────────┘

Tip: instead of a property named type you can add another label for each node denoting your type, like :A and :B. Remember that labels are ideal for grouping nodes into sets. Also, a node can have more than one label.


问:
What's Is the Best File Format for Configuration Files
I am creating a framework in PHP and need to have a few configuration files. Some of these files will unavoidably have a large number of entries.

What format would be the best for these config files?

Here is my quantification of best:

Easily parsed by PHP. It would be nice if I didn't have to write any parsing code but this is not a deal breaker.

Remains easily read by humans even when there are a large amount of entries

Is a widely used standard, no custom formats

Succinctness is appreciated

I started out using XML, but quickly gave up for obvious reasons. I've thought of JSON and YAML but wanted to see what else is out there.

答:
Another option would be to use JSON and use json_encode and json_decode.

You would be able to use richer data structures in your configuration parameters.

OwnerDisplayName: macinjosh

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: InSciTek Jeff

OwnerDisplayName: Naum


问:
Php extension problems
I get a tricky problem when i am trying to create a php extension with c, with an array returned.
I do as some tutorials said, but i need to return an array.
array_init(return_array) in all examples is said to initialize an returning-array, but i find nowhere the return_array is declared. So, i got error:
error C2065: 'return_array' : undeclared identifier, however, if i add :

zval * return_array ;

But it throws your app cannot read address 000000f
why?

Can you give me a detailed extension example containing array-returning....thanx millions times

答:
If you want to return the array, just initialize return_value:

```<code>array_init(return_value);
</code>```

return_value is a zval*, declared by the PHP_FUNCTION() macro.

Title: Php extension problems

Body:
If you want to return the array, just initialize return_value:

array_init(return_value);

return_value is a zval*, declared by the PHP_FUNCTION() macro.


问:
Str_Replace is replacing php syntax

functions/SkriptParser.php

```<code><?php
    $text = file_get_contents(basename($_SERVER['PHP_SELF']));
    preg_match_all("/{(.*?)}/", $text, $matches);
    var_dump($matches[0]);
    echo str_replace($matches[0],"Test",$text);
?>
</code>```

Is my current code, this is called from my index page which is here:

index.php

```<code>require_once 'functions/SkriptParser.php';
</code>```

When i open index.php it replace the correct strings [ It'll replace any string inside {} however, it seems to be replacing <?php and I have no clue why.

Any ideas?

答:
I'm not sure I fully understand what you are trying to do.

This line $text = file_get_contents(basename($_SERVER['PHP_SELF']));resolves to a local filename which will be the name of the script it's included in.

It won't load the page which that script would output, it will load the file without executing the code. The contents of $text will be a string containing the pure php content.

When I run your code from the command line and use "Here is a test of {your code}" as my string the output is:

```<code>{your code}<?php
require_once 'includetest.php';
print_r(basename($_SERVER['PHP_SELF']));
echo "Here's a test of Test";
</code>```

If I run it from a browser and view the source I see that too, but the browser escapes the php so it isn't rendered on the page. So (for me at least), your concept kinda works. However, the fact the code isn't executed means it will never do what you intend.

Here's what I don't really understand though. In essence within index.php what you are telling your code to do is load a script which will load another copy of index.php and replace content within it.

If you want to change the behaviour of index.php then alter the code within index.php, don't generate unsuitable output and then load another script in an attempt to parse it before returning it. Just output it the way you want the first time.

Where is the content within the {} that you want to remove coming from? Why do you want/need to remove it? If you can clarify exactly what your aim is then it will be easier to suggest a solution.

Title: Str_Replace is replacing php syntax

Body:
functions/SkriptParser.php

<?php
    $text = file_get_contents(basename($_SERVER['PHP_SELF']));
    preg_match_all("/{(.*?)}/", $text, $matches);
    var_dump($matches[0]);
    echo str_replace($matches[0],"Test",$text);
?>

Is my current code, this is called from my index page which is here:

index.php

require_once 'functions/SkriptParser.php';

When i open index.php it replace the correct strings [ It'll replace any string inside {} however, it seems to be replacing <?php and I have no clue why.

Any ideas?

Body:
I'm not sure I fully understand what you are trying to do.

This line $text = file_get_contents(basename($_SERVER['PHP_SELF']));resolves to a local filename which will be the name of the script it's included in.

It won't load the page which that script would output, it will load the file without executing the code. The contents of $text will be a string containing the pure php content.

When I run your code from the command line and use "Here is a test of {your code}" as my string the output is:

{your code}<?php
require_once 'includetest.php';
print_r(basename($_SERVER['PHP_SELF']));
echo "Here's a test of Test";

If I run it from a browser and view the source I see that too, but the browser escapes the php so it isn't rendered on the page. So (for me at least), your concept kinda works. However, the fact the code isn't executed means it will never do what you intend.

Here's what I don't really understand though. In essence within index.php what you are telling your code to do is load a script which will load another copy of index.php and replace content within it.

If you want to change the behaviour of index.php then alter the code within index.php, don't generate unsuitable output and then load another script in an attempt to parse it before returning it. Just output it the way you want the first time.

Where is the content within the {} that you want to remove coming from? Why do you want/need to remove it? If you can clarify exactly what your aim is then it will be easier to suggest a solution.


问:
save method not working in Mongoose
I am using the following code in node.js:

```<code>async function create(data) {
    utils.removeIdFields(data);
    const user = new User(data);
    console.log("user will be printed here", user);
    await user.save();
    console.log("code not reaching here");
    return user;
}
</code>```

In the above code, User is a mongoose model, which is working fine till the line above user.save(). However, it never prints the next log.

I am using mongoose version 4.11.0.

答:
I was connecting to MongoDB using the following piece of code:

```<code>function connectMongoDb() {
    if (mongoose.connect(makeMongoUrl(), { useMongoClient: true })) {
        mongoose.plugin(plugins.transformer);
    }
}
</code>```

As it turned out, removing the { useMongoClient: true } and using just the below code fixed the issue:

```<code>function connectMongoDb() {
    if (mongoose.connect(makeMongoUrl())) {
        mongoose.plugin(plugins.transformer);
    }
}
</code>```

Title: save method not working in Mongoose

Body:
I am using the following code in node.js:

async function create(data) {
    utils.removeIdFields(data);
    const user = new User(data);
    console.log("user will be printed here", user);
    await user.save();
    console.log("code not reaching here");
    return user;
}

In the above code, User is a mongoose model, which is working fine till the line above user.save(). However, it never prints the next log.

I am using mongoose version 4.11.0.

Body:
I was connecting to MongoDB using the following piece of code:

function connectMongoDb() {
    if (mongoose.connect(makeMongoUrl(), { useMongoClient: true })) {
        mongoose.plugin(plugins.transformer);
    }
}

As it turned out, removing the { useMongoClient: true } and using just the below code fixed the issue:

function connectMongoDb() {
    if (mongoose.connect(makeMongoUrl())) {
        mongoose.plugin(plugins.transformer);
    }
}


问:
Can Rebol 3 be embedded as Scripting Language for iPhone?
It is said here:
http://fourdman.blogspot.com/2009/06/cocolua-lua-objective-c.html
Lua is a very lightweight (but powerful) language which depends on C only. You don't need to pull many N-megabyte frameworks and libraries. Lua was created as an embeddable language: you add its interpreter's source code to your project and use is programmatically. Apart of many other things that means that you can use Lua even on the iPhone and no one will ever notice that.

As far as I understand new Rebol 3 core version (rebol view can't be used but cocoa gui framework) will have the capability to be an embedded scripting engine. Does this mean that it could be embedded like LUA in Corona SDK as a scripting language for the iPhone or maybe also Android ?

Rebol core is much less than 1 mo Lua I don't know I'm just downloading it.

答:
Apple allows embedded scripting languages in iOS apps (there are even Basic interpreters in the App store), but does not allow any capability for an app to download new code or scripts which that scripting language can run.  All scripts have to be built-in to the submitted app.

This was a change to their developer agreement about late-Q3 2010.

When porting a scripting language, you also have to make sure the language's run time does not reach outside the iOS process, file directory, and IO sandbox, but only uses documented Cocoa Touch APIs for IO and UI (e.g. no stdin, etc.)


问:
Can't resize iFrame
The iFrame or wrapper div will not change size, whatever i try:

The Output:

The HTML:

```<code><html>
<head>
    <link rel="stylesheet" href="CV.css">
<title>
George's CV
</title>
</head>
<body>
    <div className="phone" style="height: 737px; width: 654px">
        <div className="container" style="height: 536px; width: 350px">
            <iframe src="http://foodsharing-production.herokuapp.com"></iframe>
        </div>
    </div>
</body>
</html>
</code>```

The CSS:

```<code>.phone{
    margin:auto;
    height: 737px;
    width: 654px;
    background-image: url("/imgs/phone.png");
    position: fixed;
    top: 50%;
    left: 50%;
    display: block;
}
.container {
    position: fixed;
    left:0; right:0;
    top:0; bottom:0;
    margin: auto;
    height: 536px;
    width: 350px;
    border:1px solid #000000;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    display: block;
 }
</code>```

feel like i might be missing something obvious, any help would be appreciated...

答:
Change the width on the iframe itself. E.g.

```<code><div className="phone">
  <div className="container">
    <iframe width="600px" src="http://foodsharing-production.herokuapp.com"></iframe>
  </div>
</div>
</code>```

You can also set this in the CSS:

```<code>iframe {
  width: 600px;
}
</code>```

Title: Can't resize iFrame

Body:
The iFrame or wrapper div will not change size, whatever i try:

The Output:

The HTML:

    <link rel="stylesheet" href="CV.css">
<title>
George's CV
</title>

The CSS:

.phone{
    margin:auto;
    height: 737px;
    width: 654px;
    background-image: url("/imgs/phone.png");
    position: fixed;
    top: 50%;
    left: 50%;
    display: block;
}
.container {
    position: fixed;
    left:0; right:0;
    top:0; bottom:0;
    margin: auto;
    height: 536px;
    width: 350px;
    border:1px solid #000000;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    display: block;
 }

feel like i might be missing something obvious, any help would be appreciated...

Body:
Change the width on the iframe itself. E.g.

<div className="phone">
  <div className="container">
    <iframe width="600px" src="http://foodsharing-production.herokuapp.com"></iframe>
  </div>
</div>

You can also set this in the CSS:

iframe {
  width: 600px;
}


问:
Is `-1` correct for using as maximum value of an unsigned integer?
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

```<code>unsigned short i = -1; // unsigned short max
</code>```

can easily be changed to any other type, like

```<code>unsigned long i = -1; // unsigned long max
</code>```

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.

答:
Not using the standard way or not clearly showing the intent is often a bad idea that we pay later

I would suggest:

```<code>auto i = std::numeric_limits<unsigned int>::max();
</code>```

or @jamesdin suggested a certainly better one, closer to the C
  habits:

```<code>unsigned int i = std::numeric_limits<decltype(i)>::max();
</code>```

Your colleague argument is not admissible. Changing int -> long int, as bellow:

```<code>auto i = std::numeric_limits<unsigned long int>::max();
</code>```

does not require extra work compared to the -1 solution (thanks to the use of auto).

the '-1' solution does not directly reflect our intent, hence it possibly has harmful consequences. Consider this code snippet:

.

```<code>using index_t = unsigned int;

... now in another file (or far away from the previous line) ...

const index_t max_index = -1;
</code>```

First, we do not understand why max_index is -1.
Worst, if someone wants to improve the code and define

```<code> using index_t = ptrdiff_t;
</code>```

=> then the statement max_index=-1 is not the max anymore and you get a buggy code. Again this can not happen with something like:

```<code>const index_t max_index = std::numeric_limits<index_t>::max();
</code>```

CAVEAT: nevertheless there is a caveat when using std::numeric_limits. It has nothing to do with integers, but is related to floating point numbers.

```<code>std::cout << "\ndouble lowest: "
          << std::numeric_limits<double>::lowest()
          << "\ndouble min   : "
          << std::numeric_limits<double>::min() << '\n';
</code>```

prints:

```<code>double lowest: -1.79769e+308
double min   :  2.22507e-308  <-- maybe you expected -1.79769e+308 here!
</code>```

min returns the smallest finite value of the given type

lowest returns the lowest finite value of the given type

Always interesting to remember that, as it can be a source of bug if we do not pay attention to (using min instead of lowest).

Body:
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

unsigned short i = -1; // unsigned short max

can easily be changed to any other type, like

unsigned long i = -1; // unsigned long max

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.

Body:
Not using the standard way or not clearly showing the intent is often a bad idea that we pay later

I would suggest:

auto i = std::numeric_limits<unsigned int>::max();

or @jamesdin suggested a certainly better one, closer to the C
  habits:

unsigned int i = std::numeric_limits<decltype(i)>::max();

Your colleague argument is not admissible. Changing int -> long int, as bellow:

auto i = std::numeric_limits<unsigned long int>::max();

does not require extra work compared to the -1 solution (thanks to the use of auto).

the '-1' solution does not directly reflect our intent, hence it possibly has harmful consequences. Consider this code snippet:

.

using index_t = unsigned int;

... now in another file (or far away from the previous line) ...

const index_t max_index = -1;

First, we do not understand why max_index is -1.
Worst, if someone wants to improve the code and define

 using index_t = ptrdiff_t;

=> then the statement max_index=-1 is not the max anymore and you get a buggy code. Again this can not happen with something like:

const index_t max_index = std::numeric_limits<index_t>::max();

CAVEAT: nevertheless there is a caveat when using std::numeric_limits. It has nothing to do with integers, but is related to floating point numbers.

std::cout << "\ndouble lowest: "
          << std::numeric_limits<double>::lowest()
          << "\ndouble min   : "
          << std::numeric_limits<double>::min() << '\n';

prints:

double lowest: -1.79769e+308
double min   :  2.22507e-308  <-- maybe you expected -1.79769e+308 here!

min returns the smallest finite value of the given type

lowest returns the lowest finite value of the given type

Always interesting to remember that, as it can be a source of bug if we do not pay attention to (using min instead of lowest).


答:
You should increase its size with CSS like that </p>

```<code>iframe {
  width:350px;
  height:536px;
}
</code>```

Title: Can't resize iFrame

Body:
You should increase its size with CSS like that

iframe {
  width:350px;
  height:536px;
}


问:
Invalid default value for 'dateAdded'
I got a stupid problem with SQL that I can't fix.

```ALTER TABLE  `news`
 ADD  `dateAdded` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AUTO_INCREMENT ,
 ADD PRIMARY KEY (  `dateAdded` )
```

Error:

```<code>(#1067)Invalid default value for 'dateAdded'
</code>```

Can somebody help me?

答:
I had the same issue,
following fix solved my problem.

Select Type as 'TIMESTAMP'

DON'T ENTER ANYTHING IN LENGTH/VALUES FIELD. KEEP IT BLANK

Select CURRENT_TIMESTAMP as Default value.

I am using MySQL ver 5.5.56

Title: Invalid default value for 'dateAdded'

Body:
I got a stupid problem with SQL that I can't fix.

ALTER TABLE  `news`
 ADD  `dateAdded` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AUTO_INCREMENT ,
 ADD PRIMARY KEY (  `dateAdded` )

Error:

(#1067)Invalid default value for 'dateAdded'

Can somebody help me?


问:
Learning Python from Ruby; Differences and Similarities
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different?

I'm looking for a list similar to a primer I wrote for Learning Lua for JavaScripters: simple things like whitespace significance and looping constructs; the name of nil in Python, and what values are considered "truthy"; is it idiomatic to use the equivalent of map and each, or are mumble somethingaboutlistcomprehensions mumble the norm?

If I get a good variety of answers I'm happy to aggregate them into a community wiki. Or else  you all can fight and crib from each other to try to create the one true comprehensive list.

Edit: To be clear, my goal is "proper" and idiomatic Python. If there is a Python equivalent of inject, but nobody uses it because there is a better/different way to achieve the common functionality of iterating a list and accumulating a result along the way, I want to know how you do things. Perhaps I'll update this question with a list of common goals, how you achieve them in Ruby, and ask what the equivalent is in Python.

答:
I, like you, looked for inject and other functional methods when learning Python. I was disappointed to find that they weren't all there, or that Python favored an imperative approach. That said, most of the constructs are there if you look. In some cases, a library will make things nicer.

A couple of highlights for me:

The functional programming patterns you know from Ruby are available in Python. They just look a little different. For example, there's a map function:

```<code>  def f(x):
      return x + 1

  map(f, [1, 2, 3]) # => [2, 3, 4]
</code>```

Similarly, there is a reduce function to fold over lists, etc.

That said, Python lacks blocks and doesn't have a streamlined syntax for chaining or composing functions. (For a nice way of doing this without blocks, check out Haskell's rich syntax.)

For one reason or another, the Python community seems to prefer imperative iteration for things that would, in Ruby, be done without mutation. For example, folds (i.e., inject), are often done with an imperative for loop instead of reduce:

```<code>  running_total = 0
  for n in [1, 2, 3]:
      running_total = running_total + n
</code>```

This isn't just a convention, it's also reinforced by the Python maintainers. For example, the Python 3 release notes explicitly favor for loops over reduce:

Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.

List comprehensions are a terse way to express complex functional operations (similar to Haskell's list monad). These aren't available in Ruby and may help in some scenarios. For example, a brute-force one-liner to find all the palindromes in a string (assuming you have a function p() that returns true for palindromes) looks like this:

```<code>  s = 'string-with-palindromes-like-abbalabba'
  l = len(s)
  [s[x:y] for x in range(l) for y in range(x,l+1) if p(s[x:y])]
</code>```

Methods in Python can be treated as context-free functions in many cases, which is something you'll have to get used to from Ruby but can be quite powerful.

In case this helps, I wrote up more thoughts here in 2011: The 'ugliness' of Python. They may need updating in light of today's focus on ML.

Body:
I, like you, looked for inject and other functional methods when learning Python. I was disappointed to find that they weren't all there, or that Python favored an imperative approach. That said, most of the constructs are there if you look. In some cases, a library will make things nicer.

A couple of highlights for me:

The functional programming patterns you know from Ruby are available in Python. They just look a little different. For example, there's a map function:

  def f(x):
      return x + 1

  map(f, [1, 2, 3]) # => [2, 3, 4]

Similarly, there is a reduce function to fold over lists, etc.

That said, Python lacks blocks and doesn't have a streamlined syntax for chaining or composing functions. (For a nice way of doing this without blocks, check out Haskell's rich syntax.)

For one reason or another, the Python community seems to prefer imperative iteration for things that would, in Ruby, be done without mutation. For example, folds (i.e., inject), are often done with an imperative for loop instead of reduce:

  running_total = 0
  for n in [1, 2, 3]:
      running_total = running_total + n

This isn't just a convention, it's also reinforced by the Python maintainers. For example, the Python 3 release notes explicitly favor for loops over reduce:

Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.

List comprehensions are a terse way to express complex functional operations (similar to Haskell's list monad). These aren't available in Ruby and may help in some scenarios. For example, a brute-force one-liner to find all the palindromes in a string (assuming you have a function p() that returns true for palindromes) looks like this:

  s = 'string-with-palindromes-like-abbalabba'
  l = len(s)
  [s[x:y] for x in range(l) for y in range(x,l+1) if p(s[x:y])]

Methods in Python can be treated as context-free functions in many cases, which is something you'll have to get used to from Ruby but can be quite powerful.

In case this helps, I wrote up more thoughts here in 2011: The 'ugliness' of Python. They may need updating in light of today's focus on ML.

ContentLicense: CC BY-SA 4.0


问:
Regex to Capture last email Address
I need a regex to capture last email addresss

2017-11-30T17:00:02.596Z,10.1.20.211,RenjuXXX,X.X.X.X,mxa-0003fe01.xx.renjj.com,;250 2.0.0 2ej1k6mass-1 Message accepted for delivery;ClientSubmitTime:,Outbound to Internet,SMTP,SEND,asadasdasd1212,,b4b8c0b5-ce3b-4aca-8335-08d53813c96a,Jose.renj@renj.org,250 2.1.5 Recipient ok,41758,1,,,RE: my CV,renjujacob@renju.com,renjujacob@renju.com,

I tried using this regex below to capture the email ID , but its capturing the first email

((?P(?<=,)[a-zA-Z0-9-.]+@[a-zA-Z0-9-.]+(?=\s*(?:\w+=|,))))

need a regex to capture last email id (renjujacob@renju.com). Any help will be appreciated.

答:
You could use a negative lookahead:

```<code>[^,\s@]++@[^,\s@]++(?![^@]*@)
</code>```

Broken down, this says:

```<code>[^,\s@]++    # NOT comma nor whitespace nor @, 1+ times, possessive
@            # @ literally
[^,\s@]++    # same as above
(?![^@]*@)   # a neg. lookahead, making sure there's no @ to follow
</code>```

See a demo on regex101.com.

An alternative approach would be to grab all email addresses via

```<code>[^,\s@]++@[^,\s@]++
</code>```

and select the last item in your programming language (e.g. results[-1] in Python).

Edit:

Thanks to @Andrei for ameliorating the pattern.

Title: Regex to Capture last email Address

Body:
You could use a negative lookahead:

[^,\s@]++@[^,\s@]++(?![^@]*@)

Broken down, this says:

[^,\s@]++    # NOT comma nor whitespace nor @, 1+ times, possessive
@            # @ literally
[^,\s@]++    # same as above
(?![^@]*@)   # a neg. lookahead, making sure there's no @ to follow

See a demo on regex101.com.

An alternative approach would be to grab all email addresses via

[^,\s@]++@[^,\s@]++

and select the last item in your programming language (e.g. results[-1] in Python).

Edit:

Thanks to @Andrei for ameliorating the pattern.


问:
Nightwatch.js using data attributes
I'm new to nightwatch.js. I work in QA and the developers don't want to use ids or classes for the automated tests. They want to use data-test. So for example data-test="nav-button".

Is there way to find elements and click elements using this attribute in nightwatch.js?

答:
This is actually pretty simple. Just put the data-test in square brackets after the element type. See below for examples. In these examples, the data-test attribute is in an anchor tag.

.waitForElementVisible('a[data-test=nav-button]')
 .click(a[data-test=nav-button])

Title: Nightwatch.js using data attributes


问:
Submit multiple form on button click , one after one
I have an image website. I want user can many uploads at once. I created an image uploading script.

HTML

```<code><div class="container">
    <h1>Image Uploader</h1>
    <input type="file" name="images[]" id="images" multiple>
    <br>
    <div id="images-to-upload" class="row">
    </div>
    <br>
    <div class="col-md-12">
        <button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>
    </div>
</div>
</code>```

JQuery

```<code> <script>
    $(document).ready(function() {
        var fileCollection = new Array();
        $('#images').on('change', function(e) {
            var files = e.target.files;
            $.each(files, function(i, file) {
                fileCollection.push(file);
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    var template = '<form class="upload_form col-md-6 col-xs-12" action="/upload">' +
                        '<img class="col-md-4 col-xs-4" src="' + e.target.result + '"> ' +
                        '<input style="width:90px; height:28px" class="col-md-2 col-xs-4"  type="number" name="table" id="table" >' +
                        '<input style="margin:0px 5px 0px 5px; width:95px" type="submit" class="btn btn-sm btn-primary col-md-3 col-xs-3 submit_form" value="Upload" name="submit_weight">' +
                        '<button type="button" class="btn btn-sm btn-danger remove_form col-md-2 col-xs-6">Cancel</button>' +
                        '<div style="height: 30px; font-size: 20px; margin: 0px 0px 10px 0px; padding: 0px; text-align: center;" class="progress col-md-7 col-xs-6 progress-stripped active"><div class="progress-bar" style="font-size: 15px; width:0%"></div></div> ' +
                        '</form>';

                    $('#images-to-upload').append(template);
                };
            });
        });

        $(document).on('submit', 'form', function(e) {
            e.preventDefault();
            $form = $(this);
            var index = $(this).index();
            var formdata = new FormData($(this)[0]);

            formdata.append('images', fileCollection[index]);
            var request = new XMLHttpRequest();

            request.upload.addEventListener('progress', function(e) {
                var percent = e.loaded / e.total * 100;
                $form.find('.progress-bar').width(percent + '%').html(percent + '%');

            });
            // progress complete load event
            request.addEventListener('load', function() {
                $form.find('.progress-bar').addClass('progress-bar-success').html('Upload Completed....');
            });

            request.open('post', 'script/file_upload_admin.php');
            request.send(formdata);

            $form.on('click', '.remove_form', function() {
                console.log("Cancel");
                alert("hello");
                $(this).hide();
            });
        });
    });

    $("#upload_button").on('click', function(event) {
        event.preventDefault();
        $(".submit_form").click();
    });
</script>
</code>```

my problem is when a user submit form one by one then it works. but when user click on Upload all images then, form data got a mix like- 1-form data's Table input value set with another form.

答:
I think is not necessary to send more than one form. when you select muiltiple files and do submit, the request contains all fliles you selected.

for example in PHP $_FILES['myimagesinput'] contains an array with all files.

the same question is here

Body:
I have an image website. I want user can many uploads at once. I created an image uploading script.

HTML

Image Uploader

    <input type="file" name="images[]" id="images" multiple>

        <button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>

JQuery

my problem is when a user submit form one by one then it works. but when user click on Upload all images then, form data got a mix like- 1-form data's Table input value set with another form.


问:
covertJSONtoSQL returning empty values in NiFi
I am designing a work which takes a data from on database in MySQl to another database(MySQL) using ExecuteSQL processor followed up with ConvertAvroToJson then ConvertJsonToSQL then PutSQL as shown in below flow chart

ConvertJSONToSQL returning the empty values like below

```<code> INSERT INTO source_count (field1, field2, field3, field4, field5, field6, field7, field8, field9, field10, field11, field12) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
</code>```

The processor configuration is

what can be wrong in this workflow?

答: Besides the answer given in the comments (to use the sql relationship with ConvertJSONToSQL), then if you have at least NiFi 1.2.0, you can replace everything after ExecuteSQL with PutDatabaseRecord. It lets you configure a reader (you would choose an AvroReader that uses the Embedded Schema) and set the operation type to INSERT, and it will handle the SQL generation and execution for you.</p>

Body:
I am designing a work which takes a data from on database in MySQl to another database(MySQL) using ExecuteSQL processor followed up with ConvertAvroToJson then ConvertJsonToSQL then PutSQL as shown in below flow chart

ConvertJSONToSQL returning the empty values like below

 INSERT INTO source_count (field1, field2, field3, field4, field5, field6, field7, field8, field9, field10, field11, field12) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

The processor configuration is

what can be wrong in this workflow?


问:
Get the width and height of each element's attribute via DOM or XPATH
How can I get the width and height of each element's attribute?

For instance,

```<code>$dom = new DOMDocument;
$dom->loadHTML('<div class="item" style="width:295px; height:210px; border:1px solid #000;"></div><div></div>');

foreach( $dom->getElementsByTagName('div') as $node )
{
    $style = $node->getAttribute( 'style' );

    var_dump($style);
}
</code>```

result,

```<code>string 'width:295px; height:210px; border:1px solid #000;' (length=49)
string '' (length=0)
</code>```

but these are what I am after,

select the div that has the classname of item only.

get 295 (width) and 210 (height) only.

Is it possible with DOM? Or XPATH?

EDIT:

I seem to manage to select the div with the classname now,

```<code>$dom = new DOMDocument;
$dom->loadHTML('<div class="item" style="width:295px; height:210px; border:1px solid #000;"></div><div></div>');

$xpath = new DOMXpath($dom);

foreach ($xpath->query('//*[@class="item"]') as $node) {

    $style = $node->getAttribute( 'style' );

    var_dump($style);
}
</code>```

Now this is what I am after only,

get 295 (width) and 210 (height).

答:
```<code>function GetStyleValue($style, $type){
$value = false;
$all = explode(';',$style);
foreach($all as $part){
    $temp = explode(':', $part);
    if(trim($temp[0]) == $type){
        $value = (int)trim($temp[1]);
    }
}
return $value;}
</code>```

You can use this function to get width, height or other style value, just call:

$width = GetStyleValue($img->getAttribute("style"), 'width');

Body:
How can I get the width and height of each element's attribute?

For instance,

$dom = new DOMDocument;
$dom->loadHTML('

');

foreach( $dom->getElementsByTagName('div') as $node )
{
    $style = $node->getAttribute( 'style' );

    var_dump($style);
}

result,

string 'width:295px; height:210px; border:1px solid #000;' (length=49)
string '' (length=0)

but these are what I am after,

select the div that has the classname of item only.

get 295 (width) and 210 (height) only.

Is it possible with DOM? Or XPATH?

EDIT:

I seem to manage to select the div with the classname now,

$dom = new DOMDocument;
$dom->loadHTML('

');

$xpath = new DOMXpath($dom);

foreach ($xpath->query('//*[@class="item"]') as $node) {

    $style = $node->getAttribute( 'style' );

    var_dump($style);
}

Now this is what I am after only,

get 295 (width) and 210 (height).

Body:
function GetStyleValue($style, $type){
$value = false;
$all = explode(';',$style);
foreach($all as $part){
    $temp = explode(':', $part);
    if(trim($temp[0]) == $type){
        $value = (int)trim($temp[1]);
    }
}
return $value;}

You can use this function to get width, height or other style value, just call:

$width = GetStyleValue($img->getAttribute("style"), 'width');


问:
Spark 2.2 Scala DataFrame select from string array, catching errors
I'm new to SparkSQL/Scala and I'm struggling with a couple seemingly simple tasks.

I'm trying to build some dynamic SQL from a Scala String Array.  I'm trying to re-type some columns in my DataFrame, but I won't know exactly which I need to retype until runtime where I can see the set of columns in the DataFrame.  So I'm trying to doing this:

```<code>val cols = df.columns
val typedCols = cols.map( c => getTypedColumn(c) )
df.select( ...)  or df.selectExpr(...) // how to invoke this with vals from my string array??
</code>```

typedCols will end up being an array of strings with values like this:

```<code>["a", "cast(b as int) b", "c"]
</code>```

Do I need to create a big comma delimited string first from that array?

So, assuming this will work, I'd invoke that select statement, and it would transform my DataFrame to a new DataFrame with my desired types.  But some of those records in the DataFrame will have errors, and will fail the attempted re-typing.

How would I get a DataFrame result with all the good records that passed the typing and then throw all the bad records in some kind of error bucket?  Would I need to do a validation pass first before attempting the DataFrame select?

答:
You can just use variadic arguments:

```<code>val df = Seq(("a", "1", "c"), ("foo", "bar", "baz")).toDF("a", "b", "c")
val typedCols = Array("a", "cast(b as int) b", "c")
df.selectExpr(typedCols: _*).show

+---+----+---+
|  a|   b|  c|
+---+----+---+
|  a|   1|  c|
|foo|null|baz|
+---+----+---+
</code>```

but personally I prefer columns:

```<code>val typedCols = Array($"a", $"b" cast "int", $"c")
df.select(typedCols: _*).show
</code>```

How would I get a DataFrame result with all the good records that passed the typing and then throw all the bad records in some kind of error bucket?

Data that failed to cast is NULL. To find good records use na.drop:

```<code>val result = df.selectExpr(typedCols: _*)
val good = result.na.drop()
</code>```

To find bad check if any is NULL

```<code>import org.apache.spark.sql.functions.col

val bad = result.where(result.columns.map(col(_).isNull).reduce(_ || _))
</code>```

To get unmatched data:

If typedCols are Seq[Column] you can

```<code>df.where(typedCols.map(_.isNull).reduce(_ || _))
</code>```

If typedCols are Seq[String] you can:

```<code>import org.apache.spark.sql.functions.expr

df.where(typedCols.map(expr(_).isNull).reduce(_ || _))
</code>```

Body:
I'm new to SparkSQL/Scala and I'm struggling with a couple seemingly simple tasks.

I'm trying to build some dynamic SQL from a Scala String Array.  I'm trying to re-type some columns in my DataFrame, but I won't know exactly which I need to retype until runtime where I can see the set of columns in the DataFrame.  So I'm trying to doing this:

val cols = df.columns
val typedCols = cols.map( c => getTypedColumn(c) )
df.select( ...)  or df.selectExpr(...) // how to invoke this with vals from my string array??

typedCols will end up being an array of strings with values like this:

["a", "cast(b as int) b", "c"]

Do I need to create a big comma delimited string first from that array?

So, assuming this will work, I'd invoke that select statement, and it would transform my DataFrame to a new DataFrame with my desired types.  But some of those records in the DataFrame will have errors, and will fail the attempted re-typing.

How would I get a DataFrame result with all the good records that passed the typing and then throw all the bad records in some kind of error bucket?  Would I need to do a validation pass first before attempting the DataFrame select?

Body:
You can just use variadic arguments:

val df = Seq(("a", "1", "c"), ("foo", "bar", "baz")).toDF("a", "b", "c")
val typedCols = Array("a", "cast(b as int) b", "c")
df.selectExpr(typedCols: _*).show

+---+----+---+
|  a|   b|  c|
+---+----+---+
|  a|   1|  c|
|foo|null|baz|
+---+----+---+

but personally I prefer columns:

val typedCols = Array($"a", $"b" cast "int", $"c")
df.select(typedCols: _*).show

How would I get a DataFrame result with all the good records that passed the typing and then throw all the bad records in some kind of error bucket?

Data that failed to cast is NULL. To find good records use na.drop:

val result = df.selectExpr(typedCols: _*)
val good = result.na.drop()

To find bad check if any is NULL

import org.apache.spark.sql.functions.col

val bad = result.where(result.columns.map(col(_).isNull).reduce(_ || _))

To get unmatched data:

If typedCols are Seq[Column] you can

df.where(typedCols.map(_.isNull).reduce(_ || _))

If typedCols are Seq[String] you can:

import org.apache.spark.sql.functions.expr

df.where(typedCols.map(expr(_).isNull).reduce(_ || _))


问:
Unity: Scale a GameObject in world space
I am trying to achieve this:

This is a non-axis-aligned cube being scaled in world space in blender alongside the Z axis (Y in Unity). I want to achieve the same in Unity. I tried to find formulas for this but had no luck, I know that I can parent my object to another GameObject and scale the parent, but once I unparent my original GameObject the scale resets back and I need to scale the original GameObject. Any advise would be much appreciated.

答:
You can transform a scale (Vector3) from world space to local space by using this function:

```<code>transform.parent.InverseTransformVector(worldScale)
</code>```

To apply to your cube the correct scale you might do something like this:

```<code>cube.transform.localScale = cube.transform.parent.InverseTransformVector(worldScale);
</code>```

Body:
You can transform a scale (Vector3) from world space to local space by using this function:

transform.parent.InverseTransformVector(worldScale)

To apply to your cube the correct scale you might do something like this:

cube.transform.localScale = cube.transform.parent.InverseTransformVector(worldScale);


问:
Calling method from another class and correctness of the code
Hi I am new in android and I am writting alarm clock. I have got small problem, how to call method from other class.

```<code>public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener, OnCheckedChangeListener {
@Override
protected void onCreate(final Bundle savedInstanceState) {
final Button button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View w) {
            Alarm_Reciver alarm = new Alarm_Reciver();
            alarm.set...?
</code>```

Next class

```<code>public class Alarm_Reciver extends BroadcastReceiver {

AlarmManager alarm_manager;
private PendingIntent pending_intent;
MediaPlayer mp;

@Override
public void onReceive(Context context, Intent intent) {

}

public void setAlarm(Context context, Intent intent) {

   mp = MediaPlayer.create(context, R.raw.d_s_h);
   mp.start();
   PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
   PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
   wl.acquire();
   Toast.makeText(context, "Alarm !!!!", Toast.LENGTH_LONG).show();
   wl.release();
   ComponentName cn = new ComponentName(context, Alarm_Reciver.class);
   PackageManager pac = context.getPackageManager();
   pac.setComponentEnabledSetting(cn,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
   if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
       alarm_manager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
       Intent i = new Intent(context, Alarm_Reciver.class);
       pending_intent = PendingIntent.getBroadcast(context, 0, i, 0);
       alarm_manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60 * 1000, pending_intent);
       Toast.makeText(context, "Alarm On", Toast.LENGTH_LONG).show();
   }

}

public void cancelAlarm(Context context) {
    Intent intent = new Intent(context, Alarm_Reciver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    alarManager.cancel(sender);
    if (alarm_manager != null) {
        alarm_manager.cancel(pending_intent);
        Toast.makeText(context, "Alarm off", Toast.LENGTH_LONG).show();

    }
    ComponentName cn = new ComponentName(context, Alarm_Reciver.class);
    PackageManager pac = context.getPackageManager();
    pac.setComponentEnabledSetting(cn,PackageManager.COMPONENT_ENABLED_STATE_DISABLED,PackageManager.DONT_KILL_APP);
}
</code>```

}

1.
So, I want to call method setAlarm when the button2 is clicked, I tried several times (with context and intent for example alarm.setAlarm(context, intent) or alarm.setAlarm(this, context) , it didn`t work, also I want to call method cancel alarm in button off, but as I understand it is the same as with button on.

2.
My next question is, it is write properly, should the alarm code occur in instructions if() or it should be only in method setAlarm() outside if()? Maybe some part of code should be in onReceive() method. I will add some things later, but now it is ok right?

@UPGRADE

```<code>Ad1.
</code>```

I tried to add setAlarm in XML but it throws me:

Corresponding method handler 'public void SetAlarm(android.view.View)' not found

so I tried to add in my XML(tool:ignore): OnClick like this:

tools:ignore="MissingConstraints,OnClick"

instead of

tools:ignore="MissingConstraints"

When I have got my XML like

tools:ignore="MissingConstraints,OnClick

It throws: Method 'SetAlarm' is missing in 'MainActivity' or has incorrect signature

I have read about this on stackoverflow in another thread and somebody write this:
    Are you using the correct signature for the method?

```<code>Methods defines using the onClick attribute must meet the following requirements:

must be public
must have a void return value
must have a View object as parameter (which is the view that was clicked)
like

public void addWord(View view) {
//your action
}
</code>```

My method doesn`t have View object so I must add it? How to do this?

Ad2.
  It should be: (if statement at the end)

```<code>alarm_manager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent i = new Intent(context, Alarm_Reciver.class);
pending_intent = PendingIntent.getBroadcast(context, 0, i, 0);
alarm_manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60 * 1000, pending_intent);
Toast.makeText(context, "Alarm On", Toast.LENGTH_LONG).show();
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
});
</code>```

Or:

```<code>if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
alarm_manager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent i = new Intent(context, Alarm_Reciver.class);
pending_intent = PendingIntent.getBroadcast(context, 0, i, 0);
alarm_manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60 * 1000, pending_intent);
Toast.makeText(context, "Alarm On", Toast.LENGTH_LONG).show();
}
</code>```

I mean in if() statement should be all code or outside if() statement?

Thanks for help, I hope that I described it clear.

答:
for the first question
you can solve it by adding
android:onClick:setAlarm in the XML code for the button

i do not really understand the second question

Body:
Hi I am new in android and I am writting alarm clock. I have got small problem, how to call method from other class.

public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener, OnCheckedChangeListener {
@Override
protected void onCreate(final Bundle savedInstanceState) {
final Button button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View w) {
            Alarm_Reciver alarm = new Alarm_Reciver();
            alarm.set...?

Next class

public class Alarm_Reciver extends BroadcastReceiver {

AlarmManager alarm_manager;
private PendingIntent pending_intent;
MediaPlayer mp;

@Override
public void onReceive(Context context, Intent intent) {

}

public void setAlarm(Context context, Intent intent) {

   mp = MediaPlayer.create(context, R.raw.d_s_h);
   mp.start();
   PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
   PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
   wl.acquire();
   Toast.makeText(context, "Alarm !!!!", Toast.LENGTH_LONG).show();
   wl.release();
   ComponentName cn = new ComponentName(context, Alarm_Reciver.class);
   PackageManager pac = context.getPackageManager();
   pac.setComponentEnabledSetting(cn,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
   if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
       alarm_manager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
       Intent i = new Intent(context, Alarm_Reciver.class);
       pending_intent = PendingIntent.getBroadcast(context, 0, i, 0);
       alarm_manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60 * 1000, pending_intent);
       Toast.makeText(context, "Alarm On", Toast.LENGTH_LONG).show();
   }

}

public void cancelAlarm(Context context) {
    Intent intent = new Intent(context, Alarm_Reciver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    alarManager.cancel(sender);
    if (alarm_manager != null) {
        alarm_manager.cancel(pending_intent);
        Toast.makeText(context, "Alarm off", Toast.LENGTH_LONG).show();

    }
    ComponentName cn = new ComponentName(context, Alarm_Reciver.class);
    PackageManager pac = context.getPackageManager();
    pac.setComponentEnabledSetting(cn,PackageManager.COMPONENT_ENABLED_STATE_DISABLED,PackageManager.DONT_KILL_APP);
}

}

1.
So, I want to call method setAlarm when the button2 is clicked, I tried several times (with context and intent for example alarm.setAlarm(context, intent) or alarm.setAlarm(this, context) , it didn`t work, also I want to call method cancel alarm in button off, but as I understand it is the same as with button on.

2.
My next question is, it is write properly, should the alarm code occur in instructions if() or it should be only in method setAlarm() outside if()? Maybe some part of code should be in onReceive() method. I will add some things later, but now it is ok right?

@UPGRADE

Ad1.

I tried to add setAlarm in XML but it throws me:

Corresponding method handler 'public void SetAlarm(android.view.View)' not found

so I tried to add in my XML(tool:ignore): OnClick like this:

tools:ignore="MissingConstraints,OnClick"

instead of

tools:ignore="MissingConstraints"

When I have got my XML like

tools:ignore="MissingConstraints,OnClick

It throws: Method 'SetAlarm' is missing in 'MainActivity' or has incorrect signature

I have read about this on stackoverflow in another thread and somebody write this:
    Are you using the correct signature for the method?

Methods defines using the onClick attribute must meet the following requirements:

must be public
must have a void return value
must have a View object as parameter (which is the view that was clicked)
like

public void addWord(View view) {
//your action
}

My method doesn`t have View object so I must add it? How to do this?

Ad2.
  It should be: (if statement at the end)

alarm_manager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent i = new Intent(context, Alarm_Reciver.class);
pending_intent = PendingIntent.getBroadcast(context, 0, i, 0);
alarm_manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60 * 1000, pending_intent);
Toast.makeText(context, "Alarm On", Toast.LENGTH_LONG).show();
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
});

Or:

if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
alarm_manager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent i = new Intent(context, Alarm_Reciver.class);
pending_intent = PendingIntent.getBroadcast(context, 0, i, 0);
alarm_manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60 * 1000, pending_intent);
Toast.makeText(context, "Alarm On", Toast.LENGTH_LONG).show();
}

I mean in if() statement should be all code or outside if() statement?

Thanks for help, I hope that I described it clear.


问:
Method onCreate() is not call
app/build.gradle:

```<code>apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

dependencies {
...
implementation 'com.hannesdorfmann.mosby3:mvi:3.1.0'
    implementation 'com.hannesdorfmann.mosby3:mvp:3.1.0'
    implementation 'com.hannesdorfmann.mosby3:viewstate:3.1.0'
implementation 'com.hannesdorfmann.mosby3:mvp-lce:3.1.0'

}
</code>```

Here my activity:

```<code>import com.hannesdorfmann.mosby3.mvp.MvpActivity;
    public class OfferDetailsPdfActivity extends MvpActivity<OfferDetailsPdfMvp.View, OfferDetailsPdfPresenterImplMvp> implements OnPageChangeListener, OfferDetailsPdfMvp.View {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    }

    }
</code>```

And method onCreate() on my activity OfferDetailsPdfActivity  was success call.

But I need to pass param to activity, so here production code:

```<code>public class OfferDetailsPdfActivity extends MvpActivity<OfferDetailsPdfMvp.View, OfferDetailsPdfPresenterImplMvp> implements OnPageChangeListener, OfferDetailsPdfMvp.View {
private OfferDetailsPdfPresenterImplMvp presenter;
    private int offerId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        Debug.d(TAG, "onCreate: extras = " + AndroidUtil.bundle2String(extras)
                + "\nsavedInstanceState = " + AndroidUtil.bundle2String(savedInstanceState)
        );
        if (extras != null) {
            offerId = extras.getInt(Offer.ID);
        }
            setContentView(R.layout.offer_details_pdf);
        ButterKnife.bind(this);
    }

    @NonNull
    @Override
    public OfferDetailsPdfPresenterImplMvp createPresenter() {
        Debug.d(TAG, "createPresenter: offerId = " + offerId);
        presenter = new OfferDetailsPdfPresenterImplMvp(this, offerId);
        return presenter;
    }
</code>```

And now in my activity method onCreate() is not call, but method createPresenter() was success called. Has text "createPresenter: offerId = 0"

As you can see from logcat the method onCreate() was not called. In logcat no text "onCreate: extras..."

Why?

Here logcat:

```<code>D/com.myproject.android.customer.ui.OfferDetailsPdfActivity(  946): createPresenter: offerId = 0
        Process: com.myproject.android.customer.debug, PID: 30127
       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myproject.android.customer.debug/com.myproject.android.customer.ui.OfferDetailsPdfActivity}: java.lang.IllegalArgumentException: Null objects cannot be copied from Realm.
           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
           at android.app.ActivityThread.-wrap11(ActivityThread.java)
           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
           at android.os.Handler.dispatchMessage(Handler.java:102)
           at android.os.Looper.loop(Looper.java:148)
           at android.app.ActivityThread.main(ActivityThread.java:5417)
           at java.lang.reflect.Method.invoke(Native Method)
           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
        Caused by: java.lang.IllegalArgumentException: Null objects cannot be copied from Realm.
           at io.realm.Realm.checkValidObjectForDetach(Realm.java:1625)
           at io.realm.Realm.copyFromRealm(Realm.java:1318)
           at io.realm.Realm.copyFromRealm(Realm.java:1292)
           at com.myproject.android.customer.service.OfferService.getOffer(OfferService.java:54)
           at com.myproject.android.customer.mvp.presenter.OfferDetailsPdfPresenterImplMvp.loadData(OfferDetailsPdfPresenterImplMvp.java:64)
           at com.myproject.android.customer.mvp.presenter.OfferDetailsPdfPresenterImplMvp.<init>(OfferDetailsPdfPresenterImplMvp.java:59)
           at com.myproject.android.customer.ui.OfferDetailsPdfActivity.createPresenter(OfferDetailsPdfActivity.java:76)
           at com.myproject.android.customer.ui.OfferDetailsPdfActivity.createPresenter(OfferDetailsPdfActivity.java:35)
           at com.hannesdorfmann.mosby3.mvp.delegate.ActivityMvpDelegateImpl.createViewIdAndCreatePresenter(ActivityMvpDelegateImpl.java:90)
           at com.hannesdorfmann.mosby3.mvp.delegate.ActivityMvpDelegateImpl.onCreate(ActivityMvpDelegateImpl.java:142)
           at com.hannesdorfmann.mosby3.mvp.MvpActivity.onCreate(MvpActivity.java:42)
           at com.myproject.android.customer.ui.OfferDetailsPdfActivity.onCreate(OfferDetailsPdfActivity.java:58)
           at android.app.Activity.performCreate(Activity.java:6251)
           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
           at android.app.ActivityThread.-wrap11(ActivityThread.java)
           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
           at android.os.Handler.dispatchMessage(Handler.java:102)
           at android.os.Looper.loop(Looper.java:148)
           at android.app.ActivityThread.main(ActivityThread.java:5417)
           at java.lang.reflect.Method.invoke(Native Method)
           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
You are executing the parent onCreate method without an offerId. Change the following two lines

```<code>super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
</code>```

to this:

```<code>Bundle extras = getIntent().getExtras();
if (savedInstanceState == null) {
    super.onCreate(extras);
}
</code>```

Title: Method onCreate() is not call

Body:
app/build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

dependencies {
...
implementation 'com.hannesdorfmann.mosby3:mvi:3.1.0'
    implementation 'com.hannesdorfmann.mosby3:mvp:3.1.0'
    implementation 'com.hannesdorfmann.mosby3:viewstate:3.1.0'
implementation 'com.hannesdorfmann.mosby3:mvp-lce:3.1.0'

}

Here my activity:

import com.hannesdorfmann.mosby3.mvp.MvpActivity;
    public class OfferDetailsPdfActivity extends MvpActivity<OfferDetailsPdfMvp.View, OfferDetailsPdfPresenterImplMvp> implements OnPageChangeListener, OfferDetailsPdfMvp.View {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    }

    }

And method onCreate() on my activity OfferDetailsPdfActivity  was success call.

But I need to pass param to activity, so here production code:

public class OfferDetailsPdfActivity extends MvpActivity<OfferDetailsPdfMvp.View, OfferDetailsPdfPresenterImplMvp> implements OnPageChangeListener, OfferDetailsPdfMvp.View {
private OfferDetailsPdfPresenterImplMvp presenter;
    private int offerId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        Debug.d(TAG, "onCreate: extras = " + AndroidUtil.bundle2String(extras)
                + "\nsavedInstanceState = " + AndroidUtil.bundle2String(savedInstanceState)
        );
        if (extras != null) {
            offerId = extras.getInt(Offer.ID);
        }
            setContentView(R.layout.offer_details_pdf);
        ButterKnife.bind(this);
    }

    @NonNull
    @Override
    public OfferDetailsPdfPresenterImplMvp createPresenter() {
        Debug.d(TAG, "createPresenter: offerId = " + offerId);
        presenter = new OfferDetailsPdfPresenterImplMvp(this, offerId);
        return presenter;
    }

And now in my activity method onCreate() is not call, but method createPresenter() was success called. Has text "createPresenter: offerId = 0"

As you can see from logcat the method onCreate() was not called. In logcat no text "onCreate: extras..."

Why?

Here logcat:

D/com.myproject.android.customer.ui.OfferDetailsPdfActivity(  946): createPresenter: offerId = 0
        Process: com.myproject.android.customer.debug, PID: 30127
       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myproject.android.customer.debug/com.myproject.android.customer.ui.OfferDetailsPdfActivity}: java.lang.IllegalArgumentException: Null objects cannot be copied from Realm.
           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
           at android.app.ActivityThread.-wrap11(ActivityThread.java)
           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
           at android.os.Handler.dispatchMessage(Handler.java:102)
           at android.os.Looper.loop(Looper.java:148)
           at android.app.ActivityThread.main(ActivityThread.java:5417)
           at java.lang.reflect.Method.invoke(Native Method)
           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
        Caused by: java.lang.IllegalArgumentException: Null objects cannot be copied from Realm.
           at io.realm.Realm.checkValidObjectForDetach(Realm.java:1625)
           at io.realm.Realm.copyFromRealm(Realm.java:1318)
           at io.realm.Realm.copyFromRealm(Realm.java:1292)
           at com.myproject.android.customer.service.OfferService.getOffer(OfferService.java:54)
           at com.myproject.android.customer.mvp.presenter.OfferDetailsPdfPresenterImplMvp.loadData(OfferDetailsPdfPresenterImplMvp.java:64)
           at com.myproject.android.customer.mvp.presenter.OfferDetailsPdfPresenterImplMvp.<init>(OfferDetailsPdfPresenterImplMvp.java:59)
           at com.myproject.android.customer.ui.OfferDetailsPdfActivity.createPresenter(OfferDetailsPdfActivity.java:76)
           at com.myproject.android.customer.ui.OfferDetailsPdfActivity.createPresenter(OfferDetailsPdfActivity.java:35)
           at com.hannesdorfmann.mosby3.mvp.delegate.ActivityMvpDelegateImpl.createViewIdAndCreatePresenter(ActivityMvpDelegateImpl.java:90)
           at com.hannesdorfmann.mosby3.mvp.delegate.ActivityMvpDelegateImpl.onCreate(ActivityMvpDelegateImpl.java:142)
           at com.hannesdorfmann.mosby3.mvp.MvpActivity.onCreate(MvpActivity.java:42)
           at com.myproject.android.customer.ui.OfferDetailsPdfActivity.onCreate(OfferDetailsPdfActivity.java:58)
           at android.app.Activity.performCreate(Activity.java:6251)
           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
           at android.app.ActivityThread.-wrap11(ActivityThread.java)
           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
           at android.os.Handler.dispatchMessage(Handler.java:102)
           at android.os.Looper.loop(Looper.java:148)
           at android.app.ActivityThread.main(ActivityThread.java:5417)
           at java.lang.reflect.Method.invoke(Native Method)
           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
You are executing the parent onCreate method without an offerId. Change the following two lines

super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();

to this:

Bundle extras = getIntent().getExtras();
if (savedInstanceState == null) {
    super.onCreate(extras);
}


问:
Sort an ArrayList<MyInterface>
For rendering order purposes, I'm trying to sort an ArrayList<MyInterface> by the sum of two integers in each object. The objects in this ArrayList implement the same interface but doesn't have a motherclass in common.

```<code>class A implements MyInterface, Comparable<MyInterface> {

    @Override
    public int compareTo(MyInterface object1) {
        return (this.x+this.y)-(object1.getX()+object1.getY()); // Sort in ascending order
    }

    @Override
    public int getX() { return this.x; }

    @Override
    public int getY() { return this.y; }
    }

}

class B implements MyInterface, Comparable<MyInterface> {
    //Same than A, but A & B have no common motherclass.
}

interface MyInterface {

    int getX();
    int getY();
    int compareTo(MyInterface mi);

    ... //Other method that are the first reason I created the interface before.

}
</code>```

Then I try to sort my arraylist like this:

```<code>ArrayList<MyInterface> myArrayList = new ArrayList<MyInterface>();
myArrayList.add(new A(1,2));
myArrayList.add(new A(5,6));
myArrayList.add(new B(3,1));
Collections.sort(gameRenderables); //I get the compile error here.
</code>```

I get the error:

```<code>Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<Renderable>). The inferred type Renderable is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>.
</code>```

Maybe I'm trying to make something impossible. If that is the case can you give me alternative solutions to this sorting problem?

答:
You've defined the class as implementing Comparable instead of defining the interface as extending Comparable. Without doing that, the Java compiler cannot know that every conceivable implementation of MyInterface is in fact Comparable. The fact that the interface has a compareTo(MyInterface) method that would match the method of a class implementing Comparable<MyInterface> is inconsequential.

To make a long story short:

```<code>interface MyInterface extends Comparable<MyInterface> {
    int getX();
    int getY();

    // No need for a compareTo method - we get it from the Comparable interface
}

class A implements MyInterface {
    // No changes required to your implementation
}
</code>```

Title: Sort an ArrayList<MyInterface>

Body:
For rendering order purposes, I'm trying to sort an ArrayList<MyInterface> by the sum of two integers in each object. The objects in this ArrayList implement the same interface but doesn't have a motherclass in common.

class A implements MyInterface, Comparable<MyInterface> {

    @Override
    public int compareTo(MyInterface object1) {
        return (this.x+this.y)-(object1.getX()+object1.getY()); // Sort in ascending order
    }

    @Override
    public int getX() { return this.x; }

    @Override
    public int getY() { return this.y; }
    }

}

class B implements MyInterface, Comparable<MyInterface> {
    //Same than A, but A & B have no common motherclass.
}

interface MyInterface {

    int getX();
    int getY();
    int compareTo(MyInterface mi);

    ... //Other method that are the first reason I created the interface before.

}

Then I try to sort my arraylist like this:

ArrayList<MyInterface> myArrayList = new ArrayList<MyInterface>();
myArrayList.add(new A(1,2));
myArrayList.add(new A(5,6));
myArrayList.add(new B(3,1));
Collections.sort(gameRenderables); //I get the compile error here.

I get the error:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<Renderable>). The inferred type Renderable is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>.

Maybe I'm trying to make something impossible. If that is the case can you give me alternative solutions to this sorting problem?

Body:
You've defined the class as implementing Comparable instead of defining the interface as extending Comparable. Without doing that, the Java compiler cannot know that every conceivable implementation of MyInterface is in fact Comparable. The fact that the interface has a compareTo(MyInterface) method that would match the method of a class implementing Comparable<MyInterface> is inconsequential.

To make a long story short:

interface MyInterface extends Comparable<MyInterface> {
    int getX();
    int getY();

    // No need for a compareTo method - we get it from the Comparable interface
}

class A implements MyInterface {
    // No changes required to your implementation
}


问:
Extremly slow STS startup, loading org.springsource.ide.eclipse.dashboard.ui
when I start my STS (3.5.1.RELEASE) it takes about 5 Minutes to startup.
On the splashscreen I can see "loading org.springsource.ide.eclipse.dashboard.ui"

I've allready disabled the Option "Show Dasboad on Startup".

Does anyone has an idea?

Even my colleagues have the same problem.

Best regards,
Peter

答:
The following is what worked for me.
When STS got stuck, opened IE, Tools --> Internet Options --> Connections --> LAN settings --> unchecked all proxy settings.

Then killed STS session from Task Manager and opened it again.
And this time it did not get stuck.
 Then I went back into IE to fix the proxy settings.


问:
Python subprocess column invalid option
I want to ask the shell to display a csv file in a nice format in my python script. So I wrote the following:

```<code>printout = "column -s, -t < output.csv | less -#2 -N -S "
subprocess.call(printout.split(), shell = False)
</code>```

The error I get is:

```<code>column: invalid option -- '#'
</code>```

I have a rough idea that it is something to do with shell=False; however when I set it to True and run in cmd line, it puts me into another line and I have to ctrl+C to get out.

答:
Your original code was equivalent to the shell command:

```<code># this can be used to reproduce your bug at a shell
column -s, -t '<' output.csv '|' less -#2 -N -S
</code>```

...passing <, |, less, etc. as arguments to column, not treating them as shell directives.

See the section Replacing Shell Pipelines in the subprocess module documentation.

```<code>p1 = subprocess.Popen(['column', '-s,', '-t'],
                      stdin=open('output.csv', 'r'),
                      stdout=subprocess.PIPE)
p2 = subprocess.Popen(['less', '-#2', '-N', '-S'],
                      stdin=p1.stdout)
p1.stdout.close() # ensure that p2 has the only remaining handle on p1.stdout
p2.communicate()  # let less run
</code>```

Title: Python subprocess column invalid option

Body:
I want to ask the shell to display a csv file in a nice format in my python script. So I wrote the following:

printout = "column -s, -t < output.csv | less -#2 -N -S "
subprocess.call(printout.split(), shell = False)

The error I get is:

column: invalid option -- '#'

I have a rough idea that it is something to do with shell=False; however when I set it to True and run in cmd line, it puts me into another line and I have to ctrl+C to get out.

Body:
Your original code was equivalent to the shell command:

# this can be used to reproduce your bug at a shell
column -s, -t '<' output.csv '|' less -#2 -N -S

...passing <, |, less, etc. as arguments to column, not treating them as shell directives.

See the section Replacing Shell Pipelines in the subprocess module documentation.

p1 = subprocess.Popen(['column', '-s,', '-t'],
                      stdin=open('output.csv', 'r'),
                      stdout=subprocess.PIPE)
p2 = subprocess.Popen(['less', '-#2', '-N', '-S'],
                      stdin=p1.stdout)
p1.stdout.close() # ensure that p2 has the only remaining handle on p1.stdout
p2.communicate()  # let less run


问:
Input to a file in an array and then pulling info from file later in python
I am trying to get a program built for a class project and just need help understanding a concept and how it should work. I need to do this:

At the end of each game, the program asks you to record the scores for each team member. You type in their first name and that person's score for the game on a single line. Should print the lists into columns of name and scores entered, highest score to lowest score and alphabetical order.

My issue is that if I go in and write a file and put the information in, I can pull from that file correctly but I can't get a user input into a file and then pull from that. If anyone could help me understand that. Sorry this is kinda long.

# Input trying to figure out
scoring = []
n = int(input("Enter the amount: "))
print("Write the name followed by a ',' and then the score")
with open("scores.txt", 'w') as the_file:
    for i in range(0, n):
        name = input("Enter the Name: ")
        score = input("Enter the Score: ")
        name = the_file.write(name)
        score = the_file.write(score)

# output
scores = []
with open("scores.txt", 'r') as f:
    for line in f:
        name, score = line.split(',')
        score = int(score)
        scores.append((name, score))

list.sort(scores, reverse=True, key=lambda s: s[1])```

答:
You do not write the format that you expect when reading the file:</p>

```<code>name = input("Enter the Name: ")
score = input("Enter the Score: ")
# do not assign the return value of the write function
the_file.write('{},{}\n'.format(name, score))
</code>```

Body:
You do not write the format that you expect when reading the file:

name = input("Enter the Name: ")
score = input("Enter the Score: ")
# do not assign the return value of the write function
the_file.write('{},{}\n'.format(name, score))


问:
Slim 3 multiple routes to one function?
I've been looking all over online and can't find anything that tells you how to assign multiple routes to one callback. For example I want to move:

```<code>$app->get('/sign-in', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

$app->get('/login', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});
</code>```

into something like:

```<code>$app->get(['/sign-in', '/login'], function($request, $response) {
    return $this->view->render($response, 'home.twig');
});
</code>```

Is there a way to do this with Slim 3? I found online that in Slim 2 you could use the conditions([]); function on the end to chain multiple routes to one callback.

答:
I am using regex to do this trick:</p>

```<code>$app->get('/{router:login|sign-in}', function ($request, $response, $args) {
  echo "Hello, " . $args['router'];
});
</code>```

Title: Slim 3 multiple routes to one function?

Body:
I've been looking all over online and can't find anything that tells you how to assign multiple routes to one callback. For example I want to move:

$app->get('/sign-in', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

$app->get('/login', function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

into something like:

$app->get(['/sign-in', '/login'], function($request, $response) {
    return $this->view->render($response, 'home.twig');
});

Is there a way to do this with Slim 3? I found online that in Slim 2 you could use the conditions([]); function on the end to chain multiple routes to one callback.

Body:
I am using regex to do this trick:

$app->get('/{router:login|sign-in}', function ($request, $response, $args) {
  echo "Hello, " . $args['router'];
});