问:
How to get date from dijit.form.DateTextBox in given format?
I have a dojo text box  in a html file.Now i want to  retrieve the date from text box in a string format 'yyyy-mm-dd'. How can i do it?

  dojoType="dijit.form.DateTextBox"
```

How can I do it?

答:
try this:
HTML:

<input type="text" name="date1" id="date1" value="2005-12-30"
   dojotype="dijit.form.DateTextBox" required="true" />
```

<p>To get displayed value you can use this method of date text box:</p>

<pre class="lang-javascript prettyprint-override"><code>// get widget:
    var dtb = dijit.byId('date1');
// get value
    alert(dtb.get('displayedValue'));
</code>```

NOTE*:

Dojo format the date according user locale.

IF you can use format which differs with user locale format you need specify constraint property for date text box.

<input type="text" name="date1" id="date1" value="2005-12-30"
  constraints="{datePattern:'yyyy-MM-dd', strict:true}"
  dojotype="dijit.form.DateTextBox" required="true" />
```

HTML Page - example

Body:
I have a dojo text box  in a html file.Now i want to  retrieve the date from text box in a string format 'yyyy-mm-dd'. How can i do it?

  dojoType="dijit.form.DateTextBox"

How can I do it?

Body:
try this:
HTML:

<input type="text" name="date1" id="date1" value="2005-12-30"
   dojotype="dijit.form.DateTextBox" required="true" />

To get displayed value you can use this method of date text box:

// get widget:
    var dtb = dijit.byId('date1');
// get value
    alert(dtb.get('displayedValue'));

NOTE*:

Dojo format the date according user locale.

IF you can use format which differs with user locale format you need specify constraint property for date text box.

<input type="text" name="date1" id="date1" value="2005-12-30"
  constraints="{datePattern:'yyyy-MM-dd', strict:true}"
  dojotype="dijit.form.DateTextBox" required="true" />

HTML Page - example


来源: stackexchange

问:
How can I Convert interface{} to sql.NullString, using reflection or otherwise
I have created a map[string]interface{}, and populated it as such.

```<code>sli := make(map[string]interface{})

    str := new(sql.NullString)

    str.String = "hello"
    str.Valid = true

    i64 := new(sql.NullInt64)

    i64.Int64 = 55
    i64.Valid = true

    sli["first"] = str
    sli["second"] = i64
</code>```

This all populates fine but when I try and accessthe string from the sql.NullString element in the map I get a panic.

interface conversion: interface {} is *sql.NullString, not
  sql.NullString

Here is the code I am using to access the string...

```<code>temp := sli["first"]
    temptype := reflect.TypeOf(temp).String()
    if temptype == "*sql.NullString" {
        s := sql.NullString{}
        s = temp.(sql.NullString)
        s2 := s.String
        fmt.Print(s2)
    }
</code>```

I have tried change the type to sql.Nullstring as the error suggested but it does not then see the if condition as true.

答:
new() creates a nil pointer to the type requested. So it's expected that you're creating a *sql.NullString rather than a sql.NullString.  Your options are:

Convert it correctly for the type:

```<code>s = temp.(*sql.NullString)
</code>```

Don't create a pointer:

```<code>str := sql.NullString{}

str.String = "hello"
str.Valid = true
</code>```

which can be shortened to:

```<code>str := sql.NullString{
    String: "hello",
    Valid:  true,
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a map[string]interface{}, and populated it as such.

sli := make(map[string]interface{})

    str := new(sql.NullString)

    str.String = "hello"
    str.Valid = true

    i64 := new(sql.NullInt64)

    i64.Int64 = 55
    i64.Valid = true

    sli["first"] = str
    sli["second"] = i64

This all populates fine but when I try and accessthe string from the sql.NullString element in the map I get a panic.

interface conversion: interface {} is *sql.NullString, not
  sql.NullString

Here is the code I am using to access the string...

temp := sli["first"]
    temptype := reflect.TypeOf(temp).String()
    if temptype == "*sql.NullString" {
        s := sql.NullString{}
        s = temp.(sql.NullString)
        s2 := s.String
        fmt.Print(s2)
    }

I have tried change the type to sql.Nullstring as the error suggested but it does not then see the if condition as true.

Body:
new() creates a nil pointer to the type requested. So it's expected that you're creating a *sql.NullString rather than a sql.NullString.  Your options are:

Convert it correctly for the type:

s = temp.(*sql.NullString)

Don't create a pointer:

str := sql.NullString{}

str.String = "hello"
str.Valid = true

which can be shortened to:

str := sql.NullString{
    String: "hello",
    Valid:  true,
}


问:
Test the existence of value in different columns
I want to search my column id equal to id1 or id2 then we add column with value of col3 in the F1. else NAN.

```<code>   d = {'id1': ["ABC","ANB","ATB","BTP"],'id2':["XXX","YYY","ZZZ","TTT"], 'Name': ["A1","A2","A3","A4"]}
   F1 = pd.DataFrame(data=d)
   d = {'id': ["ABC","ANB","ZZZ"], 'col3': [0,1,1]}
   F2 = pd.DataFrame(data=d)
</code>```

I did this line of code but it didn"t give the expected result.

```<code> pd.concat([F1.merge(F2, left_on='id1', right_on='id'),F1.merge(F2, left_on='id2', right_on='id')], axis=0).drop(['Name','id'], axis=1)
</code>```

The expected output is shown in this figure.enter image description here

答:
Use double Series.map for both columns by Series created by DataFrame.set_index with Series.fillna for replace missing values:

```<code>s = F2.set_index('id')['col3']
F1['col3'] = F1['id1'].map(s).fillna(F1['id2'].map(s))
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1   0.0
1  ANB  YYY   A2   1.0
2  ATB  ZZZ   A3   1.0
3  BTP  TTT   A4   NaN
</code>```

Details:

```<code>print (F1['id1'].map(s))
0    0.0
1    1.0
2    NaN
3    NaN
Name: id1, dtype: float64

print (F1['id2'].map(s))
0    NaN
1    NaN
2    1.0
3    NaN
Name: id2, dtype: float64

print(F1['id1'].map(s).fillna(F1['id2'].map(s)))
0    0.0
1    1.0
2    1.0
3    NaN
Name: id1, dtype: float64
</code>```

Your solution should be changed with left join and fillna:

```<code>a = F1.merge(F2, left_on='id1', right_on='id', how='left')['col3']
b = F1.merge(F2, left_on='id2', right_on='id', how='left')['col3']

F1['col3'] = a.fillna(b)
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1   0.0
1  ANB  YYY   A2   1.0
2  ATB  ZZZ   A3   1.0
3  BTP  TTT   A4   NaN
</code>```

Last if need integers in last column need pandas 0.24+ with casting by Int64:

```<code>F1['col3'] = F1['id1'].astype('Int64')
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1     0
1  ANB  YYY   A2     1
2  ATB  ZZZ   A3     1
3  BTP  TTT   A4   NaN
</code>```

Body:
I want to search my column id equal to id1 or id2 then we add column with value of col3 in the F1. else NAN.

   d = {'id1': ["ABC","ANB","ATB","BTP"],'id2':["XXX","YYY","ZZZ","TTT"], 'Name': ["A1","A2","A3","A4"]}
   F1 = pd.DataFrame(data=d)
   d = {'id': ["ABC","ANB","ZZZ"], 'col3': [0,1,1]}
   F2 = pd.DataFrame(data=d)

I did this line of code but it didn"t give the expected result.

 pd.concat([F1.merge(F2, left_on='id1', right_on='id'),F1.merge(F2, left_on='id2', right_on='id')], axis=0).drop(['Name','id'], axis=1)

The expected output is shown in this figure.enter image description here

Body:
Use double Series.map for both columns by Series created by DataFrame.set_index with Series.fillna for replace missing values:

s = F2.set_index('id')['col3']
F1['col3'] = F1['id1'].map(s).fillna(F1['id2'].map(s))
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1   0.0
1  ANB  YYY   A2   1.0
2  ATB  ZZZ   A3   1.0
3  BTP  TTT   A4   NaN

Details:

print (F1['id1'].map(s))
0    0.0
1    1.0
2    NaN
3    NaN
Name: id1, dtype: float64

print (F1['id2'].map(s))
0    NaN
1    NaN
2    1.0
3    NaN
Name: id2, dtype: float64

print(F1['id1'].map(s).fillna(F1['id2'].map(s)))
0    0.0
1    1.0
2    1.0
3    NaN
Name: id1, dtype: float64

Your solution should be changed with left join and fillna:

a = F1.merge(F2, left_on='id1', right_on='id', how='left')['col3']
b = F1.merge(F2, left_on='id2', right_on='id', how='left')['col3']

F1['col3'] = a.fillna(b)
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1   0.0
1  ANB  YYY   A2   1.0
2  ATB  ZZZ   A3   1.0
3  BTP  TTT   A4   NaN

Last if need integers in last column need pandas 0.24+ with casting by Int64:

F1['col3'] = F1['id1'].astype('Int64')
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1     0
1  ANB  YYY   A2     1
2  ATB  ZZZ   A3     1
3  BTP  TTT   A4   NaN


问:
No read permission on 'MSysObjects' (Error No: -2147217911) when Using Microsoft Excel VBA to Query Access accdb files only - mdb works fine
No read permission on 'MSysObjects' (Error No: -2147217911) when Using Microsoft Excel VBA to Query Access accdb files only - mdb works fine

Using Microsoft Excel VBA to Query Access.

With an mdb file this connection string opens the mdb file fine and the SQL String returns the tables I want.

```<code>Connection String: Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\My Files\Word\ADA II Text\Chapters\9 -

8\Access\ADAIICH9TEST.mdb";User Id=admin;Password=;
SQL String: SELECT MSysObjects.Name From MSysObjects WHERE MSysObjects.Name Not Like "MSyS*" And Type=1 AND

