问:
Identify Required Placeholders in GCMLE Model
I have deployed a model a few weeks ago and I have lost track of which input features are required for the model (yes I know I should have kept better track of this).  When I run the following command

```<code>gcloud ml-engine predict \
--model $MODEL_NAME \
--version v1 \
--json-instances \
../test.json
</code>```

I get the following err:

```<code>{
  "error": "Prediction failed: Exception during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"input size does not match signature\")"
}
</code>```

I know that my issue is because there is some "required" placeholder that I have not included in my json request (test.json) but I cannot figure out any way to retroactively find out which placeholder is missing.

The issue is the same as this question where the poster was able to submit the prediction when he included the missing "threshold" tensor.

What would be the easiest way to look at the expected inputs for a given model?

答:
The service itself does not yet allow you to query the signature of your model, so my recommendation is to use saved_model_cli where possible (assuming you didn't delete the original model). Something like:

```<code>gcloud ml-engine versions describe v1 --model census | grep deploymentUri
</code>```

Which will output something like:

```<code>deploymentUri: gs://my_bucket/path/to/Servo/1488268526779
</code>```

Now, use saved_model_cli:

```<code>saved_model_cli show --all --dir gs://my_bucket/path/to/Servo/1488268526779
</code>```

Which will output something like:

```<code>MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:

signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['age'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_8:0
inputs['capital_gain'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_10:0
inputs['capital_loss'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_11:0
inputs['education'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_2:0
inputs['education_num'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_9:0
inputs['gender'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder:0
inputs['hours_per_week'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_12:0
inputs['marital_status'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_3:0
inputs['native_country'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_7:0
inputs['occupation'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_6:0
inputs['race'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_1:0
inputs['relationship'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_4:0
inputs['workclass'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_5:0
The given SavedModel SignatureDef contains the following output(s):
outputs['classes'] tensor_info:
    dtype: DT_INT64
    shape: (-1)
    name: predictions/classes:0
outputs['logistic'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, 1)
    name: predictions/logistic:0
outputs['logits'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, 1)
    name: add:0
outputs['probabilities'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, 2)
    name: predictions/probabilities:0
Method name is: tensorflow/serving/predict
</code>```

Body:
I have deployed a model a few weeks ago and I have lost track of which input features are required for the model (yes I know I should have kept better track of this).  When I run the following command

gcloud ml-engine predict \
--model $MODEL_NAME \
--version v1 \
--json-instances \
../test.json

I get the following err:

{
  "error": "Prediction failed: Exception during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"input size does not match signature\")"
}

I know that my issue is because there is some "required" placeholder that I have not included in my json request (test.json) but I cannot figure out any way to retroactively find out which placeholder is missing.

The issue is the same as this question where the poster was able to submit the prediction when he included the missing "threshold" tensor.

What would be the easiest way to look at the expected inputs for a given model?

Body:
The service itself does not yet allow you to query the signature of your model, so my recommendation is to use saved_model_cli where possible (assuming you didn't delete the original model). Something like:

gcloud ml-engine versions describe v1 --model census | grep deploymentUri

Which will output something like:

deploymentUri: gs://my_bucket/path/to/Servo/1488268526779

Now, use saved_model_cli:

saved_model_cli show --all --dir gs://my_bucket/path/to/Servo/1488268526779

Which will output something like:

MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:

signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['age'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_8:0
inputs['capital_gain'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_10:0
inputs['capital_loss'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_11:0
inputs['education'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_2:0
inputs['education_num'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_9:0
inputs['gender'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder:0
inputs['hours_per_week'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1)
    name: Placeholder_12:0
inputs['marital_status'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_3:0
inputs['native_country'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_7:0
inputs['occupation'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_6:0
inputs['race'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_1:0
inputs['relationship'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_4:0
inputs['workclass'] tensor_info:
    dtype: DT_STRING
    shape: (-1)
    name: Placeholder_5:0
The given SavedModel SignatureDef contains the following output(s):
outputs['classes'] tensor_info:
    dtype: DT_INT64
    shape: (-1)
    name: predictions/classes:0
outputs['logistic'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, 1)
    name: predictions/logistic:0
outputs['logits'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, 1)
    name: add:0
outputs['probabilities'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, 2)
    name: predictions/probabilities:0
Method name is: tensorflow/serving/predict


来源: stackexchange

问:
Scraped CSV pandas dataframe I get: ValueError('Length of values does not match length of ' 'index')
I run below code and get:

```<code>raise ValueError('Length of values does not match length of ' 'index')
</code>```

ValueError: Length of values does not match length of index

for:

```<code>print(df3)
zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)
df3['O2'] = zz  #Error Line
</code>```

I have got this to work for data in a csv that has identical column structure save for this is scraped data where as the other csv was created manually.

df1

```<code>                                                 EW      WE  \
0                                            can v can   1.900
1                       Lanus U20 v Argentinos Jrs U20   2.100

                                                    DA
0    https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1    https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
</code>```

df2

```<code>                AA                      AB                       AC      AD  \
0      Today 19:00           Indonesia U23           Kyrgyzstan U23  650.00
1      Today 23:00   Brunei Darussalam U23             Mongolia U23    3.30
2      Today 19:30                     can                      can  110.00

                                                   AE
0   https://www.betfair.com.au/exchange/plus/footb...
1   https://www.betfair.com.au/exchange/plus/footb...
2   https://www.betfair.com.au/exchange/plus/footb...
</code>```

df3

```<code>df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])
</code>```

Desired:

df3:

```<code>               DAT                      G  \
0      Today 19:00                 can v can

         TN                           O1  \
0   can v can                        1.900

                         L1  \
0   https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

        TN2                         O2  \
0   can v can                       110.00

                                                   L2    D
0   https://www.betfair.com.au/exchange/plus/footb...  108.1
</code>```

Code:

```<code>   import pandas as pd
    import time
    import numpy as np
    import pandas as pd
    print('####CURRIES###')
    df1 = pd.read_csv('C:\\O\\df1.csv',
                       index_col=False,
                       usecols=[0,1,2],
                       names=["EW", "WE", "DA"],
                       header=None)
    print(df1)

    print('####Mangoes###')
    df2 = pd.read_csv('C:\\O\\df2.csv',
                       index_col=False,
                       usecols=[0,1,2, 3, 4],
                       names=["AA", "AB", "AC", "AD", "AE"],
                       header=None)
    print(df2)

    df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

    df3['DAT'] = df2['AA']

    df3['G'] = df2['AB'] + ' v ' + df2['AC']

    df3['AK'] = df2['AB'] + ' v ' + df2['AC']
    df3['AL'] = df2['AB'] + ' v ' + df2['AC']

    print(df3)

    #TN

    print('Vlookup')
    aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan)
    print(aa)
    df3['TN'] = aa

    print('Vlookup output')
    print(df3)
    ## Not working

    #TN

    print('Vlookup')
    aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan)
    print(aa)
    df3['TN2'] = aa
    ## Not working

    #L
    df3['L1'] = df2['AE']
    df3['L2'] = df1['DA']

    print('dataframe complete')
    print(df3)
    ##O  <-- Get value beside T

    print('done')

    #O1 Mangoes
    aa = df2.AD=np.where(df3.AL.isin(df1.EW),df2.AD,np.nan)

    df3['O1'] = aa

    #O2 Curries
    #zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)

    #zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)

    ###############ERROR B#  ###############ERROR B#

    print(df3)
    zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)
    df3['O2'] = zz

###############ERROR ABOVE#
    print('output')
    df = df3[pd.notnull(df3['TN'])]

    #df3['D'] = df3['O2'] - df3['O1']

    print('tt')
    #df3.dropna(how='all')
    #df3.columns = df3.columns.droplevel(3)
    print(df3)
    #df3['AA'] = df1[zz]

    print('zza')
    df3.pop('AK')
    df3.pop('AL')

    df3['D'] = df3['O2'].sub(df3['O1'], fill_value=0)
    df3.pop('AJ')

    print(df3.dtypes)
    NaNs = df3 = df3.dropna(subset=['O1','O2'])
    print(NaNs)
    import pandas as pd

    print('test')
    print(df3)

    writer = pd.ExcelWriter('C:\\O\\dx.xlsx')
    df3.to_excel(writer, startcol=0, index = False)
    writer.save()
    print(df3)

    #df3.pop('AK')

    #df3['T1'] = df1[zz]

    #Delete Columns
    #put O in a column value
    #
</code>```

Scraping code to create dataframes here .

I then write can v can in df1 column A row 1.

I then write can in df2 Column B row 3

I then write can in df2 column C row 3

Or simply here are exact files (scraped) I am using.

df1

df2

These files below the code above works perfectly.  I don't understand why it is not working for scraped data.

Working code

df2

df1

答:
You need merge with inner join:

```<code>print('####CURRIES###')
df1 = pd.read_csv('C:\\O\\df1.csv',
                   index_col=False,
                   usecols=[0,1,2],
                   names=["EW", "WE", "DA"],
                   header=None)
print(df1.head())
####CURRIES###
                                 EW    WE  \
0                         can v can  1.90
1    Lanus U20 v Argentinos Jrs U20  2.10
2      Botafogo RJ U20 v Toluca U20  1.83
3  Atletico Mineiro U20 v Bahia U20  2.10
4                 FC Porto v Monaco  1.36

                                                  DA
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
4  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

print('####Mangoes###')
df2 = pd.read_csv('C:\\O\\df2.csv',
                   index_col=False,
                   usecols=[0,1,2, 3, 4],
                   names=["AA", "AB", "AC", "AD", "AE"],
                   header=None)
</code>```

```<code>print(df2.head())
####Mangoes###
            AA                     AB                      AC      AD  \
0  Today 19:00          Indonesia U23          Kyrgyzstan U23  650.00
1  Today 23:00  Brunei Darussalam U23            Mongolia U23    3.30
2  Today 19:30                    can                     can  110.00
3  Today 20:00  FC Zbrojovka Brno U19       Sparta Prague U19    1.97
4  Today 20:30         Rahmatgonj MFS  Sheikh Jamal Dhanmondi    1.51

                                                  AE
0  https://www.betfair.com.au/exchange/plus/footb...
1  https://www.betfair.com.au/exchange/plus/footb...
2  https://www.betfair.com.au/exchange/plus/footb...
3  https://www.betfair.com.au/exchange/plus/footb...
4  https://www.betfair.com.au/exchange/plus/footb...
</code>```

```<code>#crewte new column called EW in df2
df2['EW'] = df2['AB'] + ' v ' + df2['AC']
#merge on columns EW
df3 = pd.merge(df2, df1, on='EW')
#change columns names
df3 = df3.rename(columns={'WE':'O1','AD':'O2'})
#subtract O columns
df3['D'] = df3['O2'].sub(df3['O1'], fill_value=0)
print (df3)
            AA             AB              AC     O2  \
0  Today 19:00  Indonesia U23  Kyrgyzstan U23  650.0
1  Today 19:30            can             can  110.0

                                                  AE  \
0  https://www.betfair.com.au/exchange/plus/footb...
1  https://www.betfair.com.au/exchange/plus/footb...

                               EW   O1  \
0  Indonesia U23 v Kyrgyzstan U23  2.0
1                       can v can  1.9

                                                  DA      D
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...  648.0
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...  108.1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I run below code and get:

raise ValueError('Length of values does not match length of ' 'index')

ValueError: Length of values does not match length of index

for:

print(df3)
zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)
df3['O2'] = zz  #Error Line

I have got this to work for data in a csv that has identical column structure save for this is scraped data where as the other csv was created manually.

df1

                                                 EW      WE  \
0                                            can v can   1.900
1                       Lanus U20 v Argentinos Jrs U20   2.100

                                                    DA
0    https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1    https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

df2

                AA                      AB                       AC      AD  \
0      Today 19:00           Indonesia U23           Kyrgyzstan U23  650.00
1      Today 23:00   Brunei Darussalam U23             Mongolia U23    3.30
2      Today 19:30                     can                      can  110.00

                                                   AE
0   https://www.betfair.com.au/exchange/plus/footb...
1   https://www.betfair.com.au/exchange/plus/footb...
2   https://www.betfair.com.au/exchange/plus/footb...

df3

df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

Desired:

df3:

               DAT                      G  \
0      Today 19:00                 can v can

         TN                           O1  \
0   can v can                        1.900

                         L1  \
0   https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

        TN2                         O2  \
0   can v can                       110.00

                                                   L2    D
0   https://www.betfair.com.au/exchange/plus/footb...  108.1

Code:

   import pandas as pd
    import time
    import numpy as np
    import pandas as pd
    print('####CURRIES###')
    df1 = pd.read_csv('C:\\O\\df1.csv',
                       index_col=False,
                       usecols=[0,1,2],
                       names=["EW", "WE", "DA"],
                       header=None)
    print(df1)

    print('####Mangoes###')
    df2 = pd.read_csv('C:\\O\\df2.csv',
                       index_col=False,
                       usecols=[0,1,2, 3, 4],
                       names=["AA", "AB", "AC", "AD", "AE"],
                       header=None)
    print(df2)

    df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

    df3['DAT'] = df2['AA']

    df3['G'] = df2['AB'] + ' v ' + df2['AC']

    df3['AK'] = df2['AB'] + ' v ' + df2['AC']
    df3['AL'] = df2['AB'] + ' v ' + df2['AC']

    print(df3)

    #TN

    print('Vlookup')
    aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan)
    print(aa)
    df3['TN'] = aa

    print('Vlookup output')
    print(df3)
    ## Not working

    #TN

    print('Vlookup')
    aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan)
    print(aa)
    df3['TN2'] = aa
    ## Not working

    #L
    df3['L1'] = df2['AE']
    df3['L2'] = df1['DA']

    print('dataframe complete')
    print(df3)
    ##O  <-- Get value beside T

    print('done')

    #O1 Mangoes
    aa = df2.AD=np.where(df3.AL.isin(df1.EW),df2.AD,np.nan)

    df3['O1'] = aa

    #O2 Curries
    #zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)

    #zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)

    ###############ERROR B#  ###############ERROR B#

    print(df3)
    zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan)
    df3['O2'] = zz

###############ERROR ABOVE#
    print('output')
    df = df3[pd.notnull(df3['TN'])]

    #df3['D'] = df3['O2'] - df3['O1']

    print('tt')
    #df3.dropna(how='all')
    #df3.columns = df3.columns.droplevel(3)
    print(df3)
    #df3['AA'] = df1[zz]

    print('zza')
    df3.pop('AK')
    df3.pop('AL')

    df3['D'] = df3['O2'].sub(df3['O1'], fill_value=0)
    df3.pop('AJ')

    print(df3.dtypes)
    NaNs = df3 = df3.dropna(subset=['O1','O2'])
    print(NaNs)
    import pandas as pd

    print('test')
    print(df3)

    writer = pd.ExcelWriter('C:\\O\\dx.xlsx')
    df3.to_excel(writer, startcol=0, index = False)
    writer.save()
    print(df3)

    #df3.pop('AK')

    #df3['T1'] = df1[zz]

    #Delete Columns
    #put O in a column value
    #

Scraping code to create dataframes here .

I then write can v can in df1 column A row 1.

I then write can in df2 Column B row 3

I then write can in df2 column C row 3

Or simply here are exact files (scraped) I am using.

df1

df2

These files below the code above works perfectly.  I don't understand why it is not working for scraped data.

Working code

df2

df1

Body:
You need merge with inner join:

print('####CURRIES###')
df1 = pd.read_csv('C:\\O\\df1.csv',
                   index_col=False,
                   usecols=[0,1,2],
                   names=["EW", "WE", "DA"],
                   header=None)
print(df1.head())
####CURRIES###
                                 EW    WE  \
0                         can v can  1.90
1    Lanus U20 v Argentinos Jrs U20  2.10
2      Botafogo RJ U20 v Toluca U20  1.83
3  Atletico Mineiro U20 v Bahia U20  2.10
4                 FC Porto v Monaco  1.36

                                                  DA
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
4  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

print('####Mangoes###')
df2 = pd.read_csv('C:\\O\\df2.csv',
                   index_col=False,
                   usecols=[0,1,2, 3, 4],
                   names=["AA", "AB", "AC", "AD", "AE"],
                   header=None)

print(df2.head())
####Mangoes###
            AA                     AB                      AC      AD  \
0  Today 19:00          Indonesia U23          Kyrgyzstan U23  650.00
1  Today 23:00  Brunei Darussalam U23            Mongolia U23    3.30
2  Today 19:30                    can                     can  110.00
3  Today 20:00  FC Zbrojovka Brno U19       Sparta Prague U19    1.97
4  Today 20:30         Rahmatgonj MFS  Sheikh Jamal Dhanmondi    1.51

                                                  AE
0  https://www.betfair.com.au/exchange/plus/footb...
1  https://www.betfair.com.au/exchange/plus/footb...
2  https://www.betfair.com.au/exchange/plus/footb...
3  https://www.betfair.com.au/exchange/plus/footb...
4  https://www.betfair.com.au/exchange/plus/footb...

#crewte new column called EW in df2
df2['EW'] = df2['AB'] + ' v ' + df2['AC']
#merge on columns EW
df3 = pd.merge(df2, df1, on='EW')
#change columns names
df3 = df3.rename(columns={'WE':'O1','AD':'O2'})
#subtract O columns
df3['D'] = df3['O2'].sub(df3['O1'], fill_value=0)
print (df3)
            AA             AB              AC     O2  \
0  Today 19:00  Indonesia U23  Kyrgyzstan U23  650.0
1  Today 19:30            can             can  110.0

                                                  AE  \
0  https://www.betfair.com.au/exchange/plus/footb...
1  https://www.betfair.com.au/exchange/plus/footb...

                               EW   O1  \
0  Indonesia U23 v Kyrgyzstan U23  2.0
1                       can v can  1.9

                                                  DA      D
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...  648.0
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...  108.1


问:
MPI: Pin each instance to certain cores on each node
I want to execute several instances of my program with OpenMPI 2.11. Each instance runs on its own node (-N 1) on my cluster. This works fine. I now want to pin each program-instance to the first 2 cores of its node. To do that, it looks like I need to use rankfiles. Here is my rankfile:

```<code>rank 0=+n0 slot=0-1
rank 1=+n1 slot=0-1
</code>```

This, in my opinion, should limit each program-instance to cores 0 and 1 of the local machine it runs on.
I execute mpirun like so:

```<code>mpirun -np 2 -N 1 -rf /my/rank/file my_program
</code>```

But mpirun fails with this error without even executing my program:

```<code>Conflicting directives for mapping policy are causing the policy
to be redefined:

  New policy:   RANK_FILE
  Prior policy:  UNKNOWN

Please check that only one policy is defined.
</code>```

What's this? Did I make a mistake in the rankfile?

答:
Instead of using a rankfile, simply use a hostfile:

```<code>n0 slots=n max_slots=n
n1 slots=n max_slots=n
</code>```

Then tell Open MPI to map one process per node with two cores per process using:

```<code>mpiexec --hostfile hostfile --map-by ppr:1:node:PE=2 --bind-to core ...
</code>```

ppr:1:node:PE=2 reads as: 1 process per resource; resource type is node; 2 processing elements per process. You can check the actual binding by adding the --report-bindings option.

Body:
I want to execute several instances of my program with OpenMPI 2.11. Each instance runs on its own node (-N 1) on my cluster. This works fine. I now want to pin each program-instance to the first 2 cores of its node. To do that, it looks like I need to use rankfiles. Here is my rankfile:

rank 0=+n0 slot=0-1
rank 1=+n1 slot=0-1

This, in my opinion, should limit each program-instance to cores 0 and 1 of the local machine it runs on.
I execute mpirun like so:

mpirun -np 2 -N 1 -rf /my/rank/file my_program

But mpirun fails with this error without even executing my program:

Conflicting directives for mapping policy are causing the policy
to be redefined:

  New policy:   RANK_FILE
  Prior policy:  UNKNOWN

Please check that only one policy is defined.

What's this? Did I make a mistake in the rankfile?

Body:
Instead of using a rankfile, simply use a hostfile:

n0 slots=n max_slots=n
n1 slots=n max_slots=n

Then tell Open MPI to map one process per node with two cores per process using:

mpiexec --hostfile hostfile --map-by ppr:1:node:PE=2 --bind-to core ...

ppr:1:node:PE=2 reads as: 1 process per resource; resource type is node; 2 processing elements per process. You can check the actual binding by adding the --report-bindings option.


问:
How can I destructure tuples into typed variables?
I'm trying to decompose a tuple into variables, and then cause an error by having one of the types mentioned incorrectly:

```<code>fn main() {
    let tup = (500, 6.4, 1);
    let (x: bool, y: f32, z: i16) = tup;
    println!("{}, {}, {}", x, y, z);
}
</code>```

My idea was that the compiler would raise an error because x is given as bool but is being matched to 500. Surprisingly, it's the last statement where the compiler complains, saying that x, y, and z were not found in this scope:

I tried it another way:

```<code>fn main() {
    let tup = (500, 6.4, 1);
    let mut x: bool = true;
    let mut y: f32 = true;
    let mut z: i16 = true;
    (x, y, z) = tup;
    println!("{}, {}, {}", x, y, z);
}
</code>```

This time, the compiler does raise the expected error, but it also says that the left-hand side of (x, y, z) = tup; isn't valid. Can someone explain what's happening?

答:
You need to read the errors more carefully; the first case's very first one was:

error: expected one of `)`, `,`, or `@`, found `:`
 --> src/main.rs:3:11
  |
3 |     let (x: bool, y: f32, z: i16) = tup;
  |           ^ expected one of `)`, `,`, or `@` here
```
<p>Which indicates that you can't provide types next to the variable names when you pattern match against a tuple. This is a parsing error which rendered that whole line invalid and caused <code>x</code>, <code>y</code> and <code>z</code> not to be found for the purposes of <code>println!()</code>:</p>
<pre class="lang-none prettyprint-override"><code>error[E0425]: cannot find value `x` in this scope
 --> src/main.rs:4:28
  |
4 |     println!("{}, {}, {}", x, y, z);
  |                            ^ not found in this scope

error[E0425]: cannot find value `y` in this scope
 --> src/main.rs:4:31
  |
4 |     println!("{}, {}, {}", x, y, z);
  |                               ^ not found in this scope

error[E0425]: cannot find value `z` in this scope
 --> src/main.rs:4:34
  |
4 |     println!("{}, {}, {}", x, y, z);
  |                                  ^ not found in this scope
</code>```

As for the second case, there's a bunch of invalid assignments; y and z are numbers, but you try to assign bools to them; (x, y, z) = ... is also an invalid assignment - it doesn't pattern  match (in Rustc versions < 1.59.0) unless it's within a let binding.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to decompose a tuple into variables, and then cause an error by having one of the types mentioned incorrectly:

fn main() {
    let tup = (500, 6.4, 1);
    let (x: bool, y: f32, z: i16) = tup;
    println!("{}, {}, {}", x, y, z);
}

My idea was that the compiler would raise an error because x is given as bool but is being matched to 500. Surprisingly, it's the last statement where the compiler complains, saying that x, y, and z were not found in this scope:

I tried it another way:

fn main() {
    let tup = (500, 6.4, 1);
    let mut x: bool = true;
    let mut y: f32 = true;
    let mut z: i16 = true;
    (x, y, z) = tup;
    println!("{}, {}, {}", x, y, z);
}

This time, the compiler does raise the expected error, but it also says that the left-hand side of (x, y, z) = tup; isn't valid. Can someone explain what's happening?

Body:
You need to read the errors more carefully; the first case's very first one was:

error: expected one of `)`, `,`, or `@`, found `:`
 --> src/main.rs:3:11
  |
3 |     let (x: bool, y: f32, z: i16) = tup;
  |           ^ expected one of `)`, `,`, or `@` here

Which indicates that you can't provide types next to the variable names when you pattern match against a tuple. This is a parsing error which rendered that whole line invalid and caused x, y and z not to be found for the purposes of println!():

error[E0425]: cannot find value `x` in this scope
 --> src/main.rs:4:28
  |
4 |     println!("{}, {}, {}", x, y, z);
  |                            ^ not found in this scope

error[E0425]: cannot find value `y` in this scope
 --> src/main.rs:4:31
  |
4 |     println!("{}, {}, {}", x, y, z);
  |                               ^ not found in this scope

error[E0425]: cannot find value `z` in this scope
 --> src/main.rs:4:34
  |
4 |     println!("{}, {}, {}", x, y, z);
  |                                  ^ not found in this scope

As for the second case, there's a bunch of invalid assignments; y and z are numbers, but you try to assign bools to them; (x, y, z) = ... is also an invalid assignment - it doesn't pattern  match (in Rustc versions < 1.59.0) unless it's within a let binding.


问:
How can I change outgoing mail configuration in Laravel?
My email setting in env like this :

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=secret@gmail.com
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls
</code>```

It works. But, I want to change email sender. So I don't use email sender gmail

My boss gives me a new email setting like this :

Mail Client Manual Settings

Secure SSL/TLS Settings (Recommended)

Username:contact@secretshop.id

Password:secret

Incoming Server:

palasik.in-hell.com

IMAP Port: 9xx

POP3 Port: 9xx

Outgoing Server:

palasik.in-hell.com

SMTP Port: 465

IMAP, POP3, and SMTP require authentication.

Non-SSL Settings (NOT Recommended)

Username:contact@secretshop.id

Password:secret

Incoming Server:

mail.secretshop.id

IMAP Port: 1xx

POP3 Port: 1xx

Outgoing Server:

mail.secretshop.id

SMTP Port: 587

IMAP, POP3, and SMTP require authentication.

I want to ask some questions

What is the difference between Secure SSL / TLS Settings and Non-SSL Settings?

what is the difference between incoming Server and Outgoing Server?

What new setting is more suitable?

I tried like this:

```<code>MAIL_DRIVER=smtp
MAIL_HOST=mail.secretshop.id
MAIL_PORT=587
MAIL_USERNAME=contact@secretshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls
</code>```

Is it the best choice?

答:
Its always recommended to use SSL as it is secured & reduces the changes of the sent mail being filtered by the recipient's host as spam.

Most email accounts have two servers:

one that lets you send emails to other people,

and another that lets you receive the emails that other people send
you.

The server that lets you send mail is called an outgoing, or SMTP    server.  The server that lets you receive mail is called an incoming,    POP, or just Mail server.

To change the sender config in Laravel use in .env file:

```<code>MAIL_DRIVER=smtp
MAIL_HOST=palasik.in-hell.com
MAIL_PORT=465
MAIL_USERNAME=contact@secretshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=ssl
</code>```

Body:
My email setting in env like this :

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=secret@gmail.com
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls

It works. But, I want to change email sender. So I don't use email sender gmail

My boss gives me a new email setting like this :

Mail Client Manual Settings

Secure SSL/TLS Settings (Recommended)

Username:contact@secretshop.id

Password:secret

Incoming Server:

palasik.in-hell.com

IMAP Port: 9xx

POP3 Port: 9xx

Outgoing Server:

palasik.in-hell.com

SMTP Port: 465

IMAP, POP3, and SMTP require authentication.

Non-SSL Settings (NOT Recommended)

Username:contact@secretshop.id

Password:secret

Incoming Server:

mail.secretshop.id

IMAP Port: 1xx

POP3 Port: 1xx

Outgoing Server:

mail.secretshop.id

SMTP Port: 587

IMAP, POP3, and SMTP require authentication.

I want to ask some questions

What is the difference between Secure SSL / TLS Settings and Non-SSL Settings?

what is the difference between incoming Server and Outgoing Server?

What new setting is more suitable?

I tried like this:

MAIL_DRIVER=smtp
MAIL_HOST=mail.secretshop.id
MAIL_PORT=587
MAIL_USERNAME=contact@secretshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls

Is it the best choice?

Body:
Its always recommended to use SSL as it is secured & reduces the changes of the sent mail being filtered by the recipient's host as spam.

Most email accounts have two servers:

one that lets you send emails to other people,

and another that lets you receive the emails that other people send
you.

The server that lets you send mail is called an outgoing, or SMTP    server.  The server that lets you receive mail is called an incoming,    POP, or just Mail server.

To change the sender config in Laravel use in .env file:

MAIL_DRIVER=smtp
MAIL_HOST=palasik.in-hell.com
MAIL_PORT=465
MAIL_USERNAME=contact@secretshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=ssl


问:
Select from same table, within IF statement
I am selecting a list from a table, and would like to include the parent's label if an item has a parent, or just - if it doesn't.

For this example the table structure is basic :

```<code>id | label | parent
</code>```

This is he statment I'm trying:

SELECT id, label,
    IF (parent > 0, (SELECT id FROM meta WHERE parent = m.id), '-') AS parent
    FROM meta AS m WHERE type = 'genre'

I'm getting [NULL] for parent when the item does have a parent. If I replace the IF statement with IF (parent > 0, 'Has parent', '-') AS parent the output is correct.

Is there a better way to do this?

答:
```<code>SELECT id, label,
    CASE WHEN COALESCE(parent,0) > 0 THEN
       COALESCE(SELECT id FROM meta
           WHERE parent = m.id, '-')
    ELSE '-' END AS parent
FROM meta AS m WHERE type = 'genre'
</code>```

COALESCE will check for the NULL values and replace that values with 0

Body:
I am selecting a list from a table, and would like to include the parent's label if an item has a parent, or just - if it doesn't.

For this example the table structure is basic :

id | label | parent

This is he statment I'm trying:

SELECT id, label,
    IF (parent > 0, (SELECT id FROM meta WHERE parent = m.id), '-') AS parent
    FROM meta AS m WHERE type = 'genre'

I'm getting [NULL] for parent when the item does have a parent. If I replace the IF statement with IF (parent > 0, 'Has parent', '-') AS parent the output is correct.

Is there a better way to do this?

Body:
SELECT id, label,
    CASE WHEN COALESCE(parent,0) > 0 THEN
       COALESCE(SELECT id FROM meta
           WHERE parent = m.id, '-')
    ELSE '-' END AS parent
FROM meta AS m WHERE type = 'genre'

COALESCE will check for the NULL values and replace that values with 0


问:
How do i set slider value without 'update' firering?
I want to be able to set the slider value without getting the update event to fire. I tried with setting a second parameter (fireSetEvent) in the set function, but that doesn't work.

nouiContrast = document.getElementById('nouiContrast');
noUiSlider.create(nouiContrast, {
  start: 0,
  step: 0.01,
  behaviour: 'tap',
  connect: [true, false],
  range: {
    'min': 0,
    'max': 1
  }
});
nouiContrast.noUiSlider.on('update', function(values, handle) {
  applyFilterValue(6, 'contrast', values[handle]);
});

//....

nouiContrast.noUiSlider.set(val, false);
```

答:
If you want to handle updates only when the user dragging the slider but not when the code set an update, you can listen to the slide event.

From the docs:

This event is useful when you specifically want to listen to a handle being dragged, but want to ignore other updates to the slider value. This event also fires on a change by a 'tap'. In most cases, the update is the better choice.

nouiContrast = document.getElementById('nouiContrast');
noUiSlider.create(nouiContrast, {
  start: 0,
  step: 0.01,
  behaviour: 'tap',
  connect: [true, false],
  range: {
    'min': 0,
    'max': 1
  }
});
nouiContrast.noUiSlider.on('slide', function(values, handle) {
  applyFilterValue(6, 'contrast', values[handle]);
});

//....

nouiContrast.noUiSlider.set(val, false);
```


问:
Issue while casting amount to Double
my program is receiving amount value as string and then converting it to Double using Double.parseDouble(transAmt).

Now we are getting issue when amount passed is "100.00" .

Please advise if while casting to double zero precision digits will be lost

答: With some guessing what the "issue" might be: double in Java is an approximation of the mathematical real numbers. As such there is no difference between 100 and 100.00 it is just the same value.

Title: Issue while casting amount to Double


问:
C++ - #include "filename"
At this tutorial it mentions the following about #include "filename":

#include "filename" tells the compiler to look for the file in
  directory containing the source file
  doing the #include. If that fails,
  it will act identically to the angled
  brackets case.

What is meant by the bolded font sentence?

Thanks.

答:
While the exact details are implementation-dependent, there are a few common practices.  In most common compilers, using the quotes #include "filename.h" searches the current directory by default.  Using angle brackets #include <filename.h> searches system-defined library directories.  What it is saying is that if the current directory doesn't have the file you need, it will search the system directories instead.

Note that some compilers may be different, and your compiler itself may have options to change these directories.  There is also the possibility that system headers don't actually exist, but that #include <foo.h> is directly recognized by the compiler to enable certain built-in definitions.

ContentLicense: CC BY-SA 2.5

Title: C++ - #include "filename"


问:
Multiple MySQL statements via JDBC sampler in JMeter
So I am trying to update my database using the data extracted from the HTTP request samplers. So I have the following sql query which works fine for one record:

```<code>UPDATE optim_user
SET equip_uptime = CONCAT('${timestamp_rg1}', ',', '${timestamp_ext1}'), equip_fw = CONCAT('${firmware_rg1}',',', '${firmware_ext1}')
WHERE optim_uid = '${serialnumber_soak1}';
</code>```

I want to update 50 or so records with the data extracted from my hTTP requests.
I have tried following the steps mentioned here but It did not work. Below are the screen shots of the CSV data config and the JDBC sampler

Is there a way to include multiple sql statements? Thanks.

答:
The correct syntax of referencing a JMeter Variable would be either ${statement} or ${__V(statement)}.

Also if your CSV file contains references to other JMeter functions and/or variables you will additionally need to wrap it into __eval() function so my expectation is that you need to come up with something like:

```<code>${__eval(${statement})}
</code>```

See Here’s What to Do to Combine Multiple JMeter Variables article for more details.

Body:
So I am trying to update my database using the data extracted from the HTTP request samplers. So I have the following sql query which works fine for one record:

UPDATE optim_user
SET equip_uptime = CONCAT('${timestamp_rg1}', ',', '${timestamp_ext1}'), equip_fw = CONCAT('${firmware_rg1}',',', '${firmware_ext1}')
WHERE optim_uid = '${serialnumber_soak1}';

I want to update 50 or so records with the data extracted from my hTTP requests.
I have tried following the steps mentioned here but It did not work. Below are the screen shots of the CSV data config and the JDBC sampler

Is there a way to include multiple sql statements? Thanks.

Body:
The correct syntax of referencing a JMeter Variable would be either ${statement} or ${__V(statement)}.

Also if your CSV file contains references to other JMeter functions and/or variables you will additionally need to wrap it into __eval() function so my expectation is that you need to come up with something like:

${__eval(${statement})}

See Here’s What to Do to Combine Multiple JMeter Variables article for more details.


问:
Endeca baseline update is failing: SEVERE: Utility 'rmdir_dgraph-input-old' failed
Baseline update on endeca is failing. Please find the logs below:

```<code> INFO: Finished pushing content to dgraph.
 INFO: [AuthoringMDEXHost] Starting shell utility 'rmdir_dgraph-input-old'.
 INFO: [LiveMDEXHostA] Starting shell utility 'cleanDir_local-dgraph-input'.
 INFO: [LiveMDEXHostA] Starting shell utility 'rmdir_dgraph-input-old'.
 SEVERE: Utility 'rmdir_dgraph-input-old' failed. Refer to utility logs in [ENDECA_CONF]/logs/shell on host LiveMDEXHostA.
Occurred while executing line 7 of valid BeanShell script:

     AuthoringDgraphCluster.copyIndexToDgraphServers();
     AuthoringDgraphCluster.applyIndex();

     LiveDgraphCluster.cleanDirs();
     LiveDgraphCluster.copyIndexToDgraphServers();
     LiveDgraphCluster.applyIndex();

SEVERE: Error executing valid BeanShell script.
Occurred while executing line 19 of valid BeanShell script:

      Dgidx.run();

      // distribute index, update Dgraphs
      DistributeIndexAndApply.run();

      // Upload the generated dimension values to Workbench
      WorkbenchManager.cleanDirs();

SEVERE: Caught an exception while invoking method 'run' on object 'BaselineUpdate'. Releasing locks.

Caused by java.lang.reflect.InvocationTargetException
sun.reflect.NativeMethodAccessorImpl invoke0 - null
Caused by com.endeca.soleng.eac.toolkit.exception.AppControlException
com.endeca.soleng.eac.toolkit.script.Script runBeanShellScript - Error executing valid BeanShell script.
Caused by com.endeca.soleng.eac.toolkit.exception.AppControlException
com.endeca.soleng.eac.toolkit.script.Script runBeanShellScript - Error executing valid BeanShell script.
Caused by com.endeca.soleng.eac.toolkit.exception.EacComponentControlException
com.endeca.soleng.eac.toolkit.utility.Utility run - Utility 'rmdir_dgraph-input-old' failed. Refer to utility logs in [ENDECA_CONF]/logs/shell on host LiveMDEXHostA.
INFO: Released lock 'update_lock'.
</code>```

Has anyone seen this type of error before? Please let me know the potential solution. Also Baseline update is taking 2 to 3 hours and then it's failing, it's annoying.

Thanks!

答:
Check logs under

endeca/PlatformServices/workspace/logs/shell

There should be a log named like appName.rmdir_dgraph-input-old.log

with more info about the error.

Probably a non existing folder is trying to be removed or something like that.

If this is the case just create the folder that the utility is trying to remove and execute baseline again.

Body:
Baseline update on endeca is failing. Please find the logs below:

 INFO: Finished pushing content to dgraph.
 INFO: [AuthoringMDEXHost] Starting shell utility 'rmdir_dgraph-input-old'.
 INFO: [LiveMDEXHostA] Starting shell utility 'cleanDir_local-dgraph-input'.
 INFO: [LiveMDEXHostA] Starting shell utility 'rmdir_dgraph-input-old'.
 SEVERE: Utility 'rmdir_dgraph-input-old' failed. Refer to utility logs in [ENDECA_CONF]/logs/shell on host LiveMDEXHostA.
Occurred while executing line 7 of valid BeanShell script:

     AuthoringDgraphCluster.copyIndexToDgraphServers();
     AuthoringDgraphCluster.applyIndex();

     LiveDgraphCluster.cleanDirs();
     LiveDgraphCluster.copyIndexToDgraphServers();
     LiveDgraphCluster.applyIndex();

SEVERE: Error executing valid BeanShell script.
Occurred while executing line 19 of valid BeanShell script:

      Dgidx.run();

      // distribute index, update Dgraphs
      DistributeIndexAndApply.run();

      // Upload the generated dimension values to Workbench
      WorkbenchManager.cleanDirs();

SEVERE: Caught an exception while invoking method 'run' on object 'BaselineUpdate'. Releasing locks.

Caused by java.lang.reflect.InvocationTargetException
sun.reflect.NativeMethodAccessorImpl invoke0 - null
Caused by com.endeca.soleng.eac.toolkit.exception.AppControlException
com.endeca.soleng.eac.toolkit.script.Script runBeanShellScript - Error executing valid BeanShell script.
Caused by com.endeca.soleng.eac.toolkit.exception.AppControlException
com.endeca.soleng.eac.toolkit.script.Script runBeanShellScript - Error executing valid BeanShell script.
Caused by com.endeca.soleng.eac.toolkit.exception.EacComponentControlException
com.endeca.soleng.eac.toolkit.utility.Utility run - Utility 'rmdir_dgraph-input-old' failed. Refer to utility logs in [ENDECA_CONF]/logs/shell on host LiveMDEXHostA.
INFO: Released lock 'update_lock'.

Has anyone seen this type of error before? Please let me know the potential solution. Also Baseline update is taking 2 to 3 hours and then it's failing, it's annoying.

Thanks!


问:
Node JS res.sendFile() not working
I'm getting ReferenceError: main is not defined
when I open up the http://localhost:3000/

Here I try to open up the main.html located in views directory

This is my app.js

```<code>const express = require('express'),
  app = express(),
  config = require('./config/index'),
  routes = require('./routes/route');

app.use(express.static(`${__dirname}/public`));
app.use(express.static(`${__dirname}/views`));
app.use('/',routes);
app.listen(config.port,()=>{
console.log(`Listing at port ${config.port}`)})
</code>```

This is my route.js

```<code>const express = require('express'),
router = express.Router(),
helpers = require('../helpers/index');

router.route('/')
.get(helpers.index)

module.exports = router
</code>```

This is my helpers/index.js

```<code>var user = require('../user/user');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(main.html);
    }
    else{
        res.sendFile(chat.html)
    }
}

module.exports = exports;
</code>```

Directory Structure

```<code>>helpers
  >index.js
>routes
  >route.js
>user
  >user.js
>views
  >main.html
  >chat.html
app.js
pacakage.json
</code>```

答:
```<code>var user = require('../user/user');
var path = require('path');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(path.resolve('views/main.html'));
    }
    else{
        res.sendFile(path.resolve('views/chat.html'))
    }
}

module.exports = exports;
</code>```

Title: Node JS res.sendFile() not working

Body:
I'm getting ReferenceError: main is not defined
when I open up the http://localhost:3000/

Here I try to open up the main.html located in views directory

This is my app.js

const express = require('express'),
  app = express(),
  config = require('./config/index'),
  routes = require('./routes/route');

app.use(express.static(`${__dirname}/public`));
app.use(express.static(`${__dirname}/views`));
app.use('/',routes);
app.listen(config.port,()=>{
console.log(`Listing at port ${config.port}`)})

This is my route.js

const express = require('express'),
router = express.Router(),
helpers = require('../helpers/index');

router.route('/')
.get(helpers.index)

module.exports = router

This is my helpers/index.js

var user = require('../user/user');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(main.html);
    }
    else{
        res.sendFile(chat.html)
    }
}

module.exports = exports;

Directory Structure

>helpers
  >index.js
>routes
  >route.js
>user
  >user.js
>views
  >main.html
  >chat.html
app.js
pacakage.json


问:
AirConsole CSS different from App and from Google Chrome

Hey guys!
A quick question. if anybody can help me...

I'm creating a game for AirConsole using HTML5/Javascript for my Controller.
I'm currently testing it and I found out that the CSS is not the same:

When I play using the AirConsole App for the Controller

When I use the Google Chrome browser on my phone.

Could any of you know why ? I can't access the code on the app so I can't know what is happening...

I would expect the AirConsole app to be have a wrapper of the Google Chrome webview and therefore, have the same displayed result.

Here is the view using Google Chrome on mobile (v62.0.3202.84):
Google Chrome controller

And here is the result with the last version of the AirConsole app (v.2.0.6):
AirConsole App Controller

答:
On Android AirConsole uses Crosswalk which uses Chromium Version 53. This is not the system webview which uses the latest chrome from Android.
We are going to change this at some point in the future to use the system webview, because Crosswalk development has been discontinued.

On iOS AirConsole uses the system WebView, which uses the internal Safari.

There is an option how you should be able to debug a controller in the App:
https://people.apache.org/~pmuellr/weinre/docs/latest/

This tool allows you to debug any webkit based webview in any app. It's a pure javascript solution.

Please note that WeinRe will only work over http and not over https. This means you will have to run your AirConsole game from a local host.

Disclaimer: I haven't recently used WeinRe, but I'm pretty sure it should still work today.

If it doesn't contact the AirConsole team at hello@n-dream.com and we can provide you with a debug APK build (Android only).


问:
Dynamic Checkbox selector in jquery
I have a series of dyanmic checkboxes which are creating at runtime but with differnt Ids like this (patter is same)

ModellingTagID_1201
ModellingTagID_1202
ModellingTagID_1203
ModellingTagID_1204

I want to know that above check box change or not? how can i make a dyanmic event with dynamic selector? so that i can get that particular checkbox value has changed? is this kind of thing possible?

```<code> $jqLib("#ModellingTagID_*").change(function(){
        var lastState =$jqLib("#ModellingTagAlternativePlanning").prop("disabled");
        $jqLib("#ModellingTagAlternativePlanning").prop("disabled",!lastState);
    });
</code>```

答:
From what I understand, your issue is to distinguish the unique id of the checkbox, which is being, changed. To achieve this, you can simply add a common class to all the elements, alongwith unique random ids.

```<code>   cb_1<input type="checkbox" class="someclass" id='ModellingTagID_1201' value="value_1" checked>
   cb_2<input type="checkbox" class="someclass" id='ModellingTagID_1202' value="value_2">
   cb_3<input type="checkbox" class="someclass" id='ModellingTagID_1203' value="value_3">
</code>```

And then you can simply bind a change event listener to the common class, and fetch the value of the random id, which has been changed, from inside the event listener.

```<code>$(document).ready(function(){
    $('.someclass').on('change', function() {
        alert($(this).attr("id"));
    });
});
</code>```

Title: Dynamic Checkbox selector in jquery

Body:
I have a series of dyanmic checkboxes which are creating at runtime but with differnt Ids like this (patter is same)

ModellingTagID_1201
ModellingTagID_1202
ModellingTagID_1203
ModellingTagID_1204

I want to know that above check box change or not? how can i make a dyanmic event with dynamic selector? so that i can get that particular checkbox value has changed? is this kind of thing possible?

 $jqLib("#ModellingTagID_*").change(function(){
        var lastState =$jqLib("#ModellingTagAlternativePlanning").prop("disabled");
        $jqLib("#ModellingTagAlternativePlanning").prop("disabled",!lastState);
    });

Body:
From what I understand, your issue is to distinguish the unique id of the checkbox, which is being, changed. To achieve this, you can simply add a common class to all the elements, alongwith unique random ids.

   cb_1<input type="checkbox" class="someclass" id='ModellingTagID_1201' value="value_1" checked>
   cb_2<input type="checkbox" class="someclass" id='ModellingTagID_1202' value="value_2">
   cb_3<input type="checkbox" class="someclass" id='ModellingTagID_1203' value="value_3">

And then you can simply bind a change event listener to the common class, and fetch the value of the random id, which has been changed, from inside the event listener.

$(document).ready(function(){
    $('.someclass').on('change', function() {
        alert($(this).attr("id"));
    });
});


问:
MySql Trigger before insert not working
I am having trouble creating a BEFORE INSERT trigger.

table schema:

```<code>CREATE TABLE IF NOT EXISTS `myReferenceTable` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `linkFrom` bigint(20) NOT NULL,
  `linkTo` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `linkFrom` (`linkFrom`,`linkTo`),
  KEY `linkTo` (`linkTo`)
) ENGINE=InnoDB
</code>```

inserting data:

```<code>INSERT INTO `myReferenceTable` (`id`, `linkFrom`, `linkTo`) VALUES
(1, 1, 2), // allowed
(2, 2, 1); // allowed
</code>```

My failed attempt at creating a BEFORE INSERT trigger which will not allow linkFrom and linkTo to equal each another. This table articleReferncesTable can not have any article refering to it self,

```<code>/* This fails */
create trigger myReferenceTable_noDuplicate
BEFORE INSERT
ON myReferenceTable
FOR EACH ROW
BEGIN
 IF NEW.linkFrom = NEW.linkTo
  insert ignore()
 END IF;
END;
</code>```

Example:

```<code>INSERT INTO `myReferenceTable` (`id`, `linkFrom`, `linkTo`) VALUES
(3, 1, 1), // should fail
(4, 2, 2); // should fail
</code>```

the above data is not allowed. So i want this table to be a "set" table the following data is allowed:

```<code>INSERT INTO `myReferenceTable` (`id`, `linkFrom`, `linkTo`) VALUES
    (3, 1, 2),  // allowed
    (4, 1, 3); // allowed
</code>```

答:
INSERT ignore() doesn't cancel the insert or cause it to fail. There are a few ways to do this, but the simplest is to cause an error:

```<code>...
IF NEW.linkFrom = NEW.linkTo
    DECLARE dummy INT;
    SELECT LINKFROM_EQUALS_LINKTO INTO dummy FROM links
    WHERE links.id = new.id;
END IF;
...
</code>```

see TRIGGERs that cause INSERTs to fail? Possible?

Title: MySql Trigger before insert not working

Body:
I am having trouble creating a BEFORE INSERT trigger.

table schema:

CREATE TABLE IF NOT EXISTS `myReferenceTable` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `linkFrom` bigint(20) NOT NULL,
  `linkTo` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `linkFrom` (`linkFrom`,`linkTo`),
  KEY `linkTo` (`linkTo`)
) ENGINE=InnoDB

inserting data:

INSERT INTO `myReferenceTable` (`id`, `linkFrom`, `linkTo`) VALUES
(1, 1, 2), // allowed
(2, 2, 1); // allowed

My failed attempt at creating a BEFORE INSERT trigger which will not allow linkFrom and linkTo to equal each another. This table articleReferncesTable can not have any article refering to it self,

/* This fails */
create trigger myReferenceTable_noDuplicate
BEFORE INSERT
ON myReferenceTable
FOR EACH ROW
BEGIN
 IF NEW.linkFrom = NEW.linkTo
  insert ignore()
 END IF;
END;

Example:

INSERT INTO `myReferenceTable` (`id`, `linkFrom`, `linkTo`) VALUES
(3, 1, 1), // should fail
(4, 2, 2); // should fail

the above data is not allowed. So i want this table to be a "set" table the following data is allowed:

INSERT INTO `myReferenceTable` (`id`, `linkFrom`, `linkTo`) VALUES
    (3, 1, 2),  // allowed
    (4, 1, 3); // allowed

Body:
INSERT ignore() doesn't cancel the insert or cause it to fail. There are a few ways to do this, but the simplest is to cause an error:

...
IF NEW.linkFrom = NEW.linkTo
    DECLARE dummy INT;
    SELECT LINKFROM_EQUALS_LINKTO INTO dummy FROM links
    WHERE links.id = new.id;
END IF;
...

see TRIGGERs that cause INSERTs to fail? Possible?


问:
Passing MAVEN_OPTS in Pipeline
I'm trying to convert a free-style job to pipeline code. following are the MAVEN_OPTS got declared along with maven goals under "Invoke Artifactory Maven 3" in job.

Maven Goals: clean install

MAVEN_OPTS: -Xmx2048m

-Xms512m

-XX:PermSize=256m

-XX:MaxPermSize=1024m

-Denv.build-timestamp=${BUILD_TIMESTAMP}

-Denv.build-job=${JOB_NAME}

-Denv.build-number=${BUILD_NUMBER}

-Denv.build-url=${BUILD_URL}

-Denv.git-commit=${GIT_COMMIT}

-Denv.git-branch=${GIT_BRANCH}

My trial in pipeline:

```<code>node('node1') {

    def javaHome = tool name: 'JDK 1.8', type: 'hudson.model.JDK'
    def mvnHome = tool name: 'M3', type: 'hudson.tasks.Maven$MavenInstallation'
    sh "$mvnHome/bin/mvn -f pom.xml clean install -U -Dmaven.repo.local=$WORKSPACE/.m2/repository -Xmx2048m -Xms512m -XX:PermSize=256m -XX:MaxPermSize=1024m -Dtimestamp=${BUILD_TIMESTAMP} ..."

    }

Error:
Could not find metadata org.apache.maven.plugins/maven-metadata.xml in local
</code>```

I'm sure that I'm passing MAVEN_OPTS in a wrong way. Can someone guide me the right systax to declare MAVEN_OPTS in Pipeline

答:
Set environment variable MAVEN_OPTS and it will work.</p>

```<code>pipeline {
    agent any
    tools {
        jdk 'JDK 1.8'
        maven 'M3'
    }
    environment {
        MAVEN_OPTS = ' -Denv.build-timestamp=${BUILD_TIMESTAMP} ...'
    }
    stage('Example') {
        steps {
            sh 'mvn clean install'
        }
    }
}
</code>```

Title: Passing MAVEN_OPTS in Pipeline

Body:
I'm trying to convert a free-style job to pipeline code. following are the MAVEN_OPTS got declared along with maven goals under "Invoke Artifactory Maven 3" in job.

Maven Goals: clean install

MAVEN_OPTS: -Xmx2048m

-Xms512m

-XX:PermSize=256m

-XX:MaxPermSize=1024m

-Denv.build-timestamp=${BUILD_TIMESTAMP}

-Denv.build-job=${JOB_NAME}

-Denv.build-number=${BUILD_NUMBER}

-Denv.build-url=${BUILD_URL}

-Denv.git-commit=${GIT_COMMIT}

-Denv.git-branch=${GIT_BRANCH}

My trial in pipeline:

node('node1') {

    def javaHome = tool name: 'JDK 1.8', type: 'hudson.model.JDK'
    def mvnHome = tool name: 'M3', type: 'hudson.tasks.Maven$MavenInstallation'
    sh "$mvnHome/bin/mvn -f pom.xml clean install -U -Dmaven.repo.local=$WORKSPACE/.m2/repository -Xmx2048m -Xms512m -XX:PermSize=256m -XX:MaxPermSize=1024m -Dtimestamp=${BUILD_TIMESTAMP} ..."

    }

Error:
Could not find metadata org.apache.maven.plugins/maven-metadata.xml in local

I'm sure that I'm passing MAVEN_OPTS in a wrong way. Can someone guide me the right systax to declare MAVEN_OPTS in Pipeline

Body:
Set environment variable MAVEN_OPTS and it will work.

pipeline {
    agent any
    tools {
        jdk 'JDK 1.8'
        maven 'M3'
    }
    environment {
        MAVEN_OPTS = ' -Denv.build-timestamp=${BUILD_TIMESTAMP} ...'
    }
    stage('Example') {
        steps {
            sh 'mvn clean install'
        }
    }
}


问:
Send huge data from client to server
I am working with Go and Grpc. I have one XML file to be sent from client to server. When server calls a method on client, client responds back with an XML document which could range from few kB to 100s MB or may be more. Please help me with how should I do it? Should I

assign the value to a string variable and send normally -> rpc GetCMData (CmRequest) returns (CmReply) {}

assign the value to a string variable and send as a stream -> rpc GetCMData (CmRequest) returns (stream CmReply) {}

Is there any other better way to do so?

This is how CmReply looks like:

```<code>message CmReply {
  string name = 1;
}
</code>```

答:
The second one is more the way you want to go. But another point: Are you sure you want to have these hundreds of megabytes in your RAM? I'm not the Go-Geek, but I generally would prefer to work on a File Stream. And probably implement something like a back-pressure-system.

If you work with streams: I would also implement something to make sure that you can handle a break of the stream. Let's say you have the half of your stream and the stream breaks. You don't want to start again and get all previous stream elements, which you already have on the client side. You risk again a connection break within the stream. Maybe at the same point. So, something like pagination. Let's say

```<code>message CMRequest{
  int startAt = 0;
}

message CmReply {
  string id = 0;
  string name = 1;
}
</code>```

If the stream breaks, you send a new request with startAt= LastCmReply.id+1

Here's a video of some good practices in grpc: https://www.youtube.com/watch?v=Z_yD7YPL2oE&index=17&list=WL

Title: Send huge data from client to server

Body:
I am working with Go and Grpc. I have one XML file to be sent from client to server. When server calls a method on client, client responds back with an XML document which could range from few kB to 100s MB or may be more. Please help me with how should I do it? Should I

assign the value to a string variable and send normally -> rpc GetCMData (CmRequest) returns (CmReply) {}

assign the value to a string variable and send as a stream -> rpc GetCMData (CmRequest) returns (stream CmReply) {}

Is there any other better way to do so?

This is how CmReply looks like:

message CmReply {
  string name = 1;
}

Body:
The second one is more the way you want to go. But another point: Are you sure you want to have these hundreds of megabytes in your RAM? I'm not the Go-Geek, but I generally would prefer to work on a File Stream. And probably implement something like a back-pressure-system.

If you work with streams: I would also implement something to make sure that you can handle a break of the stream. Let's say you have the half of your stream and the stream breaks. You don't want to start again and get all previous stream elements, which you already have on the client side. You risk again a connection break within the stream. Maybe at the same point. So, something like pagination. Let's say

message CMRequest{
  int startAt = 0;
}

message CmReply {
  string id = 0;
  string name = 1;
}

If the stream breaks, you send a new request with startAt= LastCmReply.id+1

Here's a video of some good practices in grpc: https://www.youtube.com/watch?v=Z_yD7YPL2oE&index=17&list=WL


问:
Django REST Framework: Nested Serializers not appearing
I am having trouble with nested serializers and the Django rest framework.
When setting serializer_class to "UserSerializer", the nested data from the "NameSerializer" class isn't appearing.
However, when I set serializer_class to "NameSerializer", the data does appear.

The API returns when using UserSerializer:

```<code>HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
  },
  {
    "id": 2,
    "userName": "2@admin.com"
  },
  {
    "id": 3,
    "userName": "3@admin.com"
  },
  {
    "id": 4,
    "userName": "4@admin.com"
  }
]
</code>```

What I want it to return:

```<code>HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
    "name": {
      "familyName": "Joe",
      "givenName": "admin",
      "formated": "admin Joe"
    },
  },
  {
    "id": 2,
    "userName": "jane@admin.com"
    "name": {
      "familyName": "Doe",
      "givenName": "Jane",
      "formated": "Jane Doe"
    },
  },
  {
    "id": 3,
    "userName": "Billy@admin.com"
    "name": {
      "familyName": "Idol",
      "givenName": "Billy",
      "formated": "Billy Idol"
    },
  },
  {
    "id": 4,
    "userName": "User@admin.com"
    "name": {
      "familyName": "B",
      "givenName": "User",
      "formated": "User B"
    },
  }
]
</code>```

views.py

```<code>from API.models import Person
from API.serializers import *
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
   queryset = Person.objects.all()
   serializer_class = NameSerializer
</code>```

models.py

```<code>class Person(AbstractBaseUser):
    email = models.EmailField(
       verbose_name='email address',
       max_length=255,
       unique=True,
       )
    first_name = models.CharField(max_length=254, blank=True)
    last_name =  models.CharField(max_length=254, blank=True)
</code>```

serializers.py

```<code>class NameSerializer(serializers.ModelSerializer):

  familyName = serializers.CharField(source='last_name')
  givenName = serializers.CharField(source='first_name')
  formatted = serializers.SerializerMethodField()

  class Meta:
      model = Person
      fields = ('familyName', 'givenName', 'formatted',)

  def get_formatted(slef, obj):
      FullName = obj.first_name + '' + obj.last_name
      return FullName

class UserSerializer(serializers.ModelSerializer):

  name = NameSerializer(many=True, readonly=True)
  userName = serializers.EmailField(source='email')

  class Meta:
      model = Person
      fields = ('id', 'userName', 'name')
</code>```

Any help is appreciated

答:
Maybe try using SerializerMethodField:
Something like this:</p>

```<code>class UserSerializer(serializers.ModelSerializer):

    userName = serializers.EmailField(source='email')
    name = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'userName', 'name')

    def get_name(self, obj):
        return {
            'familyName': obj.first_name,
            'givenName': obj.last_name,
            'formatted': obj.first_name + ' ' + obj.last_name
        }
</code>```

Body:
I am having trouble with nested serializers and the Django rest framework.
When setting serializer_class to "UserSerializer", the nested data from the "NameSerializer" class isn't appearing.
However, when I set serializer_class to "NameSerializer", the data does appear.

The API returns when using UserSerializer:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
  },
  {
    "id": 2,
    "userName": "2@admin.com"
  },
  {
    "id": 3,
    "userName": "3@admin.com"
  },
  {
    "id": 4,
    "userName": "4@admin.com"
  }
]

What I want it to return:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
    "name": {
      "familyName": "Joe",
      "givenName": "admin",
      "formated": "admin Joe"
    },
  },
  {
    "id": 2,
    "userName": "jane@admin.com"
    "name": {
      "familyName": "Doe",
      "givenName": "Jane",
      "formated": "Jane Doe"
    },
  },
  {
    "id": 3,
    "userName": "Billy@admin.com"
    "name": {
      "familyName": "Idol",
      "givenName": "Billy",
      "formated": "Billy Idol"
    },
  },
  {
    "id": 4,
    "userName": "User@admin.com"
    "name": {
      "familyName": "B",
      "givenName": "User",
      "formated": "User B"
    },
  }
]

views.py

from API.models import Person
from API.serializers import *
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
   queryset = Person.objects.all()
   serializer_class = NameSerializer

models.py

class Person(AbstractBaseUser):
    email = models.EmailField(
       verbose_name='email address',
       max_length=255,
       unique=True,
       )
    first_name = models.CharField(max_length=254, blank=True)
    last_name =  models.CharField(max_length=254, blank=True)

serializers.py

class NameSerializer(serializers.ModelSerializer):

  familyName = serializers.CharField(source='last_name')
  givenName = serializers.CharField(source='first_name')
  formatted = serializers.SerializerMethodField()

  class Meta:
      model = Person
      fields = ('familyName', 'givenName', 'formatted',)

  def get_formatted(slef, obj):
      FullName = obj.first_name + '' + obj.last_name
      return FullName

class UserSerializer(serializers.ModelSerializer):

  name = NameSerializer(many=True, readonly=True)
  userName = serializers.EmailField(source='email')

  class Meta:
      model = Person
      fields = ('id', 'userName', 'name')

Any help is appreciated

Body:
Maybe try using SerializerMethodField:
Something like this:

class UserSerializer(serializers.ModelSerializer):

    userName = serializers.EmailField(source='email')
    name = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'userName', 'name')

    def get_name(self, obj):
        return {
            'familyName': obj.first_name,
            'givenName': obj.last_name,
            'formatted': obj.first_name + ' ' + obj.last_name
        }


问:
Removing directory using codeigniter
I'm new to codeigniter so please forgive me,  I am trying to make codeigniter delete a base folder (I don't know what the right term is, it's the folder where I put my uploaded files and its located in the root of my codeigniter project). Since I am new to codeigniter, I don't have any idea on how to make use of the File Helper reference in the codeigniter api. I hope someone can help me with this.

Furthermore, the delete function I am trying to make needs to delete also all of its contents, so empty or not, the folder gets deleted. I'm guessing, it would use a recursive type of deletion...I'm not so sure at all.

答:
You can do it using "delete_files" function:</p>

```<code>$path = "the path that has files those will be deleted";
$this->load->helper("file"); // load codeigniter file helper
delete_files($path, true , false, 1); //  second and the last parameters are required, second parameter should be true and the last parameter should be greater than 0
</code>```

Title: Removing directory using codeigniter

Body:
You can do it using "delete_files" function:

$path = "the path that has files those will be deleted";
$this->load->helper("file"); // load codeigniter file helper
delete_files($path, true , false, 1); //  second and the last parameters are required, second parameter should be true and the last parameter should be greater than 0


问:
AngularJS and Symfony 3 CORS issue with Chrome
I've been struggling this last week with a bug on my backend and frontend.

I've made a REST API (php/symfony) to manage books and authors. I had an issue on cross-origin requests on the DELETE and it has been fixed since. And now I have an issue on the PUT (POST too) and this ONLY on Chrome (v62.0.3202.94). Tried my API on postman and it's working just fine, tested on Edge and Firefox too.
I've tried to use the Allow-Control-Allow-Origin: * plugin for Chrome and didn't work either.
Everytime i got the same error :

```<code>Request URL:http://127.0.0.1/whereIsMyBook-symfony/web/app_dev.php/updateAuthor/7
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Origin:*
Allow:PUT
Cache-Control:no-cache, private
Connection:Keep-Alive
Content-Type:text/html; charset=UTF-8
Date:Tue, 05 Dec 2017 18:05:06 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.27 (Win64) PHP/5.6.31
Transfer-Encoding:chunked
X-Debug-Token:e8abc7
X-Debug-Token-Link:http://127.0.0.1/whereIsMyBook-symfony/web/app_dev.php/_profiler/e8abc7
X-Powered-By:PHP/5.6.31
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers:access-control-allow-origin,content-type
Access-Control-Request-Method:OPTIONS
Connection:keep-alive
Host:127.0.0.1
Origin:http://localhost:8000
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
</code>```

And an exception is thrown by my backend :

```<code>angular.js:12265 OPTIONS http://127.0.0.1/whereIsMyBook-symfony/web/app_dev.php/updateAuthor/7 net::ERR_ABORTED
</code>```

I've tried to modify my app.config.js and adding the lines below :

```<code>['$httpProvider', function ($httpProvider) {
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    $httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
    $httpProvider.defaults.useXDomain = true;
}]
</code>```

I think i have an issue with the pre-flight requests but can't seem to get rid of them correctly. I've browsed a lot of pages and still can't find why it's not working. As Leia once said : "You're my last hope".

Here's my method (in the service) :

```<code>this.editAuthor= function(formData, index){
         return $http({
            method : 'PUT',
            url : baseUrl + '/updateAuthor/' + index,
            data : formData,
            headers: {
                'Access-Control-Allow-Origin' : '*',
                'Content-Type': 'application/json'
            }
        })
    }
</code>```

My API is hosted on wamp on localhost with the apache headers_module activated.

Thank you for your kind help

答:
You are using angular, this framework use HTTP OPTIONS request to ask the server the authorized HTTP verbs in your backend application.

We can see some usefull informations to debug your error from the server's response

Status Code:405 Method Not Allowed, this HTTP error code is returned by the backend (Symfony here) when he can't handle the request on this route

Allow:PUT, The server return the verb which it can handle

After installation of NelmioCorsBundle  add this configuration to your app/config/config.yml file.

```<code>nelmio_cors:
        paths:
            '^/api/':
                allow_origin: ['*']
                allow_headers: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization']
                allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
                max_age: 0
</code>```

I advice you to define a base route to your symfony's api application, like /api and not just only /update

Let me know if something isn't clear :)

Body:
I've been struggling this last week with a bug on my backend and frontend.

I've made a REST API (php/symfony) to manage books and authors. I had an issue on cross-origin requests on the DELETE and it has been fixed since. And now I have an issue on the PUT (POST too) and this ONLY on Chrome (v62.0.3202.94). Tried my API on postman and it's working just fine, tested on Edge and Firefox too.
I've tried to use the Allow-Control-Allow-Origin: * plugin for Chrome and didn't work either.
Everytime i got the same error :

Request URL:http://127.0.0.1/whereIsMyBook-symfony/web/app_dev.php/updateAuthor/7
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Remote Address:127.0.0.1:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Origin:*
Allow:PUT
Cache-Control:no-cache, private
Connection:Keep-Alive
Content-Type:text/html; charset=UTF-8
Date:Tue, 05 Dec 2017 18:05:06 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.27 (Win64) PHP/5.6.31
Transfer-Encoding:chunked
X-Debug-Token:e8abc7
X-Debug-Token-Link:http://127.0.0.1/whereIsMyBook-symfony/web/app_dev.php/_profiler/e8abc7
X-Powered-By:PHP/5.6.31
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers:access-control-allow-origin,content-type
Access-Control-Request-Method:OPTIONS
Connection:keep-alive
Host:127.0.0.1
Origin:http://localhost:8000
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

And an exception is thrown by my backend :

angular.js:12265 OPTIONS http://127.0.0.1/whereIsMyBook-symfony/web/app_dev.php/updateAuthor/7 net::ERR_ABORTED

I've tried to modify my app.config.js and adding the lines below :

['$httpProvider', function ($httpProvider) {
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    $httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
    $httpProvider.defaults.useXDomain = true;
}]

I think i have an issue with the pre-flight requests but can't seem to get rid of them correctly. I've browsed a lot of pages and still can't find why it's not working. As Leia once said : "You're my last hope".

Here's my method (in the service) :

this.editAuthor= function(formData, index){
         return $http({
            method : 'PUT',
            url : baseUrl + '/updateAuthor/' + index,
            data : formData,
            headers: {
                'Access-Control-Allow-Origin' : '*',
                'Content-Type': 'application/json'
            }
        })
    }

My API is hosted on wamp on localhost with the apache headers_module activated.

Thank you for your kind help

Body:
You are using angular, this framework use HTTP OPTIONS request to ask the server the authorized HTTP verbs in your backend application.

We can see some usefull informations to debug your error from the server's response

Status Code:405 Method Not Allowed, this HTTP error code is returned by the backend (Symfony here) when he can't handle the request on this route

Allow:PUT, The server return the verb which it can handle

After installation of NelmioCorsBundle  add this configuration to your app/config/config.yml file.

nelmio_cors:
        paths:
            '^/api/':
                allow_origin: ['*']
                allow_headers: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization']
                allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
                max_age: 0

I advice you to define a base route to your symfony's api application, like /api and not just only /update

Let me know if something isn't clear :)


问:
Are all the Unicode characters supported on Android
My question is simple. Are all Unicode characters available in Android?
I actually am using the soft keyboard and I want to add a few arabic letters which I can't find the codes for.</p>

答: It does not appear so.  This open issue on the android code site lists many missing characters.</p>


问:
Service (Android Notification): Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
I'm new to Android Studio, since the past 3 months. Any ideas on my error below? Thanks! Notification will be receive once the status of rider application is equal to 0.

Below is my error, Service java class and model java class. I already call service in MainActivity.java but app crashes once entering MainActvity with errors below.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.mariamsyafiqah.coolblogserver, PID: 6206
              java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
                  at com.example.mariamsyafiqah.coolblogserver.Service.ListenRiderApplication.onChildAdded(ListenRiderApplication.java:56)
                  at com.google.android.gms.internal.zzbox.zza(Unknown Source)
                  at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
                  at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

ListenRiderApplication.java

```<code>public class ListenRiderApplication extends Service implements ChildEventListener {
FirebaseDatabase db;
DatabaseReference riderApplication;

@Override
public void onCreate() {
    super.onCreate();
    db = FirebaseDatabase.getInstance();
    riderApplication = db.getReference("Rider");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    riderApplication.addChildEventListener(this);
    return super.onStartCommand(intent, flags, startId);
}

public ListenRiderApplication() {
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    //Trigger here
    RiderApplication request = dataSnapshot.getValue(RiderApplication.class);
    if(request.getStatus().equals("0"))
        showNotification(dataSnapshot.getKey(), request);
}

private void showNotification(String key, RiderApplication request) {
    Intent intent = new Intent(getBaseContext(), RiderAppStatus.class);
    //intent.putExtra("userPhone", request.getPhone());
    PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),0,intent,0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());

    builder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setTicker("Rider Coolblog")
            .setContentInfo("New rider registration")
            .setContentText("You have new rider registered #"+key)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(contentIntent);

    NotificationManager manager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);

    //If you want to many notification show, you need to give uniqie ID for each Notification
    int randomInt = new Random().nextInt(9999-1)+1;
    manager.notify(randomInt,builder.build());

}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
}
</code>```

RiderApplication.java

```<code>public class RiderApplication {
private String phone, name, availability, noPlate;
private String status;

public RiderApplication() {}

public RiderApplication(String phone, String availability, String name, String noPlate) {
    this.phone = phone;
    this.availability = availability;
    this.name = name;
    this.noPlate = noPlate;
    this.status = "0";
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }

public String getAvailability() {
    return availability;
}

public void setAvailability(String availability) {
    this.availability = availability;
}

public String getNoPlate() {
    return noPlate;
}

public void setNoPlate(String noPlate) {
    this.noPlate = noPlate;
}
}
</code>```

答:
Try following code in onChildAdded method</p>

```<code>if(request.getStatus()!=null && request.getStatus().equals("0"))
        showNotification(dataSnapshot.getKey(), request);
</code>```

Body:
I'm new to Android Studio, since the past 3 months. Any ideas on my error below? Thanks! Notification will be receive once the status of rider application is equal to 0.

Below is my error, Service java class and model java class. I already call service in MainActivity.java but app crashes once entering MainActvity with errors below.

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.mariamsyafiqah.coolblogserver, PID: 6206
              java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
                  at com.example.mariamsyafiqah.coolblogserver.Service.ListenRiderApplication.onChildAdded(ListenRiderApplication.java:56)
                  at com.google.android.gms.internal.zzbox.zza(Unknown Source)
                  at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
                  at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

ListenRiderApplication.java

public class ListenRiderApplication extends Service implements ChildEventListener {
FirebaseDatabase db;
DatabaseReference riderApplication;

@Override
public void onCreate() {
    super.onCreate();
    db = FirebaseDatabase.getInstance();
    riderApplication = db.getReference("Rider");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    riderApplication.addChildEventListener(this);
    return super.onStartCommand(intent, flags, startId);
}

public ListenRiderApplication() {
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    //Trigger here
    RiderApplication request = dataSnapshot.getValue(RiderApplication.class);
    if(request.getStatus().equals("0"))
        showNotification(dataSnapshot.getKey(), request);
}

private void showNotification(String key, RiderApplication request) {
    Intent intent = new Intent(getBaseContext(), RiderAppStatus.class);
    //intent.putExtra("userPhone", request.getPhone());
    PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),0,intent,0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());

    builder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setTicker("Rider Coolblog")
            .setContentInfo("New rider registration")
            .setContentText("You have new rider registered #"+key)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(contentIntent);

    NotificationManager manager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);

    //If you want to many notification show, you need to give uniqie ID for each Notification
    int randomInt = new Random().nextInt(9999-1)+1;
    manager.notify(randomInt,builder.build());

}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
}

