问:
Select all non-null column names per row in spark
Suppose I have a dataframe that looks like this:

```<code>+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |
+-----+-----+-----+-----+
|  Y  |null |  Y  |null |
|null |  N  |  N  |null |
|  N  |  Y  |null |  N  |
+-----+-----+-----+-----+
</code>```

I want to add a new column that is a concatenation of the names of all non-null columns for each row.

So, for the example above, it would add a new column

```<code>+--------+
|non-null|
+--------+
| A, C   |
| B, C   |
| A, B, D|
+--------+
</code>```

Is there any easy way to do this? I've tried looking for an anti-coalesce, something that would, if not null, use the supplied name. For example, if there was an anti-coalesce:

```<code>df.withColumn("non-null", antiCoalesce("A", "A,") + antiCoalesce("B", "B,") + antiCoalesce("C", "C,") + antiCoalesce("D", "D"))
</code>```

Alas, there is no such function, but it demonstrates what I am looking for.

答:
Using Spark 2.4+, you can do something like this:

```<code>val nonNullColsExpr = df.columns.map(c => when(col(c).isNotNull, lit(c)))

df.withColumn("non_null", array(nonNullColsExpr:_*))
  .withColumn("non_null", expr("array_join(non_null, ',')"))
  .show()

//+----+----+----+----+--------+
//|   A|   B|   C|   D|non_null|
//+----+----+----+----+--------+
//|   Y|null|   Y|null|     A,C|
//|null|   N|   N|null|     B,C|
//|   N|   Y|null|   N|   A,B,D|
//+----+----+----+----+--------+
</code>```

First, we create an array column that contains column names that satisfy the condition isNotNull and those that do not satisfy will be nulled. And then join the elements with array_join using , delimiter (array_join filters the null values when joining the elements).

Body:
Suppose I have a dataframe that looks like this:

+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |
+-----+-----+-----+-----+
|  Y  |null |  Y  |null |
|null |  N  |  N  |null |
|  N  |  Y  |null |  N  |
+-----+-----+-----+-----+

I want to add a new column that is a concatenation of the names of all non-null columns for each row.

So, for the example above, it would add a new column

+--------+
|non-null|
+--------+
| A, C   |
| B, C   |
| A, B, D|
+--------+

Is there any easy way to do this? I've tried looking for an anti-coalesce, something that would, if not null, use the supplied name. For example, if there was an anti-coalesce:

df.withColumn("non-null", antiCoalesce("A", "A,") + antiCoalesce("B", "B,") + antiCoalesce("C", "C,") + antiCoalesce("D", "D"))

Alas, there is no such function, but it demonstrates what I am looking for.

Body:
Using Spark 2.4+, you can do something like this:

val nonNullColsExpr = df.columns.map(c => when(col(c).isNotNull, lit(c)))

df.withColumn("non_null", array(nonNullColsExpr:_*))
  .withColumn("non_null", expr("array_join(non_null, ',')"))
  .show()

//+----+----+----+----+--------+
//|   A|   B|   C|   D|non_null|
//+----+----+----+----+--------+
//|   Y|null|   Y|null|     A,C|
//|null|   N|   N|null|     B,C|
//|   N|   Y|null|   N|   A,B,D|
//+----+----+----+----+--------+

First, we create an array column that contains column names that satisfy the condition isNotNull and those that do not satisfy will be nulled. And then join the elements with array_join using , delimiter (array_join filters the null values when joining the elements).


来源: stackexchange

问:
Kubernetes pods graceful shutdown with TCP connections (Spring boot)
I am hosting my services on azure cloud, sometimes I get "BackendConnectionFailure" without any apparent reason, after investigation I found a correlation between this exception and autoscale (scaling down) almost at the same second in most of the cases.

According to documentation termination grace period by default is 30 seconds, which is the case. The pod will be marked terminating and the loadbalancer will not consider it anymore, so receiving no more requests. According to this if my service takes far less time than 30 seconds, I should not need prestop hook or any special implementation in my application (please correct me if I am wrong).

If the previous paragraph is correct, why does this exception occur relatively frequent? My thought is when the pod is marked terminating and the loadbalancer does not forward anymore requests to the pod while it should do.

Edit 1:

The Architecture is simply like this

Client -> Firewall(azure) -> API(azure APIM) -> Microservices(Spring boot) -> backend(third party) or azure RDB depending on the service

I think the Exception comes from APIM, I found two patterns for this exception:

Message   The underlying connection was closed: The connection was closed unexpectedly.
Exception type  BackendConnectionFailure
Failed method   forward-request

Response time  10.0 s

Message    The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
Exception type  BackendConnectionFailure
Failed method   forward-request

Response time  3.6 ms

答:
When your applications receives a SIGTERM (from the Pod termination) it needs to first stop reporting it is ready (fail the readinessProbe) but still serve requests as they come in from clients. After a certain time (depending on your readinessProbe settings) you can shut down the application.

For Spring Boot there is a small library doing exactly that: springboot-graceful-shutdown

ContentLicense: CC BY-SA 4.0


问:
Use result of get function within a javascript
I'm trying to impliment a google chart like the no dependancies one shown here
To get this to work with my data I'm importing the data for the rows like so..

$.get('http://104.12.156.29:8011/java/servlet/UTRICKC5.I00120s', function (data2) {
      console.log(data2);});

This pulls what I need... but how can I replace the data.addrows block with what I'm pulling in?

For reference, what I'm getting shown in the console is this;

```<code>['Task 1', 'Task 1','Team 1',new Date(2014 , 02, 01), new Date(2014 , 02, 10), null, 50, null],
['Task 2', 'Task 2','Team 2',new Date(2014 , 03, 01), new Date(2014 , 04, 01), null, 1, null]
</code>```

So I pretty just need to find a way of getting this to "render" as part of my javascript.

```<code><script type="text/javascript">
    google.charts.load('current', {'packages':['gantt']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Task ID');
      data.addColumn('string', 'Task Name');
      data.addColumn('string', 'Resource');
      data.addColumn('date', 'Start Date');
      data.addColumn('date', 'End Date');
      data.addColumn('number', 'Duration');
      data.addColumn('number', 'Percent Complete');
      data.addColumn('string', 'Dependencies');
            $.get('http://http://104.12.156.29:8011/java/servlet/UTRICKC5.I00120s', function (data2) {
      console.log(data2);});
      data.addRows([
        ['2014Spring', 'Spring 2014', 'spring',
         new Date(2014, 2, 22), new Date(2014, 5, 20), null, 100, null],
        ['2014Summer', 'Summer 2014', 'summer',
         new Date(2014, 5, 21), new Date(2014, 8, 20), null, 100, null],
        ['2014Autumn', 'Autumn 2014', 'autumn',
         new Date(2014, 8, 21), new Date(2014, 11, 20), null, 100, null],
        ['2014Winter', 'Winter 2014', 'winter',
         new Date(2014, 11, 21), new Date(2015, 2, 21), null, 100, null],
        ['2015Spring', 'Spring 2015', 'spring',
         new Date(2015, 2, 22), new Date(2015, 5, 20), null, 50, null],
        ['2015Summer', 'Summer 2015', 'summer',
         new Date(2015, 5, 21), new Date(2015, 8, 20), null, 0, null],
        ['2015Autumn', 'Autumn 2015', 'autumn',
         new Date(2015, 8, 21), new Date(2015, 11, 20), null, 0, null],
        ['2015Winter', 'Winter 2015', 'winter',
         new Date(2015, 11, 21), new Date(2016, 2, 21), null, 0, null],
        ['Football', 'Football Season', 'sports',
         new Date(2014, 8, 4), new Date(2015, 1, 1), null, 100, null],
        ['Baseball', 'Baseball Season', 'sports',
         new Date(2015, 2, 31), new Date(2015, 9, 20), null, 14, null],
        ['Basketball', 'Basketball Season', 'sports',
         new Date(2014, 9, 28), new Date(2015, 5, 20), null, 86, null],
        ['Hockey', 'Hockey Season', 'sports',
         new Date(2014, 9, 8), new Date(2015, 5, 21), null, 89, null]
      ]);
      var options = {
        height: 400,
        gantt: {
          trackHeight: 30
        }
      };
      var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
  </script>
</code>```

答:
first, recommend formatting the data as json, as found here...