Flags=0 ORDER BY MSysObjects.Name;
</code>```

With an accdb file this connection string opens the accdb file fine but the SQL throws the following error:

Error No: -2147217911       Error Desc: Record(s) cannot be read; no read permission on 'MSysObjects'.

Why does it have access to MSysObjects when reading the mdb file but not the accdb file?
How do I grant access either programmatically or from within the Access File?

I have already tried executing the following statements prior to running the SQL:

```<code>'cn.Execute "GRANT SELECT ON MSysObjects TO Admin;"
'cn.Execute "GRANT SELECT ON TABLE MSysObjects TO PUBLIC;"
</code>```

They throw the error:
Error No: -2147467259       Error Desc: Cannot open the Microsoft Access database engine workgroup information

file.

答:
Within Access you need to give permission for the default user to access the table.

In the immediate window with Access execute

```<code>CurrentProject.Connection.Execute "GRANT SELECT ON MSysObjects TO Admin;"
</code>```

And your SQL will work after that.

You might want to change your connection string.  IIRC Jet won't work after Access 2003 so try

```<code>Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\...ADAIICH9TEST.accdb;
</code>```

Body:
No read permission on 'MSysObjects' (Error No: -2147217911) when Using Microsoft Excel VBA to Query Access accdb files only - mdb works fine

Using Microsoft Excel VBA to Query Access.

With an mdb file this connection string opens the mdb file fine and the SQL String returns the tables I want.

Connection String: Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\My Files\Word\ADA II Text\Chapters\9 -

8\Access\ADAIICH9TEST.mdb";User Id=admin;Password=;
SQL String: SELECT MSysObjects.Name From MSysObjects WHERE MSysObjects.Name Not Like "MSyS*" And Type=1 AND

Flags=0 ORDER BY MSysObjects.Name;

With an accdb file this connection string opens the accdb file fine but the SQL throws the following error:

Error No: -2147217911       Error Desc: Record(s) cannot be read; no read permission on 'MSysObjects'.

Why does it have access to MSysObjects when reading the mdb file but not the accdb file?
How do I grant access either programmatically or from within the Access File?

I have already tried executing the following statements prior to running the SQL:

'cn.Execute "GRANT SELECT ON MSysObjects TO Admin;"
'cn.Execute "GRANT SELECT ON TABLE MSysObjects TO PUBLIC;"

They throw the error:
Error No: -2147467259       Error Desc: Cannot open the Microsoft Access database engine workgroup information

file.

Body:
Within Access you need to give permission for the default user to access the table.

In the immediate window with Access execute

CurrentProject.Connection.Execute "GRANT SELECT ON MSysObjects TO Admin;"

And your SQL will work after that.

You might want to change your connection string.  IIRC Jet won't work after Access 2003 so try

Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\...ADAIICH9TEST.accdb;


问:
How to push props to component without any connection and calls? Another page
How to push props to component without any connection and calls? Another page
I have profile and company employees structure i wanna do button what will show to users theirs place in structure, but this is two pages without any render and connections or calls like <OrgStructure employeeCode="test"/>

答:
If you have two Components that share common state but can't be directly coupled, you should use a global state container of whom both Components can read from.

You should check out https://react-redux.js.org/. It provides a global state container called "redux store". Components can independently subscribe to the store and get updated whenever the data in the store changes.


问:
query result only returns one value
I want to see multiple values from my query but when I start this query, the result has only one value

```<code>function get_prove_associati($num) {
    $this->db->select("prove.*");
    $this->db->where("prove.numero",$num);
    return $this->db->get("prove")->row_array();
}
</code>```

In my db , there are four rows, not only one

答:
To see all results you have to change row_array() to result_array()

```<code>function get_prove_associati($num) {
    $this->db->select("prove.*");
    $this->db->where("prove.numero",$num);
    return $this->db->get("prove")->result_array();//updated here
}
</code>```

Title: query result only returns one value

Body:
I want to see multiple values from my query but when I start this query, the result has only one value

function get_prove_associati($num) {
    $this->db->select("prove.*");
    $this->db->where("prove.numero",$num);
    return $this->db->get("prove")->row_array();
}

In my db , there are four rows, not only one

Body:
To see all results you have to change row_array() to result_array()

function get_prove_associati($num) {
    $this->db->select("prove.*");
    $this->db->where("prove.numero",$num);
    return $this->db->get("prove")->result_array();//updated here
}


问:
One Hot Encoding a single column
I am trying to use one hot encoder on the target column('Species') in the Iris dataset.

But I am getting the following errors:

ValueError: Expected 2D array, got 1D array instead:

Reshape your data either using array.reshape(-1, 1) if your data has a
  single feature or array.reshape(1, -1) if it contains a single sample.

```<code>Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm    Species
0   1   5.1 3.5 1.4         0.2     Iris-setosa
1   2   4.9 3.0 1.4         0.2     Iris-setosa
2   3   4.7 3.2 1.3         0.2     Iris-setosa
3   4   4.6 3.1 1.5         0.2     Iris-setosa
4   5   5.0 3.6 1.4         0.2     Iris-setosa
</code>```

I did google the issue and i found that most of the scikit learn estimators need a 2D array rather than a 1D array.

At the same time, I also found that we can try passing the dataframe with its index to encode single columns, but it didn't work

```<code>onehotencoder = OneHotEncoder(categorical_features=[df.columns.tolist().index('pattern_id')
X = dataset.iloc[:,1:5].values
y = dataset.iloc[:, 5].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder= LabelEncoder()
y = labelencoder.fit_transform(y)

onehotencoder = OneHotEncoder(categorical_features=[0])
y = onehotencoder.fit_transform(y)
</code>```

I am trying to encode a single categorical column and split into multiple columns (the way the encoding usually works)

答:
ValueError: Expected 2D array, got 1D array instead: Reshape your
  data either using array.reshape(-1, 1) if your data has a single
  feature or array.reshape(1, -1) if it contains a single sample.

Says that you need to convert your array to a vector.
You can do that by:

```<code>from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
import pandas as pd
import numpy as np

# load iris dataset
>>> iris = datasets.load_iris()
>>> iris = pd.DataFrame(data= np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['target'])
>>> y = iris.target.values
>>> onehotencoder = OneHotEncoder(categories='auto')
>>> y = onehotencoder.fit_transform(y.reshape(-1,1))
# y - will be sparse matrix of type '<class 'numpy.float64'>
# if you want it to be a array you need to
>>> print(y.toarray())
[[1. 0. 0.]
 [1. 0. 0.]
    . . . .
 [0. 0. 1.]
 [0. 0. 1.]]
</code>```

Also you can use get_dummies function (docs)

```<code>>>> pd.get_dummies(iris.target).head()
   0.0  1.0  2.0
0    1    0    0
1    1    0    0
2    1    0    0
3    1    0    0
4    1    0    0
</code>```

Hope that helps!

Title: One Hot Encoding a single column

Body:
I am trying to use one hot encoder on the target column('Species') in the Iris dataset.

But I am getting the following errors:

ValueError: Expected 2D array, got 1D array instead:

Reshape your data either using array.reshape(-1, 1) if your data has a
  single feature or array.reshape(1, -1) if it contains a single sample.

Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm    Species
0   1   5.1 3.5 1.4         0.2     Iris-setosa
1   2   4.9 3.0 1.4         0.2     Iris-setosa
2   3   4.7 3.2 1.3         0.2     Iris-setosa
3   4   4.6 3.1 1.5         0.2     Iris-setosa
4   5   5.0 3.6 1.4         0.2     Iris-setosa

I did google the issue and i found that most of the scikit learn estimators need a 2D array rather than a 1D array.

At the same time, I also found that we can try passing the dataframe with its index to encode single columns, but it didn't work

onehotencoder = OneHotEncoder(categorical_features=[df.columns.tolist().index('pattern_id')
X = dataset.iloc[:,1:5].values
y = dataset.iloc[:, 5].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder= LabelEncoder()
y = labelencoder.fit_transform(y)

onehotencoder = OneHotEncoder(categorical_features=[0])
y = onehotencoder.fit_transform(y)

I am trying to encode a single categorical column and split into multiple columns (the way the encoding usually works)

Body:
ValueError: Expected 2D array, got 1D array instead: Reshape your
  data either using array.reshape(-1, 1) if your data has a single
  feature or array.reshape(1, -1) if it contains a single sample.

Says that you need to convert your array to a vector.
You can do that by:

from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
import pandas as pd
import numpy as np

# load iris dataset
>>> iris = datasets.load_iris()
>>> iris = pd.DataFrame(data= np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['target'])
>>> y = iris.target.values
>>> onehotencoder = OneHotEncoder(categories='auto')
>>> y = onehotencoder.fit_transform(y.reshape(-1,1))
# y - will be sparse matrix of type '<class 'numpy.float64'>
# if you want it to be a array you need to
>>> print(y.toarray())
[[1. 0. 0.]
 [1. 0. 0.]
    . . . .
 [0. 0. 1.]
 [0. 0. 1.]]

Also you can use get_dummies function (docs)

>>> pd.get_dummies(iris.target).head()
   0.0  1.0  2.0
0    1    0    0
1    1    0    0
2    1    0    0
3    1    0    0
4    1    0    0

Hope that helps!


问:
Where should i store current user in node.js?
As with almost any web application, I need a way to reference the current user in my node.js app.

I have the login/session system working, but I noticed today that when I login to my app in one browser, and view it in another, I can see the same data that I see in the first browser.

I am currently storing the information about the current user in a global app.current_user object, but I realize now that this is shared across all requests/sessions because node.js is single-threaded - and therefore, is a bad idea.

What would be the correct way to store the reference to the current user? The current user is not just a hash of user data, but a Mongoose model, so I guess storing in a cookie would not be a good idea?

BTW - I also store the user's settings and a few more things that I do not want to fetch again each time I do something with the user and their settings (which can happen quite a few times during a single request). I guess you could say I'm caching the current user in memory.

答:
Since you have sessions implemented, place before all routes, a middleware that finds the currently logged in user and store it in res.locals. This make the user data available for all routes which you can access anywhere in your app like below.

The else if section is for remember me functionality. This functionality stores the remember token and userid in the cookie object/signedCookie object depending on whether there was a secret or not.

```<code>app.use(function(req, res, next){
    if (req.session.userId){
        User.findById(req.session.userId, function(err, u){
        res.locals.currentUser = res.locals.currentUser || u
        next()
        })
    }else if (req.signedCookies.userID){ // if the user previously checked remember me
        User.findById(req.signedCookies.userID, function(err, u){
            if (u && u.authenticated(req.signedCookies.rToken, u.rememberDigest)){
                req.session.userId = u._id // re logs in user by resetting session
                res.locals.currentUser = res.locals.currentUser || u
                next()
            }
        })
    }
})
</code>```

Inspired by Micheal Hartl's Rails book

ContentLicense: CC BY-SA 3.0

Body:
Since you have sessions implemented, place before all routes, a middleware that finds the currently logged in user and store it in res.locals. This make the user data available for all routes which you can access anywhere in your app like below.

The else if section is for remember me functionality. This functionality stores the remember token and userid in the cookie object/signedCookie object depending on whether there was a secret or not.

app.use(function(req, res, next){
    if (req.session.userId){
        User.findById(req.session.userId, function(err, u){
        res.locals.currentUser = res.locals.currentUser || u
        next()
        })
    }else if (req.signedCookies.userID){ // if the user previously checked remember me
        User.findById(req.signedCookies.userID, function(err, u){
            if (u && u.authenticated(req.signedCookies.rToken, u.rememberDigest)){
                req.session.userId = u._id // re logs in user by resetting session
                res.locals.currentUser = res.locals.currentUser || u
                next()
            }
        })
    }
})

Inspired by Micheal Hartl's Rails book


问:
Image Corner Radius
Is there any way to round the corners of an ImageView through xml layout? And even if not, what are the ways we can achieve that?

PS: The image urls are being fetched from an API. Not from drawable folder

答:
I don't know what you want to make. But for the borders.

You can create a drawable file like below.

line.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <stroke android:width="2dp" android:color="#000" />
</shape>
</code>```

activity_xxx.xml

```<code>    <ImageView
        android:layout_height:"200dp"
        android:layout_width:"200dp"
        android:background:"@drawable/line.xml"
    />
</code>```

Title: Image Corner Radius

Body:
I don't know what you want to make. But for the borders.

You can create a drawable file like below.

line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <stroke android:width="2dp" android:color="#000" />
</shape>

activity_xxx.xml

    <ImageView
        android:layout_height:"200dp"
        android:layout_width:"200dp"
        android:background:"@drawable/line.xml"
    />


问:
'router-outlet' is not a known element in angular 6
I get the following error on a fresh install of angular6 using the angular-cli.

Uncaught Error: Template parse errors:
  'router-outlet' is not a known element:
  1. If 'router-outlet' is an Angular component, then verify that it is part of this module.

I followed this guide: https://medium.com/@meemo_86/good-article-beeman-490eaf1399a

And then I followed up on the comment on that article which says to use <router-outlet></router-outlet> instead of <ng-content></ng-content>.

I do those corrections, then I read up on https://angular.io/tutorial/toh-pt5, and do what is stated there.

So now I have a AppRoutingModule, I import that module in app.module.ts, where I also const the routes and added RouterModule.forRoot(appRoutes) to imports.

But I cannot get this error to go away. What am I doing wrong? When I add <router-outler></router-outlet> in my layout.component.htm, the app breaks.
I have also searched this topic here and tried several changes but nothing seems to work.

Full source code is here:

https://github.com/ekstremedia/angular6

答:
I met the same problem too. And I already imported the RouterModule inside UIModule, still doesn't work. But after I restart the app, it worked, no more errors.

So, what you should do is:
1. Import the RouterModule inside UIModule;
2. Restart your app


问:
Catch the event of a blocked instance only after a timeout
I have a program where I start several process instances using a cron. For each process instance I have a maximum time, and if the execution time exceeds it, I have to consider it as failure and use some specific methods.

For now what I did was simply to check, once my process instance has finished, if the elapsed time exceeds or not the given maximum time.

But what if my process instance gets blocked for some reason (e.g. server not responding)? I need to catch this event and perform failure operations as soon as the process gets blocked and timeout is exceeded.

How can I catch these two conditions?

I had a look at the FlowableEngineEventType, but there isn’t a PROCESS_BLOCKED/SUSPENDED type of event. But, even if it were, how do I fire it only if a certain amount of time has passed?

答:
I assume that this is the same question as this from the Flowable Forum.

If you are using the Flowable HTTP Task then have a look at the documentation to see how you can set the timeouts on it and how you can react on errors there. If you are firing GET requests from your own code you would need to write your own business logic that would throw some kind of BpmnError and you would then handle that in your process.

The Flowable Process instance does not have the concept of being blocked, and you have to manually to that in your modelling.


问:
How can I update all Angular dependencies?
I want to update all my angular dependecies but whatever I did, I could not manage to update.

```<code>Package                                   Current  Wanted  Latest
@angular/animations                        5.2.11  5.2.11  7.2.15
ckoffice
@angular/cdk                                5.2.5   5.2.5   7.3.7
ckoffice
@angular/cli                                1.7.4   1.7.4   7.3.9
ckoffice
@angular/common                            5.2.11  5.2.11  7.2.15
ckoffice
@angular/compiler                          5.2.11  5.2.11  7.2.15
ckoffice
@angular/compiler-cli                      5.2.11  5.2.11  7.2.15
ckoffice
@angular/core                              5.2.11  5.2.11  7.2.15
ckoffice
@angular/forms                             5.2.11  5.2.11  7.2.15
</code>```

ng command is not working unfortunatelly, how can I update without ng commad? I read millions of document but nothing works for me.
ng command is not working unfortunatelly, how can I update without ng commad? I read millions of document but nothing works for me.

答:
You should run ng update command with --all option will attempt to update all packages in package.json file.

However, the caveat (which seems to apply also to your case) is that it won't proceed if it discovers that some package inter-dependencies are not met.
One way to proceed anyways, is to add --force option.

Body:
I want to update all my angular dependecies but whatever I did, I could not manage to update.

Package                                   Current  Wanted  Latest
@angular/animations                        5.2.11  5.2.11  7.2.15
ckoffice
@angular/cdk                                5.2.5   5.2.5   7.3.7
ckoffice
@angular/cli                                1.7.4   1.7.4   7.3.9
ckoffice
@angular/common                            5.2.11  5.2.11  7.2.15
ckoffice
@angular/compiler                          5.2.11  5.2.11  7.2.15
ckoffice
@angular/compiler-cli                      5.2.11  5.2.11  7.2.15
ckoffice
@angular/core                              5.2.11  5.2.11  7.2.15
ckoffice
@angular/forms                             5.2.11  5.2.11  7.2.15

ng command is not working unfortunatelly, how can I update without ng commad? I read millions of document but nothing works for me.
ng command is not working unfortunatelly, how can I update without ng commad? I read millions of document but nothing works for me.


问:
Delphi - Enumerate the Disk(s) and other Drives on Windows PC

Possible Duplicate:

  Get drive information (free space, etc.) for drives on Windows and populate a memo box

I am quite new to programing (especially Delphi), and have been unable to find any examples as to how to enumerate all the drives on a PC.

I really care about Hard Disks and CD-Rom drives but I have been unable to find anything useable.

Can anyone point me in the direction of a good working sample?

答:
The simplest way is actually to use GetDiskFreeSpaceEx from the sysutils.pas file.

There are 2 parts to this example. the 1st is the important part using GetDiskFreeSpaceEX.

```<code>function DriveSpace(DriveLetter : String; var FreeSpace, UsedSpace, TotalSpace : int64) : Boolean;
begin
  Result := SysUtils.GetDiskFreeSpaceEx(Pchar(DriveLetter), UsedSpace, TotalSpace, @FreeSpace);

  if UsedSpace > 0 then
    UsedSpace := TotalSpace - FreeSpace;

  if not Result then
  begin
    UsedSpace   := 0;
    TotalSpace  := 0;
    FreeSpace   := 0;
  end;
end;
</code>```

If you are going to request drives that you already know the drive letter for such as C: then that is all you need.

Usage would be something like:

```<code>var
  FS,
  US,
  TS : Int64
begin
  DriveSpace('C:', FS, US, TS);
  //Do something with the 3 variables.
end;
</code>```

Having said that if you want to find the drives as well you could use something like this:

```<code>procedure ListDrivesOfType(DriveType : Integer; var Drives : TStringList);
var
  DriveMap,
  dMask : DWORD;
  dRoot : String;
  I     : Integer;
begin
  dRoot     := 'A:\'; //' // work around highlighting
  DriveMap  := GetLogicalDrives;
  dMask     := 1;

  for I := 0 to 32 do
  begin
    if (dMask and DriveMap) <> 0 then
      if GetDriveType(PChar(dRoot)) = DriveType then
      begin
        Drives.Add(dRoot[1] + ':');
      end;

    dMask := dMask shl 1;
    Inc(dRoot[1]);
  end;
end;
</code>```

Note the DriveType integer, should be one of the following:

```<code>DRIVE_UNKNOWN     = 0;
DRIVE_NO_ROOT_DIR = 1;
DRIVE_REMOVABLE   = 2;
DRIVE_FIXED       = 3;
DRIVE_REMOTE      = 4;
DRIVE_CDROM       = 5;
DRIVE_RAMDISK     = 6;
</code>```

(I have taken these straight out of windows.pas)

Now finally to answer your question (and this is very rough) the following would add information into a memo (called memo1) for all FIXED HARD DRIVES:

```<code>Procedure TAform.SomeNameICantThinkOfNow;
const
  BytesPerMB = 1048576;
var
  MyDrives   : TStringlist;
  I : Integer;
  FreeSpace,
  UsedSpace,
  TotalSpace : int64;
begin
  MyDrives := TStringlist.Create;
  ListDrivesOfType(DRIVE_FIXED, MyDrives);

  Memo1.Lines.Clear;

  for I := 0 to MyDrives.Count - 1 do
  begin
    FreeSpace  := 0;
    UsedSpace  := 0;
    TotalSpace := 0;

    if DriveSpace(MyDrives.Strings[I], FreeSpace, UsedSpace, TotalSpace) then
    begin
      FreeSpace  := FreeSpace  div BytesPerMB;
      UsedSpace  := UsedSpace  div BytesPerMB;
      TotalSpace := TotalSpace div BytesPerMB;

      Memo1.Lines.Add('Drive: ' + MyDrives.Strings[I] + ' = Free Space :' + IntToStr(FreeSpace) +
                      ' Used Space: ' + IntToStr(UsedSpace) + ' Total Space: ' + IntToStr(TotalSpace));
    end;
  end;
end;
</code>```

I did say it would be nasty! I have just run this up in the IDE and it works, I have done as MB but really you should convert to Double and choose your formatting if doing as MB to be more precise as the example I have create above will of course just round up.

Hope this is of some small assistance.

Body:
The simplest way is actually to use GetDiskFreeSpaceEx from the sysutils.pas file.

There are 2 parts to this example. the 1st is the important part using GetDiskFreeSpaceEX.

function DriveSpace(DriveLetter : String; var FreeSpace, UsedSpace, TotalSpace : int64) : Boolean;
begin
  Result := SysUtils.GetDiskFreeSpaceEx(Pchar(DriveLetter), UsedSpace, TotalSpace, @FreeSpace);

  if UsedSpace > 0 then
    UsedSpace := TotalSpace - FreeSpace;

  if not Result then
  begin
    UsedSpace   := 0;
    TotalSpace  := 0;
    FreeSpace   := 0;
  end;
end;

If you are going to request drives that you already know the drive letter for such as C: then that is all you need.

Usage would be something like:

var
  FS,
  US,
  TS : Int64
begin
  DriveSpace('C:', FS, US, TS);
  //Do something with the 3 variables.
end;

Having said that if you want to find the drives as well you could use something like this:

procedure ListDrivesOfType(DriveType : Integer; var Drives : TStringList);
var
  DriveMap,
  dMask : DWORD;
  dRoot : String;
  I     : Integer;
begin
  dRoot     := 'A:\'; //' // work around highlighting
  DriveMap  := GetLogicalDrives;
  dMask     := 1;

  for I := 0 to 32 do
  begin
    if (dMask and DriveMap) <> 0 then
      if GetDriveType(PChar(dRoot)) = DriveType then
      begin
        Drives.Add(dRoot[1] + ':');
      end;

    dMask := dMask shl 1;
    Inc(dRoot[1]);
  end;
end;

Note the DriveType integer, should be one of the following:

DRIVE_UNKNOWN     = 0;
DRIVE_NO_ROOT_DIR = 1;
DRIVE_REMOVABLE   = 2;
DRIVE_FIXED       = 3;
DRIVE_REMOTE      = 4;
DRIVE_CDROM       = 5;
DRIVE_RAMDISK     = 6;

(I have taken these straight out of windows.pas)

Now finally to answer your question (and this is very rough) the following would add information into a memo (called memo1) for all FIXED HARD DRIVES:

Procedure TAform.SomeNameICantThinkOfNow;
const
  BytesPerMB = 1048576;
var
  MyDrives   : TStringlist;
  I : Integer;
  FreeSpace,
  UsedSpace,
  TotalSpace : int64;
begin
  MyDrives := TStringlist.Create;
  ListDrivesOfType(DRIVE_FIXED, MyDrives);

  Memo1.Lines.Clear;

  for I := 0 to MyDrives.Count - 1 do
  begin
    FreeSpace  := 0;
    UsedSpace  := 0;
    TotalSpace := 0;

    if DriveSpace(MyDrives.Strings[I], FreeSpace, UsedSpace, TotalSpace) then
    begin
      FreeSpace  := FreeSpace  div BytesPerMB;
      UsedSpace  := UsedSpace  div BytesPerMB;
      TotalSpace := TotalSpace div BytesPerMB;

      Memo1.Lines.Add('Drive: ' + MyDrives.Strings[I] + ' = Free Space :' + IntToStr(FreeSpace) +
                      ' Used Space: ' + IntToStr(UsedSpace) + ' Total Space: ' + IntToStr(TotalSpace));
    end;
  end;
end;

I did say it would be nasty! I have just run this up in the IDE and it works, I have done as MB but really you should convert to Double and choose your formatting if doing as MB to be more precise as the example I have create above will of course just round up.

Hope this is of some small assistance.


问:
How do you check if a certain index exists in a table?
Something like this:

```<code>SELECT
*
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME ='FK_TreeNodesBinaryAssets_BinaryAssets'
and TABLE_NAME = 'TreeNodesBinaryAssets'
</code>```

but for indexes.

答:
If the hidden purpose of your question is to DROP the index before making INSERT to a large table, then this is useful one-liner:

```<code>DROP INDEX IF EXISTS [IndexName] ON [dbo].[TableName]
</code>```

This syntax is available since SQL Server 2016. Documentation for IF EXISTS:

https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/

In case you deal with a primery key instead, then use this:

```<code>ALTER TABLE [TableName] DROP CONSTRAINT IF EXISTS [PK_name]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Something like this:

SELECT
*
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME ='FK_TreeNodesBinaryAssets_BinaryAssets'
and TABLE_NAME = 'TreeNodesBinaryAssets'

but for indexes.

Body:
If the hidden purpose of your question is to DROP the index before making INSERT to a large table, then this is useful one-liner:

DROP INDEX IF EXISTS [IndexName] ON [dbo].[TableName]

This syntax is available since SQL Server 2016. Documentation for IF EXISTS:

https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/

In case you deal with a primery key instead, then use this:

ALTER TABLE [TableName] DROP CONSTRAINT IF EXISTS [PK_name]


问:
Activate the Workbook containing the code
Trying to activate active workbook after UNAPP macros, but (if many workbooks are opened) activating always last opened workbook and every time is toggling (last workbook to Activeworkbook), I need to activate ALWAYS the workbook from which code is called.</p>

```<code>Sub App()
    With Application
      .ScreenUpdating = False
      .DisplayAlerts = False
      .EnableEvents = False
      .Calculation = xlManual
      .Visible = False
    End With
End Sub

Sub unApp()
    With Application
      .ScreenUpdating = True
      .DisplayAlerts = True
      .EnableEvents = True
      .Calculation = xlCalculationAutomatic
      .Visible = True
    End With
End Sub

Sub testActivate()
    Set wbT = ThisWorkbook
    App
    unApp
    wbT.Activate
End Sub
</code>```

答:
Generally, is not a good idea to use .Activate. In my opinion the best way to indirect with Workbooks is to set workbooks in variables and then use that variable in a With Statement.

```<code>Option Explicit

Sub test()

    Dim wb1 As Workbook, wb2 As Workbook

    Set wb1 = Workbooks("Book1")
    Set wb2 = Workbooks("Book2")

    With wb2
        'Close is just an example
        .Close
    End With

End Sub
</code>```

Body:
Trying to activate active workbook after UNAPP macros, but (if many workbooks are opened) activating always last opened workbook and every time is toggling (last workbook to Activeworkbook), I need to activate ALWAYS the workbook from which code is called.

Sub App()
    With Application
      .ScreenUpdating = False
      .DisplayAlerts = False
      .EnableEvents = False
      .Calculation = xlManual
      .Visible = False
    End With
End Sub

Sub unApp()
    With Application
      .ScreenUpdating = True
      .DisplayAlerts = True
      .EnableEvents = True
      .Calculation = xlCalculationAutomatic
      .Visible = True
    End With
End Sub

Sub testActivate()
    Set wbT = ThisWorkbook
    App
    unApp
    wbT.Activate
End Sub

Body:
Generally, is not a good idea to use .Activate. In my opinion the best way to indirect with Workbooks is to set workbooks in variables and then use that variable in a With Statement.

Option Explicit

Sub test()

    Dim wb1 As Workbook, wb2 As Workbook

    Set wb1 = Workbooks("Book1")
    Set wb2 = Workbooks("Book2")

    With wb2
        'Close is just an example
        .Close
    End With

End Sub


问:
How to use vue-i18n translate function in script part of component
I'm using laravel-vue-i18n-generator package to handle text translation in vuejs component in my laravel project. I've set up app.js like below:

import VueInternationalization from 'vue-i18n';
import Locale from './vue-i18n-locales.generated';

Vue.use(VueInternationalization);

const lang = 'fa';

const i18n = new VueInternationalization({
    locale: lang,
    messages: Locale
});

const app = new Vue({
    el: '#app',
    i18n,
});

```

<p>And in component:</p>

```<template>

</template>

```

Fortunately $t('component.delete.title') works correctly on template part, but in script part, I've got this error:

Uncaught TypeError: Cannot read property 't' of undefined

Where do I go wrong?

答:
This works for me.

I have a locales folder with index.js importing the two language files im using,
in this file add.

```<code>global.$t = Vue.t
</code>```

Referred to in the script part directly as

```<code>return $t('backend.faq.main')
</code>```

Body:
I'm using laravel-vue-i18n-generator package to handle text translation in vuejs component in my laravel project. I've set up app.js like below:

import VueInternationalization from 'vue-i18n';
import Locale from './vue-i18n-locales.generated';

Vue.use(VueInternationalization);

const lang = 'fa';

const i18n = new VueInternationalization({
    locale: lang,
    messages: Locale
});

const app = new Vue({
    el: '#app',
    i18n,
});

And in component:

<template>

</template>

Fortunately $t('component.delete.title') works correctly on template part, but in script part, I've got this error:

Uncaught TypeError: Cannot read property 't' of undefined

Where do I go wrong?

Body:
This works for me.

I have a locales folder with index.js importing the two language files im using,
in this file add.

global.$t = Vue.t

Referred to in the script part directly as

return $t('backend.faq.main')


问:
How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?
How can I trigger build of another job from inside the Jenkinsfile?

I assume that this job is another repository under the same github organization, one that already has its own Jenkins file.

I also want to do this only if the branch name is master, as it doesn't make sense to trigger downstream builds of any local branches.

Update:

```<code>stage 'test-downstream'
node {
     def job = build job: 'some-downtream-job-name'
}
</code>```

Still, when executed I get an error

No parameterized job named some-downtream-job-name found

I am sure that this job exists in jenkins and is under the same organization folder as the current one. It is another job that has its own Jenkinsfile.

Please note that this question is specific to the GitHub Organization Plugin which auto-creates and maintains jobs for each repository and branch from your GitHub Organization.

答:
Use build job plugin for that task in order to trigger other jobs from jenkins file.
You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.

1.example for triggering external job from jenkins file with conditional example:

```<code>if (env.BRANCH_NAME == 'master') {
  build job:'exactJobName' , parameters:[
    string(name: 'keyNameOfParam1',value: 'valueOfParam1')
    booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
 ]
}
</code>```

2.example triggering multiple jobs from jenkins file with conditionals example:

```<code> def jobs =[
    'job1Title'{
    if (env.BRANCH_NAME == 'master') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
        booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
     ]
    }
},
    'job2Title'{
    if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam3',value: 'valueOfParam3')
        booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
        booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
     ]
    }
}
</code>```

Body:
How can I trigger build of another job from inside the Jenkinsfile?

I assume that this job is another repository under the same github organization, one that already has its own Jenkins file.

I also want to do this only if the branch name is master, as it doesn't make sense to trigger downstream builds of any local branches.

Update:

stage 'test-downstream'
node {
     def job = build job: 'some-downtream-job-name'
}

Still, when executed I get an error

No parameterized job named some-downtream-job-name found

I am sure that this job exists in jenkins and is under the same organization folder as the current one. It is another job that has its own Jenkinsfile.

Please note that this question is specific to the GitHub Organization Plugin which auto-creates and maintains jobs for each repository and branch from your GitHub Organization.

Body:
Use build job plugin for that task in order to trigger other jobs from jenkins file.
You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.

1.example for triggering external job from jenkins file with conditional example:

if (env.BRANCH_NAME == 'master') {
  build job:'exactJobName' , parameters:[
    string(name: 'keyNameOfParam1',value: 'valueOfParam1')
    booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
 ]
}

2.example triggering multiple jobs from jenkins file with conditionals example:

 def jobs =[
    'job1Title'{
    if (env.BRANCH_NAME == 'master') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
        booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
     ]
    }
},
    'job2Title'{
    if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam3',value: 'valueOfParam3')
        booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
        booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
     ]
    }
}