RiderApplication.java

public class RiderApplication {
private String phone, name, availability, noPlate;
private String status;

public RiderApplication() {}

public RiderApplication(String phone, String availability, String name, String noPlate) {
    this.phone = phone;
    this.availability = availability;
    this.name = name;
    this.noPlate = noPlate;
    this.status = "0";
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }

public String getAvailability() {
    return availability;
}

public void setAvailability(String availability) {
    this.availability = availability;
}

public String getNoPlate() {
    return noPlate;
}

public void setNoPlate(String noPlate) {
    this.noPlate = noPlate;
}
}

Body:
Try following code in onChildAdded method

if(request.getStatus()!=null && request.getStatus().equals("0"))
        showNotification(dataSnapshot.getKey(), request);


问:
Does kfree fill the memory with 0x6b?
I ran into a bug that I found somehow the memory will be filled with '0x6b' for each char by someone else. (I check the memory via printk, not ICE.) After a lot of debugging I found out that it was because I accidentally did kfree to the memory (it was allocated by kmalloc).

I'm curious about who fills the '0x6b' and trace the kfree code but can't find the code doing this. Is it a debugging mechanism of Linux kernel or there is some other reason?

(the env is kernel 4.9)

Thanks!

答:
Is it a debugging mechanism of Linux kernel ...?

