问:
C++ Iterating through map from pointer
I want to iterate through a map, which address is stored in a pointer, so I can access and modify the original map, however whenever I try to iterate, it always gives me a read access violation.

```<code>#include <map>

template<typename A, typename B>
class map_array_util
{
public:
map_array_util(std::map<A,B> _m)
{
    m = &_m;
}

void copy(B *arr, int size)
{

}

bool equals(B *arr, int size) const
{
    int i = 0;
    for (auto it = (*m).begin(); it != (*m).end(); ++it)
    {
        std::pair<A, B> p = *it;
        if (*(arr + i) != p.second)
        {
            return false;
        }
        i++;
    }

    return true;
}
private:
std::map<A, B> *m;
};
</code>```

How do we iterate in the correct way?

答:
You store address of local copy with

```<code>map_array_util(std::map<A,B> _m)
{
    m = &_m;
}
</code>```

So you have dangling pointer.

You probably want to pass by reference:

```<code>map_array_util(std::map<A,B>& _m) : m(&_m) {}
</code>```

Title: C++ Iterating through map from pointer

Body:
I want to iterate through a map, which address is stored in a pointer, so I can access and modify the original map, however whenever I try to iterate, it always gives me a read access violation.

#include <map>

template<typename A, typename B>
class map_array_util
{
public:
map_array_util(std::map _m)
{
    m = &_m;
}

void copy(B *arr, int size)
{

}

bool equals(B *arr, int size) const
{
    int i = 0;
    for (auto it = (*m).begin(); it != (*m).end(); ++it)
    {
        std::pair p = *it;
        if (*(arr + i) != p.second)
        {
            return false;
        }
        i++;
    }

    return true;
}
private:
std::map *m;
};

How do we iterate in the correct way?

Body:
You store address of local copy with

map_array_util(std::map<A,B> _m)
{
    m = &_m;
}

So you have dangling pointer.

You probably want to pass by reference:

map_array_util(std::map<A,B>& _m) : m(&_m) {}


来源: stackexchange

问:
dplyr sample_n by one variable through another one
I have a data frame with a "grouping" variable season and another variable year which is repeated for each month.

```<code>df <- data.frame(month = as.character(sapply(month.name,function(x)rep(x,4))),
                  season = c(rep("winter",8),rep("spring",12),rep("summer",12),rep("autumn",12),rep("winter",4)),
                  year = rep(2021:2024,12))
</code>```

I would like to use dplyr::sample_n or something similar to choose 2 months in the data frame for each season and keep the same months for all the years, for example:

```<code>     month        season     year
1     January     winter     2021
2     January     winter     2022
3     January     winter     2023
4     January     winter     2024
5     February    winter     2021
6     February    winter     2022
7     February    winter     2023
8     February    winter     2024
9     March       spring     2021
10    March       spring     2022
11    March       spring     2023
12    March       spring     2024
13    May         spring     2021
14    May         spring     2022
15    May         spring     2023
16    May         spring     2024
17    June        summer     2021
18    June        summer     2022
19    June        summer     2023
20    June        summer     2024
21    July        summer     2021
22    July        summer     2022
23    July        summer     2023
24    July        summer     2024
25    October     autumn     2021
26    October     autumn     2022
27    October     autumn     2023
28    October     autumn     2024
29    November    autumn     2021
30    November    autumn     2022
31    November    autumn     2023
32    November    autumn     2024

</code>```

I cannot make df %>% group_by(season,year) %>% sample_n(2) since it chooses different months for each year.

Thanks!

答:
An option using slice

```<code>library(dplyr)
df %>%
   group_by(season) %>%
    slice(which(!is.na(match(month, sample(unique(month), 2)))))
# A tibble: 32 x 3
# Groups:   season [4]
#   month    season  year
#   <fct>    <fct>  <int>
# 1 October  autumn  2021
# 2 October  autumn  2022
# 3 October  autumn  2023
# 4 October  autumn  2024
# 5 November autumn  2021
# 6 November autumn  2022
# 7 November autumn  2023
# 8 November autumn  2024
# 9 April    spring  2021
#10 April    spring  2022
# … with 22 more rows
</code>```

Or using base R

```<code>by(df, df$season, FUN = function(x) subset(x, month %in% sample(unique(month), 2 )))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame with a "grouping" variable season and another variable year which is repeated for each month.

df <- data.frame(month = as.character(sapply(month.name,function(x)rep(x,4))),
                  season = c(rep("winter",8),rep("spring",12),rep("summer",12),rep("autumn",12),rep("winter",4)),
                  year = rep(2021:2024,12))

I would like to use dplyr::sample_n or something similar to choose 2 months in the data frame for each season and keep the same months for all the years, for example:

     month        season     year
1     January     winter     2021
2     January     winter     2022
3     January     winter     2023
4     January     winter     2024
5     February    winter     2021
6     February    winter     2022
7     February    winter     2023
8     February    winter     2024
9     March       spring     2021
10    March       spring     2022
11    March       spring     2023
12    March       spring     2024
13    May         spring     2021
14    May         spring     2022
15    May         spring     2023
16    May         spring     2024
17    June        summer     2021
18    June        summer     2022
19    June        summer     2023
20    June        summer     2024
21    July        summer     2021
22    July        summer     2022
23    July        summer     2023
24    July        summer     2024
25    October     autumn     2021
26    October     autumn     2022
27    October     autumn     2023
28    October     autumn     2024
29    November    autumn     2021
30    November    autumn     2022
31    November    autumn     2023
32    November    autumn     2024

I cannot make df %>% group_by(season,year) %>% sample_n(2) since it chooses different months for each year.

Thanks!

Body:
An option using slice

library(dplyr)
df %>%
   group_by(season) %>%
    slice(which(!is.na(match(month, sample(unique(month), 2)))))
# A tibble: 32 x 3
# Groups:   season [4]
#   month    season  year
#   <fct>    <fct>  <int>
# 1 October  autumn  2021
# 2 October  autumn  2022
# 3 October  autumn  2023
# 4 October  autumn  2024
# 5 November autumn  2021
# 6 November autumn  2022
# 7 November autumn  2023
# 8 November autumn  2024
# 9 April    spring  2021
#10 April    spring  2022
# … with 22 more rows

Or using base R

by(df, df$season, FUN = function(x) subset(x, month %in% sample(unique(month), 2 )))


答:
Instead of map_array_util(std::map _m), you possibly meant

```<code>map_array_util(std::map<A,B> &_m)
//                           ^
</code>```

BTW this class is not a good idea IMO. You can better drive your class from a reference_wrapper.

Title: C++ Iterating through map from pointer

Body:
Instead of map_array_util(std::map<A,B> _m), you possibly meant

map_array_util(std::map<A,B> &_m)
//                           ^

BTW this class is not a good idea IMO. You can better drive your class from a reference_wrapper.


问:
Server hub connection from asp.net core 2.2 signalr console app
I have a server running .net 4.5.1 with SignalR (IIS)

I want to connect to the server using a console client app on .net core 2,2.  I have installed the below Nuget package on the client

Microsoft.AspNetCore.SignalR.Client;

and have followed

https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-2.2

I keep getting the below error

"There was an error opening the connection:System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found)."

The name of my Hub on the server is correct so I'm not sure of the problem

I have also tried

```<code>.WithUrl("http://172.10.0.20:81/client/?hub=myHub")
</code>```

please help

```<code>connection = new HubConnectionBuilder()

//.WithUrl("http://172.10.0.20:81/client/?hub=myHub")

.WithUrl("http://172.10.0.20:81/myHub")

.Build();

connection.StartAsync().ContinueWith(task => {

if (task.IsFaulted)

{Console.WriteLine("There was an error opening the connection:{0}",

task.Exception.GetBaseException());}

else

{Console.WriteLine("Connected");}}).Wait();