```<code>{
  "cols": [
    {"label": "Task ID", "type": "string"},
    {"label": "Task Name", "type": "string"},
    {"label": "Resource", "type": "string"},
    {"label": "Start Date", "type": "date"},
    {"label": "End Date", "type": "date"},
    {"label": "Duration", "type": "number"},
    {"label": "Percent Complete", "type": "number"},
    {"label": "Dependencies", "type": "string"}
  ],
  "rows": [
    {"c":[{"v": "Task 1"}, {"v": "Task 1"}, {"v": "Team 1"}, {"v": "Date(2014, 2, 1)"}, {"v": "Date(2014, 2, 10)"}, {"v": null}, {"v": 50}, {"v": null}]},
    {"c":[{"v": "Task 2"}, {"v": "Task 2"}, {"v": "Team 2"}, {"v": "Date(2014, 3, 1)"}, {"v": "Date(2014, 4, 1)"}, {"v": null}, {"v": 1}, {"v": null}]}
  ]
}
</code>```

this will allow you to create the data table directly, without client-side manipulation.

and it is the fastest way to load the data table.

next, both $.get and $.ajax are asynchronous,

which means you will need to wait until the data is received,

before trying to create the data table and draw the chart.

recommend using $.ajax so you can specify the dataType as json.

see following working snippet,

here, I use the fail promise method so the snippet will work,

you can remove on your server and just keep the done method.