Yes, it's called "slab poisoning".

Here is the 0x6b declared in the source for memory freeing:

https://elixir.free-electrons.com/linux/v4.9/source/include/linux/poison.h#L56

And here's a short blurb about it:

https://whatilearned2day.wordpress.com/2006/12/13/slab-poisoning/

Title: Does kfree fill the memory with 0x6b?


问:
how to merge two html files through tornado
I have two HTML files( Home1.html and Home2.html ). I want to merge these two HTML files and serve it as one page using Tornado framework. But I get an error :"Runtime Error: Cannot render() after finish()" when I tried the following:

```<code>class Setup(tornado.web.RequestHandler):
def get(self):
    self.render("Home1.html")
    self.render("Home2.html")

application = tornado.web.Application([
    (r"/setup",Setup ),

])
if __name__ == "__main__":
    application.listen(5500)
tornado.ioloop.IOLoop.instance().start()
</code>```

答:
You'll have to learn how templating works. Read this page on the docs to learn more: http://www.tornadoweb.org/en/stable/guide/templates.html#template-syntax

After that, you can find the complete template syntax reference on this page: http://www.tornadoweb.org/en/stable/template.html#syntax-reference

Anyway, you can "merge" two templates and render them as one by using the {% include %} template tag. Example:

Your Home1.html template should look roughly like this:

    {% include 'Home2.html' %}