问:
How to insert missing values between two specific values from another table and then copy down the other column's values
In my main table, I have a date, an article and a category column. Rows are only added when a category changes. I am looking to build a query that shows the date range in-between the category changes. I have a separate table that contains the full date range.

So the query should copy in the missing dates between when the article was first and then next added to the table. Then copy down the article and it's category until the next addition.

Before:

```<code>Date    Article Category
20190101    1234    A
20190105    1234    C
</code>```

After:

```<code>Date    Article Category
20190101    1234    A
20190102    1234    A
20190103    1234    A
20190104    1234    A
20190105    1234    C
</code>```

答:
Try this:</p>

```<code>with tab (Date, Article, Category) as (values
  (20190101, 1234, 'A')
, (20190105, 1234, 'C')
--, (20190108, 1234, 'D')
)
-- We use date arithmetic below,
-- so it's better to understand if we convert int to date beforehand
, mytab (Date, Article, Category) as (
select date(to_date(char(date), 'YYYYMMDD')) as Date, Article, Category
from tab
)
, a (date_max, date, article, category) as (
select g.date_max, m.date, m.article, m.category
from
(
  select
    article
  , min(date) date_min
  , max(date) date_max
  from mytab
  group by article
) g
join mytab m on m.article=g.article and m.date=g.date_min
  union all
select
  a.date_max, a.date + 1 day as date
, a.article
, coalesce(
(
select m.category
from mytab m
where m.article=a.article and m.date=a.date + 1 day
)
, a.category) as category
from a
where a.date_max <> a.date
)
select
  --back to int from date
  int(to_char(date, 'YYYYMMDD')) as date
, article, category
from a;
</code>```