google.charts.load('current', {
  packages: ['gantt']
}).then(function () {
  var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
  var options = {
    height: 400,
    gantt: {
      trackHeight: 30
    }
  };

  $.ajax({
    url: 'http://104.12.156.29:8011/java/servlet/UTRICKC5.I00120s',
    dataType: 'json'
  }).done(drawChart).fail(function () {
    var chartData = {
      "cols": [
        {"label": "Task ID", "type": "string"},
        {"label": "Task Name", "type": "string"},
        {"label": "Resource", "type": "string"},
        {"label": "Start Date", "type": "date"},
        {"label": "End Date", "type": "date"},
        {"label": "Duration", "type": "number"},
        {"label": "Percent Complete", "type": "number"},
        {"label": "Dependencies", "type": "string"}
      ],
      "rows": [
        {"c":[{"v": "Task 1"}, {"v": "Task 1"}, {"v": "Team 1"}, {"v": "Date(2014, 2, 1)"}, {"v": "Date(2014, 2, 10)"}, {"v": null}, {"v": 50}, {"v": null}]},
        {"c":[{"v": "Task 2"}, {"v": "Task 2"}, {"v": "Team 2"}, {"v": "Date(2014, 3, 1)"}, {"v": "Date(2014, 4, 1)"}, {"v": null}, {"v": 1}, {"v": null}]}
      ]
    };
    drawChart(chartData);
  });

  function drawChart(chartData) {
    var data = new google.visualization.DataTable(chartData);
    chart.draw(data, options);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div></code>```

Body:
I'm trying to impliment a google chart like the no dependancies one shown here
To get this to work with my data I'm importing the data for the rows like so..

$.get('http://104.12.156.29:8011/java/servlet/UTRICKC5.I00120s', function (data2) {
      console.log(data2);});

This pulls what I need... but how can I replace the data.addrows block with what I'm pulling in?

For reference, what I'm getting shown in the console is this;

['Task 1', 'Task 1','Team 1',new Date(2014 , 02, 01), new Date(2014 , 02, 10), null, 50, null],
['Task 2', 'Task 2','Team 2',new Date(2014 , 03, 01), new Date(2014 , 04, 01), null, 1, null]

So I pretty just need to find a way of getting this to "render" as part of my javascript.

Body:
first, recommend formatting the data as json, as found here...

{
  "cols": [
    {"label": "Task ID", "type": "string"},
    {"label": "Task Name", "type": "string"},
    {"label": "Resource", "type": "string"},
    {"label": "Start Date", "type": "date"},
    {"label": "End Date", "type": "date"},
    {"label": "Duration", "type": "number"},
    {"label": "Percent Complete", "type": "number"},
    {"label": "Dependencies", "type": "string"}
  ],
  "rows": [
    {"c":[{"v": "Task 1"}, {"v": "Task 1"}, {"v": "Team 1"}, {"v": "Date(2014, 2, 1)"}, {"v": "Date(2014, 2, 10)"}, {"v": null}, {"v": 50}, {"v": null}]},
    {"c":[{"v": "Task 2"}, {"v": "Task 2"}, {"v": "Team 2"}, {"v": "Date(2014, 3, 1)"}, {"v": "Date(2014, 4, 1)"}, {"v": null}, {"v": 1}, {"v": null}]}
  ]
}

this will allow you to create the data table directly, without client-side manipulation.

and it is the fastest way to load the data table.

next, both $.get and $.ajax are asynchronous,

which means you will need to wait until the data is received,

before trying to create the data table and draw the chart.

recommend using $.ajax so you can specify the dataType as json.

see following working snippet,

here, I use the fail promise method so the snippet will work,

you can remove on your server and just keep the done method.

google.charts.load('current', {
  packages: ['gantt']
}).then(function () {
  var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
  var options = {
    height: 400,
    gantt: {
      trackHeight: 30
    }
  };

  $.ajax({
    url: 'http://104.12.156.29:8011/java/servlet/UTRICKC5.I00120s',
    dataType: 'json'
  }).done(drawChart).fail(function () {
    var chartData = {
      "cols": [
        {"label": "Task ID", "type": "string"},
        {"label": "Task Name", "type": "string"},
        {"label": "Resource", "type": "string"},
        {"label": "Start Date", "type": "date"},
        {"label": "End Date", "type": "date"},
        {"label": "Duration", "type": "number"},
        {"label": "Percent Complete", "type": "number"},
        {"label": "Dependencies", "type": "string"}
      ],
      "rows": [
        {"c":[{"v": "Task 1"}, {"v": "Task 1"}, {"v": "Team 1"}, {"v": "Date(2014, 2, 1)"}, {"v": "Date(2014, 2, 10)"}, {"v": null}, {"v": 50}, {"v": null}]},
        {"c":[{"v": "Task 2"}, {"v": "Task 2"}, {"v": "Team 2"}, {"v": "Date(2014, 3, 1)"}, {"v": "Date(2014, 4, 1)"}, {"v": null}, {"v": 1}, {"v": null}]}
      ]
    };
    drawChart(chartData);
  });

  function drawChart(chartData) {
    var data = new google.visualization.DataTable(chartData);
    chart.draw(data, options);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


问:
I have created a Sharepoint list in 2013 with Expiry date and email ID. The requirement is auto mail has to be generated
I have created a SharePoint list in 2013 with Expiry date and email ID. The requirement is auto mail has to be generated to with number of item which is going to expire. </p>

答: Create workflow using SP Designer or VS.</p>


问:
Why can't you store an extremely large single value in a dynamically allocated block of memory?
Why can't I store a large integer in this allocated block of memory?

```<code>int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);
</code>```

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?

答:
*dyn = 9999999999; does not instruct the computer to use all the memory that was allocated for dyn to store the value 9999999999.

In C, dyn has a type. The type is “pointer to int”. Then *dyn has type int, which has a specific, fixed number of bits. It does not have a type meaning “all the memory that was allocated for dyn”.

Since *dyn is an int, *dyn = 9999999999; tells the computer to put 9999999999 into an int. Since 9999999999 is too big for an int in your C implementation, an overflow occurs.

We can program computers and design programming languages to manage integers of arbitrary sizes. Some languages, such as Python, do this. However that requires extra software, particularly software that has to do some variable amount of work when the program is running in order to handle whatever sizes of numbers come along. C is designed to be an elementary language. It works with objects of specific sizes and generally translates C code to fixed amounts of work in processor instructions. These provide building blocks for programmers to build bigger software. So, in C, int objects have fixed sizes. Allocating 16 bytes of memory provides space for several int objects, but it does not provide a big integer object.

Body:
Why can't I store a large integer in this allocated block of memory?

int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?


问:
android studio with Java compiler error: string too large to encode using UTF-8 written instead as 'STRING_TOO_LARGE'
When I clean the android project in android studio, the error happen, I have backed to previous commit or different branch, which works find couple days ago, but has this error now. I have checked this question and there is not large image or strings added for my project. STRING_TOO_LARGE String in Kothlin</p>

答: In my case, i deleted a view from xml but forgot to remove its references in my kotlin code. Make sure to check this before doing anything fancy.</p>


答:
Just use aggregation:

```<code>select sum(price * quantity) + fee
from t
group by id_test, fee;
</code>```

If you have different fees for the same test, you might want:

```<code>select sum(price * quantity) + avg(fee)
from t
group by id_test;
</code>```

Title: SQL Query SUM with conditions

Body:
I'm having some difficulties finding the good query I need, looking for help.
After multiple JOIN and a lot of WHERE, I have this columns and values :

+---------+----------+--------+-------+
| id_test | quantity | price  |  fee  |
+---------+----------+--------+-------+
| "1-3"   |        1 | 33.52  | 29.00 |
| "1-5"   |        1 | 33.52  | 29.00 |
| "1-6"   |        1 | 33.52  | 29.00 |
| "1-8"   |        1 | 86.49  | 29.00 |
| "19-1"  |        1 | 176.54 | 29.00 |
| "19-4"  |        1 | 176.54 | 29.00 |
| "19-5"  |        4 | 176.54 | 29.00 |
| "19-6"  |        1 | 199.47 | 29.00 |
| "19-6"  |        1 | 176.54 | 29.00 |
| "20-10" |        2 | 72.67  | 29.00 |
| "20-11" |        2 | 18.95  | 29.00 |
| "20-9"  |        1 | 22.13  | 29.00 |
+---------+----------+--------+-------+

Each id_test object as a quantity, a price and a fee. I would like to SUM everything so to have a global price : (quantity*price)+fee
The thing is, and that's where I'm stuck, the fee has to be added only once by id_test. Yet, I have here two id_test "19-6".

If I SUM everything I have 1827.67 (price*quantity) + 348 (fee).

Since I have two "19-6", I need 1827.67 (price*quantity) + 319 (fee).

How would you do in SQL ?

Thanks

Body:
Just use aggregation:

select sum(price * quantity) + fee
from t
group by id_test, fee;

If you have different fees for the same test, you might want:

select sum(price * quantity) + avg(fee)
from t
group by id_test;


问:
How to extend a Button using Androidx
I seem to have run into a classic Android gotcha: use a deprecated api, or an api that doesn't work yet..

I've migrated my project to use AndroidX rather than the AppCompat support libraries.

And now I want to extend android.widget.Button to make a custom Button. However, Android Studio 3.5.3 won't have it, saying I should instead extend android.support.v7.widget.AppCompatButton. Which is part of the now-deprecated support libraries - and for which there should, therefore, presumably be an AndroidX equivalent. But I can't find such a thing....

Is there a convenient cross-reference tool to help us find AndroidX equivalents to all the old support library classes?

答:
In your case you can extend one of these:

com.google.android.material.button.MaterialButton provided by the material components library

androidx.appcompat.widget.AppCompatButton provided by the androidx appcompat library

android.widget.Button

You can use the androidx class Mappings to check the current mappings from the old support library packages to the new androidx packages.

Title: How to extend a Button using Androidx


问:
How to get first element in a list of tuples?
I have a list like below where the first element is the id and the other is a string:

```<code>[(1, u'abc'), (2, u'def')]
</code>```

I want to create a list of ids only from this list of tuples as below:

```<code>[1,2]
</code>```

I'll use this list in __in so it needs to be a list of integer values.

答:
I was thinking that it might be useful to compare the runtimes of the different approaches so I made a benchmark (using simple_benchmark library)

I) Benchmark having tuples with 2 elements

As you may expect to select the first element from tuples by index 0 shows to be the fastest solution very close to the unpacking solution by expecting exactly 2 values

```<code>import operator
import random

from simple_benchmark import BenchmarkBuilder

b = BenchmarkBuilder()

@b.add_function()
def rakesh_by_index(l):
    return [i[0] for i in l]

@b.add_function()
def wayneSan_zip(l):
    return list(list(zip(*l))[0])

@b.add_function()
def bcattle_itemgetter(l):
     return list(map(operator.itemgetter(0), l))

@b.add_function()
def ssoler_upacking(l):
    return [idx for idx, val in l]

@b.add_function()
def kederrack_unpacking(l):
    return [f for f, *_ in l]

@b.add_arguments('Number of tuples')
def argument_provider():
    for exp in range(2, 21):
        size = 2**exp
        yield size, [(random.choice(range(100)), random.choice(range(100))) for _ in range(size)]

r = b.run()
r.plot()
</code>```

II) Benchmark having tuples with 2 or more elements

```<code>import operator
import random

from simple_benchmark import BenchmarkBuilder

b = BenchmarkBuilder()

@b.add_function()
def kederrack_unpacking(l):
    return [f for f, *_ in l]

@b.add_function()
def rakesh_by_index(l):
    return [i[0] for i in l]

@b.add_function()
def wayneSan_zip(l):
    return list(list(zip(*l))[0])

@b.add_function()
def bcattle_itemgetter(l):
     return list(map(operator.itemgetter(0), l))

@b.add_arguments('Number of tuples')
def argument_provider():
    for exp in range(2, 21):
        size = 2**exp
        yield size, [tuple(random.choice(range(100)) for _
                     in range(random.choice(range(2, 100)))) for _ in range(size)]

from pylab import rcParams
rcParams['figure.figsize'] = 12, 7

r = b.run()
r.plot()
</code>```

Body:
I have a list like below where the first element is the id and the other is a string:

[(1, u'abc'), (2, u'def')]

I want to create a list of ids only from this list of tuples as below:

[1,2]

I'll use this list in __in so it needs to be a list of integer values.

Body:
I was thinking that it might be useful to compare the runtimes of the different approaches so I made a benchmark (using simple_benchmark library)

I) Benchmark having tuples with 2 elements

As you may expect to select the first element from tuples by index 0 shows to be the fastest solution very close to the unpacking solution by expecting exactly 2 values

import operator
import random

from simple_benchmark import BenchmarkBuilder

b = BenchmarkBuilder()

@b.add_function()
def rakesh_by_index(l):
    return [i[0] for i in l]

@b.add_function()
def wayneSan_zip(l):
    return list(list(zip(*l))[0])

@b.add_function()
def bcattle_itemgetter(l):
     return list(map(operator.itemgetter(0), l))

@b.add_function()
def ssoler_upacking(l):
    return [idx for idx, val in l]

@b.add_function()
def kederrack_unpacking(l):
    return [f for f, *_ in l]

@b.add_arguments('Number of tuples')
def argument_provider():
    for exp in range(2, 21):
        size = 2**exp
        yield size, [(random.choice(range(100)), random.choice(range(100))) for _ in range(size)]

r = b.run()
r.plot()

II) Benchmark having tuples with 2 or more elements

import operator
import random

from simple_benchmark import BenchmarkBuilder

b = BenchmarkBuilder()

@b.add_function()
def kederrack_unpacking(l):
    return [f for f, *_ in l]

@b.add_function()
def rakesh_by_index(l):
    return [i[0] for i in l]

@b.add_function()
def wayneSan_zip(l):
    return list(list(zip(*l))[0])

@b.add_function()
def bcattle_itemgetter(l):
     return list(map(operator.itemgetter(0), l))

@b.add_arguments('Number of tuples')
def argument_provider():
    for exp in range(2, 21):
        size = 2**exp
        yield size, [tuple(random.choice(range(100)) for _
                     in range(random.choice(range(2, 100)))) for _ in range(size)]

from pylab import rcParams
rcParams['figure.figsize'] = 12, 7

r = b.run()
r.plot()


问:
What is OS Load in Elasticsearch node stat?
In Elasticsearch node stat API when I send a query for OS stat:

```<code>curl -XGET "http://esls1.ping-service.com:9200/_nodes/stats/os"
</code>```

In the response I get a metric load_average:

```<code>"load_average": [0,0.04,0.13]
</code>```

What does is means?

答:
Sigar is not used in Elasticsearch anymore since the first Beta of 2.0.0: github.com/elastic/elasticsearch/pull/12010 github.com/elastic/elasticsearch/issues/11034

since then, they switched to generic OS load metrics. similar to what you see with the top command. see here for an explanation what this means: https://askubuntu.com/questions/532845/what-is-system-load

beware: this means if you run ES in a docker container, the load shown will be actually from the host machine, and not from only the docker container!

ContentLicense: CC BY-SA 3.0

Body:
In Elasticsearch node stat API when I send a query for OS stat:

curl -XGET "http://esls1.ping-service.com:9200/_nodes/stats/os"

In the response I get a metric load_average:

"load_average": [0,0.04,0.13]

What does is means?


问:
Access the current android activity
How can I access the current Android activity class?

I am using the necessitas framework (QT in Android). Basically, using the Android NDK an activity calls a QT application (.so). All runs fine. Now I am working on some bindings to access the GPS from the QT application. From some java examples that access the GPS I saw that the most vital part is to allow access to the GPS service:

LocationManager lm;
lm = (LocationManager) getSystemService(LOCATION_SERVICE);

Here getSystemService is a method of class activity. Because I am using the JNI inside the QT application I need to access the current activity that is running my QT application, so I can call the function getSystemService.

So the question is. How do I get the current activity where my QT application is running from?

答:
I solved this by passing the current application (running my QT application) to my QT application using JNI's RegisterNatives().

Carlos.

Title: Access the current android activity


问:
Can't quit incorrect mySQL command line
When you type a command into mySQL the wrong way, mySQL won't run the command.  Instead of giving an error it sometimes gives an endless list of:

```<code>'>
'>
'>
'>
</code>```

each time you enter something, no matter what input you give it (besides using quit command).  I'd like to stay logged in though, so quitting, logging back in and retrying the command with different syntax is very annoying.

Is there a shortcut to just quit a line if it bugs out and stay in the connection?

答:
I prefer to do it using '\c' to clear wrong commands which is also suggested by mysql itself.

In your case you should

Close the string with " (or')

Use \c to clear the command.

Title: Can't quit incorrect mySQL command line

Body:
When you type a command into mySQL the wrong way, mySQL won't run the command.  Instead of giving an error it sometimes gives an endless list of:

'>
'>
'>
'>

each time you enter something, no matter what input you give it (besides using quit command).  I'd like to stay logged in though, so quitting, logging back in and retrying the command with different syntax is very annoying.

Is there a shortcut to just quit a line if it bugs out and stay in the connection?


问:
Use results from first query as criteria for second query
I have the following SQL table which you can also find in the SQL fiddle here:

```<code>CREATE TABLE Products (
    Supplier TEXT,
    Product TEXT,
    Quantity VARCHAR(255)
);

INSERT INTO Products
(Supplier, Product, Quantity)
VALUES

("Supplier_01", "Product A", "500"),
("Supplier_05", "Product A", "300"),
("Supplier_09", "Product A", "250"),

("Supplier_05", "Product B", "900"),
("Supplier_06", "Product B", "270"),
("Supplier_02", "Product B", "850"),
("Supplier_05", "Product B", "950"),
("Supplier_10", "Product B", "630");
</code>```

I currently use the following query for it:

```<code>SELECT Supplier, Product, Quantity
FROM Products
WHERE Product = "Product B";
</code>```

However, now I want to use part of the results from the query above as WHERE criteria for a second query.
 Basically, I want that all Suppliers which exist for Product B are used for the WHERE criteria for Product A.
 Something like this:

```<code>SELECT Supplier, Product, Quantity
FROM Products
WHERE Product = "Product A"
AND Supplier EXISTS IN
   (SELECT Supplier
    FROM Products
    WHERE Product = "Product B") table_01;
</code>```

In the end the desired result should look like this:

```<code>Supplier             Product          Quantity
Supplier_05          Product A         300
Supplier_02          Product B         850
Supplier_05          Product B         900
Supplier_06          Product B         270
Supplier_10          Product B         630
</code>```

What do I need to change in my code to make it work?

答:
You were almost there:

SELECT Supplier, Product, Quantity
FROM Products
WHERE Supplier IN
   (SELECT Supplier
    FROM Products
    WHERE Product = "Product B")
GROUP BY 1,2
ORDER BY 2,1;
```

Body:
I have the following SQL table which you can also find in the SQL fiddle here:

CREATE TABLE Products (
    Supplier TEXT,
    Product TEXT,
    Quantity VARCHAR(255)
);

INSERT INTO Products
(Supplier, Product, Quantity)
VALUES

("Supplier_01", "Product A", "500"),
("Supplier_05", "Product A", "300"),
("Supplier_09", "Product A", "250"),

("Supplier_05", "Product B", "900"),
("Supplier_06", "Product B", "270"),
("Supplier_02", "Product B", "850"),
("Supplier_05", "Product B", "950"),
("Supplier_10", "Product B", "630");

I currently use the following query for it:

SELECT Supplier, Product, Quantity
FROM Products
WHERE Product = "Product B";

However, now I want to use part of the results from the query above as WHERE criteria for a second query.
 Basically, I want that all Suppliers which exist for Product B are used for the WHERE criteria for Product A.
 Something like this:

SELECT Supplier, Product, Quantity
FROM Products
WHERE Product = "Product A"
AND Supplier EXISTS IN
   (SELECT Supplier
    FROM Products
    WHERE Product = "Product B") table_01;

In the end the desired result should look like this:

Supplier             Product          Quantity
Supplier_05          Product A         300
Supplier_02          Product B         850
Supplier_05          Product B         900
Supplier_06          Product B         270
Supplier_10          Product B         630

What do I need to change in my code to make it work?


问:
How to load angular application with zone 0.8.5 on click of back button
Im loading my angular application in another (A) application. So there is an option for user to come back to A and again go back to angular application.

With zonejs version 0.9.0 this will work fine, where as it will have an impact in my angular(4) application iframe load(removeeventlistener has got only 1 argument instead of two).

So any idea to reolve this issue with zone js version 0.8.5?

Or by using commonchunkplugins how can i resolve?

答: This issue got solved after adding arguments in the ngDestroy removeventlistener. So using zone.js 0.9.0 with the above fix worked for me.</p>


问:
Get a 404 Not Found from nginx when ng build
I'm new to angular. I try to run my angular application in a docker.

When I do ng build or ng build -prod and try to let it run in a docker with this dockerfile:

```<code>### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
COPY --from=build /usr/src/app/dist/TBH-GUI /usr/share/nginx/html
</code>```

my startpage is shown properly. At this startpage I have some links to some other components. When I hit the links I get a 404 Not Found nginx/1.17.1.

I guess I have a mistake with my building process.

My package.json

```<code>{
  "name": "tbh-gui",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.1",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}
</code>```

My angular.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "TBH-GUI": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/TBH-GUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TBH-GUI:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "TBH-GUI:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "TBH-GUI:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "TBH-GUI:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "TBH-GUI:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "TBH-GUI"
}
</code>```

My project structure:

My nginx.conf:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}
</code>```

答:
Try adding this to your ngnix config file:</p>

```<code>http {
    ... other configs
    location / {
        try_files $uri $uri/ index.html
    }
}
</code>```

Body:
I'm new to angular. I try to run my angular application in a docker.

When I do ng build or ng build -prod and try to let it run in a docker with this dockerfile:

### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
COPY --from=build /usr/src/app/dist/TBH-GUI /usr/share/nginx/html

my startpage is shown properly. At this startpage I have some links to some other components. When I hit the links I get a 404 Not Found nginx/1.17.1.

I guess I have a mistake with my building process.

My package.json

{
  "name": "tbh-gui",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.1",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.7.5"
  }
}

My angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "TBH-GUI": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/TBH-GUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TBH-GUI:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "TBH-GUI:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "TBH-GUI:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "TBH-GUI:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "TBH-GUI:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "TBH-GUI"
}

My project structure:

My nginx.conf:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

Body:
Try adding this to your ngnix config file:

http {
    ... other configs
    location / {
        try_files $uri $uri/ index.html
    }
}


问:
Unknown error when running train.py or model_main.py
I've been following this guide on github with a couple of changes since I'm using the ssdlite_mobilenet_v2_coco model and I'm getting an unkown error.

https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10

message:

```<code>**Traceback (most recent call last):
  File "model_main.py", line 109, in <module>
    tf.app.run()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 126, in run
    _sys.exit(main(argv))
  File "model_main.py", line 105, in main
    tf.estimator.train_and_evaluate(estimator, train_spec, eval_specs[0])
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\training.py", line 439, in train_and_evaluate
    executor.run()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\training.py", line 518, in run
    self.run_local()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\training.py", line 650, in run_local
    hooks=train_hooks)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 363, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 843, in _train_model
    return self._train_model_default(input_fn, hooks, saving_listeners)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 853, in _train_model_default
    input_fn, model_fn_lib.ModeKeys.TRAIN))
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 691, in _get_features_and_labels_from_input_fn
    result = self._call_input_fn(input_fn, mode)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 798, in _call_input_fn
    return input_fn(**kwargs)
  File "C:\tensorflow\models\research\object_detection\inputs.py", line 504, in _train_input_fn
    params=params)
  File "C:\tensorflow\models\research\object_detection\inputs.py", line 607, in train_input
    batch_size=params['batch_size'] if params else train_config.batch_size)
  File "C:\tensorflow\models\research\object_detection\builders\dataset_builder.py", line 130, in build
    num_additional_channels=input_reader_config.num_additional_channels)
  File "C:\tensorflow\models\research\object_detection\data_decoders\tf_example_decoder.py", line 319, in __init__
    default_value=''),
  File "C:\tensorflow\models\research\object_detection\data_decoders\tf_example_decoder.py", line 64, in __init__
    label_map_proto_file, use_display_name=False)
  File "C:\tensorflow\models\research\object_detection\utils\label_map_util.py", line 172, in get_label_map_dict
    label_map = load_labelmap(label_map_path_or_proto)
  File "C:\tensorflow\models\research\object_detection\utils\label_map_util.py", line 139, in load_labelmap
    label_map_string = fid.read()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 120, in read
    self._preread_check()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 80, in _preread_check
    compat.as_bytes(self.__name), 1024 * 512, status)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 519, in __exit__
    c_api.TF_GetCode(self.status.status))
esearch\object_detection        raining\labelmap.pbtxt : The filename, directory name, or volume label syntax is incorrect.odels
; Unknown error**
</code>```