connection.StartAsync();
</code>```

答:
thanks that pushed me in the right direction.

I'm using signalR with webforms so the hub is located at

http://172.10.0.20:82/signalr/myHub

After changing path I got the below informative error

```<code>There was an error opening the connection:System.IO.InvalidDataException: Invalid negotiation response received. ---> System.InvalidOperationException: Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server.
</code>```

Body:
I have a server running .net 4.5.1 with SignalR (IIS)

I want to connect to the server using a console client app on .net core 2,2.  I have installed the below Nuget package on the client

Microsoft.AspNetCore.SignalR.Client;

and have followed

https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-2.2

I keep getting the below error

"There was an error opening the connection:System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found)."

The name of my Hub on the server is correct so I'm not sure of the problem

I have also tried

.WithUrl("http://172.10.0.20:81/client/?hub=myHub")

please help

connection = new HubConnectionBuilder()

//.WithUrl("http://172.10.0.20:81/client/?hub=myHub")

.WithUrl("http://172.10.0.20:81/myHub")

.Build();

connection.StartAsync().ContinueWith(task => {

if (task.IsFaulted)

{Console.WriteLine("There was an error opening the connection:{0}",

task.Exception.GetBaseException());}

else

{Console.WriteLine("Connected");}}).Wait();

connection.StartAsync();

Body:
thanks that pushed me in the right direction.

I'm using signalR with webforms so the hub is located at

http://172.10.0.20:82/signalr/myHub

After changing path I got the below informative error

There was an error opening the connection:System.IO.InvalidDataException: Invalid negotiation response received. ---> System.InvalidOperationException: Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server.


问:
Saving timestamp in mysql table using php
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

```<code>INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')
</code>```

答: Better is use datatype varchar(15).

ContentLicense: CC BY-SA 3.0

Body:
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')

Body: Better is use datatype varchar(15).


问:
How to convert month name to month number in a timeseries in DataFrame?
I have a column in my DataFrame with timeseries data as '01-Jun-2018'.
I need to convert the date to format '01-06-2018' for all the other months as well.
What should I do for this using pandas or even without pandas?</p>

答:
First convert column to datetimes and then add Series.dt.strftime for strings in custom format - DD-MM-YYYY:

```<code>df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d-%m-%Y')
</code>```

Or:

```<code>df['Date'] = pd.to_datetime(df['Date'], format='%d-%b-%Y').dt.strftime('%d-%m-%Y')
</code>```

If need datetimes only omit .dt.strftime, but default format is YYYY-MM-DD.

Body:
First convert column to datetimes and then add Series.dt.strftime for strings in custom format - DD-MM-YYYY:

df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d-%m-%Y')

Or:

df['Date'] = pd.to_datetime(df['Date'], format='%d-%b-%Y').dt.strftime('%d-%m-%Y')

If need datetimes only omit .dt.strftime, but default format is YYYY-MM-DD.


问:
How to select the rows by range?
I have following table named 'T'

My desired output should be as following,

I want to select those rows where column 'Actual' should have range between column 'Basic', however if you take example for 'Model' = HT65
'Actual' = 23.2 which has range between 22 & 24 of column 'Basic' so I should get row as following where column 'Level' is 2

Likewise other rows should be selected.
your help would be appreciated.

答:
You can use the following solution using multiple LEFT JOIN to join the next and last row of the current row. With some additional conditions you can check for the range:

```<code>SELECT t1.Model, t1.Level, t1.Basic, t1.Actual
FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
  FROM test
) t1 LEFT JOIN (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
  FROM test
) t2 ON t1.Model = t2.Model AND t1.rn + 1 = t2.rn LEFT JOIN (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
  FROM test
) t3 ON t1.Model = t3.Model AND t1.rn - 1 = t3.rn
WHERE (t1.Actual BETWEEN t3.Basic AND t1.Basic)
  OR (t3.Model IS NULL AND t1.Actual < t1.Basic)
  OR (t2.Model IS NULL AND t1.Actual > t1.Basic)
ORDER BY t1.Model ASC
</code>```

The above query gets all expected rows. I also added some additional cases to improve the query for these (special) cases. The above solution is working with SQL-Server 2008.

Since SQL-Server 2012 you can use the following solution using LAG and LEAD:

```<code>SELECT t.Model, t.Level, t.Basic, t.Actual
FROM (
  SELECT *, LAG(Basic, 1,0) OVER (PARTITION BY Model ORDER BY Basic) AS prevBasic,
    LEAD(Basic, 1, 0) OVER (PARTITION BY Model ORDER BY Basic) AS nextBasic
  FROM test
) t
WHERE (t.Actual BETWEEN t.prevBasic AND t.Basic)
   OR (t.nextBasic = 0 AND t.Actual > t.Basic)
ORDER BY t.Model ASC
</code>```

demo on dbfiddle.uk

Title: How to select the rows by range?

Body:
You can use the following solution using multiple LEFT JOIN to join the next and last row of the current row. With some additional conditions you can check for the range:

SELECT t1.Model, t1.Level, t1.Basic, t1.Actual
FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
  FROM test
) t1 LEFT JOIN (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
  FROM test
) t2 ON t1.Model = t2.Model AND t1.rn + 1 = t2.rn LEFT JOIN (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Model ORDER BY Basic) AS rn
  FROM test
) t3 ON t1.Model = t3.Model AND t1.rn - 1 = t3.rn
WHERE (t1.Actual BETWEEN t3.Basic AND t1.Basic)
  OR (t3.Model IS NULL AND t1.Actual < t1.Basic)
  OR (t2.Model IS NULL AND t1.Actual > t1.Basic)
ORDER BY t1.Model ASC

The above query gets all expected rows. I also added some additional cases to improve the query for these (special) cases. The above solution is working with SQL-Server 2008.

Since SQL-Server 2012 you can use the following solution using LAG and LEAD:

SELECT t.Model, t.Level, t.Basic, t.Actual
FROM (
  SELECT *, LAG(Basic, 1,0) OVER (PARTITION BY Model ORDER BY Basic) AS prevBasic,
    LEAD(Basic, 1, 0) OVER (PARTITION BY Model ORDER BY Basic) AS nextBasic
  FROM test
) t
WHERE (t.Actual BETWEEN t.prevBasic AND t.Basic)
   OR (t.nextBasic = 0 AND t.Actual > t.Basic)
ORDER BY t.Model ASC

demo on dbfiddle.uk


问:
amCharts 4 - Second Y Axis doesn't show values
I am setting up a new chart using amCharts 4 js library. I need to show the y Axis both on the left side and on the right side.

I followed the documentation and set "opposite = true" for the second y Axis (to have it on the right). This Axis seems to be rendered but without the values which are on the left side.

If I use only one y Axis and set "opposite = true", it works perfectly. But when I set it up for the second y Axis, the chart does not show the values of the right Axis but only on the left one.

```<code>// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
var valueAxisLeft = chart.yAxes.push(new am4charts.ValueAxis());
var valueAxisRight = chart.yAxes.push(new am4charts.ValueAxis());
valueAxisRight.renderer.opposite = true;
</code>```

https://jsfiddle.net/zs2gnd41/

In this jsfiddle example, the chart has the "empty" space for the right Y Axis but it doesn't show it. If you comment out the latest 2 lines of this above snippet, the chart will become wider.

Do you have any idea? Thanks a lot

答:
You can create one more series for right axis fiddle,</p>

```<code>var valSeriesRight = chart.series.push(new am4charts.LineSeries());
valSeriesRight.dataFields.valueY = "value";
valSeriesRight.dataFields.dateX = "date";
valSeriesRight.yAxis = valueAxisRight;
</code>```

Body:
I am setting up a new chart using amCharts 4 js library. I need to show the y Axis both on the left side and on the right side.

I followed the documentation and set "opposite = true" for the second y Axis (to have it on the right). This Axis seems to be rendered but without the values which are on the left side.

If I use only one y Axis and set "opposite = true", it works perfectly. But when I set it up for the second y Axis, the chart does not show the values of the right Axis but only on the left one.

// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
var valueAxisLeft = chart.yAxes.push(new am4charts.ValueAxis());
var valueAxisRight = chart.yAxes.push(new am4charts.ValueAxis());
valueAxisRight.renderer.opposite = true;

https://jsfiddle.net/zs2gnd41/

In this jsfiddle example, the chart has the "empty" space for the right Y Axis but it doesn't show it. If you comment out the latest 2 lines of this above snippet, the chart will become wider.

Do you have any idea? Thanks a lot

Body:
You can create one more series for right axis fiddle,

var valSeriesRight = chart.series.push(new am4charts.LineSeries());
valSeriesRight.dataFields.valueY = "value";
valSeriesRight.dataFields.dateX = "date";
valSeriesRight.yAxis = valueAxisRight;


问:
System.Data.Entity.Validation.DbEntityValidationException：'validation of one or more entities failed
Problem of insert data to database :

e.g:  goods.GoodPhoto = "/Content/img/imageGood/"+imageName;
         replace it with this：goods.GoodPhoto=""+imageName;
         and it worked.

```<code>    [HttpPost]
    public ActionResult AddGoods(Good goods)
            {
                HttpPostedFileBase image = Request.Files["image"];
                string SavePath = Server.MapPath("~/Content/img/imageGood/");
                string imageName = DateTime.Now.ToFileTime().ToString()+image.FileName;
                image.SaveAs(Path.Combine(SavePath, imageName));
                goods.GoodPhoto = "/Content/img/imageGood/"+imageName;
                goods.ShopID = Convert.ToInt32(Session["ShopID"]);
                db.Goods.Add(goods);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }
</code>```

Once I code “ goods.GoodPhoto = "/Content/img/imageGood/"+imageName;” and then it failed. And Error message is :

System.Data.Entity.Validation.DbEntityValidationException: 'validation
  of one or more entities failed. For more information, see the
  EntityValidationErrors property. '

答:
add try catch to find to an exact error message</p>

```<code>try
  {
     db.SaveChanges();

   }
 catch (DbEntityValidationException e)
 {
 foreach (var valErrors in e.EntityValidationErrors)
       {
         foreach (var errors in valErrors.ValidationErrors)
          {
            //here you will get property name and error message
                Trace.TraceInformation("Property: {0} Error: {1}",
                                errors .PropertyName,
                                errors .ErrorMessage);
          }

       }
   throw;
  }
</code>```

Body:
Problem of insert data to database :

e.g:  goods.GoodPhoto = "/Content/img/imageGood/"+imageName;
         replace it with this：goods.GoodPhoto=""+imageName;
         and it worked.

    [HttpPost]
    public ActionResult AddGoods(Good goods)
            {
                HttpPostedFileBase image = Request.Files["image"];
                string SavePath = Server.MapPath("~/Content/img/imageGood/");
                string imageName = DateTime.Now.ToFileTime().ToString()+image.FileName;
                image.SaveAs(Path.Combine(SavePath, imageName));
                goods.GoodPhoto = "/Content/img/imageGood/"+imageName;
                goods.ShopID = Convert.ToInt32(Session["ShopID"]);
                db.Goods.Add(goods);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }

Once I code “ goods.GoodPhoto = "/Content/img/imageGood/"+imageName;” and then it failed. And Error message is :

System.Data.Entity.Validation.DbEntityValidationException: 'validation
  of one or more entities failed. For more information, see the
  EntityValidationErrors property. '

Body:
add try catch to find to an exact error message

try
  {
     db.SaveChanges();

   }
 catch (DbEntityValidationException e)
 {
 foreach (var valErrors in e.EntityValidationErrors)
       {
         foreach (var errors in valErrors.ValidationErrors)
          {
            //here you will get property name and error message
                Trace.TraceInformation("Property: {0} Error: {1}",
                                errors .PropertyName,
                                errors .ErrorMessage);
          }

       }
   throw;
  }


问:
How can I get the timezone of given gps coordinates on iPhone?
My question is simple. I have the GPS coordinates of a place and I need to know, in what time zone (and daylight saving settings) is on that place. Is any easy solution for this problem in objective c?</p>

答: Geonames.org has a REST style free web service that provides geolocation to timezone conversion under CC attribution license. Response is XML or JSON.</p>

ContentLicense: CC BY-SA 2.5


问:
Undefined output shape of custom Keras layer
I am writing a custom Keras layer that flattens all except the last dimension of the input. However, when feeding the output of the layer into the next layer an error occurs because the output shape of the layer is None in all dimensions.

class FlattenLayers( Layer ):
    """
    Takes a nD tensor flattening the middle dimensions, ignoring the edge dimensions.
    [ n, x, y, z ] -> [ n, xy, z ]
    """

    def __init__( self, **kwargs ):
        super( FlattenLayers, self ).__init__( **kwargs )

    def build( self, input_shape ):
        super( FlattenLayers, self ).build( input_shape )

    def call( self, inputs ):
        input_shape = tf.shape( inputs )

        flat = tf.reshape(
            inputs,
            tf.stack( [
                -1,
                K.prod( input_shape[ 1 : -1 ] ),
                input_shape[ -1 ]
            ] )
        )

        return flat

    def compute_output_shape( self, input_shape ):
        if not all( input_shape[ 1: ] ):
            raise ValueError( 'The shape of the input to "Flatten" '
                             'is not fully defined '
                             '(got ' + str( input_shape[ 1: ] ) + '). '
                             'Make sure to pass a complete "input_shape" '
                             'or "batch_input_shape" argument to the first '
                             'layer in your model.' )

        output_shape = (
            input_shape[ 0 ],
            np.prod( input_shape[ 1 : -1 ] ),
            input_shape[ -1 ]
        )

        return output_shape

```

For example, when a Dense layer follows I receive the error ValueError: The last dimension of the inputs to Dense should be defined. Found None.

答:
Why do you have tf.stack() in new shape? You want to flatten all dimensions except the last one; this is how you could do it:

import tensorflow as tf
from tensorflow.keras.layers import Layer
import numpy as np

class FlattenLayer(Layer):

    def __init__( self, **kwargs):
        super(FlattenLayer, self).__init__(**kwargs)

    def build( self, input_shape ):
        super(FlattenLayer, self).build(input_shape)

    def call( self, inputs):
        new_shape = self.compute_output_shape(tf.shape(inputs))
        return tf.reshape(inputs, new_shape)

    def compute_output_shape(self, input_shape):
        new_shape = (input_shape[0]*input_shape[1]*input_shape[2],
                     input_shape[3])
        return new_shape
```

<p>Testing with a single data point (<code>tf.__version__=='1.13.1'</code>):</p>

<pre class="lang-py prettyprint-override"><code>inputs = tf.keras.layers.Input(shape=(10, 10, 1))
res = tf.keras.layers.Conv2D(filters=3, kernel_size=2)(inputs)
res = FlattenLayer()(res)
model = tf.keras.models.Model(inputs=inputs, outputs=res)

x_data = np.random.normal(size=(1, 10, 10, 1))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    evaled = model.outputs[0].eval({model.inputs[0]:x_data})
    print(evaled.shape) # (81, 3)
</code>```

Body:
I am writing a custom Keras layer that flattens all except the last dimension of the input. However, when feeding the output of the layer into the next layer an error occurs because the output shape of the layer is None in all dimensions.

class FlattenLayers( Layer ):
    """
    Takes a nD tensor flattening the middle dimensions, ignoring the edge dimensions.
    [ n, x, y, z ] -> [ n, xy, z ]
    """

    def __init__( self, **kwargs ):
        super( FlattenLayers, self ).__init__( **kwargs )

    def build( self, input_shape ):
        super( FlattenLayers, self ).build( input_shape )

    def call( self, inputs ):
        input_shape = tf.shape( inputs )

        flat = tf.reshape(
            inputs,
            tf.stack( [
                -1,
                K.prod( input_shape[ 1 : -1 ] ),
                input_shape[ -1 ]
            ] )
        )

        return flat

    def compute_output_shape( self, input_shape ):
        if not all( input_shape[ 1: ] ):
            raise ValueError( 'The shape of the input to "Flatten" '
                             'is not fully defined '
                             '(got ' + str( input_shape[ 1: ] ) + '). '
                             'Make sure to pass a complete "input_shape" '
                             'or "batch_input_shape" argument to the first '
                             'layer in your model.' )

        output_shape = (
            input_shape[ 0 ],
            np.prod( input_shape[ 1 : -1 ] ),
            input_shape[ -1 ]
        )

        return output_shape

For example, when a Dense layer follows I receive the error ValueError: The last dimension of the inputs to Dense should be defined. Found None.

Body:
Why do you have tf.stack() in new shape? You want to flatten all dimensions except the last one; this is how you could do it:

import tensorflow as tf
from tensorflow.keras.layers import Layer
import numpy as np

class FlattenLayer(Layer):

    def __init__( self, **kwargs):
        super(FlattenLayer, self).__init__(**kwargs)

    def build( self, input_shape ):
        super(FlattenLayer, self).build(input_shape)

    def call( self, inputs):
        new_shape = self.compute_output_shape(tf.shape(inputs))
        return tf.reshape(inputs, new_shape)

    def compute_output_shape(self, input_shape):
        new_shape = (input_shape[0]*input_shape[1]*input_shape[2],
                     input_shape[3])
        return new_shape

Testing with a single data point (tf.__version__=='1.13.1'):

inputs = tf.keras.layers.Input(shape=(10, 10, 1))
res = tf.keras.layers.Conv2D(filters=3, kernel_size=2)(inputs)
res = FlattenLayer()(res)
model = tf.keras.models.Model(inputs=inputs, outputs=res)

x_data = np.random.normal(size=(1, 10, 10, 1))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    evaled = model.outputs[0].eval({model.inputs[0]:x_data})
    print(evaled.shape) # (81, 3)


问:
can't unsubscribe on my ngrx selector call
I have the following code

```<code>selectProduct(id){
    const sub = this.store$.select(ProductStoreSelector.selectProductByID(id)).subscribe((product) => {
      this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
      sub.unsubscribe();
    });
}
</code>```

Basically, I would like to get my list of product, and get one by ID, then change my store state so that the selectedProduct become the one I just selected