Body:
In my main table, I have a date, an article and a category column. Rows are only added when a category changes. I am looking to build a query that shows the date range in-between the category changes. I have a separate table that contains the full date range.

So the query should copy in the missing dates between when the article was first and then next added to the table. Then copy down the article and it's category until the next addition.

Before:

Date    Article Category
20190101    1234    A
20190105    1234    C

After:

Date    Article Category
20190101    1234    A
20190102    1234    A
20190103    1234    A
20190104    1234    A
20190105    1234    C

Body:
Try this:

with tab (Date, Article, Category) as (values
  (20190101, 1234, 'A')
, (20190105, 1234, 'C')
--, (20190108, 1234, 'D')
)
-- We use date arithmetic below,
-- so it's better to understand if we convert int to date beforehand
, mytab (Date, Article, Category) as (
select date(to_date(char(date), 'YYYYMMDD')) as Date, Article, Category
from tab
)
, a (date_max, date, article, category) as (
select g.date_max, m.date, m.article, m.category
from
(
  select
    article
  , min(date) date_min
  , max(date) date_max
  from mytab
  group by article
) g
join mytab m on m.article=g.article and m.date=g.date_min
  union all
select
  a.date_max, a.date + 1 day as date
, a.article
, coalesce(
(
select m.category
from mytab m
where m.article=a.article and m.date=a.date + 1 day
)
, a.category) as category
from a
where a.date_max <> a.date
)
select
  --back to int from date
  int(to_char(date, 'YYYYMMDD')) as date