I've tried both train.py and model_main.py as I'm running on tensorflow-gpu 1.8 through anaconda.

in the training folder labelmap.pbtxt does exist I'm not sure why it is trying to find "raining\labelmap.pbtxt"

答: Replace backslash (\) with forward (/) in the file path you specified. It worked for me.</p>

Body:
I've been following this guide on github with a couple of changes since I'm using the ssdlite_mobilenet_v2_coco model and I'm getting an unkown error.

https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10

message:

**Traceback (most recent call last):
  File "model_main.py", line 109, in <module>
    tf.app.run()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 126, in run
    _sys.exit(main(argv))
  File "model_main.py", line 105, in main
    tf.estimator.train_and_evaluate(estimator, train_spec, eval_specs[0])
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\training.py", line 439, in train_and_evaluate
    executor.run()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\training.py", line 518, in run
    self.run_local()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\training.py", line 650, in run_local
    hooks=train_hooks)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 363, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 843, in _train_model
    return self._train_model_default(input_fn, hooks, saving_listeners)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 853, in _train_model_default
    input_fn, model_fn_lib.ModeKeys.TRAIN))
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 691, in _get_features_and_labels_from_input_fn
    result = self._call_input_fn(input_fn, mode)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\estimator\estimator.py", line 798, in _call_input_fn
    return input_fn(**kwargs)
  File "C:\tensorflow\models\research\object_detection\inputs.py", line 504, in _train_input_fn
    params=params)
  File "C:\tensorflow\models\research\object_detection\inputs.py", line 607, in train_input
    batch_size=params['batch_size'] if params else train_config.batch_size)
  File "C:\tensorflow\models\research\object_detection\builders\dataset_builder.py", line 130, in build
    num_additional_channels=input_reader_config.num_additional_channels)
  File "C:\tensorflow\models\research\object_detection\data_decoders\tf_example_decoder.py", line 319, in __init__
    default_value=''),
  File "C:\tensorflow\models\research\object_detection\data_decoders\tf_example_decoder.py", line 64, in __init__
    label_map_proto_file, use_display_name=False)
  File "C:\tensorflow\models\research\object_detection\utils\label_map_util.py", line 172, in get_label_map_dict
    label_map = load_labelmap(label_map_path_or_proto)
  File "C:\tensorflow\models\research\object_detection\utils\label_map_util.py", line 139, in load_labelmap
    label_map_string = fid.read()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 120, in read
    self._preread_check()
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 80, in _preread_check
    compat.as_bytes(self.__name), 1024 * 512, status)
  File "C:\Users\luke9\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 519, in __exit__
    c_api.TF_GetCode(self.status.status))
esearch\object_detection        raining\labelmap.pbtxt : The filename, directory name, or volume label syntax is incorrect.odels
; Unknown error**

I've tried both train.py and model_main.py as I'm running on tensorflow-gpu 1.8 through anaconda.

in the training folder labelmap.pbtxt does exist I'm not sure why it is trying to find "raining\labelmap.pbtxt"


问:
Moving objects together
Write a public instance method move() that takes two integer arguments representing the amount by which to change the values of the instance variables xPos and yPos. The method should return no value. It should make use of the provided method delay() to pause so that the effects of running the method repeatedly are visible, e.g. this.delay(20);

pauses execution for 20 ms.

Test your code by moving an instance of StickFigure and checking that it remains aligned.

My code I have is below but I cannot seem to figure out on how to move all 3 shapes together, only the triangle seems to move.

```<code>public class StickFigure
{
   /*Instance variables*/
   private int xPos;//The horizontal position of a StickFigure
   private int yPos;//The vertical position of a StickFigure
   private Circle head;
   private Triangle body;
   private Rectangle leg;
   //   add your declarations here for part (a)(i)

   /**
    * Constructor for objects of class StickFigure that
    * provides a default stick figure near the bottom left corner of the graphical display.
    *
    */
   public StickFigure()
   {
      super();
      this.head = new Circle (30, OUColour.PINK);
      this.body = new Triangle (50, 50, OUColour.RED);
      this.leg = new Rectangle (6, 50, OUColour.PINK);
      this.setXPos(25);  //sets starting position towards bottom left of Shapes window
      this.setYPos(220);
      this.alignAll();
   }

   /**
    * Sets the xPos of the receiver to the value of the argument.
    */
   public void setXPos(int newPos)
   {
      this.xPos = newPos;
      this.body.setXPos(newPos);
      this.alignAll();
      //part (b)(iii)
   }

   /**
    * Returns the xPos of the receiver.
    */
   public int getXPos()
   {
      return this.xPos;
   }

   /**
    * Sets the yPos of the receiver to the value of the argument.
    */
   public void setYPos(int newPos)
   {
      this.yPos = newPos;
      this.body.setYPos(newPos);
      this.alignAll();

      //part (b)(iii)
   }

   /**
    * Returns the yPos of the receiver.
    */
   public int getYPos()
   {
      return this.yPos;
   }

   /**You will need to uncomment these methods when directed to*******/

   /**
    * Returns a reference to the head of the receiver.
    */
   public Circle getHead()
   {
      return this.head;
   }

   /**
    * Returns a reference to the body of the receiver.
    */
   public Triangle getBody()
   {
      return this.body;
   }

   /**
    * Returns a reference to the leg of the receiver.
    */
   public Rectangle getLeg()
   {
      return this.leg;
   }

   /**
    * Aligns the head of the receiver relative to the xPos and yPos of the body.
    */
   public void alignHead()
   {
      this.head.setXPos(this.body.getXPos() + (this.body.getWidth() - this.head.getDiameter())/2);
      this.head.setYPos(this.body.getYPos() - this.head.getDiameter());
   }

   /**
    * Aligns the body of the receiver relative to the xPos and yPos of the head.
    */
   public void alignBody()
   {
      this.body.setXPos(25);
      this.body.setYPos(220);
   }

   /**
    * Aligns the leg of the receiver relative to the xPos and yPos of the head and body.
    */
   public void alignLeg()
   {
      this.leg.setXPos(this.body.getXPos() + (this.body.getWidth() - this.leg.getWidth())/2);
      this.leg.setYPos(this.body.getYPos() + this.leg.getHeight());
   }

   /**
    * Aligns all the body parts of the receiver to form the
    * StickFigure-type figure.
    */

   public void alignAll()
   {
      this.alignBody();
      this.alignHead();
      this.alignLeg();
   }

   public void move(int xPos, int yPos)
   {
      this.alignAll();
      this.body.setXPos(xPos + xPos);
      this.body.setYPos(yPos + yPos);
      this.delay(20);

   }
</code>```

答:
Shouldn't your move() set the xPos and yPos. so:

```<code> this.body.setXPos(xPos + xPos);
 this.body.setYPos(yPos + yPos);
</code>```

should be

```<code> this.setXPos(this.xPos + xPos);
 this.setYPos(this.yPos + yPos);
</code>```

followed by alignAll()

Then your alignBody() says: "Aligns the body of the receiver relative to the xPos and yPos of the head" but your method doesn't do that ...
It seems the head/leg are relative to body. So maybe the bodies X, Y should be relative to the xPos and yPos?

Title: Moving objects together

Body:
Write a public instance method move() that takes two integer arguments representing the amount by which to change the values of the instance variables xPos and yPos. The method should return no value. It should make use of the provided method delay() to pause so that the effects of running the method repeatedly are visible, e.g. this.delay(20);

pauses execution for 20 ms.

Test your code by moving an instance of StickFigure and checking that it remains aligned.

My code I have is below but I cannot seem to figure out on how to move all 3 shapes together, only the triangle seems to move.

public class StickFigure
{
   /*Instance variables*/
   private int xPos;//The horizontal position of a StickFigure
   private int yPos;//The vertical position of a StickFigure
   private Circle head;
   private Triangle body;
   private Rectangle leg;
   //   add your declarations here for part (a)(i)

   /**
    * Constructor for objects of class StickFigure that
    * provides a default stick figure near the bottom left corner of the graphical display.
    *
    */
   public StickFigure()
   {
      super();
      this.head = new Circle (30, OUColour.PINK);
      this.body = new Triangle (50, 50, OUColour.RED);
      this.leg = new Rectangle (6, 50, OUColour.PINK);
      this.setXPos(25);  //sets starting position towards bottom left of Shapes window
      this.setYPos(220);
      this.alignAll();
   }

   /**
    * Sets the xPos of the receiver to the value of the argument.
    */
   public void setXPos(int newPos)
   {
      this.xPos = newPos;
      this.body.setXPos(newPos);
      this.alignAll();
      //part (b)(iii)
   }

   /**
    * Returns the xPos of the receiver.
    */
   public int getXPos()
   {
      return this.xPos;
   }