```<code>export const featureAdapter: EntityAdapter<IProduct> = createEntityAdapter<IProduct>({
  selectId: model => model.id,
});
export const selectAllProducts: (state: object) => Array<IProduct> = featureAdapter.getSelectors(selectProductsState).selectAll;
export const selectProductByID = (id: string) => createSelector(
  selectAllProducts,
  (products) => products.find((product) => product.id === id)
);
</code>```

and my store is an entityState of products with one selected

```<code>export interface State extends EntityState<IProduct> {
  selectedProduct: IProduct;
}
</code>```

but the problem is,

althougt I do get my productId back, I can't unsubscribe to sub.unsubscribe() because it is undefined.

答:
You can use either take(1) to listen for values only one time. Otherwise try to unsubscribe like below:

```<code>selectProduct(id){
   this.store$.select(ProductStoreSelector.selectProductByID(id)).subscribe((product) => {
      this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
    }).unsubscribe();
}
</code>```

using take(1):

```<code>    selectProduct(id){
           this.store$.select(ProductStoreSelector.selectProductByID(id))
                .take(1)
                .subscribe((product) => {
                   this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
            });
        }
</code>```

Body:
I have the following code

selectProduct(id){
    const sub = this.store$.select(ProductStoreSelector.selectProductByID(id)).subscribe((product) => {
      this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
      sub.unsubscribe();
    });
}

Basically, I would like to get my list of product, and get one by ID, then change my store state so that the selectedProduct become the one I just selected

export const featureAdapter: EntityAdapter<IProduct> = createEntityAdapter<IProduct>({
  selectId: model => model.id,
});
export const selectAllProducts: (state: object) => Array<IProduct> = featureAdapter.getSelectors(selectProductsState).selectAll;
export const selectProductByID = (id: string) => createSelector(
  selectAllProducts,
  (products) => products.find((product) => product.id === id)
);

and my store is an entityState of products with one selected

export interface State extends EntityState<IProduct> {
  selectedProduct: IProduct;
}

but the problem is,

althougt I do get my productId back, I can't unsubscribe to sub.unsubscribe() because it is undefined.

Body:
You can use either take(1) to listen for values only one time. Otherwise try to unsubscribe like below:

selectProduct(id){
   this.store$.select(ProductStoreSelector.selectProductByID(id)).subscribe((product) => {
      this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
    }).unsubscribe();
}

using take(1):

    selectProduct(id){
           this.store$.select(ProductStoreSelector.selectProductByID(id))
                .take(1)
                .subscribe((product) => {
                   this.store$.dispatch(new ProductStoreAction.SetSelectedProduct({productID: product.id}));
            });
        }


问:
Retrieve current value of an observable
If I want to get the value of an observable, I typically call it as a function.

Say, I have a model with observables as below

```<code>export interface ClientModel {
    name: KnockoutObservable<string>;
    age: KnockoutObservable<number>;
}
</code>```

And a model without observable as below

```<code>export interface ServerModel {
   name: string;
   age: number;
}
</code>```

Below are two implementations of converting from one model to another.

A

```<code>export function getServerModelJson(person: ClientModel) : ServerModel {
   const personJson: ServerModel = {
      name: ko.unwrap(person.name),
      age: ko.unwrap(person.age)
   }
   return personJson;
}
</code>```

B

```<code>export function getServerModelJson(person: ClientModel) : ServerModel {
   const personJson: ServerModel = {
      name: person.name(),
      age: perosn.age()
   }
   return personJson;
}
</code>```

Is there a difference between the two (calling the observable as function versus using ko.unwrap). What is the recommended way? What changes if the fields are complex types. In those cases, how do you do the conversion?

答:
Is there a different between the two (calling the observable as function versus using ko.unwrap).

Two:

If you call the VM property as a function directly, it must be a function (e.g., an observable or whatever). If it's a simple non-function data property, you'll get an error. With ko.unwrap, it gives you the simple non-function data property's value in that case (or, of course, the observable's value).

ko.unwrap adds a function call and a couple of checks (the call to ko.unwrap and the work it does to determine whether what you've passed it is an obserable).

If you know it's observable, as in your example, there's no real reason to use ko.unwap. (If you know it's not observable, similarly there's no real reason to use ko.unwrap.)

What is the recommended way?

It's up to you, based on what your properties are and whether you know they're observables.

What changes if the fields are complex types. In those cases, how do you do the conversion?

Nothing, you just do it the same way —note that if the properties of the complex type are also observables, you'll have to handle them separately (ko.unwrap doesn't go deep).

Title: Retrieve current value of an observable

Body:
If I want to get the value of an observable, I typically call it as a function.

Say, I have a model with observables as below

export interface ClientModel {
    name: KnockoutObservable<string>;
    age: KnockoutObservable<number>;
}

And a model without observable as below

export interface ServerModel {
   name: string;
   age: number;
}

Below are two implementations of converting from one model to another.

A

export function getServerModelJson(person: ClientModel) : ServerModel {
   const personJson: ServerModel = {
      name: ko.unwrap(person.name),
      age: ko.unwrap(person.age)
   }
   return personJson;
}

B

export function getServerModelJson(person: ClientModel) : ServerModel {
   const personJson: ServerModel = {
      name: person.name(),
      age: perosn.age()
   }
   return personJson;
}

Is there a difference between the two (calling the observable as function versus using ko.unwrap). What is the recommended way? What changes if the fields are complex types. In those cases, how do you do the conversion?


问:
Intermittent file lock exception when calling File.AppendAllLines many times and file is open in Visual Studio
I have a number of methods on a class which I am calling via reflection:

```<code>var instances = new TestsBase[] {
    new CompilerGeneratedTestData(),
    new ConstructedTestData(),
    new VBCompilerGeneratedTestData()
};

var methods = instances
    .SelectMany(x =>
        x.GetType()
            .GetMethods()
            .Select(m => (instance: x, method: m))
    )
    .OrderBy(x => x.method.ReflectedType.Name)
    .ThenBy(x => x.method.Name)
    .ToList();
</code>```

Each of these methods ultimately calls the following code:

```<code>string[] toWrite = ...
var outfileName = @"c:\path\to\text.txt";
File.AppendAllLines(outfileName, toWrite);
</code>```

When I run the code, at some point I get the following exception at the call to File.AppendAllLines:

System.IO.IOException: 'The process cannot access the file 'c:\path\to\text.txt' because it is being used by another process.'

The original method call appears to be different each time; it's not failing on a particular method.

The application is a simple console project, with no multithreading in my code.

How can I avoid this error?

I have a set of abstract classes with XUnit test methods:

```<code>public class ConstructedBase {
    protected abstract void RunTest(object o, string csharp, string vb, string factoryMethods);

    [Fact]
    public void ConstructAdd() => RunTest(Expression.Add(x, y), "x + y", "x + y", "Add(x, y)");

    ...
}
</code>```

and a class which defines the implementation of RunTest:

```<code>class ConstructedTestData : ConstructedBase {
    protected override void RunTest(object o, string csharp, string vb, string factoryMethods) => Runner.WriteData(o, factoryMethods);
}
</code>```

as forwarding to a static method:

```<code>public static class Runner {
    public static readonly string outfileName = @"c:\path\to\text.txt";
    public static void WriteData(object o, string testData) {
        string[] toWrite = ...
        File.AppendAllLines(outfileName, toWrite);
    }
}
</code>```

Update

This error only appears to happen if the text file is simultaneously open in Visual Studio.

答:
Two alternatives:

Store all the output data in memory, and write it all in one shot using File.WriteAllLines.

If it is impractical to store everything in memory, it might be possible to write everything to a temporary file, then copy that file over to the destination.

Body:
I have a number of methods on a class which I am calling via reflection:

var instances = new TestsBase[] {
    new CompilerGeneratedTestData(),
    new ConstructedTestData(),
    new VBCompilerGeneratedTestData()
};

var methods = instances
    .SelectMany(x =>
        x.GetType()
            .GetMethods()
            .Select(m => (instance: x, method: m))
    )
    .OrderBy(x => x.method.ReflectedType.Name)
    .ThenBy(x => x.method.Name)
    .ToList();

Each of these methods ultimately calls the following code:

string[] toWrite = ...
var outfileName = @"c:\path\to\text.txt";
File.AppendAllLines(outfileName, toWrite);

When I run the code, at some point I get the following exception at the call to File.AppendAllLines:

System.IO.IOException: 'The process cannot access the file 'c:\path\to\text.txt' because it is being used by another process.'

The original method call appears to be different each time; it's not failing on a particular method.

The application is a simple console project, with no multithreading in my code.

How can I avoid this error?

I have a set of abstract classes with XUnit test methods:

public class ConstructedBase {
    protected abstract void RunTest(object o, string csharp, string vb, string factoryMethods);

    [Fact]
    public void ConstructAdd() => RunTest(Expression.Add(x, y), "x + y", "x + y", "Add(x, y)");