, article, category
from a;


问:
Entitlements are not valid
Recently, I have upgraded my iPhone SDK OS from version 2.2.1 to 3.0 version. After that, while building my application, I get an error that the provisioning profile has expired. So I created a new provisioning profile.

Then I made the distribution of my application with the provisioning profile. But I get an error in iTunes while synchronising my application into an iPhone device. The error message is "The application 'iGVA' was not installed on the iPhone because the entitlements are not valid."

I checked the code signing Entitlements contains the correct entitlement plist file.

How can this be solved?

答:
This happened to me as well, and the other answers did not solve it for me.

After spending half a day building, installing, cleaning, clicking to no avail - I finally erased Entitlements.plist from the box under Code Signing Entitlements, saved, and typed it in again - voila! It worked again! I never touched the actual Entitlements file, just the setting.

Title: Entitlements are not valid


问:
Flutter: ListView in a SimpleDialog
I want to show a SimpleDialog with ListView.builder in my Flutter app with this code:

```<code>showDialog(
  context: context,
  builder: (BuildContext context) {
    return new SimpleDialog(
      children: <Widget>[
        new FittedBox(
          child: new ListView(
            children: <Widget>[
              new Text("one"),
              new Text("two"),
            ],
          ),
        )
      ],
    );
  },
);
</code>```

which gives this error (sorry, I couldn't wrap the logs as code because Stackoverflow complains that there's too much code):

══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
  I/flutter ( 4481): The following assertion was thrown during performLayout():
  I/flutter ( 4481): RenderViewport does not support returning intrinsic dimensions.
  I/flutter ( 4481): Calculating the intrinsic dimensions would require instantiating every child of the viewport, which
  I/flutter ( 4481): defeats the point of viewports being lazy.
  I/flutter ( 4481): If you are merely trying to shrink-wrap the viewport in the main axis direction, consider a
  I/flutter ( 4481): RenderShrinkWrappingViewport render object (ShrinkWrappingViewport widget), which achieves that
  I/flutter ( 4481): effect without implementing the intrinsic dimension API.
  I/flutter ( 4481):
  ...
  I/flutter ( 4481): Another exception was thrown: RenderBox was not laid out: RenderPhysicalShape#83d92 relayoutBoundary=up2 NEEDS-PAINT
  I/flutter ( 4481): Another exception was thrown: 'package:flutter/src/rendering/shifted_box.dart': Failed assertion: line 310 pos 12: 'child.hasSize': is not true.
  I/flutter ( 4481): Another exception was thrown: RenderBox was not laid out: RenderPhysicalShape#83d92 relayoutBoundary=up2

I tried using Container with specific height and width, and it works, but I want the ListView to fit itself in the Dialog.

How to include a ListView in a SimpleDialog?

答:
Wraping the ListView in a Container and giving it a width: double.maxFinite, solves the problem with iOS/Android having trouble with ListView inside a dialog:

```<code>showDialog(
   context: context,
   builder: (BuildContext context) {
      return AlertDialog(
         content: Container(
            width: double.maxFinite,
            child: ListView(
               children: <Widget>[]
            ),
         ),
      );
   }
);
</code>```

In the case of a ListView inside a Column that is inside an AlertDialog:

```<code>showDialog(
   context: context,
   builder: (BuildContext context) {
      return AlertDialog(
         content: Container(
            width: double.maxFinite,
            child: Column(
               mainAxisSize: MainAxisSize.min,
               children: <Widget>[
                  Expanded(
                     child: ListView(
                        shrinkWrap: true,
                        children: <Widget>[]
                     )
                  )
               ]
            ),
         ),
      );
   }
);
</code>```

Title: Flutter: ListView in a SimpleDialog

Body:
I want to show a SimpleDialog with ListView.builder in my Flutter app with this code:

showDialog(
  context: context,
  builder: (BuildContext context) {
    return new SimpleDialog(
      children: <Widget>[
        new FittedBox(
          child: new ListView(
            children: <Widget>[
              new Text("one"),
              new Text("two"),
            ],
          ),
        )
      ],
    );
  },
);

which gives this error (sorry, I couldn't wrap the logs as code because Stackoverflow complains that there's too much code):

══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
  I/flutter ( 4481): The following assertion was thrown during performLayout():
  I/flutter ( 4481): RenderViewport does not support returning intrinsic dimensions.
  I/flutter ( 4481): Calculating the intrinsic dimensions would require instantiating every child of the viewport, which
  I/flutter ( 4481): defeats the point of viewports being lazy.
  I/flutter ( 4481): If you are merely trying to shrink-wrap the viewport in the main axis direction, consider a
  I/flutter ( 4481): RenderShrinkWrappingViewport render object (ShrinkWrappingViewport widget), which achieves that
  I/flutter ( 4481): effect without implementing the intrinsic dimension API.
  I/flutter ( 4481):
  ...
  I/flutter ( 4481): Another exception was thrown: RenderBox was not laid out: RenderPhysicalShape#83d92 relayoutBoundary=up2 NEEDS-PAINT
  I/flutter ( 4481): Another exception was thrown: 'package:flutter/src/rendering/shifted_box.dart': Failed assertion: line 310 pos 12: 'child.hasSize': is not true.
  I/flutter ( 4481): Another exception was thrown: RenderBox was not laid out: RenderPhysicalShape#83d92 relayoutBoundary=up2

I tried using Container with specific height and width, and it works, but I want the ListView to fit itself in the Dialog.

How to include a ListView in a SimpleDialog?

Body:
Wraping the ListView in a Container and giving it a width: double.maxFinite, solves the problem with iOS/Android having trouble with ListView inside a dialog:

showDialog(
   context: context,
   builder: (BuildContext context) {
      return AlertDialog(
         content: Container(
            width: double.maxFinite,
            child: ListView(
               children: <Widget>[]
            ),
         ),
      );
   }
);

In the case of a ListView inside a Column that is inside an AlertDialog:

showDialog(
   context: context,
   builder: (BuildContext context) {
      return AlertDialog(
         content: Container(
            width: double.maxFinite,
            child: Column(
               mainAxisSize: MainAxisSize.min,
               children: <Widget>[
                  Expanded(
                     child: ListView(
                        shrinkWrap: true,
                        children: <Widget>[]
                     )
                  )
               ]
            ),
         ),
      );
   }
);


问:
Angular 4 Test FileReader onload
I try to test a method for transform my file into Base64 with Dropzone.js. My method work, but for test the FileReader, it gets hard. Actually, I created a test (see below) for called the FileReader, but I can't be enter in onload property. I want to test the inner of onload property. Thank you for your answers.

My Code Coverage

My component

```<code>fileTransform(event, action): void {
  const reader = new FileReader();
  reader.onload = (evt) => {
    const file = evt.target['result'];
    if (action === 'add') {
      this.filesDrop.push(file);
    }
    if (action === 'remove') {
      const index = this.filesDrop.indexOf(file);
      if (index > -1) {
        this.filesDrop.splice(index, 1);
      }
    }
  };
  reader.readAsDataURL(event);
}
</code>```

My test

```<code>const file = {
  'upload': {
    'progress': 0,
    'total': 17343,
    'bytesSent': 0,
    'filename': 'TEST.jpeg'
  },
  'type': 'images/jpeg',
  'width': 350,
  'height': 200,
  'size': 17343,
  'name': 'TEST.jpeg',
  'dataURL': 'data:image/jpeg;base64, FOO'
};

const fileFR = {
  'bubbles': false,
  'returnValue': true,
  'target': {
    'readyState': 2,
    'result': 'data:image/jpeg;base64, FOO',
    'onload': 'bar'
  }
};

it('should fileTransform()', () => {

  spyOn(<any>window, 'FileReader').and.returnValue({
    readAsDataURL: function() {},
    onload: function() {}
  });

  component.fileTransform(fileFR, 'add');
  expect(FileReader).toHaveBeenCalled();

});
</code>```

答:
maybe a bit late but I had the same question today.
I would suggest to exclude the processing of the response and have a separate function for this.

```<code>    fileTransform(event, action): void {
      const reader = new FileReader();
      reader.onload = (evt) => {
        this.processFileLoad(evt);
      };
      reader.readAsDataURL(event);
    }

    /**
    * Function which processes the results of a file read
    * @param evt: any - the data to process
    */
    processFileLoad(evt: any){
      ...do your magic here...
    }
</code>```

Now it is possible to test processFileLoad separately and it would make the code more readable.

Title: Angular 4 Test FileReader onload

Body:
I try to test a method for transform my file into Base64 with Dropzone.js. My method work, but for test the FileReader, it gets hard. Actually, I created a test (see below) for called the FileReader, but I can't be enter in onload property. I want to test the inner of onload property. Thank you for your answers.

My Code Coverage

My component

fileTransform(event, action): void {
  const reader = new FileReader();
  reader.onload = (evt) => {
    const file = evt.target['result'];
    if (action === 'add') {
      this.filesDrop.push(file);
    }
    if (action === 'remove') {
      const index = this.filesDrop.indexOf(file);
      if (index > -1) {
        this.filesDrop.splice(index, 1);
      }
    }
  };
  reader.readAsDataURL(event);
}