   /**
    * Sets the yPos of the receiver to the value of the argument.
    */
   public void setYPos(int newPos)
   {
      this.yPos = newPos;
      this.body.setYPos(newPos);
      this.alignAll();

      //part (b)(iii)
   }

   /**
    * Returns the yPos of the receiver.
    */
   public int getYPos()
   {
      return this.yPos;
   }

   /**You will need to uncomment these methods when directed to*******/

   /**
    * Returns a reference to the head of the receiver.
    */
   public Circle getHead()
   {
      return this.head;
   }

   /**
    * Returns a reference to the body of the receiver.
    */
   public Triangle getBody()
   {
      return this.body;
   }

   /**
    * Returns a reference to the leg of the receiver.
    */
   public Rectangle getLeg()
   {
      return this.leg;
   }

   /**
    * Aligns the head of the receiver relative to the xPos and yPos of the body.
    */
   public void alignHead()
   {
      this.head.setXPos(this.body.getXPos() + (this.body.getWidth() - this.head.getDiameter())/2);
      this.head.setYPos(this.body.getYPos() - this.head.getDiameter());
   }

   /**
    * Aligns the body of the receiver relative to the xPos and yPos of the head.
    */
   public void alignBody()
   {
      this.body.setXPos(25);
      this.body.setYPos(220);
   }

   /**
    * Aligns the leg of the receiver relative to the xPos and yPos of the head and body.
    */
   public void alignLeg()
   {
      this.leg.setXPos(this.body.getXPos() + (this.body.getWidth() - this.leg.getWidth())/2);
      this.leg.setYPos(this.body.getYPos() + this.leg.getHeight());
   }

   /**
    * Aligns all the body parts of the receiver to form the
    * StickFigure-type figure.
    */

   public void alignAll()
   {
      this.alignBody();
      this.alignHead();
      this.alignLeg();
   }

   public void move(int xPos, int yPos)
   {
      this.alignAll();
      this.body.setXPos(xPos + xPos);
      this.body.setYPos(yPos + yPos);
      this.delay(20);

   }

Body:
Shouldn't your move() set the xPos and yPos. so:

 this.body.setXPos(xPos + xPos);
 this.body.setYPos(yPos + yPos);

should be

 this.setXPos(this.xPos + xPos);
 this.setYPos(this.yPos + yPos);

followed by alignAll()

Then your alignBody() says: "Aligns the body of the receiver relative to the xPos and yPos of the head" but your method doesn't do that ...
It seems the head/leg are relative to body. So maybe the bodies X, Y should be relative to the xPos and yPos?


问:
Spring security 5 api key filter
I'm trying to create a filter with spring security 5 and boot 2 that protects some but no all endpoints with an API Key and without sessions.
However after the filter authenticates it tires to redirect to "/" instead of the original url as SavedRequestAwareAuthenticationSuccessHandler has an empy request cache and falls back to the default "/".

How can I make it to carry on to the targeted resource instead of '/' and why it worked like this?

I'd also appreciate if someone could explain to me why AbstractPreAuthenticatedProcessingFilter is designed to carry on with the filter chain after a sucessfull authentication but AbstractAuthenticationProcessingFilter is not.

This is the security config class:

@Configuration
@Order(SecurityProperties.BASIC_AUTH_ORDER - 10)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${secret.admin.api.key}")
    String validApiKey;

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.authenticationProvider(new ApiKeyAuthenticationProvider(validApiKey));
    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security
            .csrf().disable()
            .sessionManagement()
                .sessionCreationPolicy(STATELESS)
                .and()
            .addFilterBefore(new ApiKeyAuthenticationFilter(authenticationManager()), AnonymousAuthenticationFilter.class)
            .requestMatchers()
                .antMatchers("/v1/admin/**")
                .antMatchers("/actuator/**")
                .and()
            .authorizeRequests().anyRequest().authenticated();
    }

}

```

<p>My filter matches requests that have Authorization header with a custom value. Extracts the api key from the header and passes the token with the principal and credentials(api key) to the authentication manager.</p>

<pre class="lang-java prettyprint-override"><code>public class ApiKeyAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

//...

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
        var apiKey = extractApiKey(request.getHeader(AUTHORIZATION));
        var token = new ApiKeyAuthenticationToken(apiKey);
        var authentication = getAuthenticationManager().authenticate(token);
        return authentication;
    }

//...
}
</code>```

The following class validates the credentials and creates and authenticated token with a principal  and without credentials:

public class ApiKeyAuthenticationProvider implements AuthenticationProvider {

// ...

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        var apiKey = (String) authentication.getCredentials();
        if (validApiKey.equals(apiKey)) {
            var auth = new ApiKeyAuthenticationToken();
            auth.setAuthenticated(true);
            return auth;
        } else {
            throw new BadCredentialsException("Bad ApiKey credentials");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return ApiKeyAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
```

<p>And the logs:</p>

```OrRequestMatcher: Trying to match using Ant [pattern='/v1/admin/**']
AntPathRequestMatcher: Checking match of request : '/v1/admin/namespace'; against '/v1/admin/**'
OrRequestMatcher: matched
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
[...]
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 5 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 6 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 7 of 11 in additional filter chain; firing Filter: 'ApiKeyAuthenticationFilter'
ProviderManager: Authentication attempt using ....security.ApiKeyAuthenticationProvider
AbstractAuthenticationTargetUrlRequestHandler: Using default Url: /
DefaultRedirectStrategy: Redirecting to '/'
```

I tried to make this work based on this.

答:
I had to override the successfulAuthentication method in the filter and continue the chain to make it work.

@Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain, Authentication authResult) throws IOException, ServletException {

        log.info("Successful authentication");
        SecurityContextHolder.getContext().setAuthentication(authResult);
        chain.doFilter(request,response);
    }
```

Title: Spring security 5 api key filter

Body:
I'm trying to create a filter with spring security 5 and boot 2 that protects some but no all endpoints with an API Key and without sessions.
However after the filter authenticates it tires to redirect to "/" instead of the original url as SavedRequestAwareAuthenticationSuccessHandler has an empy request cache and falls back to the default "/".

How can I make it to carry on to the targeted resource instead of '/' and why it worked like this?

I'd also appreciate if someone could explain to me why AbstractPreAuthenticatedProcessingFilter is designed to carry on with the filter chain after a sucessfull authentication but AbstractAuthenticationProcessingFilter is not.

This is the security config class:

@Configuration
@Order(SecurityProperties.BASIC_AUTH_ORDER - 10)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${secret.admin.api.key}")
    String validApiKey;

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.authenticationProvider(new ApiKeyAuthenticationProvider(validApiKey));
    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security
            .csrf().disable()
            .sessionManagement()
                .sessionCreationPolicy(STATELESS)
                .and()
            .addFilterBefore(new ApiKeyAuthenticationFilter(authenticationManager()), AnonymousAuthenticationFilter.class)
            .requestMatchers()
                .antMatchers("/v1/admin/**")
                .antMatchers("/actuator/**")
                .and()
            .authorizeRequests().anyRequest().authenticated();
    }

}

My filter matches requests that have Authorization header with a custom value. Extracts the api key from the header and passes the token with the principal and credentials(api key) to the authentication manager.

public class ApiKeyAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

//...

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
        var apiKey = extractApiKey(request.getHeader(AUTHORIZATION));
        var token = new ApiKeyAuthenticationToken(apiKey);
        var authentication = getAuthenticationManager().authenticate(token);
        return authentication;
    }

//...
}

The following class validates the credentials and creates and authenticated token with a principal  and without credentials:

public class ApiKeyAuthenticationProvider implements AuthenticationProvider {

// ...

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        var apiKey = (String) authentication.getCredentials();
        if (validApiKey.equals(apiKey)) {
            var auth = new ApiKeyAuthenticationToken();
            auth.setAuthenticated(true);
            return auth;
        } else {
            throw new BadCredentialsException("Bad ApiKey credentials");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return ApiKeyAuthenticationToken.class.isAssignableFrom(authentication);
    }

}

And the logs:

OrRequestMatcher: Trying to match using Ant [pattern='/v1/admin/**']
AntPathRequestMatcher: Checking match of request : '/v1/admin/namespace'; against '/v1/admin/**'
OrRequestMatcher: matched
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
[...]
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 5 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 6 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
FilterChainProxy$VirtualFilterChain: /v1/admin/namespace at position 7 of 11 in additional filter chain; firing Filter: 'ApiKeyAuthenticationFilter'
ProviderManager: Authentication attempt using ....security.ApiKeyAuthenticationProvider
AbstractAuthenticationTargetUrlRequestHandler: Using default Url: /
DefaultRedirectStrategy: Redirecting to '/'

