问:
How to flatten a list of dicts from a Pandas DataFrame into several columns?
I have a pandas dataframe that looks like this:

```<code>User | Query|                                 Filters
-----------------------------------------------------------------------------------------
1    |  abc | [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]
1    |  efg | [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]
1    |  fgs | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]
2    |  hij | [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]
2    |  dcv | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]
2    |  tyu | [{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]
3    |  jhg | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]
4    |  mlh | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]
</code>```

The result that I expect:

```<code>User| Query |  date | sex | col
--------------------------------
1   | abc   | 1992  |  F  |
1   | efg   | 2000  |     | Blue
1   | fgs   | 2001  |     | Red
2   | hij   | 2002  |     |
2   | dcv   | 2001  |  F  |
2   | tyu   | 1999  |     | Yellow
3   | jhg   | 2001  |     |
4   | mlh   | 2001  |  H  |
</code>```

I'm using pandas 0.21.0 with python 2.7.

Example data:

```<code>df = pd.DataFrame([{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]},
              {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]},
              {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]},
              {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]},
              {'user': 3 ,'query': 'jhg', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]},
              {'user': 4 ,'query': 'mlh', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]},
             ])
</code>```

I tried many solutions:

Handling of nested JSON records

Pandas read nested json

Any suggestions would be much appreciated!

答:
Assuming you have already imported your data, as defined in your MCWE:

```<code>data = [{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]},
              {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]},
              {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]},
              {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]},
              {'user': 3 ,'query': 'jhg', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]},
              {'user': 4 ,'query': 'mlh', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]},
             ]
</code>```

Then, you are looking for Pandas json_normalize method for data normalization:

```<code>from pandas.io.json import json_normalize
df = json_normalize(data, 'Filters', ['query', 'user'])
</code>```

It returns a normalized DataFrame version where your column of json is expanded into eponymous typed columns:

```<code>     Op  Type     Val  user query
0   and  date    1992     1   abc
1   and   sex       F     1   abc
2   and  date    2000     1   efg
3   and   col    Blue     1   efg
4   and  date    2001     1   fgs
5   and   col     Red     1   fgs
6   and  date    2002     2   hij
7   and  date    2001     2   dcv
8   and   sex       F     2   dcv
9   and  date    1999     2   tyu
10  and   col  Yellow     2   tyu
11  and  date    2001     3   jhg
12  and   sex       M     3   jhg
13  and  date    2001     4   mlh
</code>```

Now, you would pivot your DataFrame to convert Type modalities into columns:

```<code>df = df.pivot_table(index=['user', 'query', 'Op'], columns='Type', aggfunc='first')
</code>```

It leads to:

```<code>                   Val
Type               col  date   sex
user query Op
1    abc   and    None  1992     F
     efg   and    Blue  2000  None
     fgs   and     Red  2001  None
2    dcv   and    None  2001     F
     hij   and    None  2002  None
     tyu   and  Yellow  1999  None
3    jhg   and    None  2001     M
4    mlh   and    None  2001  None
</code>```

Finally, you can clean and reset index, if they bother you:

```<code>df.columns = df.columns.droplevel(0)
df.reset_index(inplace=True)
</code>```

Which returns your requested MCVE output:

```<code>Type  user query   Op     col  date   sex
0        1   abc  and    None  1992     F
1        1   efg  and    Blue  2000  None
2        1   fgs  and     Red  2001  None
3        2   dcv  and    None  2001     F
4        2   hij  and    None  2002  None
5        2   tyu  and  Yellow  1999  None
6        3   jhg  and    None  2001     M
7        4   mlh  and    None  2001  None
</code>```

Not column

In this final DataFrame the first column seems to be called Type, but it is not. It is instead a Integer Index without Name:

```<code>df.index
RangeIndex(start=0, stop=8, step=1)
</code>```

And Columns index is called Type which does not hold any modality called Type (therefore no column with this name).

```<code>df.columns
Index(['user', 'query', 'Op', 'col', 'date', 'sex'], dtype='object', name='Type')
</code>```

This is why you cannot remove the column Type (column used in pivot_table), because it does not exist.

If you want to remove this fake column, you need to create a new index for rows:

```<code>df.set_index(['user', 'query'], inplace=True)
</code>```

If Column index Name bothers you, you can reset it:

```<code>from pandas.io.json import json_normalize
df = json_normalize(data, 'Filters', ['query', 'user'])
</code>```0

It leads to:

```<code>from pandas.io.json import json_normalize
df = json_normalize(data, 'Filters', ['query', 'user'])
</code>```1

It is a good practice when you create a new index to always check it is unique:

```<code>from pandas.io.json import json_normalize
df = json_normalize(data, 'Filters', ['query', 'user'])
</code>```2

Data from file

If your data are in a file, you should first import it into a variable using PSL json module:

```<code>import json
with open(path) as file:
    data = json.load(file)
</code>```

This will do the trick, then come back to the beginning of my answer.

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

User | Query|                                 Filters
-----------------------------------------------------------------------------------------
1    |  abc | [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]
1    |  efg | [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]
1    |  fgs | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]
2    |  hij | [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]
2    |  dcv | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]
2    |  tyu | [{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]
3    |  jhg | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]
4    |  mlh | [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]

The result that I expect:

User| Query |  date | sex | col
--------------------------------
1   | abc   | 1992  |  F  |
1   | efg   | 2000  |     | Blue
1   | fgs   | 2001  |     | Red
2   | hij   | 2002  |     |
2   | dcv   | 2001  |  F  |
2   | tyu   | 1999  |     | Yellow
3   | jhg   | 2001  |     |
4   | mlh   | 2001  |  H  |

I'm using pandas 0.21.0 with python 2.7.

Example data:

df = pd.DataFrame([{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]},
              {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]},
              {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]},
              {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]},
              {'user': 3 ,'query': 'jhg', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]},
              {'user': 4 ,'query': 'mlh', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]},
             ])

I tried many solutions:

Handling of nested JSON records

Pandas read nested json

Any suggestions would be much appreciated!

Body:
Assuming you have already imported your data, as defined in your MCWE:

data = [{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]},
              {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]},
              {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]},
              {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]},
              {'user': 3 ,'query': 'jhg', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]},
              {'user': 4 ,'query': 'mlh', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]},
             ]

Then, you are looking for Pandas json_normalize method for data normalization:

from pandas.io.json import json_normalize
df = json_normalize(data, 'Filters', ['query', 'user'])

It returns a normalized DataFrame version where your column of json is expanded into eponymous typed columns:

     Op  Type     Val  user query
0   and  date    1992     1   abc
1   and   sex       F     1   abc
2   and  date    2000     1   efg
3   and   col    Blue     1   efg
4   and  date    2001     1   fgs
5   and   col     Red     1   fgs
6   and  date    2002     2   hij
7   and  date    2001     2   dcv
8   and   sex       F     2   dcv
9   and  date    1999     2   tyu
10  and   col  Yellow     2   tyu
11  and  date    2001     3   jhg
12  and   sex       M     3   jhg
13  and  date    2001     4   mlh

Now, you would pivot your DataFrame to convert Type modalities into columns:

df = df.pivot_table(index=['user', 'query', 'Op'], columns='Type', aggfunc='first')

It leads to:

                   Val
Type               col  date   sex
user query Op
1    abc   and    None  1992     F
     efg   and    Blue  2000  None
     fgs   and     Red  2001  None
2    dcv   and    None  2001     F
     hij   and    None  2002  None
     tyu   and  Yellow  1999  None
3    jhg   and    None  2001     M
4    mlh   and    None  2001  None

Finally, you can clean and reset index, if they bother you:

df.columns = df.columns.droplevel(0)
df.reset_index(inplace=True)

Which returns your requested MCVE output:

Type  user query   Op     col  date   sex
0        1   abc  and    None  1992     F
1        1   efg  and    Blue  2000  None
2        1   fgs  and     Red  2001  None
3        2   dcv  and    None  2001     F
4        2   hij  and    None  2002  None
5        2   tyu  and  Yellow  1999  None
6        3   jhg  and    None  2001     M
7        4   mlh  and    None  2001  None

Not column

In this final DataFrame the first column seems to be called Type, but it is not. It is instead a Integer Index without Name:

df.index
RangeIndex(start=0, stop=8, step=1)

And Columns index is called Type which does not hold any modality called Type (therefore no column with this name).

df.columns
Index(['user', 'query', 'Op', 'col', 'date', 'sex'], dtype='object', name='Type')

This is why you cannot remove the column Type (column used in pivot_table), because it does not exist.

If you want to remove this fake column, you need to create a new index for rows:

df.set_index(['user', 'query'], inplace=True)

If Column index Name bothers you, you can reset it:

df.columns.name = None

It leads to:

             Op     col  date   sex
user query
1    abc    and    None  1992     F
     efg    and    Blue  2000  None
     fgs    and     Red  2001  None
2    dcv    and    None  2001     F
     hij    and    None  2002  None
     tyu    and  Yellow  1999  None
3    jhg    and    None  2001     M
4    mlh    and    None  2001  None

It is a good practice when you create a new index to always check it is unique:

df.index.is_unique
True

Data from file

If your data are in a file, you should first import it into a variable using PSL json module:

import json
with open(path) as file:
    data = json.load(file)

This will do the trick, then come back to the beginning of my answer.


来源: stackexchange