My test

const file = {
  'upload': {
    'progress': 0,
    'total': 17343,
    'bytesSent': 0,
    'filename': 'TEST.jpeg'
  },
  'type': 'images/jpeg',
  'width': 350,
  'height': 200,
  'size': 17343,
  'name': 'TEST.jpeg',
  'dataURL': 'data:image/jpeg;base64, FOO'
};

const fileFR = {
  'bubbles': false,
  'returnValue': true,
  'target': {
    'readyState': 2,
    'result': 'data:image/jpeg;base64, FOO',
    'onload': 'bar'
  }
};

it('should fileTransform()', () => {

  spyOn(<any>window, 'FileReader').and.returnValue({
    readAsDataURL: function() {},
    onload: function() {}
  });

  component.fileTransform(fileFR, 'add');
  expect(FileReader).toHaveBeenCalled();

});

Body:
maybe a bit late but I had the same question today.
I would suggest to exclude the processing of the response and have a separate function for this.

    fileTransform(event, action): void {
      const reader = new FileReader();
      reader.onload = (evt) => {
        this.processFileLoad(evt);
      };
      reader.readAsDataURL(event);
    }

    /**
    * Function which processes the results of a file read
    * @param evt: any - the data to process
    */
    processFileLoad(evt: any){
      ...do your magic here...
    }

Now it is possible to test processFileLoad separately and it would make the code more readable.


问:
How to accomodate different arguments for entity class
I am calling my entity class in an if/else-if statement for 2 different conditions and the values I pass into the parameters depend on the condition.  In the if block, I am passing 3 parameters and in the else-if block, I am passing 4.  The entity's object is throwing an error because it is expecting 4 parameters.  I want the first parameter to be optional and I'd like to know if there is a way to do that in Kotlin.

This is my entity class:

```<code>@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null,

    val username: String? = null,
    val hint: String? = null,
    val password: String? = null)
</code>```

And this is the if/else-if block where I'm inserting values into the entity object:

```<code>if (requestCode == ADD_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(username, hint, password)
            ...

        } else if (requestCode == EDIT_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(id, username, hint, password)
            ...

        }
</code>```

In Java, you could solve this problem by creating 2 constructors with matching number of parameters but I wonder if we can do the same in Kotlin or if there is a different approach.

答:
You can and probably should use multiple constructors.

The downside with your approach is that all the properties must be optional for technical reasons. But I guess, username and password actually are mandatory. The consequences are loss of compile time checks (and therefore prone to NPEs) and cumbersome reading (!! needed when accessing username).

You can avoid these problems following this approach:

To make your class have the default no-arg constructor, that is required by JPA, use the compiler plugin https://kotlinlang.org/docs/reference/compiler-plugins.html#jpa-support

Make mandatory properties non-nullable (I assume, only hint is optional)

Use as many secondary constructors as you like

```<code>@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true)
    val id: Int,

    val username: String,
    val hint: String?,
    val password: String
) {
    constructor(
        username: String,
        hint: String = null,
        password: String = "change it"
    ) : this(0, username, hint, password)
}
</code>```

In a more realistic scenario, only id and username were immutable. password and hint should be allowed to change.

```<code>@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val username: String
) {
    constructor(
        username: String,
    ) : this(0, username)

    var hint: String? = null
    var password: String = "change it"
}
</code>```

Body:
I am calling my entity class in an if/else-if statement for 2 different conditions and the values I pass into the parameters depend on the condition.  In the if block, I am passing 3 parameters and in the else-if block, I am passing 4.  The entity's object is throwing an error because it is expecting 4 parameters.  I want the first parameter to be optional and I'd like to know if there is a way to do that in Kotlin.

This is my entity class:

@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null,

    val username: String? = null,
    val hint: String? = null,
    val password: String? = null)

And this is the if/else-if block where I'm inserting values into the entity object:

if (requestCode == ADD_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(username, hint, password)
            ...

        } else if (requestCode == EDIT_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(id, username, hint, password)
            ...

        }

In Java, you could solve this problem by creating 2 constructors with matching number of parameters but I wonder if we can do the same in Kotlin or if there is a different approach.

Body:
You can and probably should use multiple constructors.

The downside with your approach is that all the properties must be optional for technical reasons. But I guess, username and password actually are mandatory. The consequences are loss of compile time checks (and therefore prone to NPEs) and cumbersome reading (!! needed when accessing username).

You can avoid these problems following this approach:

To make your class have the default no-arg constructor, that is required by JPA, use the compiler plugin https://kotlinlang.org/docs/reference/compiler-plugins.html#jpa-support

Make mandatory properties non-nullable (I assume, only hint is optional)

Use as many secondary constructors as you like

@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true)
    val id: Int,

    val username: String,
    val hint: String?,
    val password: String
) {
    constructor(
        username: String,
        hint: String = null,
        password: String = "change it"
    ) : this(0, username, hint, password)
}

In a more realistic scenario, only id and username were immutable. password and hint should be allowed to change.

@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val username: String
) {
    constructor(
        username: String,
    ) : this(0, username)

    var hint: String? = null
    var password: String = "change it"
}


问:
Docker - unable to copy file after downloading due to intermediate container gets removed
I have a larger docker file involving a lot of steps (it's single stage however) at the very end of the docker file I am trying to download a configuration file and then copy it to a specific path and run the program.

```<code>EXPOSE 830

RUN wget https://myurl/supervisord.conf

COPY supervisord.conf /etc/supervisord.conf

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
</code>```

However, it seems like when the file get's downloaded successfully the intermediate docker container gets removed an another interim container gets created, and because of that it gives an error saying it can not find the configuration file.

How to avoid this situation? I have also tried using the --rm=true flag when building the docker file to avoid deleting the intermediate container and that did not solve the problem.

答:
You can directly put the file at /etc/supervisord.conf using -O with wget -

```<code>RUN wget https://myurl/supervisord.conf -O /etc/supervisord.conf
</code>```

In case you do not want this to be done by wget, you can do a normal cp -

```<code>RUN cp supervisord.conf /etc/supervisord.conf
</code>```

COPY statement in Dockerfile is basically used to copy contents from
  host to the relevant docker image layer or the container that you want to create. Your
  COPY is supposed to fail because supervisord.conf doesn't exist on
  your host.

Body:
I have a larger docker file involving a lot of steps (it's single stage however) at the very end of the docker file I am trying to download a configuration file and then copy it to a specific path and run the program.

EXPOSE 830

RUN wget https://myurl/supervisord.conf

COPY supervisord.conf /etc/supervisord.conf

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]

However, it seems like when the file get's downloaded successfully the intermediate docker container gets removed an another interim container gets created, and because of that it gives an error saying it can not find the configuration file.

How to avoid this situation? I have also tried using the --rm=true flag when building the docker file to avoid deleting the intermediate container and that did not solve the problem.

Body:
You can directly put the file at /etc/supervisord.conf using -O with wget -

RUN wget https://myurl/supervisord.conf -O /etc/supervisord.conf

In case you do not want this to be done by wget, you can do a normal cp -

RUN cp supervisord.conf /etc/supervisord.conf

COPY statement in Dockerfile is basically used to copy contents from
  host to the relevant docker image layer or the container that you want to create. Your
  COPY is supposed to fail because supervisord.conf doesn't exist on
  your host.


问:
Using xsl to parse xml output, use of variables?
I'm trying to parse an xml file output from googletest to display the results in a pretty way in an html page. I have had a fair crack at it and have a working solution. Only one thing left to do.
Currently each class has a header and each function+test is displayed underneath, I'm looking for a way to extract the function name from the xml attribute to have it as its own sub-heading. Example below

Current Output

Class Name

functionName_testName

functionName_test2Name

function2Name_testName

Desired Output

Class Name

functionName

testName

test2Name

function2Name

testName

XML To be Parsed

```<code><testsuite name="testPacketProcessor" tests="27" failures="0" disabled="0" errors="0" time="36.875">
    <testcase name="testInitialise_IpNotSet" status="run" time="0" classname="testPacketProcessor" />
    <testcase name="testInitialise_GoodIp" status="run" time="2.046" classname="testPacketProcessor" />
    <testcase name="testInitialise_BadIp" status="run" time="0.032" classname="testPacketProcessor" />
</testsuite>
</code>```

XSL Currently Implemented

```<code><xsl:for-each select="testsuites/testsuite">
    <div class="testHeading">
        <span><xsl:value-of select="substring-after(@name,'test')"/></span>
    </div>
    <xsl:for-each select="testcase">
    <div class="testReport">
        <xsl:if test="not(starts-with(@name,'DISABLED'))"><xsl:value-of select="substring-after(@name,'test')"/></xsl:if>
        <xsl:if test="starts-with(@name,'DISABLED')"><xsl:value-of select="substring-after(@name,'DISABLED_test')"/></xsl:if>
        <xsl:text> - </xsl:text>
        <xsl:if test="starts-with(@status,'run')">
            <xsl:if test="failure"><xsl:text>Fail</xsl:text></xsl:if>
            <xsl:if test= "not(failure)"><xsl:text>Pass</xsl:text></xsl:if>
        </xsl:if>
        <xsl:if test="starts-with(@status,'not')"><xsl:text>Disabled</xsl:text></xsl:if>
    </div>
    </xsl:for-each>
</xsl:for-each>
</code>```

Using the above xml as an example I would like a subheading of "Initialise" under the packet processor heading with each test doucumented under the subheading

Any advice on the best way to go about this would be much appreciated. I've looked at xsl variables but cannot fathom how to deal with not being able to change the value. Have also read a little on xsl templates and recursion but I'm not sure how that would work for this situation.

Thanks in advance

Dougie

答:
This transformation produces the subheading and name for each testcase:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="testcase">
  Subheading: <xsl:value-of select=
   "substring-before(substring-after(@name, 'test'),
                     '_'
                     )
   "/>
   Name: <xsl:value-of select="substring-after(@name, '_')"/>
   <xsl:text>\n</xsl:text>
 </xsl:template>
</xsl:stylesheet>
</code>```

When applied on the provided XML document:

```<code><testsuites>
    <testsuite name="testPacketProcessor" tests="27" failures="0" disabled="0" errors="0" time="36.875">
        <testcase name="testInitialise_IpNotSet" status="run" time="0" classname="testPacketProcessor" />
        <testcase name="testInitialise_GoodIp" status="run" time="2.046" classname="testPacketProcessor" />
        <testcase name="testInitialise_BadIp" status="run" time="0.032" classname="testPacketProcessor" />
    </testsuite>
</testsuites>
</code>```

the wanted, correct result is produced:

```<code>  Subheading: Initialise
   Name: IpNotSet

  Subheading: Initialise
   Name: GoodIp

  Subheading: Initialise
   Name: BadIp