    ...
}

and a class which defines the implementation of RunTest:

class ConstructedTestData : ConstructedBase {
    protected override void RunTest(object o, string csharp, string vb, string factoryMethods) => Runner.WriteData(o, factoryMethods);
}

as forwarding to a static method:

public static class Runner {
    public static readonly string outfileName = @"c:\path\to\text.txt";
    public static void WriteData(object o, string testData) {
        string[] toWrite = ...
        File.AppendAllLines(outfileName, toWrite);
    }
}

Update

This error only appears to happen if the text file is simultaneously open in Visual Studio.


问:
How to change fontFamily of TextView in Android
So I'd like to change the android:fontFamily in Android but I don't see any pre-defined fonts in Android. How do I select one of the pre-defined ones? I don't really need to define my own TypeFace but all I need is something different from what it shows right now.

```<code><TextView
    android:id="@+id/HeaderText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="52dp"
    android:gravity="center"
    android:text="CallerBlocker"
    android:textSize="40dp"
    android:fontFamily="Arial"
 />
</code>```

It seems what I did up there won't really work! BTW android:fontFamily="Arial" was a stupid attempt!

答:
You can also change standard fonts with setTextAppearance (requires API 16), see https://stackoverflow.com/a/36301508/2914140:

```<code><style name="styleA">
    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="styleB">
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?android:attr/textColorTertiary</item>
</style>

if(condition){
    TextViewCompat.setTextAppearance(textView, R.style.styleA);
} else {
    TextViewCompat.setTextAppearance(textView,R.style.styleB);
}
</code>```

Body:
So I'd like to change the android:fontFamily in Android but I don't see any pre-defined fonts in Android. How do I select one of the pre-defined ones? I don't really need to define my own TypeFace but all I need is something different from what it shows right now.

<TextView
    android:id="@+id/HeaderText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="52dp"
    android:gravity="center"
    android:text="CallerBlocker"
    android:textSize="40dp"
    android:fontFamily="Arial"
 />

It seems what I did up there won't really work! BTW android:fontFamily="Arial" was a stupid attempt!

Body:
You can also change standard fonts with setTextAppearance (requires API 16), see https://stackoverflow.com/a/36301508/2914140:

<style name="styleA">
    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="styleB">
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?android:attr/textColorTertiary</item>
</style>

if(condition){
    TextViewCompat.setTextAppearance(textView, R.style.styleA);
} else {
    TextViewCompat.setTextAppearance(textView,R.style.styleB);
}


问:
What does the "declare a static final serialVersionUID" warning mean and how to fix?

Possible Duplicate:

  What does it mean: The serializable class does not declare a static final serialVersionUID field?

Java compiler warning: The serializable class [*****] does not declare a static final serialVersionUID field of type long.

Why? How to fix it?

答:
Are you extending a Swing object?

I often use the @suppressWarnings annotation to rid myself of this warning.

I guess the question of surpressing the warning or supplying a unique ID depends on the scale of your application and your intended use of Object serialisation.


问:
RegEx for specific extension validation
I'm trying to validate upload file extensions on client side (razor) with DataAnnotations, however it looks like no matter what file I'm uploading I always get the "Error Message",

```<code> [RegularExpression(@"^.*\.(jpg | JPG | gif | docx | doc | DOC | pdf | PDF)$",
           ErrorMessage = "bla bla")]
        public IFormFile MyImage { get; set; }
</code>```

My code is as follows:

```<code> <input name="MyImage" class="input-validation-error" id="MyImage" aria-invalid="true" aria-describedby="MyImage-error" type="file" data-val="true" data-val-regex-pattern="^.*\.(jpg | JPG | gif | docx | doc | DOC | pdf | PDF)$" data-val-regex="bla bla">
</code>```

答:
Your original expression works fine and let's just slightly simplify it using an i flag:

```<code>(.*\.)(jpe?g|gif|docx?|pdf)$
</code>```

DEMO

TEST

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.*\.)(jpe?g|gif|docx?|pdf)$";
        string input = @"any_file_name_we_wish_here_with_!@#$%^&*_1234567.jpg
any_file_name_we_wish_here_with_!@#$%^&*_1234567.jpeg
any_file_name_we_wish_here_with_!@#$%^&*_1234567.JPG
any_file_name_we_wish_here_with_!@#$%^&*_1234567.docx
any_file_name_we_wish_here_with_!@#$%^&*_1234567.doc
any_file_name_we_wish_here_with_!@#$%^&*_1234567.pdf
any_file_name_we_wish_here_with_!@#$%^&*_1234567.gif
any_file_name_we_wish_here_with_!@#$%^&*_1234567.mp3
any_file_name_we_wish_here_with_!@#$%^&*_1234567.mp4";
        RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

Title: RegEx for specific extension validation

Body:
I'm trying to validate upload file extensions on client side (razor) with DataAnnotations, however it looks like no matter what file I'm uploading I always get the "Error Message",

 [RegularExpression(@"^.*\.(jpg | JPG | gif | docx | doc | DOC | pdf | PDF)$",
           ErrorMessage = "bla bla")]
        public IFormFile MyImage { get; set; }

My code is as follows:

 <input name="MyImage" class="input-validation-error" id="MyImage" aria-invalid="true" aria-describedby="MyImage-error" type="file" data-val="true" data-val-regex-pattern="^.*\.(jpg | JPG | gif | docx | doc | DOC | pdf | PDF)$" data-val-regex="bla bla">

Body:
Your original expression works fine and let's just slightly simplify it using an i flag:

(.*\.)(jpe?g|gif|docx?|pdf)$

DEMO

TEST

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.*\.)(jpe?g|gif|docx?|pdf)$";
        string input = @"any_file_name_we_wish_here_with_!@#$%^&*_1234567.jpg
any_file_name_we_wish_here_with_!@#$%^&*_1234567.jpeg
any_file_name_we_wish_here_with_!@#$%^&*_1234567.JPG
any_file_name_we_wish_here_with_!@#$%^&*_1234567.docx
any_file_name_we_wish_here_with_!@#$%^&*_1234567.doc
any_file_name_we_wish_here_with_!@#$%^&*_1234567.pdf
any_file_name_we_wish_here_with_!@#$%^&*_1234567.gif
any_file_name_we_wish_here_with_!@#$%^&*_1234567.mp3
any_file_name_we_wish_here_with_!@#$%^&*_1234567.mp4";
        RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

RegEx Circuit

jex.im visualizes regular expressions:


问:
Unable to access react environment variables using process.env
In my React App, I use a .env file to keep some API keys. However when I tried to access those variables using process.env the values seem to be undefined.

I start the app using below command.

```<code>yarn build; cd dist; static-server --index ./login/index.html -p 1234
</code>```

I tried restarting server, removing dist folder and rebuilding but didn't work.

This is where I access the variables.
In constants.js

```<code>const MY_API_KEY = process.env.REACT_APP_MY_API_KEY;
// some more consts here

module.exports = {MY_API_KEY};
</code>```

However when I did console.log(process.env.REACT_APP_MY_API_KEY) in constants.js file, it printed the key to console and MY_API_KEY was initialized to correct value.

What could have gone wrong here ?

答:
You defined your environment variables correctly as described in https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Since it prints the right value when you console.log(process.env.REACT_APP_MY_API_KEY), it sounds like an import/export issue.

try

export const MY_API_KEY = process.env.REACT_APP_MY_API_KEY;
```

<pre class="lang-js prettyprint-override"><code>import {MY_API_KEY} from '../my-environment-variables'
</code>```

Body:
In my React App, I use a .env file to keep some API keys. However when I tried to access those variables using process.env the values seem to be undefined.

I start the app using below command.

yarn build; cd dist; static-server --index ./login/index.html -p 1234

I tried restarting server, removing dist folder and rebuilding but didn't work.

This is where I access the variables.
In constants.js

const MY_API_KEY = process.env.REACT_APP_MY_API_KEY;
// some more consts here

module.exports = {MY_API_KEY};

However when I did console.log(process.env.REACT_APP_MY_API_KEY) in constants.js file, it printed the key to console and MY_API_KEY was initialized to correct value.

What could have gone wrong here ?

Body:
You defined your environment variables correctly as described in https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Since it prints the right value when you console.log(process.env.REACT_APP_MY_API_KEY), it sounds like an import/export issue.

try

export const MY_API_KEY = process.env.REACT_APP_MY_API_KEY;

import {MY_API_KEY} from '../my-environment-variables'


问:
Errno 22 Invalid Argument Python
I'm trying to copy one file's content to another, and error appears, what do i do wrong?

for file in os.listdir('offer'):
    if '.css' in file:
        print(file)
        with open(f'offer/{file}', 'r+') as f:
            with open('offer/id.css', 'w+') as style_file:
                shutil.copyfile(f'offer/{f}', f'offer/{style_file}')