答:
```<code>import pandas as pd

df = pd.DataFrame([{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]},
              {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]},
              {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]},
              {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]},
              {'user': 3 ,'query': 'jhg', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]},
              {'user': 4 ,'query': 'mlh', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]},
             ])

def func(x):
    date = x[0]['Val']
    sex = ''
    col = ''
    if len(x) > 1:
        if x[1]['Val'] in ['F','M']:
            sex = x[1]['Val']
        else:
            col = x[1]['Val']
    return pd.Series([date,sex,col])

df[['date','sex','color']] = df['Filters'].apply(func)

df
</code>```

Outputs (not showing filter):

```<code>  query  user  date sex   color
0   abc     1  1992   F
1   efg     1  2000        Blue
2   fgs     1  2001         Red
3   hij     2  2002
4   dcv     2  2001   F
5   tyu     2  1999      Yellow
6   jhg     3  2001   M
7   mlh     4  2001
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to flatten a list of dicts from a Pandas DataFrame into several columns?

Body:
import pandas as pd

df = pd.DataFrame([{'user': 1,'query': 'abc', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'1992'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 1,'query': 'efg', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2000'},{u'Op': u'and', u'Type': u'col', u'Val': u'Blue'}]},
              {'user': 1,'query': 'fgs', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'col', u'Val': u'Red'}]},
              {'user': 2 ,'query': 'hij', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2002'}]},
              {'user': 2 ,'query': 'dcv', 'Filters': [{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'F'}]},
              {'user': 2 ,'query': 'tyu', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'1999'},{u'Op': u'and', u'Type': u'col', u'Val': u'Yellow'}]},
              {'user': 3 ,'query': 'jhg', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'},{u'Op': u'and', u'Type': u'sex', u'Val': u'M'}]},
              {'user': 4 ,'query': 'mlh', 'Filters':[{u'Op': u'and', u'Type': u'date', u'Val': u'2001'}]},
             ])

def func(x):
    date = x[0]['Val']
    sex = ''
    col = ''
    if len(x) > 1:
        if x[1]['Val'] in ['F','M']:
            sex = x[1]['Val']
        else:
            col = x[1]['Val']
    return pd.Series([date,sex,col])

df[['date','sex','color']] = df['Filters'].apply(func)

df

Outputs (not showing filter):

  query  user  date sex   color
0   abc     1  1992   F
1   efg     1  2000        Blue
2   fgs     1  2001         Red
3   hij     2  2002
4   dcv     2  2001   F
5   tyu     2  1999      Yellow
6   jhg     3  2001   M
7   mlh     4  2001

ContentLicense: CC BY-SA 3.0


问:
Find the longest diagonal of an element in a matrix-python
I fairly new to programming, so my question may seem naive.
I need a function that given a matrix like this one:

```<code>m=[['2','3','2','4','2','2','1']
   ['5','2','6','2','7','2','2']
   ['5','3','9','4','2','6','8']]
</code>```

-finds the longest diagonal of the element '2' (it doesn't have to start in row one):

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

-outputs the position of the first element of the diagonal in the matrix:

```<code>m[0][2]
</code>```

Thanks

答:
```<code>result=[0,0]
maxdiag = 0
for i in range (0, len(m)):
  for j in range (0, len(m[i])):
    k = 0;
    while (i+k < len(m) and j+k < len(m[0]) and m[i+k][j+k] == '2'):
      k+=1;
      if (k > maxdiag):
        maxdiag = k;
        result[0]=i;
        result[1]=j;
</code>```

Coordinates are stored in result.

This is, in my opinion, the empirical solution.

Iterate over the matrix, and when you find a '2', iterate "diagonally" adding the iterator k to i and j (for example, if you find a '2' on m[1][1] your loop iterates on m[2][2], m[3][3], etc...), and when you find a higher diagonal than the current one, replace the coordinates in the result (sorry for my bad english).

Body:
I fairly new to programming, so my question may seem naive.
I need a function that given a matrix like this one:

m=[['2','3','2','4','2','2','1']
   ['5','2','6','2','7','2','2']
   ['5','3','9','4','2','6','8']]

-finds the longest diagonal of the element '2' (it doesn't have to start in row one):

['2','2','2']

-outputs the position of the first element of the diagonal in the matrix:

m[0][2]

Thanks

Body:
result=[0,0]
maxdiag = 0
for i in range (0, len(m)):
  for j in range (0, len(m[i])):
    k = 0;
    while (i+k < len(m) and j+k < len(m[0]) and m[i+k][j+k] == '2'):
      k+=1;
      if (k > maxdiag):
        maxdiag = k;
        result[0]=i;
        result[1]=j;

Coordinates are stored in result.

This is, in my opinion, the empirical solution.

Iterate over the matrix, and when you find a '2', iterate "diagonally" adding the iterator k to i and j (for example, if you find a '2' on m[1][1] your loop iterates on m[2][2], m[3][3], etc...), and when you find a higher diagonal than the current one, replace the coordinates in the result (sorry for my bad english).


问:
C++ Reading numbers from a file into an array and printing them into a different array
edit here's what's on the file

```<code>76 89 150 135 200 76 12 100 150 28 178 189 167 200 175 150 87 99 129 149 176 200 87 35 157 189
</code>```

I want help with something pretty simple. Below is a program that reads a text file with a number of grades on it. The program takes those numbers, stores them in an array, then determines what category they belong in, hence the setCategories function I've written. Once it sets the categories the number of each number in a category is stored in an array and that array is printed to another text file. Or at least it's supposed to - as of right now I don't have the getData and printData functions defined, which are the two I have positioned to do all the leg work/ I need some help writing these functions, for some reason I can't seem to wrap my head around them.

```<code> #include <iostream>
#include <fstream>

using namespace std;

void getData(istream & in, int A[], int & count)
{
    while(!in.eof())
    {
        in >> A[count++];
    }
}

void printData(ostream & out, int ctd[], int count)
{
    for (int i=0; i < count; i++)
    {
        out << ctd[i] << endl;
    }
}

void setCategories(int c[], int g[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        if (g[i] > 174)
            c[7]++;
        else if (g[i] > 149)
            c[6]++;
        else if (g[i] > 124)
            c[5]++;
        else if (g[i] > 99)
            c[4]++;
        else if (g[i] > 74)
            c[3]++;
        else if (g[i] > 49)
            c[2]++;
        else if (g[i] > 24)
            c[1]++;
        else c[0]++;
    }
}