I tried to make this work based on this.


问:
ngOnit not getting triggerd
I have two components : TileComponent.ts and FullScreenComponent.ts.

On clicking the TileComponent, the FullScreenComponent opens up. In the TileComponent,I have the following code. ngOnInit() method gets triggered whenever the TileComponent loads.

TileComponent.ts:

```<code>ngOnInit() {
    console.log("TileCompnent :ngOnInit");

    this.crossDomainService.globalSelectors.subscribe(selectors => {
      globalCountries = selectors.jurisdiction || [];
      this.getArticles(globalCountries);
    });

    // Multiple Language
    this.crossDomainService.globalLanguage.subscribe(() => {
      console.log("TileCompnent :ngOnInit : crossDomainService");
      this.getArticles(globalCountries || countries);
    });
  }
</code>```

Now on closing the FullScreenComponent leads to the loading of the TileComponent but this time I see that ngOnInit() method is not getting triggered.

Can anyone help me to know any reason this is not working?

tile.component.html:

```<code><div class="carousel-inner">
      <a
        (click)="openFullScreen(article)"
        *ngFor="let article of articles"
        [ngClass]="getItemClassNames(article)"
        class="item"
      >
</div>
</code>```

tile.component.ts

```<code>ngOnInit() {
    console.log("TileCompnent :ngOnInit");
    const countries =
      this.crossDomainService.initialGlobalSelectors &&
      this.crossDomainService.initialGlobalSelectors.jurisdiction.length
        ? this.crossDomainService.initialGlobalSelectors.jurisdiction
        : [];
    this.getArticles(countries);

    let globalCountries;

    this.crossDomainService.globalSelectors.subscribe(selectors => {
      globalCountries = selectors.jurisdiction || [];
      this.getArticles(globalCountries);
    });

    // Multiple Language
    this.crossDomainService.globalLanguage.subscribe(() => {
      console.log("TileCompnent :ngOnInit : crossDomainService");
      this.getArticles(globalCountries || countries);
    });
  }
    openFullScreen(article: ArticlePreview) {
        this.crossDomainService.openFullScreen(article);
      }
</code>```

full-screen.component.html:

```<code><div class="layout-center-wrapper" [hidden]="isPolicyShown">
  <app-header></app-header>

  <div class="row wrapper">
    <app-sidebar></app-sidebar>
    <router-outlet></router-outlet>
  </div>
</div>

<app-policy [hidden]="!isPolicyShown"></app-policy>
</code>```

header.component.html:

```<code><header class="row header">
  <p class="header__title">
    Application Name
    <a (click)="closeFullScreen()" class="header__close">
      <span class="icon icon_close"></span>
    </a>
  </p>
</header>
</code>```

header.component.ts:

```<code>import { Component } from '@angular/core';
import { CrossDomainService } from '../../core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.less']
})
export class HeaderComponent {
  constructor(private crossDomainService: CrossDomainService, private analyticsService: AnalyticsService) {}

  closeFullScreen() {
    this.crossDomainService.closeFullScreen();
  }
}
</code>```

答:
One of the simple workaround would be to use changedetectorRef to hook up the initial state of component.

```<code>`import { Component, OnInit, ChangeDetectorRef } from '@angular/core';`
</code>```

and insert it in constructor and you can keep OnInit function blank

constructor(){
 this.changeDetectorRef.detectChanges();}

Title: ngOnit not getting triggerd

Body:
I have two components : TileComponent.ts and FullScreenComponent.ts.

On clicking the TileComponent, the FullScreenComponent opens up. In the TileComponent,I have the following code. ngOnInit() method gets triggered whenever the TileComponent loads.

TileComponent.ts:

ngOnInit() {
    console.log("TileCompnent :ngOnInit");

    this.crossDomainService.globalSelectors.subscribe(selectors => {
      globalCountries = selectors.jurisdiction || [];
      this.getArticles(globalCountries);
    });

    // Multiple Language
    this.crossDomainService.globalLanguage.subscribe(() => {
      console.log("TileCompnent :ngOnInit : crossDomainService");
      this.getArticles(globalCountries || countries);
    });
  }

Now on closing the FullScreenComponent leads to the loading of the TileComponent but this time I see that ngOnInit() method is not getting triggered.

Can anyone help me to know any reason this is not working?

tile.component.html:

tile.component.ts

ngOnInit() {
    console.log("TileCompnent :ngOnInit");
    const countries =
      this.crossDomainService.initialGlobalSelectors &&
      this.crossDomainService.initialGlobalSelectors.jurisdiction.length
        ? this.crossDomainService.initialGlobalSelectors.jurisdiction
        : [];
    this.getArticles(countries);

    let globalCountries;

    this.crossDomainService.globalSelectors.subscribe(selectors => {
      globalCountries = selectors.jurisdiction || [];
      this.getArticles(globalCountries);
    });

    // Multiple Language
    this.crossDomainService.globalLanguage.subscribe(() => {
      console.log("TileCompnent :ngOnInit : crossDomainService");
      this.getArticles(globalCountries || countries);
    });
  }
    openFullScreen(article: ArticlePreview) {
        this.crossDomainService.openFullScreen(article);
      }

full-screen.component.html:

  <app-header></app-header>

    <app-sidebar></app-sidebar>
    <router-outlet></router-outlet>

<app-policy [hidden]="!isPolicyShown"></app-policy>

header.component.html:

    Application Name

header.component.ts:

import { Component } from '@angular/core';
import { CrossDomainService } from '../../core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.less']
})
export class HeaderComponent {
  constructor(private crossDomainService: CrossDomainService, private analyticsService: AnalyticsService) {}

  closeFullScreen() {
    this.crossDomainService.closeFullScreen();
  }
}

Body:
One of the simple workaround would be to use changedetectorRef to hook up the initial state of component.

`import { Component, OnInit, ChangeDetectorRef } from '@angular/core';`

and insert it in constructor and you can keep OnInit function blank

constructor(){
 this.changeDetectorRef.detectChanges();}


答:
Here you can use below script. INNER JOIN can be used for filtering a query.

```<code>SELECT A.SUPPLIER, A.PRODUCT, A.QUANTITY
  FROM (SELECT A.SUPPLIER, A.PRODUCT, A.QUANTITY
         FROM PRODUCTS A) A
   INNER JOIN (SELECT DISTINCT SUPPLIER
                 FROM PRODUCTS
                WHERE PRODUCT = "Product B") B
      ON B.SUPPLIER = A.SUPPLIER
</code>```

sqlfiddle demo

Title: Use results from first query as criteria for second query

Body:
Here you can use below script. INNER JOIN can be used for filtering a query.

SELECT A.SUPPLIER, A.PRODUCT, A.QUANTITY
  FROM (SELECT A.SUPPLIER, A.PRODUCT, A.QUANTITY
         FROM PRODUCTS A) A
   INNER JOIN (SELECT DISTINCT SUPPLIER
                 FROM PRODUCTS
                WHERE PRODUCT = "Product B") B
      ON B.SUPPLIER = A.SUPPLIER

sqlfiddle demo


问:
response query works in shell but in code gives a SyntaxError: invalid syntax
If I do

```<code>scrapy shell https://en.wikipedia.org/wiki/Electric_battery
</code>```

and then

```<code>response.css('h1#firstHeading::text').extract()
</code>```

i get the correct output of

```<code>['Electric battery']
</code>```

But if I make this python code ;

```<code>import scrapy

class WikiSpider(scrapy.Spider):
    name = 'wiki'
    allowed_domains = ['wikipedia.com']
    start_urls = ['https://en.wikipedia.org/wiki/Electric_battery']

    def parse(self, response):
        print response.css('h1#firstHeading::text').extract()
</code>```

and I run it I get the error message

```<code>C:\python\wikipedia>scrapy runspider wiki
Traceback (most recent call last):
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\thega\AppData\Local\Programs\Python\Python38-32\Scripts\scrapy.exe\__main__.py", line 7, in <module>
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\cmdline.py", line 145, in execute
    cmd.crawler_process = CrawlerProcess(settings)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\crawler.py", line 267, in __init__
    super(CrawlerProcess, self).__init__(settings)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\crawler.py", line 145, in __init__
    self.spider_loader = _get_spider_loader(settings)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\crawler.py", line 347, in _get_spider_loader
    return loader_cls.from_settings(settings.frozencopy())
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\spiderloader.py", line 61, in from_settings
    return cls(settings)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\spiderloader.py", line 25, in __init__
    self._load_all_spiders()
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\spiderloader.py", line 47, in _load_all_spiders
    for module in walk_modules(name):
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\utils\misc.py", line 73, in walk_modules
    submod = import_module(fullpath)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 779, in exec_module
  File "<frozen importlib._bootstrap_external>", line 916, in get_code
  File "<frozen importlib._bootstrap_external>", line 846, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\python\wikipedia\wikipedia\spiders\wiki.py", line 11
    print response.css('h1#firstHeading::text').extract()
          ^
SyntaxError: invalid syntax
</code>```