</code>```

Explanation: Using the standard XPath functions substring-before() and substring-after()

Edit: In a comment the OP clarified that he wanted grouping by function (tired of bad questions ?):

This transformation performs the wanted grouping:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="kTestsByFunction" match="testcase"
     use="substring-before(substring-after(@name, 'test'),
                             '_'
                              )"
  />

    <xsl:template match=
     "testcase
     [generate-id()
   =
    generate-id(key('kTestsByFunction',
                    substring-before(substring-after(@name, 'test'),
                                     '_'
                                      )
                    )[1]
               )
      ]
     ">
    Subheading:
        <xsl:value-of select=
        "substring-before(substring-after(@name, 'test'),
                          '_'
                          )
     "/>
    <xsl:for-each select=
     "key('kTestsByFunction',
           substring-before(substring-after(@name, 'test'),
                                '_'
                                )
         )
     ">
      Name:
           <xsl:value-of select="substring-after(@name, '_')"/>
           <xsl:text>\n</xsl:text>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

and produces the wanted result:

```<code>    Subheading:
        Initialise
  Name:
           IpNotSet

  Name:
           GoodIp

  Name:
           BadIp
</code>```

Body:
I'm trying to parse an xml file output from googletest to display the results in a pretty way in an html page. I have had a fair crack at it and have a working solution. Only one thing left to do.
Currently each class has a header and each function+test is displayed underneath, I'm looking for a way to extract the function name from the xml attribute to have it as its own sub-heading. Example below

Current Output

Class Name

functionName_testName

functionName_test2Name

function2Name_testName

Desired Output

Class Name

functionName

testName

test2Name

function2Name

testName

XML To be Parsed

<testsuite name="testPacketProcessor" tests="27" failures="0" disabled="0" errors="0" time="36.875">
    <testcase name="testInitialise_IpNotSet" status="run" time="0" classname="testPacketProcessor" />
    <testcase name="testInitialise_GoodIp" status="run" time="2.046" classname="testPacketProcessor" />
    <testcase name="testInitialise_BadIp" status="run" time="0.032" classname="testPacketProcessor" />
</testsuite>

XSL Currently Implemented

<xsl:for-each select="testsuites/testsuite">

        <xsl:value-of select="substring-after(@name,'test')"/>

    <xsl:for-each select="testcase">

        <xsl:if test="not(starts-with(@name,'DISABLED'))"><xsl:value-of select="substring-after(@name,'test')"/></xsl:if>
        <xsl:if test="starts-with(@name,'DISABLED')"><xsl:value-of select="substring-after(@name,'DISABLED_test')"/></xsl:if>
        <xsl:text> - </xsl:text>
        <xsl:if test="starts-with(@status,'run')">
            <xsl:if test="failure"><xsl:text>Fail</xsl:text></xsl:if>
            <xsl:if test= "not(failure)"><xsl:text>Pass</xsl:text></xsl:if>
        </xsl:if>
        <xsl:if test="starts-with(@status,'not')"><xsl:text>Disabled</xsl:text></xsl:if>

    </xsl:for-each>
</xsl:for-each>

Using the above xml as an example I would like a subheading of "Initialise" under the packet processor heading with each test doucumented under the subheading

Any advice on the best way to go about this would be much appreciated. I've looked at xsl variables but cannot fathom how to deal with not being able to change the value. Have also read a little on xsl templates and recursion but I'm not sure how that would work for this situation.

Thanks in advance

Dougie

Body:
This transformation produces the subheading and name for each testcase:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="testcase">
  Subheading: <xsl:value-of select=
   "substring-before(substring-after(@name, 'test'),
                     '_'
                     )
   "/>
   Name: <xsl:value-of select="substring-after(@name, '_')"/>
   <xsl:text>&#xA;</xsl:text>
 </xsl:template>
</xsl:stylesheet>

When applied on the provided XML document:

<testsuites>
    <testsuite name="testPacketProcessor" tests="27" failures="0" disabled="0" errors="0" time="36.875">
        <testcase name="testInitialise_IpNotSet" status="run" time="0" classname="testPacketProcessor" />
        <testcase name="testInitialise_GoodIp" status="run" time="2.046" classname="testPacketProcessor" />
        <testcase name="testInitialise_BadIp" status="run" time="0.032" classname="testPacketProcessor" />
    </testsuite>
</testsuites>

the wanted, correct result is produced:

  Subheading: Initialise
   Name: IpNotSet

  Subheading: Initialise
   Name: GoodIp

  Subheading: Initialise
   Name: BadIp

Explanation: Using the standard XPath functions substring-before() and substring-after()

Edit: In a comment the OP clarified that he wanted grouping by function (tired of bad questions ?):

This transformation performs the wanted grouping:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="kTestsByFunction" match="testcase"
     use="substring-before(substring-after(@name, 'test'),
                             '_'
                              )"
  />

    <xsl:template match=
     "testcase
     [generate-id()
   =
    generate-id(key('kTestsByFunction',
                    substring-before(substring-after(@name, 'test'),
                                     '_'
                                      )
                    )[1]
               )
      ]
     ">
    Subheading:
        <xsl:value-of select=
        "substring-before(substring-after(@name, 'test'),
                          '_'
                          )
     "/>
    <xsl:for-each select=
     "key('kTestsByFunction',
           substring-before(substring-after(@name, 'test'),
                                '_'
                                )
         )
     ">
      Name:
           <xsl:value-of select="substring-after(@name, '_')"/>
           <xsl:text>&#xA;</xsl:text>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

and produces the wanted result:

    Subheading:
        Initialise
  Name:
           IpNotSet

  Name:
           GoodIp

  Name:
           BadIp


问:
Check if any of the files within a folder contain a pattern then return filename
I'm writing a script that aim to automate the fulfill of some variables and I'm looking for help to achieve this:

I have a nginx sites-enabled folder which contain some reverses proxied sites.
I need to:

check if a pattern $var1 is found in any of the files in "/volume1/nginx/sites-enabled/"

return the name of the file containing $var1 as $var2

Many thanks for your attention and help!

I have found some lines but none try any files in a folder

```<code>if grep -q $var1 "/volume1/nginx/sites-enabled/testfile"; then
  echo "found"
fi
</code>```

答:
This command is the most traditional and efficient one which works on any Unix
without the requirement to have GNU versions of grep with special features.

The efficiency is, that xargs feeds the grep command as many filenames as arguments as it is possible according to the limits of the system (how long a shell command may be) and it excecutes the grep command by this only as least as possible.

With the -l option of grep it shows you only the filename once on a successful pattern search.

```<code>find /path -type f -print | xargs grep -l pattern
</code>```

Body:
I'm writing a script that aim to automate the fulfill of some variables and I'm looking for help to achieve this:

I have a nginx sites-enabled folder which contain some reverses proxied sites.
I need to:

check if a pattern $var1 is found in any of the files in "/volume1/nginx/sites-enabled/"

return the name of the file containing $var1 as $var2

Many thanks for your attention and help!

I have found some lines but none try any files in a folder

if grep -q $var1 "/volume1/nginx/sites-enabled/testfile"; then
  echo "found"
fi

Body:
This command is the most traditional and efficient one which works on any Unix
without the requirement to have GNU versions of grep with special features.

The efficiency is, that xargs feeds the grep command as many filenames as arguments as it is possible according to the limits of the system (how long a shell command may be) and it excecutes the grep command by this only as least as possible.

With the -l option of grep it shows you only the filename once on a successful pattern search.

find /path -type f -print | xargs grep -l pattern


问:
How to check number of digits from BigDecimal?
The requirement is to check if the number of digits is less than 7 digits in that case insert in DB else don't. I have tried the following solutions:

First solution:

```<code>public static void checkNoOfDigitVal(BigDecimal bigDecVal) {
    BigInteger digits = bigDecVal.toBigInteger();
    BigInteger ten = BigInteger.valueOf(10);
    int count = 0;
    do {
        digits = digits.divide(ten);
        count++;
    } while (!digits.equals(BigInteger.ZERO));
    System.out.println("Number of digits : " + count);
}
</code>```

First solution works fine sometimes but sometimes the condition in while loop is not satisfied and it keeps on increasing the count number leading to endless count.

Second solution:

```<code>public static void checkNoOfDigitsVal(BigDecimal bigDecVal) {
    String string = bigDecVal.toString();
    String[] splitedString = string.split("\\.");
    String[] newVal = splitedString[0].split("");
    int a = newVal.length - 1;
    if (a <= 6) {
        System.out.println("correct size insert into DB: " + a);
    } else {
        System.out.println("Incorrect size insert cancel: " + a);
    }
}
</code>```

For example, if the value is 999999.9999, the second solution will return newVal.length = 6.

Please suggest a better solution to check the number of digits for big decimal where looping overhead can be minimized.

答:
Because the current answers are not robust enough IMO, Here's my solution.
This method will scale a BigDecimal to the given length, but only scales the fractional part. It will throw an Exception if the integer part will be scaled. For my use case this is what I want. Tweak it to your liking.

```<code>public static BigDecimal scaleBigDecimalToLength(BigDecimal bigDecimal, int length) throws NumbersUtilException {
  int digitCount = bigDecimal.toPlainString().replaceAll("[.,-]", "").length();
  if (digitCount > length) {
      int scale = bigDecimal.scale();
      int newScale = length - (digitCount - scale);
      if (scale > 0 && newScale >= 0) {
          bigDecimal = bigDecimal
                  .setScale(length - (digitCount - scale), RoundingMode.HALF_UP);
      } else {
          throw new NumbersUtilException(
                  String.format("Cannot scale %s to a length of %s", bigDecimal, length));
    }
  }
  return bigDecimal;
}
</code>```

scaleBigDecimalToLength(BigDecimal.valueOf(0.0000012345600000), 8)
Output: 0.0000012

Body:
The requirement is to check if the number of digits is less than 7 digits in that case insert in DB else don't. I have tried the following solutions:

First solution:

public static void checkNoOfDigitVal(BigDecimal bigDecVal) {
    BigInteger digits = bigDecVal.toBigInteger();
    BigInteger ten = BigInteger.valueOf(10);
    int count = 0;
    do {
        digits = digits.divide(ten);
        count++;
    } while (!digits.equals(BigInteger.ZERO));
    System.out.println("Number of digits : " + count);
}

First solution works fine sometimes but sometimes the condition in while loop is not satisfied and it keeps on increasing the count number leading to endless count.

Second solution:

public static void checkNoOfDigitsVal(BigDecimal bigDecVal) {
    String string = bigDecVal.toString();
    String[] splitedString = string.split("\\.");
    String[] newVal = splitedString[0].split("");
    int a = newVal.length - 1;
    if (a <= 6) {
        System.out.println("correct size insert into DB: " + a);
    } else {
        System.out.println("Incorrect size insert cancel: " + a);
    }
}

For example, if the value is 999999.9999, the second solution will return newVal.length = 6.

Please suggest a better solution to check the number of digits for big decimal where looping overhead can be minimized.

Body:
Because the current answers are not robust enough IMO, Here's my solution.
This method will scale a BigDecimal to the given length, but only scales the fractional part. It will throw an Exception if the integer part will be scaled. For my use case this is what I want. Tweak it to your liking.

public static BigDecimal scaleBigDecimalToLength(BigDecimal bigDecimal, int length) throws NumbersUtilException {
  int digitCount = bigDecimal.toPlainString().replaceAll("[.,-]", "").length();
  if (digitCount > length) {
      int scale = bigDecimal.scale();
      int newScale = length - (digitCount - scale);
      if (scale > 0 && newScale >= 0) {
          bigDecimal = bigDecimal
                  .setScale(length - (digitCount - scale), RoundingMode.HALF_UP);
      } else {
          throw new NumbersUtilException(
                  String.format("Cannot scale %s to a length of %s", bigDecimal, length));
    }
  }
  return bigDecimal;
}

scaleBigDecimalToLength(BigDecimal.valueOf(0.0000012345600000), 8)
Output: 0.0000012


问:
Why index variable not display indexing in *ngFor loop in Angular 2?
If we want to display the index of ng-repeat in angular 1,

we use the following code

```<code><div ng-repeat="car in cars">
 <ul>
  <li>Index: {{$index+1}}</li>
  <li>Car Name:{{car.name}}</li>
 </ul>