```

<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
  File "C:/Users/Katerina/Desktop/python/test_attempt.py", line 50, in <module>
    shutil.copyfile(f'offer/{f}', f'offer/{style_file}')
  File "C:\Users\Katerina\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:
OSError: [Errno 22] Invalid argument: "offer/<_io.TextIOWrapper name='offer/id.css' mode='r+' encoding='cp1251'>"
</code>```

答:
I guess you are looking for something like

```<code>with open('offer/id.css', 'w') as style_file:
    for file in os.listdir('offer'):
        if '.css' in file:
            #print(file)
            with open(f'offer/{file}', 'r+') as f:
                for line in f:
                    style_file.write(line)
</code>```

The purpose of shutil.copyfile is different; it doesn't really allow you to access or modify the contents of either file, it just copies one to the other.

Title: Errno 22 Invalid Argument Python

Body:
I'm trying to copy one file's content to another, and error appears, what do i do wrong?

for file in os.listdir('offer'):
    if '.css' in file:
        print(file)
        with open(f'offer/{file}', 'r+') as f:
            with open('offer/id.css', 'w+') as style_file:
                shutil.copyfile(f'offer/{f}', f'offer/{style_file}')

Traceback (most recent call last):
  File "C:/Users/Katerina/Desktop/python/test_attempt.py", line 50, in <module>
    shutil.copyfile(f'offer/{f}', f'offer/{style_file}')
  File "C:\Users\Katerina\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 120, in copyfile
    with open(src, 'rb') as fsrc:
OSError: [Errno 22] Invalid argument: "offer/<_io.TextIOWrapper name='offer/id.css' mode='r+' encoding='cp1251'>"

Body:
I guess you are looking for something like

with open('offer/id.css', 'w') as style_file:
    for file in os.listdir('offer'):
        if '.css' in file:
            #print(file)
            with open(f'offer/{file}', 'r+') as f:
                for line in f:
                    style_file.write(line)

The purpose of shutil.copyfile is different; it doesn't really allow you to access or modify the contents of either file, it just copies one to the other.


问:
Does Objective-C support Mixin like Ruby?
In Ruby, there's Modules and you can extend a class by "mixing-in" the module.

```<code>module MyModule
  def printone
    print "one"
  end
end

class MyClass
  include MyModule
end

theOne = MyClass.new
theOne.printone
>> one
</code>```

In Objective-C, I find that I have a set of common methods that I want a number of Class to "inherit". What other ways can I achieve this without creating a common class and deriving all from that common class?

答:
Shameless plug: ObjectiveMixin

It takes advantage of Objective-C runtime's capability of adding methods to a class in runtime (as opposed to categories, which are compile-time only). Check it out, it works pretty good and in a similar fashion to Ruby's mixins.

Body:
In Ruby, there's Modules and you can extend a class by "mixing-in" the module.

module MyModule
  def printone
    print "one"
  end
end

class MyClass
  include MyModule
end

theOne = MyClass.new
theOne.printone
>> one

In Objective-C, I find that I have a set of common methods that I want a number of Class to "inherit". What other ways can I achieve this without creating a common class and deriving all from that common class?


问:
New shell/window in Prism/WPF shows wrong view
Inspired by this answer, I created a general purpose Shell (Prism, WPF) like this:

```<code><Window x:Class="VRMDataLogger.UI.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" Title="My App" Height="450" Width="800">
    <Grid>
        <ContentControl prism:RegionManager.RegionManager="{Binding RegionManager}" prism:RegionManager.RegionName="MainShellRegion" />
    </Grid>
</Window>
</code>```

```<code>public partial class Shell : Window
{
    public Shell(IRegionManager regionManager, Type contentType)
    {
        RegionManager = regionManager;
        InitializeComponent();
        RegionManager.RegisterViewWithRegion("MainShellRegion", contentType);
    }

    public IRegionManager RegionManager { get; }
}

</code>```

The initial shell gets created in App.CreateShell():

```<code>protected override Window CreateShell()
{
    return new Shell(Container.Resolve<IRegionManager>(), typeof(StartScreen));
}
</code>```

This works fine and the correct view is shown in that initial shell.

I then try to create a second Shell from StartScreenViewModel which shows a different view:

```<code>var shell = new Shell(RegionManager.CreateRegionManager(), typeof(MainScreen));
shell.Show();
</code>```

This opens a new window, but it shows the same view like the first window (StartScreen) instead of MainScreen. What am I doing wrong here?

答:
Try to use a unique region name for each shell:

```<code>public partial class Shell : Window
{
    public Shell(IRegionManager regionManager, Type contentType)
    {
        RegionManager = regionManager;
        InitializeComponent();
        MainRegionName = Guid.NewGuid().ToString();
        RegionManager.RegisterViewWithRegion(MainRegionName, contentType);
    }

    public string MainRegionName { get; }
    public IRegionManager RegionManager { get; }

}
</code>```

XAML:

```<code><ContentControl prism:RegionManager.RegionManager="{Binding RegionManager}"
                prism:RegionManager.RegionName="{Binding MainRegionName, RelativeSource={RelativeSource AncestorType=Window}}" />
</code>```

Body:
Inspired by this answer, I created a general purpose Shell (Prism, WPF) like this:

<Window x:Class="VRMDataLogger.UI.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" Title="My App" Height="450" Width="800">
    <Grid>
        <ContentControl prism:RegionManager.RegionManager="{Binding RegionManager}" prism:RegionManager.RegionName="MainShellRegion" />
    </Grid>
</Window>

public partial class Shell : Window
{
    public Shell(IRegionManager regionManager, Type contentType)
    {
        RegionManager = regionManager;
        InitializeComponent();
        RegionManager.RegisterViewWithRegion("MainShellRegion", contentType);
    }

    public IRegionManager RegionManager { get; }
}

The initial shell gets created in App.CreateShell():

protected override Window CreateShell()
{
    return new Shell(Container.Resolve<IRegionManager>(), typeof(StartScreen));
}

This works fine and the correct view is shown in that initial shell.

I then try to create a second Shell from StartScreenViewModel which shows a different view:

var shell = new Shell(RegionManager.CreateRegionManager(), typeof(MainScreen));
shell.Show();

This opens a new window, but it shows the same view like the first window (StartScreen) instead of MainScreen. What am I doing wrong here?

Body:
Try to use a unique region name for each shell:

public partial class Shell : Window
{
    public Shell(IRegionManager regionManager, Type contentType)
    {
        RegionManager = regionManager;
        InitializeComponent();
        MainRegionName = Guid.NewGuid().ToString();
        RegionManager.RegisterViewWithRegion(MainRegionName, contentType);
    }

    public string MainRegionName { get; }
    public IRegionManager RegionManager { get; }

}

XAML:

<ContentControl prism:RegionManager.RegionManager="{Binding RegionManager}"
                prism:RegionManager.RegionName="{Binding MainRegionName, RelativeSource={RelativeSource AncestorType=Window}}" />


问:
Problem with displaying user-pictures relation in Laravel 5.8
I'm very beginner in Laravel.

I have standard login User model (generated by Laravel):

```<code>class UploadedFiles extends Model
{
    protected $quarded = [];
    protected $fillable = ['company_id', 'enable', 'photoable_type', 'photoable_id', 'path', 'ip', 'number'];
    protected $table = 'uploaded_files';

}

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function mainRole()
    {
        return $this->hasOne('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }

    public function images()
    {   // find(['photoable_type', '=', 'AdminImage'] ::with('director')->get();
        return $this->hasMany('App\UploadedFiles' );
    }

    public function images2()
    {   // ->where('photoable_type', 'AdminImage')
        return $this->hasManyThrough('App\UploadedFiles', 'App\User', 'photoable_id', 'id');
    }

    public function hasRole(array $roles)
    {

        foreach($roles as $role)
        {

            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            }
            else
            {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }
        return false;
    }

    public function loginHistory()
    {
        return $this->hasMany('App\UserLoginHistory');
    }

    public function companies()
    {
        return $this->belongsTo('App\Companies','company_id');
    }

}
</code>```

My schema:

```<code>Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('uploaded_files', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('photoable_type', 150);
            $table->integer('photoable_id');
            $table->string('path', 255);
            $table->string('ip', 25);
            $table->bigInteger('number')->default(0);
            $table->timestamps();
            $table->engine = "InnoDB";
        });
</code>```

I have the following record in the database:
https://ibb.co/ZhHGkKX

```<code>INSERT INTO `uploaded_files` (`id`, `company_id`, `enable`, `photoable_type`, `photoable_id`, `path`, `ip`, `number`, `created_at`, `updated_at`) VALUES
(46, 1, 1, 'AdminImage', 1, 'upload/images/AdminImage/627e653871183f639c8d9460f37111b1.jpg', '172.29.0.1', 0, '2019-05-27 08:50:08', '2019-05-27 08:50:08');
COMMIT;
</code>```