```

Then render only the Home1.html from your request handler.

This answer is far from perfect. You'll have to invest some time to actually learn about templates.

Body:
I have two HTML files( Home1.html and Home2.html ). I want to merge these two HTML files and serve it as one page using Tornado framework. But I get an error :"Runtime Error: Cannot render() after finish()" when I tried the following:

class Setup(tornado.web.RequestHandler):
def get(self):
    self.render("Home1.html")
    self.render("Home2.html")

application = tornado.web.Application([
    (r"/setup",Setup ),

])
if __name__ == "__main__":
    application.listen(5500)
tornado.ioloop.IOLoop.instance().start()

Body:
You'll have to learn how templating works. Read this page on the docs to learn more: http://www.tornadoweb.org/en/stable/guide/templates.html#template-syntax

After that, you can find the complete template syntax reference on this page: http://www.tornadoweb.org/en/stable/template.html#syntax-reference

Anyway, you can "merge" two templates and render them as one by using the {% include %} template tag. Example:

Your Home1.html template should look roughly like this:

<html>
    <!-- do something -->
    {% include 'Home2.html' %}
    <!-- do something else -->
</html>

Then render only the Home1.html from your request handler.

This answer is far from perfect. You'll have to invest some time to actually learn about templates.


问:
Row deletion animation issue with swipe to delete
I am implementing swipe to delete feature on one of my table that uses custom table view cells. The issue I am facing is when I tap on "Delete" button, I see a weird transition while cell is being removed.

Below is my code in "commitEditingStyle" and also see the attached screenshot I captured while row is being removed.

PS: I have tried with all types of row removal animation styles but no luck.

```<code>- (void)tableView:(UITableView *)iTableView commitEditingStyle:(UITableViewCellEditingStyle)iEditingStyle forRowAtIndexPath:(NSIndexPath *)iIndexPath {
    if (iEditingStyle == UITableViewCellEditingStyleDelete && iTableView == self.temporaryCartTable) {
        if (self.temporaryCartTable.frame.size.height == kMyAppCartTableViewExpandedHeight) {

            [self.temporaryCartTable beginUpdates];
            [self.temporaryCartTable deleteRowsAtIndexPaths:[NSArray arrayWithObjects: iIndexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];

            MyAppCartInfo *aMyAppCartInfo = [self cart];

            if (([[aMyAppCartInfo.tempProducts allKeys] count] > iIndexPath.row) && [aMyAppCartInfo.tempProducts containsObjectForKey:[[aMyAppCartInfo.tempProducts allKeys] objectAtIndex:iIndexPath.row]]) {
                [aMyAppCartInfo.tempProducts removeObjectForKey:[[aMyAppCartInfo.tempProducts allKeys] objectAtIndex:iIndexPath.row]];
            }

            [self.temporaryCartTable endUpdates];
        }
    }
}

- (BOOL)tableView:(UITableView *)iTableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return (iTableView == self.temporaryCartTable) ? YES : NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)iTableView editingStyleForRowAtIndexPath:(NSIndexPath *)iIndexPath {
    return UITableViewCellEditingStyleDelete;
}