I am taking the code from a tutorial at https://www.makeuseof.com/tag/build-basic-web-crawler-pull-information-website-2/

I'm confused how the syntax is wrong when it's been tested as working in shell???

答:
you are writing the code for python 2 but running it in python 3 you are missing the brackets,here is the way to do it</p>

```<code>import scrapy

class WikiSpider(scrapy.Spider):
    name = 'wiki'
    allowed_domains = ['wikipedia.com']
    start_urls = ['https://en.wikipedia.org/wiki/Electric_battery']

    def parse(self, response):
        print(response.css('h1#firstHeading::text').extract())
</code>```

Body:
If I do

scrapy shell https://en.wikipedia.org/wiki/Electric_battery

and then

response.css('h1#firstHeading::text').extract()

i get the correct output of

['Electric battery']

But if I make this python code ;

import scrapy

class WikiSpider(scrapy.Spider):
    name = 'wiki'
    allowed_domains = ['wikipedia.com']
    start_urls = ['https://en.wikipedia.org/wiki/Electric_battery']

    def parse(self, response):
        print response.css('h1#firstHeading::text').extract()

and I run it I get the error message

C:\python\wikipedia>scrapy runspider wiki
Traceback (most recent call last):
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\thega\AppData\Local\Programs\Python\Python38-32\Scripts\scrapy.exe\__main__.py", line 7, in <module>
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\cmdline.py", line 145, in execute
    cmd.crawler_process = CrawlerProcess(settings)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\crawler.py", line 267, in __init__
    super(CrawlerProcess, self).__init__(settings)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\crawler.py", line 145, in __init__
    self.spider_loader = _get_spider_loader(settings)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\crawler.py", line 347, in _get_spider_loader
    return loader_cls.from_settings(settings.frozencopy())
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\spiderloader.py", line 61, in from_settings
    return cls(settings)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\spiderloader.py", line 25, in __init__
    self._load_all_spiders()
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\spiderloader.py", line 47, in _load_all_spiders
    for module in walk_modules(name):
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\site-packages\scrapy\utils\misc.py", line 73, in walk_modules
    submod = import_module(fullpath)
  File "c:\users\thega\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 779, in exec_module
  File "<frozen importlib._bootstrap_external>", line 916, in get_code
  File "<frozen importlib._bootstrap_external>", line 846, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\python\wikipedia\wikipedia\spiders\wiki.py", line 11
    print response.css('h1#firstHeading::text').extract()
          ^
SyntaxError: invalid syntax

I am taking the code from a tutorial at https://www.makeuseof.com/tag/build-basic-web-crawler-pull-information-website-2/

I'm confused how the syntax is wrong when it's been tested as working in shell???

Body:
you are writing the code for python 2 but running it in python 3 you are missing the brackets,here is the way to do it

import scrapy

class WikiSpider(scrapy.Spider):
    name = 'wiki'
    allowed_domains = ['wikipedia.com']
    start_urls = ['https://en.wikipedia.org/wiki/Electric_battery']

    def parse(self, response):
        print(response.css('h1#firstHeading::text').extract())


问:
Angular 4 - Could not resolve submodule for routing
I'm building a webapp with Angular 4. I have a top-level routing module and a separate routing module for each submodule (e.g. HomeModule).

This is my top-level routing configuration:

```<code>export const ROUTES: Routes = [
  {path: '', loadChildren: './home#HomeModule'},
  {path: '**', component: NotFoundComponent},
];
</code>```

When I run ng server, I get a strange error, that module home was not found. The app does not work in the browser.

The strange part is the following: When a file is changed and webpack recompiles the project, everything works just fine and the routing works.

The error does only appear when I'm running ng serve.

This is the error I get when I'm running ng serve, not when the project is recompiled because of a file change:

```<code>ERROR in Error: Could not resolve module ./home relative to /path/to/my/project/src/app/app.module.ts
    at StaticSymbolResolver.getSymbolByModule (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:31884:30)
    at StaticReflector.resolveExternalReference (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:30350:62)
    at parseLazyRoute (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:28616:55)
    at listLazyRoutes (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:28578:36)
    at visitLazyRoute (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:29995:47)
    at AotCompiler.listLazyRoutes (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:29963:20)
    at AngularCompilerProgram.listLazyRoutes (/path/to/my/project/node_modules/@angular/compiler-cli/src/transformers/program.js:157:30)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (/path/to/my/project/node_modules/@angular/compiler-cli/src/ngtools_api.js:44:36)
    at AngularCompilerPlugin._getLazyRoutesFromNgtools (/path/to/my/project/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:247:66)
    at Promise.resolve.then.then (/path/to/my/project/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:538:50)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
</code>```

Thanks in advance.

答:
I had a similar problem which took days to resolve but I ended up going back to recheck the structure of each statement/path. Below is what I had before:

```<code>      {
    path: 'payments',
    loadChildren: './pages/service-payments/service-payments.module#ServicePaymentsPageModule'
  }
</code>```

I then changed the path as below:

```<code>      {
    path: 'payments',
    loadChildren: '../service-payments/service-payments.module#ServicePaymentsPageModule'
  }
</code>```

I hope it helps somebody in the future.

Body:
I'm building a webapp with Angular 4. I have a top-level routing module and a separate routing module for each submodule (e.g. HomeModule).

This is my top-level routing configuration:

export const ROUTES: Routes = [
  {path: '', loadChildren: './home#HomeModule'},
  {path: '**', component: NotFoundComponent},
];

When I run ng server, I get a strange error, that module home was not found. The app does not work in the browser.

The strange part is the following: When a file is changed and webpack recompiles the project, everything works just fine and the routing works.

The error does only appear when I'm running ng serve.

This is the error I get when I'm running ng serve, not when the project is recompiled because of a file change:

ERROR in Error: Could not resolve module ./home relative to /path/to/my/project/src/app/app.module.ts
    at StaticSymbolResolver.getSymbolByModule (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:31884:30)
    at StaticReflector.resolveExternalReference (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:30350:62)
    at parseLazyRoute (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:28616:55)
    at listLazyRoutes (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:28578:36)
    at visitLazyRoute (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:29995:47)
    at AotCompiler.listLazyRoutes (/path/to/my/project/node_modules/@angular/compiler/bundles/compiler.umd.js:29963:20)
    at AngularCompilerProgram.listLazyRoutes (/path/to/my/project/node_modules/@angular/compiler-cli/src/transformers/program.js:157:30)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (/path/to/my/project/node_modules/@angular/compiler-cli/src/ngtools_api.js:44:36)
    at AngularCompilerPlugin._getLazyRoutesFromNgtools (/path/to/my/project/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:247:66)
    at Promise.resolve.then.then (/path/to/my/project/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:538:50)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

Thanks in advance.

Body:
I had a similar problem which took days to resolve but I ended up going back to recheck the structure of each statement/path. Below is what I had before:

      {
    path: 'payments',
    loadChildren: './pages/service-payments/service-payments.module#ServicePaymentsPageModule'
  }

I then changed the path as below:

      {
    path: 'payments',
    loadChildren: '../service-payments/service-payments.module#ServicePaymentsPageModule'
  }

I hope it helps somebody in the future.


问:
What does "CONST func(arg);" mean in C language?
This is a c program demonstrating some basic usage of the libxml2 library.  Below is quoted from the main function:

```<code>LIBXML_TEST_VERSION example1Func(argv[1]);
</code>```

What does this statement stand for?

I can only tell that LIBXML_TEST_VERSION is obviously a constant, and after that is a function call, that function returns nothing (void). But I've no idea what it means the statement in whole.

答:
It appears as though LIBXML_TEST_VERSION is a macro that expands to one or more statements. From Google code search, it appears the definition is something like:

```<code>#define LIBXML_TEST_VERSION xmlCheckVersion(20703);
</code>```

where 20703 is whatever version you're compiling against.

This statement is independent from the call to example1Func().

Body:
This is a c program demonstrating some basic usage of the libxml2 library.  Below is quoted from the main function:

LIBXML_TEST_VERSION example1Func(argv[1]);

What does this statement stand for?

I can only tell that LIBXML_TEST_VERSION is obviously a constant, and after that is a function call, that function returns nothing (void). But I've no idea what it means the statement in whole.

Body:
It appears as though LIBXML_TEST_VERSION is a macro that expands to one or more statements. From Google code search, it appears the definition is something like:

#define LIBXML_TEST_VERSION xmlCheckVersion(20703);

where 20703 is whatever version you're compiling against.

This statement is independent from the call to example1Func().