int main() {

    ofstream outFile;
    ifstream inFile;

    int categories[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    int grades[40];
    int count = 0;

    inFile.open("/Users/holdentatlow/Desktop/computer_science_projects/test_scores.txt");
    outFile.open("/Users/holdentatlow/Desktop/computer_science_projects/results.txt");

    outFile << "Matthew Holden Tatlow" << endl;

    getData(inFile, grades, count);
    setCategories(categories, grades, count);
    printData(outFile, categories, count);

    return 0;

}
</code>```

Right now, my output file is pure nonsense:

```<code>  Matthew Holden Tatlow
1
2
0
6
1
3
5
8
262169208
1
0
0
262169416
1
-1196213792
32767
-520085504
32712
-520085410
32712
-520085410
32712
0
0
0
0
</code>```

答:
Here's what worked for me:</p>

```<code>#include <iostream>
#include <fstream>

using namespace std;

void getData(istream & in, int A[], int & count)
{
    while(!in.eof())
    {
        in >> A[count++];
    }
}

void printData(ostream & out, int ctd[], int count)
{
    for (int i=0; i < 8; i++)
    {
        out << ctd[i] << endl;
    }
}

void setCategories(int c[], int g[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        if (g[i] > 174)
            c[7]++;
        else if (g[i] > 149)
            c[6]++;
        else if (g[i] > 124)
            c[5]++;
        else if (g[i] > 99)
            c[4]++;
        else if (g[i] > 74)
            c[3]++;
        else if (g[i] > 49)
            c[2]++;
        else if (g[i] > 24)
            c[1]++;
        else c[0]++;
    }
}

int main() {

    ofstream outFile;
    ifstream inFile;

    int categories[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    int grades[26];
    int count = 0;

    inFile.open("/Users/holdentatlow/Desktop/computer_science_projects/test_scores.txt");
    outFile.open("/Users/holdentatlow/Desktop/computer_science_projects/results.txt");

    outFile << "Matthew Holden Tatlow" << endl;

    getData(inFile, grades, count);
    setCategories(categories, grades, count);
    printData(outFile, categories, count);

    return 0;

}
</code>```

Body:
edit here's what's on the file

76 89 150 135 200 76 12 100 150 28 178 189 167 200 175 150 87 99 129 149 176 200 87 35 157 189

I want help with something pretty simple. Below is a program that reads a text file with a number of grades on it. The program takes those numbers, stores them in an array, then determines what category they belong in, hence the setCategories function I've written. Once it sets the categories the number of each number in a category is stored in an array and that array is printed to another text file. Or at least it's supposed to - as of right now I don't have the getData and printData functions defined, which are the two I have positioned to do all the leg work/ I need some help writing these functions, for some reason I can't seem to wrap my head around them.

 #include <iostream>
#include <fstream>

using namespace std;

void getData(istream & in, int A[], int & count)
{
    while(!in.eof())
    {
        in >> A[count++];
    }
}

void printData(ostream & out, int ctd[], int count)
{
    for (int i=0; i < count; i++)
    {
        out << ctd[i] << endl;
    }
}

void setCategories(int c[], int g[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        if (g[i] > 174)
            c[7]++;
        else if (g[i] > 149)
            c[6]++;
        else if (g[i] > 124)
            c[5]++;
        else if (g[i] > 99)
            c[4]++;
        else if (g[i] > 74)
            c[3]++;
        else if (g[i] > 49)
            c[2]++;
        else if (g[i] > 24)
            c[1]++;
        else c[0]++;
    }
}

int main() {

    ofstream outFile;
    ifstream inFile;

    int categories[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    int grades[40];
    int count = 0;

    inFile.open("/Users/holdentatlow/Desktop/computer_science_projects/test_scores.txt");
    outFile.open("/Users/holdentatlow/Desktop/computer_science_projects/results.txt");

    outFile << "Matthew Holden Tatlow" << endl;

    getData(inFile, grades, count);
    setCategories(categories, grades, count);
    printData(outFile, categories, count);

    return 0;

}

Right now, my output file is pure nonsense:

  Matthew Holden Tatlow
1
2
0
6
1
3
5
8
262169208
1
0
0
262169416
1
-1196213792
32767
-520085504
32712
-520085410
32712
-520085410
32712
0
0
0
0

Body:
Here's what worked for me:

#include <iostream>
#include <fstream>

using namespace std;

void getData(istream & in, int A[], int & count)
{
    while(!in.eof())
    {
        in >> A[count++];
    }
}

void printData(ostream & out, int ctd[], int count)
{
    for (int i=0; i < 8; i++)
    {
        out << ctd[i] << endl;
    }
}

void setCategories(int c[], int g[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        if (g[i] > 174)
            c[7]++;
        else if (g[i] > 149)
            c[6]++;
        else if (g[i] > 124)
            c[5]++;
        else if (g[i] > 99)
            c[4]++;
        else if (g[i] > 74)
            c[3]++;
        else if (g[i] > 49)
            c[2]++;
        else if (g[i] > 24)
            c[1]++;
        else c[0]++;
    }
}

int main() {

    ofstream outFile;
    ifstream inFile;

    int categories[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    int grades[26];
    int count = 0;

    inFile.open("/Users/holdentatlow/Desktop/computer_science_projects/test_scores.txt");
    outFile.open("/Users/holdentatlow/Desktop/computer_science_projects/results.txt");

    outFile << "Matthew Holden Tatlow" << endl;

    getData(inFile, grades, count);
    setCategories(categories, grades, count);
    printData(outFile, categories, count);

    return 0;

}


问:
Can you start and stop boundschecker (DevPartner)?
I'm trying to use boundschecker to analyze a rather complex program.  Running the program with boundschecker is almost too slow for it to be of any use since it takes me almost a day to run the program to the point in the code where I suspect the issue exists.  Can anyone give me some ideas for how to inspect only certain parts of my software using boundschecker (DevPartner) in Visual Studio 2005?

Thanks in advance for all your help!

答:
I last used BoundsChecker a few years ago, and had the same problems. With large projects, it makes everything run so slowly that it is useless. We ended up ditching it.

But, we still needed some of it's functionality, but like you, not for the whole program. So we had to do it ourselves.

In our case, we mainly used it to try and track down memory leaks. If that's your objective as well, there are other options.

Visual Studio does a pretty good job of telling you about memory leaks when your program exits

It reports leaks in the order that they were created

It will tell you exactly where the leaked memory was created if your source files have this at the top

```<code>#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
</code>```

Those help a lot, but it's often not enough. Adding that snippet everywhere isn't always feasible. If you use factory classes, knowing where memory was allocated doesn't help at all. So when all else fails, we take advantage of #2.

Add something like the following:

```<code>#define LEAK(str) {char *s = (char*)malloc(100); strcpy(s, str);}
</code>```

Then, pepper your code with "LEAK("leak1");" or whatever. Run the program, and exit it. Your new leaked strings will display in Visual Studio's leak dump surrounding the existing leaks. Keep adding/moving your LEAK statements and re-running the program to narrow your search until you've pinpointed the exact location. Then fix the leak, remove your debugging leaks, and you're all set!

OwnerDisplayName: Joe Crotchett

ContentLicense: CC BY-SA 2.5

Body:
I last used BoundsChecker a few years ago, and had the same problems. With large projects, it makes everything run so slowly that it is useless. We ended up ditching it.

But, we still needed some of it's functionality, but like you, not for the whole program. So we had to do it ourselves.

In our case, we mainly used it to try and track down memory leaks. If that's your objective as well, there are other options.

Visual Studio does a pretty good job of telling you about memory leaks when your program exits

It reports leaks in the order that they were created

It will tell you exactly where the leaked memory was created if your source files have this at the top

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

Those help a lot, but it's often not enough. Adding that snippet everywhere isn't always feasible. If you use factory classes, knowing where memory was allocated doesn't help at all. So when all else fails, we take advantage of #2.

Add something like the following:

#define LEAK(str) {char *s = (char*)malloc(100); strcpy(s, str);}

Then, pepper your code with "LEAK("leak1");" or whatever. Run the program, and exit it. Your new leaked strings will display in Visual Studio's leak dump surrounding the existing leaks. Keep adding/moving your LEAK statements and re-running the program to narrow your search until you've pinpointed the exact location. Then fix the leak, remove your debugging leaks, and you're all set!

OwnerDisplayName: Joe


问:
Return value of interrupt handlers in linux kernel
Interrupt handlers occur asynchronously and hence cannot be called by other functions. Then, why do interrupt handlers in the linux kernel return a value ? How are the input arguments passed to it ?</p>

答:
Interrupt handlers are not interrupt vector. Interrupt vector is the code the processor jumps to when an interrupt is triggered. This is a gross simplification, but here is how it looks :

```<code>  interrupt_vector {
    num = check_interrupt_number()
    f = get_interrupt_handler_func(num);
    d = get_interrupt_handler_data(num);
    /* call interrupt handler */
    ret = f(d);
  }
</code>```

So handler and data are registered together, and the interrupt vector code call the registererd handler, passing the registered data, and checks the return value.
Of course, here we have a single level of handler, but you can have several, with for example one handler for all PCI Irq, that in turns checks for registered handler for a specific PCI irq and eventually calls itn passing registered data etc...

Of course, real code tends to be much more complicated. You can try this lxr link to navigate through the linux kernel sources

Body:
Interrupt handlers are not interrupt vector. Interrupt vector is the code the processor jumps to when an interrupt is triggered. This is a gross simplification, but here is how it looks :

  interrupt_vector {
    num = check_interrupt_number()
    f = get_interrupt_handler_func(num);
    d = get_interrupt_handler_data(num);
    /* call interrupt handler */
    ret = f(d);
  }

So handler and data are registered together, and the interrupt vector code call the registererd handler, passing the registered data, and checks the return value.
Of course, here we have a single level of handler, but you can have several, with for example one handler for all PCI Irq, that in turns checks for registered handler for a specific PCI irq and eventually calls itn passing registered data etc...

Of course, real code tends to be much more complicated. You can try this lxr link to navigate through the linux kernel sources


问:
Invalid value encountered in greater - numpy array logic
The question "Why do I get an invalid value ..." has been discussed a few times already. Here is another variant which I don't quite understand yet - this is why I am opening this thread:

(1) in

```<code>y = np.nan
(~np.isnan(y)) & (y > 5.)
</code>```

I get the correct result and no error is thrown.

(2) However, in

```<code>y = np.array([np.isnan, 6.])
(~np.isnan(y)) & (y > 5.)
</code>```

the "Invalid value encountered in greater" warning is shown.

This means that the short-circuiting (Python reference) in the boolean and expression does not work if this expression is used with numpy arrays.

Digging a bit on stackoverflow (e.g. ref ) and elsewhere it seems that under the hood the array expression is written as

```<code>np.logical_and.reduce([~np.isnan(y), y>5.])
</code>```

This means that both expressions are first evaluated for all elements before they are combined (indeed, this produces the same warning). Could someone please confirm that this is what is happening? And does anyone have asolution for this problem other than looping over all array elements?

The context I am using this expression in is to set additional values in an array to nan if they exceed a threshold, i.e. the actual code has something like

```<code>y[(~np.isnan(y)) & (y > 5.)] = np.nan
</code>```

答:
OK: seems I have found a solution myself:

```<code>array_and = np.frompyfunc(lambda x: (~np.isnan(x)) & (x > 5.), 1, 1)
array_and(y)
</code>```

appears to work. Reference: [1]

Body:
The question "Why do I get an invalid value ..." has been discussed a few times already. Here is another variant which I don't quite understand yet - this is why I am opening this thread:

(1) in

y = np.nan
(~np.isnan(y)) & (y > 5.)

I get the correct result and no error is thrown.

(2) However, in

y = np.array([np.isnan, 6.])
(~np.isnan(y)) & (y > 5.)

the "Invalid value encountered in greater" warning is shown.

This means that the short-circuiting (Python reference) in the boolean and expression does not work if this expression is used with numpy arrays.

Digging a bit on stackoverflow (e.g. ref ) and elsewhere it seems that under the hood the array expression is written as

np.logical_and.reduce([~np.isnan(y), y>5.])

This means that both expressions are first evaluated for all elements before they are combined (indeed, this produces the same warning). Could someone please confirm that this is what is happening? And does anyone have asolution for this problem other than looping over all array elements?

The context I am using this expression in is to set additional values in an array to nan if they exceed a threshold, i.e. the actual code has something like

y[(~np.isnan(y)) & (y > 5.)] = np.nan

Body:
OK: seems I have found a solution myself:

array_and = np.frompyfunc(lambda x: (~np.isnan(x)) & (x > 5.), 1, 1)
array_and(y)

appears to work. Reference: [1]


问:
How do I keep programs in CentOS7?
I am a beginner in using Linux.
I have run programs in the server through the Windows Terminal.

```<code># gitbook build &
# ng serve &
</code>```

But when I quit the terminal window, it ended with gitbook, anguler.
How can I keep it going?
I want to know the most common ways.

答:
Try to run with nohup, it runs a command immune to hangups:

nohup gitbook build > /dev/null

or

nohup gitbook build > /dev/null &

Title: How do I keep programs in CentOS7?

Body:
I am a beginner in using Linux.
I have run programs in the server through the Windows Terminal.

# gitbook build &
# ng serve &

But when I quit the terminal window, it ended with gitbook, anguler.
How can I keep it going?
I want to know the most common ways.


问:
Get property Type and convert String to corresponding Type
I am using CSOM to update some Task of a Project Server Project.

Which property has to be updated is not defined the code finds out dynamically what to update based on the property name as String.

For better understanding I wore a simplified version of my code

```<code>//fieldName = "ActualWorkTimeSpan"; value = "16:00:00";
private void Start(string fieldName, string value)
{
    DraftTask draftTask = GetDraftTask();

    Update(draftTask, fieldName, value);

    PublishAndCheckin(draftTask);
}

private static void Update(DraftTask draftTask, string fieldName, string value)
{
    // skip updating if field is Equal
    if (GetPropValue(draftTask, fieldName).ToString() == value)
        return;

    // update of the task
    SetPropValue(draftTask, fieldName, value);

}

private static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

private static void SetPropValue(DraftTask src, string propName, object value)
{
    src.GetType().GetProperty(propName).SetValue(src, value);
}
</code>```

I can use GetPropValue() without problem but for SetPropValue() I would need the value to be in the right type.

In this case it would be "System.TimeSpan" for the property "ActualWorkTimeSpan". So I would need to convert the string "15:00:00" to TimeSpan.

It would be easy to do if it were TimeSpan every time, but I could be that the Field "Cost" is set to be updated.

```<code>Update(draftTask, "Cost", "500");
</code>```

So my question is if it is Possible to find out what type the field has and than convert my value to the same type.

答:
I use TypeDescriptor.GetConverter that takes a Type and returns a TypeConverter that knows how to convert a string to the specified Type.

You can then call TypeConverter.ConvertFromString to convert the string to the required Type.

Your code would look like:

```<code>var propType = src.GetType().GetProperty(propName).PropertyType;
var converter = TypeDescriptor.GetConverter(propType);
var convertedObject = converter.ConvertFromString(src);
</code>```

Body:
I am using CSOM to update some Task of a Project Server Project.

Which property has to be updated is not defined the code finds out dynamically what to update based on the property name as String.

For better understanding I wore a simplified version of my code

//fieldName = "ActualWorkTimeSpan"; value = "16:00:00";
private void Start(string fieldName, string value)
{
    DraftTask draftTask = GetDraftTask();

    Update(draftTask, fieldName, value);

    PublishAndCheckin(draftTask);
}

private static void Update(DraftTask draftTask, string fieldName, string value)
{
    // skip updating if field is Equal
    if (GetPropValue(draftTask, fieldName).ToString() == value)
        return;

    // update of the task
    SetPropValue(draftTask, fieldName, value);

}

private static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

private static void SetPropValue(DraftTask src, string propName, object value)
{
    src.GetType().GetProperty(propName).SetValue(src, value);
}

I can use GetPropValue() without problem but for SetPropValue() I would need the value to be in the right type.

In this case it would be "System.TimeSpan" for the property "ActualWorkTimeSpan". So I would need to convert the string "15:00:00" to TimeSpan.

It would be easy to do if it were TimeSpan every time, but I could be that the Field "Cost" is set to be updated.

Update(draftTask, "Cost", "500");

So my question is if it is Possible to find out what type the field has and than convert my value to the same type.

Body:
I use TypeDescriptor.GetConverter that takes a Type and returns a TypeConverter that knows how to convert a string to the specified Type.

You can then call TypeConverter.ConvertFromString to convert the string to the required Type.

Your code would look like:

var propType = src.GetType().GetProperty(propName).PropertyType;
var converter = TypeDescriptor.GetConverter(propType);
var convertedObject = converter.ConvertFromString(src);


问:
How to determine the correct end of a range function in Python?
I noticed that I get the exact same results when I am trying to do this, for example:

```<code>   range(1,13,2)
=> [1, 3, 5, 7, 9, 11]
</code>```

And

```<code>   range(1,12,2)
=> [1, 3, 5, 7, 9, 11]
</code>```

The result is the exact same, but which one would be correct in this case and why?

Does the end of a range have to do something with the steps you take?

Like, the idea that a list should give me 11 as the last number, so I
  should take 13 because we have a step of 2, or is this a bad thought?

答:
According to the documentation, if step is strictly positive, the largest element in the range will be the largest start + i * step less than stop.

It means that the largest element is:

```<code>start + ((stop - start - 1)//step) * step
</code>```

The result is the same for range(1,13,2) and range(1,12,2) (11) because of the integer division:

```<code>>>> 11 // 2
5
>>> 10 // 2
5
</code>```

To avoid any surprise, you could always use max + 1 as stop. For your example, that'd be range(1,12,2).

Body:
I noticed that I get the exact same results when I am trying to do this, for example:

   range(1,13,2)
=> [1, 3, 5, 7, 9, 11]

And

   range(1,12,2)
=> [1, 3, 5, 7, 9, 11]

The result is the exact same, but which one would be correct in this case and why?

Does the end of a range have to do something with the steps you take?

Like, the idea that a list should give me 11 as the last number, so I
  should take 13 because we have a step of 2, or is this a bad thought?

Body:
According to the documentation, if step is strictly positive, the largest element in the range will be the largest start + i * step less than stop.

It means that the largest element is:

start + ((stop - start - 1)//step) * step

The result is the same for range(1,13,2) and range(1,12,2) (11) because of the integer division:

>>> 11 // 2
5
>>> 10 // 2
5

To avoid any surprise, you could always use max + 1 as stop. For your example, that'd be range(1,12,2).


问:
Rename the APK file with its packageName + versionCode + versionName
I have the APK files which are named by their versionCode (default policy, APKs were pulled directly from Google).

Running this command -- aapt dump badging apk-name.apk | grep package:\ name -- gets me its package name, versionCode and versionName, all of three are needed in new name.

Let's take a Google Maps files as an example. I have this file 964100232.apk, for which I if I run this command -- aapt dump badging 964100232.apk | grep package:\ name -- it gives me this output:

package: name='com.google.android.apps.maps' versionCode='964100232' versionName='9.64.1' platformBuildVersionName='8.1.0'

My maps files is named 964100232.apk, and I need it to be com.google.android.apps.maps-964100232-9.64.1.apk

I need a command/script on Linux which allows me to rename all the APK files in the directory recursively, but the new name should be in package name-versionCode-versionName format.

Please help with this. I need this on Linux mainly, but would a windows fix would also make-do.

Thanks!

答:
You can make the apk name by the build.gradle file</p>

```<code>    buildTypes {
    release {
        lintOptions {
            disable 'MissingTranslation'
        }
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        applicationVariants.all { variant ->
            variant.outputs.each { output ->

                def flavor = "Test";
                if (variant.productFlavors.size() > 0)
                    flavor = variant.productFlavors.get(0);

                def finalName = flavor.applicationId + "-" + variant.buildType.name + "-v" + variant.versionName + '-' + variant.versionCode + ".apk";
                output.outputFile = new File(output.outputFile.parent, finalName)

            }
        }
    }
}
</code>```

Body:
You can make the apk name by the build.gradle file

    buildTypes {
    release {
        lintOptions {
            disable 'MissingTranslation'
        }
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        applicationVariants.all { variant ->
            variant.outputs.each { output ->

                def flavor = "Test";
                if (variant.productFlavors.size() > 0)
                    flavor = variant.productFlavors.get(0);

                def finalName = flavor.applicationId + "-" + variant.buildType.name + "-v" + variant.versionName + '-' + variant.versionCode + ".apk";
                output.outputFile = new File(output.outputFile.parent, finalName)

            }
        }
    }
}


问:
Converting line breaks into
 tags
I'm creating an upload form that has a text area for users to input cooking recipes with. Essentially, what I want to do is wrap each line in a
 tag for output purposes. I've been trying to manipulate the nl2br function but to no avail. Can anyone help?

I'm retrieving the text area's content via POST and storing entries in a MySQL database.
Here's what the code looks like at the moment (the check_input function strips slashes, etc.):

```<code>$prepText=check_input($_POST['preparationText']);
$cookText=check_input($_POST['cookingText']);
</code>```

答:
The simplest way to do it:</p>

```<code>function ln2ul($string) {
  return '<ul><li>' . str_replace("\n", '</li><li>', trim($string)) . '</li></ul>';
}
</code>```

Title: Converting line breaks into <li> tags

Body:
I'm creating an upload form that has a text area for users to input cooking recipes with. Essentially, what I want to do is wrap each line in a
 tag for output purposes. I've been trying to manipulate the nl2br function but to no avail. Can anyone help?

I'm retrieving the text area's content via POST and storing entries in a MySQL database.
Here's what the code looks like at the moment (the check_input function strips slashes, etc.):

$prepText=check_input($_POST['preparationText']);
$cookText=check_input($_POST['cookingText']);

Body:
The simplest way to do it:

function ln2ul($string) {
  return '<ul><li>' . str_replace("\n", '</li><li>', trim($string)) . '</li></ul>';
}


问:
String compare strange bug
I have strange bug in my code. I have variable type and when I load that from class Settings ( implements persistable ) it has value "CPU 21" (type="CPU 21"), but when I try
 if(type=="CPU 21") the condition is false. How is that possible ? </p>

答:
You have to use .equals() to compare string content:

```<code>if (type.equals("CPU 21")) ...
</code>```

This is because the == operator only compares two references to see whether they are pointing to the same object or not. Since your string type is not the same object as the literal "CPU 21", the comparison is false. The .equals() method actually checks the strings themselves.

You may also find that people often write this the other way around:

```<code>if ("CPU 21".equals(type)) ...
</code>```

This means the same thing, but will not throw an exception if type happens to be null.

Title: String compare strange bug

Body:
You have to use .equals() to compare string content:

if (type.equals("CPU 21")) ...

This is because the == operator only compares two references to see whether they are pointing to the same object or not. Since your string type is not the same object as the literal "CPU 21", the comparison is false. The .equals() method actually checks the strings themselves.

You may also find that people often write this the other way around:

if ("CPU 21".equals(type)) ...

This means the same thing, but will not throw an exception if type happens to be null.


问:
How to find the "href" of a
 a particular frame?
Image here I am trying to get the "href" of a particular frame which you can find in the image , i tried as much as i can but i am not able to get the "href"

```<code>List<WebElement> list=d.findElements(By.xpath(".//*[@id='collegeFilter']/div/div/div/div/div/div[13]/div"));
                   for(WebElement e : list){
                       String link = e.getAttribute("href");
                       System.out.println(link);
</code>```

I tried the above code , i took the Xpath of that frame and tried to get the href of that frame . Link: http://freevideolectures.com/Subject/Business-Management  [image]

答:
To get the "href" attribute of page numbers at the bottom of the page you can use the following code block :

```<code>List<WebElement> list = d.findElements(By.xpath("//ul[@class='pagination']/li/a"));
    for(WebElement e : list)
        System.out.println(e.getAttribute("href"));
</code>```

Title: How to find the "href" of a <ul> a particular frame?

Body:
Image here I am trying to get the "href" of a particular frame which you can find in the image , i tried as much as i can but i am not able to get the "href"

List<WebElement> list=d.findElements(By.xpath(".//*[@id='collegeFilter']/div/div/div/div/div/div[13]/div"));
                   for(WebElement e : list){
                       String link = e.getAttribute("href");
                       System.out.println(link);

I tried the above code , i took the Xpath of that frame and tried to get the href of that frame . Link: http://freevideolectures.com/Subject/Business-Management  [image]

Body:
To get the "href" attribute of page numbers at the bottom of the page you can use the following code block :

List<WebElement> list = d.findElements(By.xpath("//ul[@class='pagination']/li/a"));
    for(WebElement e : list)
        System.out.println(e.getAttribute("href"));


问:
How to use phpmailer and send mail as html from ckeditor
I'm use phpmailer to sending email, I have problems when inserting the contents of the html code on the form ckeditor, but data sent to the e-mail text only.

This is my code:

```<code>require_once ('class.phpmailer.php');

$mail = new PHPMailer(true);
if (isset($_POST['btn_send']))
    {

    $smtp_username = strip_tags($_POST['username']);
    $smtp_password = strip_tags($_POST['password']);
    $ssl_port = strip_tags($_POST['port']);
    $my_smtp = strip_tags($_POST['host']);
    $my_ssl = strip_tags($_POST['type']);
    $realname = strip_tags($_POST['realname']);
    $subject = strip_tags($_POST['subject']);
    $body = strip_tags($_POST['editor']);
    $emaillist = strip_tags($_POST['emaillist']);

//...now get on with sending...
try
{
//$mail->isSendmail();
        $mail->isSMTP();
        $mail->Body = ($body);
        $mail->isHTML(true);
        $mail->SMTPDebug = 0;
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = "$my_ssl";
        $mail->Host = "$my_smtp";
        $mail->Port = "$ssl_port";
        $mail->AddAddress($emaillist);
        $mail->Username = "$smtp_username";
        $mail->Password = "$smtp_password";
        $mail->SetFrom("$smtp_username", "$realname");
        $mail->AddAddress($emaillist);
        $mail->epriority = "3";
        $mail->AddReplyTo("$smtp_username");
        $mail->Subject = "$subject";
        $mail->encode = ("yes");
        $mail->CharSet = "utf-8";
if($mail->Send())
{
$msg = "<div class='alert alert-success'>
Hi,<br /> bro mail terkirim ke ".$emaillist."
</div>";
}
}
catch(phpmailerException $ex)
{
$msg = "<div class='alert alert-warning'>".$ex->errorMessage()."</div>";
}}
</code>```

I do not know what went wrong

答:
If you are using Codeigniter, you might face a problem if doing:

```<code>$body = $this->input->post('some_field_with_html_body');
</code>```

You can fix it by doing:

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

Body:
I'm use phpmailer to sending email, I have problems when inserting the contents of the html code on the form ckeditor, but data sent to the e-mail text only.

This is my code:

require_once ('class.phpmailer.php');

$mail = new PHPMailer(true);
if (isset($_POST['btn_send']))
    {

    $smtp_username = strip_tags($_POST['username']);
    $smtp_password = strip_tags($_POST['password']);
    $ssl_port = strip_tags($_POST['port']);
    $my_smtp = strip_tags($_POST['host']);
    $my_ssl = strip_tags($_POST['type']);
    $realname = strip_tags($_POST['realname']);
    $subject = strip_tags($_POST['subject']);
    $body = strip_tags($_POST['editor']);
    $emaillist = strip_tags($_POST['emaillist']);

//...now get on with sending...
try
{
//$mail->isSendmail();
        $mail->isSMTP();
        $mail->Body = ($body);
        $mail->isHTML(true);
        $mail->SMTPDebug = 0;
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = "$my_ssl";
        $mail->Host = "$my_smtp";
        $mail->Port = "$ssl_port";
        $mail->AddAddress($emaillist);
        $mail->Username = "$smtp_username";
        $mail->Password = "$smtp_password";
        $mail->SetFrom("$smtp_username", "$realname");
        $mail->AddAddress($emaillist);
        $mail->epriority = "3";
        $mail->AddReplyTo("$smtp_username");
        $mail->Subject = "$subject";
        $mail->encode = ("yes");
        $mail->CharSet = "utf-8";
if($mail->Send())
{
$msg = "

Hi,
 bro mail terkirim ke ".$emaillist."

";
}
}
catch(phpmailerException $ex)
{
$msg = "
".$ex->errorMessage()."
";
}}

I do not know what went wrong

Body:
If you are using Codeigniter, you might face a problem if doing:

$body = $this->input->post('some_field_with_html_body');

You can fix it by doing:

$body = $_POST['some_field_with_html_body'];


问:
How to select all records with relation and where clause Laravel MySQL
I'm new to Laravel so I have a bit of a problem. I have tables 'Categories' and 'Products' in my DB. In my models I setup the relations like:

Product.php:

```<code>public function category()
{
    return $this->belongsToMany(Category::class);
}
</code>```

Category.php:

```<code>public function products()
{
    return $this->hasMany(Product::class);
}
</code>```

What I need now is that I want to select all of the Categories with their related Products. (User enters in search bar category name and gets list of Categories and when user selects Category I get all of the columns from Categories and ALSO Products related with this Category).

I have tried something like this:

```<code>public function findCategory(Request $request)
{
    return Category::with('products')
        ->where('name', 'like', '%' . $request->category_name . '%')
        ->limit(15)
        ->get();
}
</code>```

ALSO:

```<code>public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')
        ->products()
        ->limit(15)
        ->get();
}
</code>```

But this doesn't seem to work and I ran out of ideas. Does anyone know if there is a way to do this? Any help would be much appreciated :)

答:
Your query is almost complete except that you didn't load related model. Therefore, you last example should be:</p>

```<code>public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')->
      ->with('products') //load related products
      ->limit(15)
      ->get();
}
</code>```

Body:
I'm new to Laravel so I have a bit of a problem. I have tables 'Categories' and 'Products' in my DB. In my models I setup the relations like:

Product.php:

public function category()
{
    return $this->belongsToMany(Category::class);
}

Category.php:

public function products()
{
    return $this->hasMany(Product::class);
}

What I need now is that I want to select all of the Categories with their related Products. (User enters in search bar category name and gets list of Categories and when user selects Category I get all of the columns from Categories and ALSO Products related with this Category).

I have tried something like this:

public function findCategory(Request $request)
{
    return Category::with('products')
        ->where('name', 'like', '%' . $request->category_name . '%')
        ->limit(15)
        ->get();
}

ALSO:

public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')
        ->products()
        ->limit(15)
        ->get();
}

But this doesn't seem to work and I ran out of ideas. Does anyone know if there is a way to do this? Any help would be much appreciated :)

Body:
Your query is almost complete except that you didn't load related model. Therefore, you last example should be:

public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')->
      ->with('products') //load related products
      ->limit(15)
      ->get();
}


问:
VBA Excel TimeValue() input possibilities
new here. Read a lot of topics but really can't figure this out.
I'm converting a string from a userform textbox to a double, representing a time. Current code works pretty good:

```<code>Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
On Error Resume Next
With textbox_inMyUserform
TimeValue(.Value)
    If Err.Number <> 0 Then
        startingTime = CDbl(.Value)
        Err.Clear
        On Error GoTo 0
    Else
        On Error GoTo 0
        startingTime = 24 * TimeValue(.Value)
    End If
End With
</code>```

the TimeValue(.value) checks if the format is correct. No error means that function is used in else, an error makes the if run a normal Cdbl(.value).

Works great, except... decimals apparantly don't trigger an error. "5" becomes 5 because of an error on TimeValue, "5:30" becomes 5,5 because no error on TimeValue but "5.5" and "5,5" don't trigger errors giving respective results of 5.0833333 and 0 through the TimeValue(.value). I expect errors on those strings?

My solution now would be to just not use decimals, but I wan't to know what's wrong.

Thanks.

update

So based on the answer of Slai I got it to work. Apparently TimeValue() in VBA and TIMEVALUE() inside of excel behave differently. Also I put my originally planned 'if not IsError()' back in.

```<code>Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
With textbox_starttijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value & """)")) Then
        startingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        startingTime = CDbl(.Value)
    Else
        startingTime = 0
    End If
End With
With textbox_eindtijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value & """)")) Then
        endingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        endingTime = CDbl(.Value)
    Else
        endingTime = 0
    End If
End With
totalTime = endingTime - startingTime
</code>```

Update 2

might as well keep this code up to date: an empty textbox in the userform throws an error at 'CDbl(.value)' so I updated the code above with an ElseIf that checks against vbNullString and the Else sets my time to 0 so the string now is never empty.

答:
The TimeValue-function tries to convert a string into a date and time field. It works similar to Excel itself. Format a cell as time and try out different values: Excel will try to interpret the value as date/time. "5.5" for example is taken as 5th of May, and as TimeValue reads only the time part, it returns 0.

Either you force the user to enter the time in the form hh:mm and check the input manually (by regEx etc), or you change you input field to a DateTime picker. On Excel <= 2010, you probably have to select this first: Right click on the Toolbox Window, choose "Additional controls..." and search "Microsoft Date and Time Picker Control". However, if you are on Excel above 2010, this is no longer installed, maybe this can help:
Excel VBA Macro - Date / Time Picker

Body:
new here. Read a lot of topics but really can't figure this out.
I'm converting a string from a userform textbox to a double, representing a time. Current code works pretty good:

Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
On Error Resume Next
With textbox_inMyUserform
TimeValue(.Value)
    If Err.Number <> 0 Then
        startingTime = CDbl(.Value)
        Err.Clear
        On Error GoTo 0
    Else
        On Error GoTo 0
        startingTime = 24 * TimeValue(.Value)
    End If
End With

the TimeValue(.value) checks if the format is correct. No error means that function is used in else, an error makes the if run a normal Cdbl(.value).

Works great, except... decimals apparantly don't trigger an error. "5" becomes 5 because of an error on TimeValue, "5:30" becomes 5,5 because no error on TimeValue but "5.5" and "5,5" don't trigger errors giving respective results of 5.0833333 and 0 through the TimeValue(.value). I expect errors on those strings?

My solution now would be to just not use decimals, but I wan't to know what's wrong.

Thanks.

update

So based on the answer of Slai I got it to work. Apparently TimeValue() in VBA and TIMEVALUE() inside of excel behave differently. Also I put my originally planned 'if not IsError()' back in.

Dim startingTime As Double, endingTime As Double
Dim totalTime As Double
With textbox_starttijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value & """)")) Then
        startingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        startingTime = CDbl(.Value)
    Else
        startingTime = 0
    End If
End With
With textbox_eindtijd
    If Not IsError(Evaluate("TIMEVALUE(""" & .Value & """)")) Then
        endingTime = 24 * TimeValue(.Value)
    ElseIf .Value <> vbNullString Then
        endingTime = CDbl(.Value)
    Else
        endingTime = 0
    End If
End With
totalTime = endingTime - startingTime

Update 2

might as well keep this code up to date: an empty textbox in the userform throws an error at 'CDbl(.value)' so I updated the code above with an ElseIf that checks against vbNullString and the Else sets my time to 0 so the string now is never empty.


问:
modify checkbox using javascript
I had declared 5 checkboxes with name and id attribute in a html:

```<code><input type="checkbox" name="category" value="One" id=11>One<br/>
<input type="checkbox" name="category" value="Two" id=12>Two<br/>
<input type="checkbox" name="category" value="Three" id=13>Three<br/>
<input type="checkbox" name="category" value="Four" id=14>Four<br/>
</code>```

After declaration, I want to run a javascript that would enable the checkbox1 using that checkbox id.

Let me know to clarify something.

答:
```<code>document.getElementById('checkbox1').checked = true;
</code>```

Title: modify checkbox using javascript

Body:
I had declared 5 checkboxes with name and id attribute in a html:

<input type="checkbox" name="category" value="One" id=11>One

<input type="checkbox" name="category" value="Two" id=12>Two

<input type="checkbox" name="category" value="Three" id=13>Three

<input type="checkbox" name="category" value="Four" id=14>Four

After declaration, I want to run a javascript that would enable the checkbox1 using that checkbox id.

Let me know to clarify something.


问:
The server was unable to process the request due to an internal error
When i try to load method from webservice, i get an error:

"The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the  configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs"

This is my app.config endpoint def:

```<code><services>
  <service name="Service" behaviorConfiguration="debug">
</services>

<client>
  <endpoint name="Service" address="net.tcp://localhost:12708/" binding="netTcpBinding" bindingConfiguration="netTcp" contract="path.IService" >
    <identity>
      <servicePrincipalName />
    </identity>
  </endpoint>
</client>

<serviceBehaviors>
    <behavior name="debug">
      <serviceDebug includeExceptionDetailInFaults="True" />
    </behavior>
  </serviceBehaviors>
</code>```

I cannot see more information event if i have declared serviceBehaviors.
Could somebody tell me how can i see more details about this error?

答:
you should add diagnostics your config file:</p>

```<code> <system.diagnostics>
      <sources>
        <source name="System.ServiceModel"
                switchValue="All"
                propagateActivity="true">
          <listeners>
            <add name="traceListener"
                type="System.Diagnostics.XmlWriterTraceListener"
                initializeData= "D:\AppLogs\Traces.svclog" />
          </listeners>
        </source>
      </sources>
    </system.diagnostics>
</code>```

Body:
When i try to load method from webservice, i get an error:

"The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the  configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs"

This is my app.config endpoint def:

<services>
  <service name="Service" behaviorConfiguration="debug">
</services>

<client>
  <endpoint name="Service" address="net.tcp://localhost:12708/" binding="netTcpBinding" bindingConfiguration="netTcp" contract="path.IService" >
    <identity>
      <servicePrincipalName />
    </identity>
  </endpoint>
</client>

<serviceBehaviors>
    <behavior name="debug">
      <serviceDebug includeExceptionDetailInFaults="True" />
    </behavior>
  </serviceBehaviors>

I cannot see more information event if i have declared serviceBehaviors.
Could somebody tell me how can i see more details about this error?

Body:
you should add diagnostics your config file:

 <system.diagnostics>
      <sources>
        <source name="System.ServiceModel"
                switchValue="All"
                propagateActivity="true">
          <listeners>
            <add name="traceListener"
                type="System.Diagnostics.XmlWriterTraceListener"
                initializeData= "D:\AppLogs\Traces.svclog" />
          </listeners>
        </source>
      </sources>
    </system.diagnostics>


问:
Link a PDF File to Output of EBS Concurrent Program
We have created a Java Concurrent program which merges multiple PDF files into one. This new PDF created, sits on the Unix server and has a definite path.

I need to link this PDF file to the output of Oracle EBS Concurrent Program, i.e. when user clicks 'View Output', this PDF file should open up.

Any pointers are appreciated.

Thanks,
Shubham

答:
The answer will be generic since you did not submit any code to your question.

Took for granted that your architecture is a client-server model.

Lets suppose that you have a link (View Output) where on the user clicks in order to download the specific PDF file. Since you are using an MVC architecture then, when the user clicks on the aforementioned link a method of YourController class will be invoked. Lets say that this method is named getPDF(). Subsequently this method will call the download() method of the supposed DownloaderService service. Finally this service will use a Download utility which will proceed to the necessary actions in order the file to be retrieved from the server.

On the below link you could find some ideas of how you could implement this feature suggested by Oracle.

Reading from URL

In case you enrich your question with more details(code snippets) the answer will be updated accordingly.


问:
How to get local computer name after New-PSSession -Computername?
I am getting the below error, please advise how to fix this error for null-valued expression

```<code>You cannnot call a method on a null-valued expression
+CategoryInfo : InvalidOoperation: (:)[], RuntimeException
+FullyQualifiedErrorId: InvokeMethodonNull
+PSComputerName: DC1
</code>```

Code below

```<code>function myfunction (){
$remoteserver = 'DC1'
$Session = New-PSSession -Computername $remoteserver -Credential $Cred
Import-Module ActiveDirectory
$local= $env:COMPUTERNAME

Invoke-Command -ComputerName $remoteserver -Credential $cred -ScriptBlock
{$using:local
if($local.substring(5,3) -imatch "Sys") {
Get-ADComputer $local | Move-ADObject -Targetpath "ou=PRD,ou=Servers,dc=com,dc=Companycorp,dc=net"}
}
} #end function
Invoke-Command -ComputerName $remoteserver -ScriptBlock ${Function:myFunction}
</code>```

答:
You have to use Invoke-Command :

```<code>$session = New-PSSession -Computername DC01 -Credential $cred

Invoke-Command -Session $session -ScriptBlock {
    $remoteComputerName = $env:computername
}
</code>```

Body:
I am getting the below error, please advise how to fix this error for null-valued expression

You cannnot call a method on a null-valued expression
+CategoryInfo : InvalidOoperation: (:)[], RuntimeException
+FullyQualifiedErrorId: InvokeMethodonNull
+PSComputerName: DC1

Code below

function myfunction (){
$remoteserver = 'DC1'
$Session = New-PSSession -Computername $remoteserver -Credential $Cred
Import-Module ActiveDirectory
$local= $env:COMPUTERNAME

Invoke-Command -ComputerName $remoteserver -Credential $cred -ScriptBlock
{$using:local
if($local.substring(5,3) -imatch "Sys") {
Get-ADComputer $local | Move-ADObject -Targetpath "ou=PRD,ou=Servers,dc=com,dc=Companycorp,dc=net"}
}
} #end function
Invoke-Command -ComputerName $remoteserver -ScriptBlock ${Function:myFunction}

Body:
You have to use Invoke-Command :

$session = New-PSSession -Computername DC01 -Credential $cred

Invoke-Command -Session $session -ScriptBlock {
    $remoteComputerName = $env:computername
}


问:
Why do I have to wrap an Async<T> into another async workflow and let! it?
I'm trying to understand async workflows in F# but I found one part that I really don't understand.

The following code works fine:

```<code>let asynWorkflow = async{
    let! result = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    return result
    }

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I define a async workflow where TryOpenAsync returns a Task<StreamOpenResult> type. I convert it to Async<StreamOpenResult> with Async.AwaitTask. (Side quest: "Await"Task? It doesn't await it just convert it, does it? I think it has nothing to do with Task.Wait or the await keyword). I "await" it with let! and return it.
To start the workflow I use RunSynchronously which should start the workflow and return the result (bind it). On the result I check if the Stream is Found or not.

But now to my first question. Why do I have to wrap the TryOpenAsync call in another async computation and let! ("await") it?
E.g. the following code does not work:

```<code>let asynWorkflow =  Stream.TryOpenAsync(partition) |> Async.AwaitTask

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I thought the AwaitTask makes it an Async<T> and RunSynchronously should start it. Then use the result. What do I miss?

My second question is why is there any "Async.Let!" function available? Maybe because it does not work or better why doesn't it work with the following code?

```<code>let ``let!`` task = async{
    let! result = task |> Async.AwaitTask
   return result
   }

let stream = Async.RunSynchronously ( ``let!`` (Stream.TryOpenAsync(partition))  )
         |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I just insert the TryOpenAsync as a parameter but it does not work. By saying does not work I mean the whole FSI will hang. So it has something to do with my async/"await".

--- Update:

Result of working code in FSI:

```<code>>

Real: 00:00:00.051, CPU: 00:00:00.031, GC gen0: 0, gen1: 0, gen2: 0
val asynWorkflow : Async<StreamOpenResult>
val stream : Stream
</code>```

Result of not working code in FSI:

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

And you cannot execute anything in the FSI anymore

--- Update 2

I'm using Streamstone. Here the C# example: https://github.com/yevhen/Streamstone/blob/master/Source/Example/Scenarios/S04_Write_to_stream.cs

and here the Stream.TryOpenAsync: https://github.com/yevhen/Streamstone/blob/master/Source/Streamstone/Stream.Api.cs#L192

答:
The second code block looks like it should work to me. It does run it if I provide dummy implementations for Stream and StreamOpenResult.

You should avoid using Async.RunSynchronously wherever possible because it defeats the purpose of async. Put all of this code within a larger async block and then you will have access to the StreamOpenResult:

```<code>async {
    let! openResult = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    let stream = if openResult.Found then openResult.Stream else Stream(partition)
    return () // now do something with the stream
    }
</code>```

You may need to put a Async.Start or Async.RunSynchronously at the very outer edge of your program to actually run it, but it's better if you have the async (or convert it to a Task) and pass it to some other code (e.g. a web framework) that can call it in a non-blocking manner.

Body:
I'm trying to understand async workflows in F# but I found one part that I really don't understand.

The following code works fine:

let asynWorkflow = async{
    let! result = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    return result
    }

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I define a async workflow where TryOpenAsync returns a Task<StreamOpenResult> type. I convert it to Async<StreamOpenResult> with Async.AwaitTask. (Side quest: "Await"Task? It doesn't await it just convert it, does it? I think it has nothing to do with Task.Wait or the await keyword). I "await" it with let! and return it.
To start the workflow I use RunSynchronously which should start the workflow and return the result (bind it). On the result I check if the Stream is Found or not.

But now to my first question. Why do I have to wrap the TryOpenAsync call in another async computation and let! ("await") it?
E.g. the following code does not work:

let asynWorkflow =  Stream.TryOpenAsync(partition) |> Async.AwaitTask

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I thought the AwaitTask makes it an Async<T> and RunSynchronously should start it. Then use the result. What do I miss?

My second question is why is there any "Async.Let!" function available? Maybe because it does not work or better why doesn't it work with the following code?

let ``let!`` task = async{
    let! result = task |> Async.AwaitTask
   return result
   }

let stream = Async.RunSynchronously ( ``let!`` (Stream.TryOpenAsync(partition))  )
         |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I just insert the TryOpenAsync as a parameter but it does not work. By saying does not work I mean the whole FSI will hang. So it has something to do with my async/"await".

--- Update:

Result of working code in FSI:

>

Real: 00:00:00.051, CPU: 00:00:00.031, GC gen0: 0, gen1: 0, gen2: 0
val asynWorkflow : Async<StreamOpenResult>
val stream : Stream

Result of not working code in FSI:

>

And you cannot execute anything in the FSI anymore

--- Update 2

I'm using Streamstone. Here the C# example: https://github.com/yevhen/Streamstone/blob/master/Source/Example/Scenarios/S04_Write_to_stream.cs

and here the Stream.TryOpenAsync: https://github.com/yevhen/Streamstone/blob/master/Source/Streamstone/Stream.Api.cs#L192

Body:
The second code block looks like it should work to me. It does run it if I provide dummy implementations for Stream and StreamOpenResult.

You should avoid using Async.RunSynchronously wherever possible because it defeats the purpose of async. Put all of this code within a larger async block and then you will have access to the StreamOpenResult:

async {
    let! openResult = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    let stream = if openResult.Found then openResult.Stream else Stream(partition)
    return () // now do something with the stream
    }

You may need to put a Async.Start or Async.RunSynchronously at the very outer edge of your program to actually run it, but it's better if you have the async (or convert it to a Task) and pass it to some other code (e.g. a web framework) that can call it in a non-blocking manner.


答:
What you're looking for is the $using: scope.  If you define variables that you want to use in your remote execution, you need to access them like:

```<code>$PC = $env:ComputerName
Invoke-Command -Computer DC01 -ScriptBlock { $using:PC <# logic #> }
</code>```

If you mean you want to remote into DC01 to run commands against localhost, you're going to run into the second-hop problem due to Kerberos.

Update: Your new example looks pretty convoluted.  Here's an example that should work:

```<code>$MyPC = $env:ComputerName
$Session = New-PSSession -Credential (Get-Credential) -ComputerName 'DC1'

Invoke-Command -Session $Session -ScriptBlock {
    Import-Module -Name 'ActiveDirectory'

    $PC = $using:MyPC
    If ($PC.Substring(5,3) -eq 'sys')
    {
        Get-ADComputer -Identity $PC |
            Move-ADObject -TargetPath 'ou=PRD,ou=Servers,dc=com,dc=Companycorp,dc=net'
    }
}
</code>```

Title: How to get local computer name after New-PSSession -Computername?

Body:
What you're looking for is the $using: scope.  If you define variables that you want to use in your remote execution, you need to access them like:

$PC = $env:ComputerName
Invoke-Command -Computer DC01 -ScriptBlock { $using:PC <# logic #> }

If you mean you want to remote into DC01 to run commands against localhost, you're going to run into the second-hop problem due to Kerberos.

Update: Your new example looks pretty convoluted.  Here's an example that should work:

$MyPC = $env:ComputerName
$Session = New-PSSession -Credential (Get-Credential) -ComputerName 'DC1'

Invoke-Command -Session $Session -ScriptBlock {
    Import-Module -Name 'ActiveDirectory'

    $PC = $using:MyPC
    If ($PC.Substring(5,3) -eq 'sys')
    {
        Get-ADComputer -Identity $PC |
            Move-ADObject -TargetPath 'ou=PRD,ou=Servers,dc=com,dc=Companycorp,dc=net'
    }
}


问:
What is the difference between a class "Attribute" and "Property"?
Can someone carefully describe the nuance between "attributes" and "properties"? I find them used interchangeably at times, and as differentiators at others. </p>

答:
The attribute and property terms are synonyms in most cases (also member, field), although property is often (python, C#, pascal, etc) used to describe the "virtual attribute" which is actually implemented by get/set methods (and attribute is used for regular attributes).

For example (python-like pseudocode):

```<code>class MyClass:

    string first_name_attribute;
    string last_name_attribute;

    @property
    def full_name(self):
        """Getter method returns the virtual "full name"."""
        return self.first_name_attribute + " " + self.last_name_attribute

    @full_name.setter
    def full_name(self, string value):
        """Setter method sets the virtual "full name"."""
        first_name, last_name = value.split(" ")
        self.first_name_attribute = first_name
        self.last_name_attribute = last_name
</code>```

Here we have two "real" attributes - first_name_attribute and last_name_attribute and a "virtual" property - full_name.

Body:
The attribute and property terms are synonyms in most cases (also member, field), although property is often (python, C#, pascal, etc) used to describe the "virtual attribute" which is actually implemented by get/set methods (and attribute is used for regular attributes).

For example (python-like pseudocode):

class MyClass:

    string first_name_attribute;
    string last_name_attribute;

    @property
    def full_name(self):
        """Getter method returns the virtual "full name"."""
        return self.first_name_attribute + " " + self.last_name_attribute

    @full_name.setter
    def full_name(self, string value):
        """Setter method sets the virtual "full name"."""
        first_name, last_name = value.split(" ")
        self.first_name_attribute = first_name
        self.last_name_attribute = last_name

Here we have two "real" attributes - first_name_attribute and last_name_attribute and a "virtual" property - full_name.


问:
why i get error when I trying to print quotation
I am learning c pragramming and when I try to print "Hello World" in quotation I get an error:

id returned 1 exit status

Here is my code, I am using codeblock:

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

int main()
  {
    printf("\"Hello World\" ");

    return 0;
}
</code>```

答:
```<code>error: id returned 1 exit status
       ^
 should be "l", not "i"
</code>```

I believe it's ld, not id. Code::Blocks uses GCC as compiler, and this is extremely likely that you did not close the running program before trying to compile it again.

Generally, ld (ld.exe on Windows) returns 1 when it can't access required files. This usually includes

Can't find the object file to be linked (or Access denied)

Can't find one or more symbols to link

Can't open the executable for writing (or AD)

Your program looks completely fine, so the second point should not hit. In usual cases, it's impossible for ld to fail to open the object file (unless you have a faulty drive and a dirty filesystem), so the first point is also nearly impossible. Now we get to the third point.

A simple Google search gives a full page of the same answer: You forgot to close the program, before trying to re-compile.

That's all.

Body:
I am learning c pragramming and when I try to print "Hello World" in quotation I get an error:

id returned 1 exit status

Here is my code, I am using codeblock:

#include <stdio.h>

int main()
  {
    printf("\"Hello World\" ");

    return 0;
}

Body:
error: id returned 1 exit status
       ^
 should be "l", not "i"

I believe it's ld, not id. Code::Blocks uses GCC as compiler, and this is extremely likely that you did not close the running program before trying to compile it again.

Generally, ld (ld.exe on Windows) returns 1 when it can't access required files. This usually includes

Can't find the object file to be linked (or Access denied)

Can't find one or more symbols to link

Can't open the executable for writing (or AD)

Your program looks completely fine, so the second point should not hit. In usual cases, it's impossible for ld to fail to open the object file (unless you have a faulty drive and a dirty filesystem), so the first point is also nearly impossible. Now we get to the third point.

A simple Google search gives a full page of the same answer: You forgot to close the program, before trying to re-compile.

That's all.


问:
Have an excel cell value list except when the value is null
I have an integer list "myList" that corresponds to empty excel lines and I would like to retrieve the values of all cells that are not empty thanks to LINQ
I already dit that to get all the value:

```<code> var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString()).ToList();
</code>```

and i tried that to get all the value without the empty cell:

```<code> var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString().Where(p => { x.Row != ctrl.myList.ElementAt(p); })).ToList();
</code>```

and that :

```<code>var colonneB = selectedRange.Rows.Cast<Excel.Range>().Where(y => ctrl.myList.ForEach(p =>
            {
                int i = ctrl.myList.ElementAt(p);
                if (i != y.Row)
                {
                }
            }) != y.Row).Select(x => x.Value2.ToString()).ToList();
</code>```

but of course it doesn't compile, I have tried other things but it doesn't work either and I am short of ideas...
Thank you for your help.

all the code :

```<code> int nInLastRow = worksheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
 Excel.Range selectedRange = (Excel.Range)worksheet.get_Range("B2:B" + nInLastRow);
 var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString()).ToList();
</code>```

答:
Well well well, I finally found the answer by myself (and i'm proud of me^^)
It was simple, just have to do :</p>

```<code>var colonneB = selectedRange.Rows.Cast<Excel.Range>().Where(y=>y.Value2 != null).Select(x => x.Value2.ToString()).ToList();
</code>```

Body:
I have an integer list "myList" that corresponds to empty excel lines and I would like to retrieve the values of all cells that are not empty thanks to LINQ
I already dit that to get all the value:

 var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString()).ToList();

and i tried that to get all the value without the empty cell:

 var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString().Where(p => { x.Row != ctrl.myList.ElementAt(p); })).ToList();

and that :

var colonneB = selectedRange.Rows.Cast<Excel.Range>().Where(y => ctrl.myList.ForEach(p =>
            {
                int i = ctrl.myList.ElementAt(p);
                if (i != y.Row)
                {
                }
            }) != y.Row).Select(x => x.Value2.ToString()).ToList();

but of course it doesn't compile, I have tried other things but it doesn't work either and I am short of ideas...
Thank you for your help.

all the code :

 int nInLastRow = worksheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
 Excel.Range selectedRange = (Excel.Range)worksheet.get_Range("B2:B" + nInLastRow);
 var colonneB = selectedRange.Rows.Cast<Excel.Range>().Select(x => x.Value2.ToString()).ToList();

Body:
Well well well, I finally found the answer by myself (and i'm proud of me^^)
It was simple, just have to do :

var colonneB = selectedRange.Rows.Cast<Excel.Range>().Where(y=>y.Value2 != null).Select(x => x.Value2.ToString()).ToList();


问:
C++ Move semantics and Exceptions
In the forthcoming C++0x standard, what happens when an exception is thrown within/during the move constructor?

Will the original object remain? or are both the original and move-to object in an undefined state? what are the guarantees afforded by the language?

答:
Your question then amounts to a question about Exception Guarantees. There are 3 types of Exceptions Guarantees (that apply to functions):

No exception guarantee at all (not really a type... but it may happen if no concern is given to the matter)

Basic Exception Guarantee: Technically correct, but not Functionally correct (ie no resource is leaked, the program will terminate without an abrupt halt, but it may have undesired side-effects, like the payment being cashed-in but the command not being registered)

Strong Exception Guarantee: All or Nothing (like a transaction), that is either everything is done right, or we rollback to the previous state.

No Throw Exception Guarantee: This does not throw, ever, so no worry.

When you compose your function, you usually pick up existing functions with their own guarantees. It is difficult to increase the exception guarantee, that is your are generally limited by the weakest guarantee used.

W.r.t your question, it takes at least a Strong Exception Guarantee for the original object to be left untouched if an exception is thrown.

So, what happens if an exception is thrown during move-construction ? It depends on the guarantees exhibited by the sub-objects and the way you combined the calls...

If an exception is thrown from a constructor, the object is not being built and all built subobjects are destroyed, in reverse order. This rule is also applicable to a move-constructor

Unless you "wrap" the constructor in a try catch and somehow restore the objects that have been moved, they'll have lost their resources. Note that they must still be in a destructable state anyway, so technically the program will be correct.

In terms of exceptions guarantees, it means that by default, if all of the subobjects' constructors at least meet the Basic Exception Guarantee, then your move constructor will too, without any special care.

However, even if all the subobjects' constructors meet the Strong Exception Guarantee, it's unlikely you'll succeed in having your own move constructor meet it: this is the same issue that chaining transactions does not yield a transaction.

If only one of the subobjects' constructors may throw, and it meets the Strong Exception Guarantee, then your move constructor will naturally meet it itself if you initialize the throwing object first.

Hope this helped... exceptions are a wild beast to tame :)

OwnerDisplayName: Matthieu N.

Title: C++ Move semantics and Exceptions


问:
CKEditor 4: How to save and restore the cursor / caret position?
I know that there are some similar questions posted here but none seemed to answer my problematic (or maybe it is that I don't understand well the concept). I started by wanting to get and set the caret position within a CKeditor instance (question is here). With help, I understood that I needed to use ranges and offsets to achieve this goal.

However my problem now is that I don't know how to save this position somewhere, possibly a database and restore the position of the caret. You can imagine a user modifying a document and saving it. When he comes back to continue the edition, the document should be loaded and the caret returned to the last known position.

So, to get the caret position from CKeditor in javascript, that is ok. I can get my range object. But how do I save it? How do I send it to the server for storing? How do I get it back? As a string?
Are there mechanisms to serialize and deserialize ranges or dom nodes?

Thank you for the help!

答:
Are there mechanisms to serialize and deserialize ranges or dom nodes?

There is a mechanism called bookmarks in CKEditor 4. You can use CKEDITOR.dom.range.createBookmark, which basically creates a bookmark for the current range (selection) and then it can be restored via CKEDITOR.dom.range.moveToBookmark.

To make bookmark serializable (so you can save whole content with it to DB and then restore selection when content is loaded), you have to pass true to creatBookmark like createBookmark( true ), this indicates that the bookmark nodes must contain IDs, which can be used to restore the range.