</div>
</code>```

Now when the same I implement in Angular 2, it is not displaying index value

```<code><div *ngFor="#car of cars">
 <ul>
      <li>Index: {{index+1}}</li>
      <li>Car Name:{{car.name}}</li>
     </ul>
 </div>
</code>```

But when I add #i = index in *ngFor, it suddenly display index value

```<code> <div *ngFor="#car of cars; #i = index">
     <ul>
          <li>Index: {{i+1}}</li>
          <li>Car Name:{{car.name}}</li>
         </ul>
 </div>
</code>```

As both 2nd and 3rd code are same, but it work only when we declare the local variable and assign the variable to index.

Such an ambiguous thing.

Will any one help to understand better use of this ?

答:
```<code><div *ngFor="let car of cars; index as i">
  <ul>
    <li>Index: {{i}}</li>
    <li>Car Name:{{car.name}}</li>
  </ul>
</div>
</code>```

Body:
If we want to display the index of ng-repeat in angular 1,

we use the following code

Index: {{$index+1}}

Car Name:{{car.name}}

Now when the same I implement in Angular 2, it is not displaying index value

Index: {{index+1}}

Car Name:{{car.name}}

But when I add #i = index in *ngFor, it suddenly display index value

Index: {{i+1}}

Car Name:{{car.name}}

As both 2nd and 3rd code are same, but it work only when we declare the local variable and assign the variable to index.

Such an ambiguous thing.

Will any one help to understand better use of this ?


问:
Matching std::index_sequence by default argument
Is the following allowed by template argument deduction or is that an undeduced context?

#include <utility>
#include<tuple>

template<std::size_t... I>
auto make(std::index_sequence = std::make_index_sequence<2>())
{
    return;
}

int main() {
    make();
}

```

Compile warning is pretty weird

答:
Default arguments are not part of deduction.

So you cannot do what you want here (that way).

If appropriate, you might do:

```<code>template <typename Seq = std::index_sequence<0, 1>>
auto make(Seq = std::make_index_sequence<2>())
{
    /*...*/
}
</code>```

Body:
Is the following allowed by template argument deduction or is that an undeduced context?

#include <utility>
#include<tuple>

template<std::size_t... I>
auto make(std::index_sequence = std::make_index_sequence<2>())
{
    return;
}

int main() {
    make();
}

Compile warning is pretty weird

Body:
Default arguments are not part of deduction.

So you cannot do what you want here (that way).

If appropriate, you might do:

template <typename Seq = std::index_sequence<0, 1>>
auto make(Seq = std::make_index_sequence<2>())
{
    /*...*/
}


问:
What happens if arguments passed to sscanf are cast
While reviewing and old piece of code, I stumbled upon some coding horror like this one:

```<code>struct Foo
{
    unsigned int  bar;
    unsigned char qux;
    unsigned char xyz;
    unsigned int  etc;
};

void horror(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo)
{
    sscanf(s1, "%u", &(foo->bar));
    sscanf(s2, "%u", (unsigned int*) &(foo->qux));
    sscanf(s3, "%u", (unsigned int*) &(foo->xyz));
    sscanf(s4, "%u", &(foo->etc));
}
</code>```

So, what is actually happening in the second and third sscanf, with the argument passed being a unsigned char* cast to unsigned int*, but with the format specifier for an unsigned integer? Whatever happens is due to undefined behavior, but why is this even "working"?

As far as I know, the cast effectively does nothing in this case (the actual type of the arguments passed as ... is unknown to the called function). However this has been in production for years and it has never crashed and the surrounding values apparently are not overwritten, I suppose because the members of the structure are all aligned to 32 bits. This is even reading the correct value on the target machine (a little endian 32 bit ARM) but I think that it would no longer work on a different endianness.

Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

Please note that the original question had uint32_t instead of unsigned int and unsigned char instead of uint8_t but that was just misleading and out of topic, and by the way the original code I was reviewing uses its own typedefs.

答:
Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

The <stdint.h> header and its types were introduced in C99, so a C89 compiler won't support them except as an extension.

The correct way to use the *scanf() and *printf() families of functions with the various fixed or minimum-width types is to use the macros from <inttypes.h>. For example:

```<code>#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
  int8_t foo;
  uint_least16_t bar;

  puts("Enter two numbers");
  if (scanf("%" SCNd8 " %" SCNuLEAST16, &foo, &bar) != 2) {
    fputs("Input failed!\n", stderr);
    return EXIT_FAILURE;
  }
  printf("You entered %" PRId8 " and %" PRIuLEAST16 "\n", foo, bar);
}
</code>```

Body:
While reviewing and old piece of code, I stumbled upon some coding horror like this one:

struct Foo
{
    unsigned int  bar;
    unsigned char qux;
    unsigned char xyz;
    unsigned int  etc;
};

void horror(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo)
{
    sscanf(s1, "%u", &(foo->bar));
    sscanf(s2, "%u", (unsigned int*) &(foo->qux));
    sscanf(s3, "%u", (unsigned int*) &(foo->xyz));
    sscanf(s4, "%u", &(foo->etc));
}

So, what is actually happening in the second and third sscanf, with the argument passed being a unsigned char* cast to unsigned int*, but with the format specifier for an unsigned integer? Whatever happens is due to undefined behavior, but why is this even "working"?

As far as I know, the cast effectively does nothing in this case (the actual type of the arguments passed as ... is unknown to the called function). However this has been in production for years and it has never crashed and the surrounding values apparently are not overwritten, I suppose because the members of the structure are all aligned to 32 bits. This is even reading the correct value on the target machine (a little endian 32 bit ARM) but I think that it would no longer work on a different endianness.

Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

Please note that the original question had uint32_t instead of unsigned int and unsigned char instead of uint8_t but that was just misleading and out of topic, and by the way the original code I was reviewing uses its own typedefs.

Body:
Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

The <stdint.h> header and its types were introduced in C99, so a C89 compiler won't support them except as an extension.

The correct way to use the *scanf() and *printf() families of functions with the various fixed or minimum-width types is to use the macros from <inttypes.h>. For example:

#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
  int8_t foo;
  uint_least16_t bar;

  puts("Enter two numbers");
  if (scanf("%" SCNd8 " %" SCNuLEAST16, &foo, &bar) != 2) {
    fputs("Input failed!\n", stderr);
    return EXIT_FAILURE;
  }
  printf("You entered %" PRId8 " and %" PRIuLEAST16 "\n", foo, bar);
}


问:
Socket.io: Same image not sending two times in succession
i have chat application and it has feature you can send images with but i discovered now that it can not send two images two times in succession, but you can send same images two times like this

-send image 1

-send image 2

-send image 1

i also has feature you could paste images and send with (clipboard) and it could send images in succession so i got confused what causes that?
here us my code:

Client side:

```<code>document.getElementById('fileselect').addEventListener('change', function () {
   if (this.files.length != 0) {
      var file = this.files[0],
          reader = new FileReader();

    reader.onload = function (e) {

       this.value = '';
       socket.emit('img', {
            image: e.target.result

       })
    };
       reader.readAsDataURL(file);
  };
}, false);
</code>```

and Server-side

```<code>socket.on('img', function(data) {
io.in(socket.current_room).emit('img', {image: data.image, id: socket.id});
</code>```

What is wrong? What how can i fix it

答: It's because the fileselect element doesn't get refreshed if you pick the same file twice, therefore the "change" event doesn't get triggered. Solution here : How to detect input type=file "change" for the same file?

Body:
i have chat application and it has feature you can send images with but i discovered now that it can not send two images two times in succession, but you can send same images two times like this

-send image 1

-send image 2

-send image 1

i also has feature you could paste images and send with (clipboard) and it could send images in succession so i got confused what causes that?
here us my code:

Client side:

document.getElementById('fileselect').addEventListener('change', function () {
   if (this.files.length != 0) {
      var file = this.files[0],
          reader = new FileReader();

    reader.onload = function (e) {

       this.value = '';
       socket.emit('img', {
            image: e.target.result

       })
    };
       reader.readAsDataURL(file);
  };
}, false);

and Server-side

socket.on('img', function(data) {
io.in(socket.current_room).emit('img', {image: data.image, id: socket.id});

What is wrong? What how can i fix it


问:
what is visual state in wpf? and anyone knows how to start understand and use that?
what is visual state in wpf? and anyone knows how to start understand and use that?

maybe like a complete tutorial, because i never touch visual state before. or just a simple example code

thx yeah

答:
Visual States in WPF are about controlling the appearance of controls. It is possible for the state of a control to change then have the appearance of the control change in response to the state change. For example if a control is pressed/disabled/in focus it may have a different appearance for each state. There is an example of how to use WPF's trigger mechanism to change the appearance of controls here; that will provide you with some general background information on changing the appearance of controls.
There is a nice general tutorial on WPF here and a good explanation of Visual State here.
For more advanced use there is information from Microsoft on the Visual State Manager here</p>


问:
How to analyze only a part of an image?
I want to analyse a specific part of an image, as an example I'd like to focus on the bottom right 200x200 section and count all the black pixels, so far I have:</p>

```<code>im1 = Image.open(path)
rgb_im1 = im1.convert('RGB')
for pixel in rgb_im1.getdata():
</code>```

答:
```<code>from PIL import Image
img = Image.open("ImageName.jpg")
crop_area = (a,b,c,d)
cropped_img = img.crop(crop_area)
</code>```

Title: How to analyze only a part of an image?

Body:
I want to analyse a specific part of an image, as an example I'd like to focus on the bottom right 200x200 section and count all the black pixels, so far I have:

im1 = Image.open(path)
rgb_im1 = im1.convert('RGB')
for pixel in rgb_im1.getdata():