- (CGFloat)tableView:(UITableView *)iTableView heightForRowAtIndexPath:(NSIndexPath *)iIndexPath {

    if (iTableView == self.temporaryCartTable) {
        if (self.isTempCartCell)
            return 92.0;
        else
            return 58.0;
    } else {
        return 58.0;
    }
}
</code>```

答:
If anyone else is having this, the problem in my case was heightForRowAtIndexPath: When cells have dynamic size delete animation behaves strange. In my case the solution was to use a different approach and not spend time investigating. But you can test it and see results. Assign a fixed height for cells:

```<code>self.tableView.rowHeight = Constant;
</code>```

comment out heightForRowAtIndexPath:. And animations should be ok now.

I know this is not the solution but may still help someone.

Body:
I am implementing swipe to delete feature on one of my table that uses custom table view cells. The issue I am facing is when I tap on "Delete" button, I see a weird transition while cell is being removed.

Below is my code in "commitEditingStyle" and also see the attached screenshot I captured while row is being removed.

PS: I have tried with all types of row removal animation styles but no luck.

- (void)tableView:(UITableView *)iTableView commitEditingStyle:(UITableViewCellEditingStyle)iEditingStyle forRowAtIndexPath:(NSIndexPath *)iIndexPath {
    if (iEditingStyle == UITableViewCellEditingStyleDelete && iTableView == self.temporaryCartTable) {
        if (self.temporaryCartTable.frame.size.height == kMyAppCartTableViewExpandedHeight) {

            [self.temporaryCartTable beginUpdates];
            [self.temporaryCartTable deleteRowsAtIndexPaths:[NSArray arrayWithObjects: iIndexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];

            MyAppCartInfo *aMyAppCartInfo = [self cart];

            if (([[aMyAppCartInfo.tempProducts allKeys] count] > iIndexPath.row) && [aMyAppCartInfo.tempProducts containsObjectForKey:[[aMyAppCartInfo.tempProducts allKeys] objectAtIndex:iIndexPath.row]]) {
                [aMyAppCartInfo.tempProducts removeObjectForKey:[[aMyAppCartInfo.tempProducts allKeys] objectAtIndex:iIndexPath.row]];
            }

            [self.temporaryCartTable endUpdates];
        }
    }
}

- (BOOL)tableView:(UITableView *)iTableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return (iTableView == self.temporaryCartTable) ? YES : NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)iTableView editingStyleForRowAtIndexPath:(NSIndexPath *)iIndexPath {
    return UITableViewCellEditingStyleDelete;
}

- (CGFloat)tableView:(UITableView *)iTableView heightForRowAtIndexPath:(NSIndexPath *)iIndexPath {

    if (iTableView == self.temporaryCartTable) {
        if (self.isTempCartCell)
            return 92.0;
        else
            return 58.0;
    } else {
        return 58.0;
    }
}

Body:
If anyone else is having this, the problem in my case was heightForRowAtIndexPath: When cells have dynamic size delete animation behaves strange. In my case the solution was to use a different approach and not spend time investigating. But you can test it and see results. Assign a fixed height for cells:

self.tableView.rowHeight = Constant;

comment out heightForRowAtIndexPath:. And animations should be ok now.

I know this is not the solution but may still help someone.


问:
CKEditor .Net Security Exception
I have another issue with a Security Exception, although this feels like it should be easier to solve.

I've added in to my site the CKEditor .Net library (from here: http://cksource.com/forums/viewtopic.php?f=11&t=15882)

I've included it on my page as a normal control:

```<code><%@ Register Assembly="FredCK.CKEditor" Namespace="FredCK.CKEditor" TagPrefix="ck" %>
</code>```

and put it on the page:

```<code><ck:CkEditor runat="server" id="Editor" Width="692px" Height="400px" />
</code>```

However, when I run the page, I get this message:

```<code>Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
</code>```

In the CKEditor .Net project, there is a strongKey file...I imagine this is where I'm going wrong somewhere, but I just can't work out where.

Any ideas from anyone please?

答: In the end I managed to get it working by downloading a newer version of the dlls</p>

Title: CKEditor .Net Security Exception

Body:
I have another issue with a Security Exception, although this feels like it should be easier to solve.

I've added in to my site the CKEditor .Net library (from here: http://cksource.com/forums/viewtopic.php?f=11&t=15882)

I've included it on my page as a normal control:

<%@ Register Assembly="FredCK.CKEditor" Namespace="FredCK.CKEditor" TagPrefix="ck" %>

and put it on the page:

<ck:CkEditor runat="server" id="Editor" Width="692px" Height="400px" />

However, when I run the page, I get this message:

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

In the CKEditor .Net project, there is a strongKey file...I imagine this is where I'm going wrong somewhere, but I just can't work out where.

Any ideas from anyone please?