In my base I have relations:
- uploaded_files.photoable_id = User.id

I need to display all images belonging to the user that have the photoable_type = AdminImage

How can I do this? Please help

答:
just add in User model

```<code>public function images2()
{
    return $this->hasMany('App\UploadedFiles', 'company_id','company_id');
}

public function AdminImage()
{
    return $this->images2()->where('photoable_type','=','AdminImage');
}
</code>```

now you can access all  user that have the photoable_type = AdminImage

```<code>User::with('AdminImage')->get();
</code>```

Body:
I'm very beginner in Laravel.

I have standard login User model (generated by Laravel):

class UploadedFiles extends Model
{
    protected $quarded = [];
    protected $fillable = ['company_id', 'enable', 'photoable_type', 'photoable_id', 'path', 'ip', 'number'];
    protected $table = 'uploaded_files';

}

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function mainRole()
    {
        return $this->hasOne('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }

    public function images()
    {   // find(['photoable_type', '=', 'AdminImage'] ::with('director')->get();
        return $this->hasMany('App\UploadedFiles' );
    }

    public function images2()
    {   // ->where('photoable_type', 'AdminImage')
        return $this->hasManyThrough('App\UploadedFiles', 'App\User', 'photoable_id', 'id');
    }

    public function hasRole(array $roles)
    {

        foreach($roles as $role)
        {

            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            }
            else
            {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }
        return false;
    }

    public function loginHistory()
    {
        return $this->hasMany('App\UserLoginHistory');
    }

    public function companies()
    {
        return $this->belongsTo('App\Companies','company_id');
    }

}

My schema:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('uploaded_files', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('photoable_type', 150);
            $table->integer('photoable_id');
            $table->string('path', 255);
            $table->string('ip', 25);
            $table->bigInteger('number')->default(0);
            $table->timestamps();
            $table->engine = "InnoDB";
        });

I have the following record in the database:
https://ibb.co/ZhHGkKX

INSERT INTO `uploaded_files` (`id`, `company_id`, `enable`, `photoable_type`, `photoable_id`, `path`, `ip`, `number`, `created_at`, `updated_at`) VALUES
(46, 1, 1, 'AdminImage', 1, 'upload/images/AdminImage/627e653871183f639c8d9460f37111b1.jpg', '172.29.0.1', 0, '2019-05-27 08:50:08', '2019-05-27 08:50:08');
COMMIT;

In my base I have relations:
- uploaded_files.photoable_id = User.id

I need to display all images belonging to the user that have the photoable_type = AdminImage

How can I do this? Please help

Body:
just add in User model

public function images2()
{
    return $this->hasMany('App\UploadedFiles', 'company_id','company_id');
}

public function AdminImage()
{
    return $this->images2()->where('photoable_type','=','AdminImage');
}

now you can access all  user that have the photoable_type = AdminImage

User::with('AdminImage')->get();


问:
PHP Function pt_register
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

```<code>function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}
</code>```

Can anyone walk through this in English for me?

答:
I have absolutely no idea why one would want to use this function. It basically copies variables from the session, request or environment to the global namespace.

How are you using it? If you want to access form fields, use $_POST:

```<code>$value = $_POST['value'];
</code>```

Instead of:

```<code>pt_register('POST', 'value');
</code>```

OwnerDisplayName: HaArD

Title: PHP Function pt_register

Body:
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}

Can anyone walk through this in English for me?

LastEditorDisplayName: RoBorg

Body:
I have absolutely no idea why one would want to use this function. It basically copies variables from the session, request or environment to the global namespace.

How are you using it? If you want to access form fields, use $_POST:

$value = $_POST['value'];

Instead of:

pt_register('POST', 'value');

OwnerDisplayName: Ferdinand


问:
I have 'expression changed after it has been checked error 'if I use *ngif, but it not appears if i use [hidden]
I have a big doubt, case 1 produces an error, but if I substitute case 2 does not fail.

Case 1:

```<code> <div class="col-8" *ngIf="customstreetType">
    <app-input-text
      [valueIn]="_address?.custom_street_type"
      (valueOut)="_address.custom_street_type = $event; change()"
    ></app-input-text>
  </div>
</code>```

Case 2:

```<code>  <div class="col-8" [hidden]="!customstreetType">
    <app-input-text
      [valueIn]="_address?.custom_street_type"
      (valueOut)="_address.custom_street_type = $event; change()"
    ></app-input-text>
  </div>
</code>```

Error:

```<code>DemandsActionAddressComponent.html:21 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'.
    at viewDebugError (core.js:7594)
    at expressionChangedAfterItHasBeenCheckedError (core.js:7582)
    at checkBindingNoChanges (core.js:7684)
    at checkNoChangesNodeInline (core.js:10545)
    at checkNoChangesNode (core.js:10534)
    at debugCheckNoChangesNode (core.js:11137)
    at debugCheckDirectivesFn (core.js:11065)
    at Object.eval [as updateDirectives] (DemandsActionAddressComponent.html:21)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
    at checkNoChangesView (core.js:10433)
</code>```

I don't understand why it is happening. *ngIf is more fast than [hidden] or something like this?

答:
They work differently. *ngIf can put or remove a component inside DOM (and all that goes with it, like firing relevant lifecycle hooks, ngOnInit, ngOnChanges, ngOnDestroy etc. for the element and every element inside it).

Meanwhile, [hidden] adds a 'hidden' attribute to the element, but doesn't affect component(s) life cycle.

Body:
I have a big doubt, case 1 produces an error, but if I substitute case 2 does not fail.

Case 1:

    <app-input-text
      [valueIn]="_address?.custom_street_type"
      (valueOut)="_address.custom_street_type = $event; change()"
    ></app-input-text>

Case 2:

    <app-input-text
      [valueIn]="_address?.custom_street_type"
      (valueOut)="_address.custom_street_type = $event; change()"
    ></app-input-text>

Error:

DemandsActionAddressComponent.html:21 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'.
    at viewDebugError (core.js:7594)
    at expressionChangedAfterItHasBeenCheckedError (core.js:7582)
    at checkBindingNoChanges (core.js:7684)
    at checkNoChangesNodeInline (core.js:10545)
    at checkNoChangesNode (core.js:10534)
    at debugCheckNoChangesNode (core.js:11137)
    at debugCheckDirectivesFn (core.js:11065)
    at Object.eval [as updateDirectives] (DemandsActionAddressComponent.html:21)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
    at checkNoChangesView (core.js:10433)

I don't understand why it is happening. *ngIf is more fast than [hidden] or something like this?


问:
How can I push a branch to remote after resolving rebase conflicts without using force push?
I have a Git branch with an open pull request in GitHub. But I can't merge it because GitHub complains that there are some conflicting files with latest master. Then I pull master and rebase master to my local branch and during rebase, I got conflicts. So I resolved the conflicts and when trying to push the branch to origin, my push was rejected and error says that the tip of my current branch is behind. However when I do force push it will get accepted. Anyway I can achieve this without using force push?</p>

答:
Push your code to a new branch on GitHub.
git push origin old-conflicts-branch:new-remote-branch

Then you can continue working with the new branch. The old branch is still there, so you can delete it or keep it as backup.


问:
Click on Cancel doesn't work on first click. But it works on next attempt
There is a function which try to scan given folder. While scanning, there is a cancel button available to user. but it doesn't cancel the scanning on first attempt, however it succeed on next attempt.

Here's my code skeleton:

```<code> private CancellationTokenSource _tokenSource;

 CallingMethod()
 {
   var cancelationToken = GetCancelationToken();
    Task.Run(() => { MethodA(true, stringVal, cancelationToken); }, cancelationToken);
 }

 internal void MethodA(bool isCreateNewRequested, string directoryPath, CancellationToken token)
    {
        bool sucess = true;

        if (isCreateNewRequested)
            sucess = MethodB(directoryPath, token);

        if (token.IsCancellationRequested) return;

        //some more code
    }

    private bool MethodB(string directoryPath, CancellationToken token)
    {
        var fileEntries = ProcessSubDirectories(directoryPath);
        var totalFileCount = fileEntries.Count;

        foreach (var fileEntry in fileEntries)
        {
            if (token.IsCancellationRequested) break;

            //dosomething here
        }

        if (token.IsCancellationRequested) return false;

    }

 private CancellationToken GetCancelationToken()
    {
        _tokenSource?.Cancel();
        _tokenSource = new CancellationTokenSource();

        return _tokenSource.Token;
    }
</code>```

答:
First you have to create simple cancellation token:

```<code>CancellationToken cToken = new CancellationToken();
</code>```

just like that. This token has to be passed to async method, and then:

```<code>CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cToken);
</code>```

Then use this cts.

```<code>if(cts.Cancelled) //written from head, so there may be other way to check it
    cts.Token.ThrowIfCancellationRequested();
</code>```

or:

```<code>cts.Cancel(true); //if you want to cancel manually something
cts.Token.ThrowIfCancellationRequested();
</code>```

You cannot just return. You have to throw to cancel the operation.

Body:
There is a function which try to scan given folder. While scanning, there is a cancel button available to user. but it doesn't cancel the scanning on first attempt, however it succeed on next attempt.

Here's my code skeleton:

 private CancellationTokenSource _tokenSource;

 CallingMethod()
 {
   var cancelationToken = GetCancelationToken();
    Task.Run(() => { MethodA(true, stringVal, cancelationToken); }, cancelationToken);
 }

 internal void MethodA(bool isCreateNewRequested, string directoryPath, CancellationToken token)
    {
        bool sucess = true;

        if (isCreateNewRequested)
            sucess = MethodB(directoryPath, token);

        if (token.IsCancellationRequested) return;

        //some more code
    }

    private bool MethodB(string directoryPath, CancellationToken token)
    {
        var fileEntries = ProcessSubDirectories(directoryPath);
        var totalFileCount = fileEntries.Count;

        foreach (var fileEntry in fileEntries)
        {
            if (token.IsCancellationRequested) break;

            //dosomething here
        }

        if (token.IsCancellationRequested) return false;

    }

 private CancellationToken GetCancelationToken()
    {
        _tokenSource?.Cancel();
        _tokenSource = new CancellationTokenSource();

        return _tokenSource.Token;
    }

Body:
First you have to create simple cancellation token:

CancellationToken cToken = new CancellationToken();

just like that. This token has to be passed to async method, and then:

CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cToken);

Then use this cts.

if(cts.Cancelled) //written from head, so there may be other way to check it
    cts.Token.ThrowIfCancellationRequested();

or:

cts.Cancel(true); //if you want to cancel manually something
cts.Token.ThrowIfCancellationRequested();

You cannot just return. You have to throw to cancel the operation.


问:
Checkbox display content without using HTML and CSS only (no JS)
I'm setting up checkbox in a side navigation fashion in my html pages, I want the check box to display content upon selection. Example: Choose checkbox 1,2 display content only of that, No checkbox selected display all content.. How can i do this without Jquery/javascript. I want my webpage to maintain same functionality even if Javascript in browser is disabled. Can i do this by including w3.css as these styles are responsive without involving bootstrap</p>

答:
Below code has id for different checkbox and for there contents , onclick of any checkboxthat content will be display:

#content {
  display: none;
}

#show:checked ~ #content {
  display: block;
 }

#content1 {
  display: none;
}

#show1:checked ~ #content1 {
  display: block;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="show">
<label for="show">check1</label>|
<input type="checkbox"id="show1">
<label for="show1">check2</label>

<span id="content">jvdkvdkvjdl</span>

<span id="content1">dkjvvhjvhkjdklhdlvk</span></code>```

Body:
Below code has id for different checkbox and for there contents , onclick of any checkboxthat content will be display:

#content {
  display: none;
}

#show:checked ~ #content {
  display: block;
 }

#content1 {
  display: none;
}

#show1:checked ~ #content1 {
  display: block;
  }

<input type="checkbox" id="show">
<label for="show">check1</label>|
<input type="checkbox"id="show1">
<label for="show1">check2</label>

<span id="content">jvdkvdkvjdl</span>

<span id="content1">dkjvvhjvhkjdklhdlvk</span>


问:
How to run a command in another pod in another namespace from an Airflow worker in a Kubernetes cluster
I want to run a papermill command in a pod and get the errors (if any). This has to be done from an Airflow worker using the bash operator i Airflow.

I have tried running the command as needed, I have tried running multiple bash commands from my own worker, commands that were meant to be executed inside the worker. But this just gives me the idea that something like this is possible. Although, if there is any better approach that would solve this, I am all ears.

The bash command to be run is:

```<code>papermill check1.ipynb check1_output.ipynb -p params '{"aviral":"srivastava", "apoorv":"srivastava"}'
</code>```

Manually, I exec in my pod and then run this command. I want to make this a bash command in airflow's dag.

答:
To use kubectl from within a pod you need to have binaries available in your pod.

You can either Create a Docker image with installation of kubectl.

I think the Dockerfile might look like this:

```<code>FROM ubuntu:14.04

# Install.
RUN \
  sed -i 's/# \(.*multiverse$\)/\1/g' /etc/apt/sources.list && \
  apt-get update && \
  apt-get -y upgrade && \
  apt-get install -y build-essential && \
  apt-get install -y software-properties-common && \
  apt-get install -y byobu curl git htop man unzip vim wget && \
  rm -rf /var/lib/apt/lists/* && \
# Installing kubectl using native package management
  apt-get install -y apt-transport-https && \
  curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - && \
  echo 'deb https://apt.kubernetes.io/ kubernetes-xenial main' | sudo tee -a /etc/apt/sources.list.d/kubernetes.list && \
  apt-get update && \
  apt-get install -y kubectl

# Add files.
ADD root/.bashrc /root/.bashrc
ADD root/.gitconfig /root/.gitconfig
ADD root/.scripts /root/.scripts

# Set environment variables.
ENV HOME /root

# Define working directory.
WORKDIR /root

# Define default command.
CMD ["bash"]
</code>```

Or Define a Command and Arguments for a Container and use it to install kubectl when pod is starting.

If you want to use it from within Kubernetes Deployment the part of .yaml might look like this:

```<code>...
spec:
  containers:
  - name: ubuntu-with-kubectl
    image: ubuntu
    command: ["/bin/sh","-c"]
    args:
      - apt-get update && apt-get install -y apt-transport-https;
        curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -;
        echo 'deb https://apt.kubernetes.io/ kubernetes-xenial main' | tee -a /etc/apt/sources.list.d/kubernetes.list;
        apt-get update;
        apt-get install -y kubectl;
...
</code>```

You can also kubectl exec -it <pod_name> bash into the pod and install is manually using this guide Install and Set Up kubectl, but it will be gone on container restart.

Body:
I want to run a papermill command in a pod and get the errors (if any). This has to be done from an Airflow worker using the bash operator i Airflow.

I have tried running the command as needed, I have tried running multiple bash commands from my own worker, commands that were meant to be executed inside the worker. But this just gives me the idea that something like this is possible. Although, if there is any better approach that would solve this, I am all ears.

The bash command to be run is:

papermill check1.ipynb check1_output.ipynb -p params '{"aviral":"srivastava", "apoorv":"srivastava"}'

Manually, I exec in my pod and then run this command. I want to make this a bash command in airflow's dag.

Body:
To use kubectl from within a pod you need to have binaries available in your pod.

You can either Create a Docker image with installation of kubectl.

I think the Dockerfile might look like this:

FROM ubuntu:14.04

# Install.
RUN \
  sed -i 's/# \(.*multiverse$\)/\1/g' /etc/apt/sources.list && \
  apt-get update && \
  apt-get -y upgrade && \
  apt-get install -y build-essential && \
  apt-get install -y software-properties-common && \
  apt-get install -y byobu curl git htop man unzip vim wget && \
  rm -rf /var/lib/apt/lists/* && \
# Installing kubectl using native package management
  apt-get install -y apt-transport-https && \
  curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - && \
  echo 'deb https://apt.kubernetes.io/ kubernetes-xenial main' | sudo tee -a /etc/apt/sources.list.d/kubernetes.list && \
  apt-get update && \
  apt-get install -y kubectl

# Add files.
ADD root/.bashrc /root/.bashrc
ADD root/.gitconfig /root/.gitconfig
ADD root/.scripts /root/.scripts

# Set environment variables.
ENV HOME /root

# Define working directory.
WORKDIR /root

# Define default command.
CMD ["bash"]

Or Define a Command and Arguments for a Container and use it to install kubectl when pod is starting.

If you want to use it from within Kubernetes Deployment the part of .yaml might look like this:

...
spec:
  containers:
  - name: ubuntu-with-kubectl
    image: ubuntu
    command: ["/bin/sh","-c"]
    args:
      - apt-get update && apt-get install -y apt-transport-https;
        curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -;
        echo 'deb https://apt.kubernetes.io/ kubernetes-xenial main' | tee -a /etc/apt/sources.list.d/kubernetes.list;
        apt-get update;
        apt-get install -y kubectl;
...

You can also kubectl exec -it <pod_name> bash into the pod and install is manually using this guide Install and Set Up kubectl, but it will be gone on container restart.