问:
JqGrid data export to PDF
I'm trying to export jqgrid to pdf document.
I tried this code but what is missing is saving html to pdf file.
How to add that?

```<code>function ExportPDF() {
                 mya = $("#orwellRadnici").getDataIDs(); // Get All IDs
                    var data = $("#" + table).getRowData(mya[0]); // Get First row to get the
                    // labels
                    var colNames = new Array();
                    var ii = 0;
                    for (var i in data) {
                        colNames[ii++] = i;
                    } // capture col names

                    var html = "<html><head>"
                    + "<style script="css/text">"
                    + "orwellRadnici.tableList_1 th {border:1px solid black; text-align:center; "
                    + "vertical-align: middle; padding:5px;}"
                    + "orwellRadnici.tableList_1 td {border:1px solid black; text-align: left; vertical-align: top; padding:5px;}"
                    + "</style>"
                    + "</head>"
                    + "<body style="page:land;">";

                    for (var k = 0; k < colNames.length; k++) {
                        html = html + "<th>" + colNames[k] + "</th>";
                    }
                    html = html + "</tr>"; // Output header with end of line
                    for (i = 0; i < mya.length; i++) {
                        html = html + "<tr>";
                        data = $("#orwellRadnici").getRowData(mya[i]); // get each row
                        for (var j = 0; j < colNames.length; j++) {
                            html = html + "<td>" + data[colNames[j]] + "</td>"; // output each Row as
                            // tab delimited
                        }
                        html = html + "</tr>"; // output each row with end of line
                    }
                    html = html + "</table></body></html>"; // end of line at the end
                    html = html.replace(/'/g, ''');

                }
</code>```

Is there a simpler way to do this?

答:
I found better and simple solution:

```<code><script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.26/build/pdfmake.min.js">   </script>
    <script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.26/build/vfs_fonts.js"></script>

grid.jqGrid('navGrid', '#ptoolbar', { pdf: true } );

    grid.jqGrid('navButtonAdd', '#ptoolbar', {
    id:'ExportToPDF',
    caption:'',
    title:'Export To Pdf',
    onClickButton : function(e)
    {
        try {
           // ExportPDF();

            $("#orwellRadnici").jqGrid("exportToPdf",{
                    title: 'PDF Export',
                    orientation: 'landscape',
                    pageSize: 'A3',
                    description: 'Events',
                    customSettings: null,
                    download: 'download',
                    includeLabels : true,
                    includeGroupHeader : true,
                    includeFooter: true,
                    fileName : "File.pdf"
                })

        } catch (e) {
            alert(e);
        }
    },
    buttonicon: 'ui-icon-print'
});
</code>```

And that's it !

Title: JqGrid data export to PDF

Body:
I'm trying to export jqgrid to pdf document.
I tried this code but what is missing is saving html to pdf file.
How to add that?

function ExportPDF() {
                 mya = $("#orwellRadnici").getDataIDs(); // Get All IDs
                    var data = $("#" + table).getRowData(mya[0]); // Get First row to get the
                    // labels
                    var colNames = new Array();
                    var ii = 0;
                    for (var i in data) {
                        colNames[ii++] = i;
                    } // capture col names

                    var html = ""
                    + ""
                    + ""
                    + "";

                    for (var k = 0; k < colNames.length; k++) {
                        html = html + "" + colNames[k] + "	";
                    }
                    html = html + "
"; // Output header with end of line
                    for (i = 0; i < mya.length; i++) {
                        html = html + "
";
                        data = $("#orwellRadnici").getRowData(mya[i]); // get each row
                        for (var j = 0; j < colNames.length; j++) {
                            html = html + "" + data[colNames[j]] + "	"; // output each Row as
                            // tab delimited
                        }
                        html = html + "
"; // output each row with end of line
                    }
                    html = html + "
"; // end of line at the end
                    html = html.replace(/'/g, ''');

                }

Is there a simpler way to do this?

Body:
I found better and simple solution:

<script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.26/build/pdfmake.min.js">   </script>
    <script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.26/build/vfs_fonts.js"></script>

grid.jqGrid('navGrid', '#ptoolbar', { pdf: true } );

    grid.jqGrid('navButtonAdd', '#ptoolbar', {
    id:'ExportToPDF',
    caption:'',
    title:'Export To Pdf',
    onClickButton : function(e)
    {
        try {
           // ExportPDF();

            $("#orwellRadnici").jqGrid("exportToPdf",{
                    title: 'PDF Export',
                    orientation: 'landscape',
                    pageSize: 'A3',
                    description: 'Events',
                    customSettings: null,
                    download: 'download',
                    includeLabels : true,
                    includeGroupHeader : true,
                    includeFooter: true,
                    fileName : "File.pdf"
                })

        } catch (e) {
            alert(e);
        }
    },
    buttonicon: 'ui-icon-print'
});

And that's it !


来源: stackexchange

问:
how to replace all words from sentences from a pandas column with numbers from a dictionary and then sum them?
I have the following dataframe

```<code>import pandas as pd
df = pd.DataFrame({'col': ['bad good better three worst', 'awful best one']})
</code>```

and I have the following dictionary dc = dict({'bad':-1,'good':1,'better':2,'worst':-3,'awful':-5})

I would like to replace all the words from the col with the numbers that correspond with this word from the dc and then sum the numbers.

First I tried the replacement using

```<code>def replace_words(s, words):
    for k, v in words.items():
        s = s.replace('^'k+'$', v, regex=True)
    return s
</code>```

df['col'] = df['col'].apply(lambda x: [replace_words(i, dc) for i in x.split(' ')])

but this does not work.

Any ideas ?

答:
Use list comprehension with get for lookup values with default value 0 and sum:

```<code>df['col'] = [sum(dc.get(x, 0) for x in i.split()) for i in df['col']]
print (df)
   col
0   -1
1   -5
</code>```

Another solution for test values in dict with in:

```<code>df['col'] = [sum(dc.get(x) for x in i.split() if x in dc) for i in df['col']]
</code>```

Details:

```<code>print ([list(dc.get(x, 0) for x in i.split()) for i in df['col']])
[[-1, 1, 2, 0, -3], [-5, 0, 0]]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following dataframe

import pandas as pd
df = pd.DataFrame({'col': ['bad good better three worst', 'awful best one']})

and I have the following dictionary dc = dict({'bad':-1,'good':1,'better':2,'worst':-3,'awful':-5})

I would like to replace all the words from the col with the numbers that correspond with this word from the dc and then sum the numbers.

First I tried the replacement using

def replace_words(s, words):
    for k, v in words.items():
        s = s.replace('^'k+'$', v, regex=True)
    return s

df['col'] = df['col'].apply(lambda x: [replace_words(i, dc) for i in x.split(' ')])

but this does not work.

Any ideas ?

Body:
Use list comprehension with get for lookup values with default value 0 and sum:

df['col'] = [sum(dc.get(x, 0) for x in i.split()) for i in df['col']]
print (df)
   col
0   -1
1   -5

Another solution for test values in dict with in:

df['col'] = [sum(dc.get(x) for x in i.split() if x in dc) for i in df['col']]

Details:

print ([list(dc.get(x, 0) for x in i.split()) for i in df['col']])
[[-1, 1, 2, 0, -3], [-5, 0, 0]]


问:
Display validation message with duplicate StudentId one by one
I want to check duplicate Id validation in sql server, that validation grid display
row number , validation message & duplicate ID from sql server

I am not able to understand that how can I do it ?

Help is really appreciate

Create Table

```<code>    CREATE TEMPORARY TABLE IF NOT EXISTS Tbl_Student
    (RowID INT PRIMARY KEY auto_increment, StudentID BIGINT);
</code>```

Insert Records

```<code>Insert into Tbl_Student(RowID,StudentID) values (1,101)
Insert into Tbl_Student(RowID,StudentID) values (2,102)
Insert into Tbl_Student(RowID,StudentID) values (3,101)
Insert into Tbl_Student(RowID,StudentID) values (4,102)
Insert into Tbl_Student(RowID,StudentID) values (5,103)
</code>```

Please let share if any solution over there

Thank you

答:
Here is T-SQL code, you might need to transform it to MySql format:

```<code>Select * from(
      Select RowId, Count(*) Over(Partition By StudentId Order By RowId) as Cnt From [YourTable]
) as K
Where Cnt>1
</code>```

You can also use Row_Number or Count aggregate function to achieve the same result too.

Here is plenty of MySql solutions for this problem:

Find duplicate records in MySQL

Body:
I want to check duplicate Id validation in sql server, that validation grid display
row number , validation message & duplicate ID from sql server

I am not able to understand that how can I do it ?

Help is really appreciate

Create Table

    CREATE TEMPORARY TABLE IF NOT EXISTS Tbl_Student
    (RowID INT PRIMARY KEY auto_increment, StudentID BIGINT);

Insert Records

Insert into Tbl_Student(RowID,StudentID) values (1,101)
Insert into Tbl_Student(RowID,StudentID) values (2,102)
Insert into Tbl_Student(RowID,StudentID) values (3,101)
Insert into Tbl_Student(RowID,StudentID) values (4,102)
Insert into Tbl_Student(RowID,StudentID) values (5,103)

Please let share if any solution over there

Thank you

Body:
Here is T-SQL code, you might need to transform it to MySql format:

Select * from(
      Select RowId, Count(*) Over(Partition By StudentId Order By RowId) as Cnt From [YourTable]
) as K
Where Cnt>1

You can also use Row_Number or Count aggregate function to achieve the same result too.

Here is plenty of MySql solutions for this problem:

Find duplicate records in MySQL


答:
To display the duplicates I would do:</p>

```<code>select
  RowID,
  concat('Student ', StudentID, ' is duplicate') as StudentID
from Tbl_Student where StudentID in (
  select StudentID from Tbl_Student group by StudentID having count(*) > 1
)
</code>```

Title: Display validation message with duplicate StudentId one by one

Body:
To display the duplicates I would do:

select
  RowID,
  concat('Student ', StudentID, ' is duplicate') as StudentID
from Tbl_Student where StudentID in (
  select StudentID from Tbl_Student group by StudentID having count(*) > 1
)


问:
How to find which unicode letters look good in URL
For some examples:

These characters are too short or overlap the surrounding characters:

```<code>/b5/ີ/foo
/31/ั/foo
/39/᤹/foo
/a3/ᮣ/foo
</code>```

These are too long to fit into monospace character slot:

```<code>/4b/ോ/foo
/23/ᠣ/fo
/61/ᡡ/foo
/86/ᢆ/foo
/ba/຺/foo
</code>```

Then blank/whitespace/invisible characters would also be considered ones that don't fit well in the URL.

Wondering if there is a simple way to figure out which characters fall into these slots:

Fits well in URL (latin characters, chinese characters, etc.).

Too large for monospace (chinese characters, the above examples, etc.).

Combining character or overlaps surrounding URL characters (examples above).

Maybe by checking some property on the unicode character there is a way to tell this programmatically, so I don't need to go through each character individually and visually check which category it falls into.

Mainly I am looking for which characters need to be either (a) placed on another character (combining characters), or (b) need some extra padding like the examples above, so you can see them in the URL).

答:
The problem is ill-defined. You claim that the latter five don't fit, but for me they render in one column, which is precisely according to how it's specified in Unicode. Also see: https://stackoverflow.com/a/56216985/46395</p>

```<code>use 5.030;
use Unicode::GCString qw();

for (
    "\N{WORD JOINER}",                  # U+2060
    "\N{LATIN SMALL LETTER L}",         # U+006C
    "\N{CJK UNIFIED IDEOGRAPH-4E2D}",   # U+4E2D

    "\N{LAO VOWEL SIGN II}",                # U+0EB5
    "\N{THAI CHARACTER MAI HAN-AKAT}",      # U+0E31
    "\N{LIMBU SIGN MUKPHRENG}",             # U+1939
    "\N{SUNDANESE CONSONANT SIGN PANYIKU}", # U+1BA3

    "\N{MALAYALAM VOWEL SIGN OO}",                  # U+0D4B
    "\N{MONGOLIAN LETTER O}",                       # U+1823
    "\N{MONGOLIAN LETTER SIBE U}",                  # U+1861
    "\N{MONGOLIAN LETTER ALI GALI THREE BALUDA}",   # U+1886
    "\N{LAO SIGN PALI VIRAMA}",                     # U+0EBA
) {
    say Unicode::GCString->new($_)->columns
}
__END__
0
1
2
0
0
0
0
1
1
1
1
1
</code>```

Body:
For some examples:

These characters are too short or overlap the surrounding characters:

/b5/ີ/foo
/31/ั/foo
/39/᤹/foo
/a3/ᮣ/foo

These are too long to fit into monospace character slot:

/4b/ോ/foo
/23/ᠣ/fo
/61/ᡡ/foo
/86/ᢆ/foo
/ba/຺/foo

Then blank/whitespace/invisible characters would also be considered ones that don't fit well in the URL.

Wondering if there is a simple way to figure out which characters fall into these slots:

Fits well in URL (latin characters, chinese characters, etc.).

Too large for monospace (chinese characters, the above examples, etc.).

Combining character or overlaps surrounding URL characters (examples above).

Maybe by checking some property on the unicode character there is a way to tell this programmatically, so I don't need to go through each character individually and visually check which category it falls into.

Mainly I am looking for which characters need to be either (a) placed on another character (combining characters), or (b) need some extra padding like the examples above, so you can see them in the URL).

Body:
The problem is ill-defined. You claim that the latter five don't fit, but for me they render in one column, which is precisely according to how it's specified in Unicode. Also see: https://stackoverflow.com/a/56216985/46395

use 5.030;
use Unicode::GCString qw();

for (
    "\N{WORD JOINER}",                  # U+2060
    "\N{LATIN SMALL LETTER L}",         # U+006C
    "\N{CJK UNIFIED IDEOGRAPH-4E2D}",   # U+4E2D

    "\N{LAO VOWEL SIGN II}",                # U+0EB5
    "\N{THAI CHARACTER MAI HAN-AKAT}",      # U+0E31
    "\N{LIMBU SIGN MUKPHRENG}",             # U+1939
    "\N{SUNDANESE CONSONANT SIGN PANYIKU}", # U+1BA3

    "\N{MALAYALAM VOWEL SIGN OO}",                  # U+0D4B
    "\N{MONGOLIAN LETTER O}",                       # U+1823
    "\N{MONGOLIAN LETTER SIBE U}",                  # U+1861
    "\N{MONGOLIAN LETTER ALI GALI THREE BALUDA}",   # U+1886
    "\N{LAO SIGN PALI VIRAMA}",                     # U+0EBA
) {
    say Unicode::GCString->new($_)->columns
}
__END__
0
1
2
0
0
0
0
1
1
1
1
1


答:
Try the following Query,</p>

```<code>SELECT RowID, CONCAT('StudentID ',StudentID, ' is Duplicate) AS Error FROM Tbl_Student WHERE StudentID IN (SELECT StudentID FROM Tbl_Student GROUP BY StudentID  HAVING COUNT(*) > 1)
</code>```

Body:
Try the following Query,

SELECT RowID, CONCAT('StudentID ',StudentID, ' is Duplicate) AS Error FROM Tbl_Student WHERE StudentID IN (SELECT StudentID FROM Tbl_Student GROUP BY StudentID  HAVING COUNT(*) > 1)


问:
Error when fitting 3D convolutional neural network
I am trying to train a convolutional neural network on google colab for a medical classification problem. The data set is 89 256x256x256 images for training and 11 for testing. When I try to make my model train it gives me the following error:

import keras
from keras import optimizers
import keras.models
from keras.models import Sequential
import keras.layers
from keras.layers.convolutional import Conv3D
from keras.layers.convolutional import MaxPooling3D
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers import Dense
from keras import metrics
model = Sequential()
model.add(Conv3D(64, kernel_size=(3,3,3),
                 activation='relu',
                 input_shape=(10,1,256,256,256)))
model.add(Conv3D(64, (2,2,2), activation='relu'))
model.add(MaxPooling3D(pool_size=(2,2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))

opt=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
model.compile(opt, loss='categorical_crossentropy', metrics=['mae','acc'])
model.fit(x=train_data, y=train_labels,epochs=100, batch_size=10, verbose=2 ,callbacks=None, validation_split=0.0, validation_data=(validation_data,validation_labels), shuffle=True)
```

This is the error i get:

ValueError: Input 0 is incompatible with layer conv3d_56: expected ndim=5, found ndim=6

答:
Assuming you are using channels first data_format, your input_shape argugment to the first Conv3D layer  should be (CHANNELS, HEIGHT, WIDTH, DEPTH). But your input shape tuple has length of 5, and that is not what Conv3D layer expecting. Assuming the batch_size(of 10) is specified by mistake, making the following changes should fix the problem

model.add(Conv3D(64, kernel_size=(3,3,3),
                 activation='relu',
                 input_shape=(1,256,256,256)))
```
<h2>Edit</h2>
<p>If you are using channels_last data-format your <code>input_shape</code> should be <code>(HEIGHT, WIDTH, DEPTH, CHANNELS)</code>. And assuming your images have 1 channels, the above line should be,</p>
<pre class="lang-py prettyprint-override"><code>model.add(Conv3D(64, kernel_size=(3,3,3),
                 activation='relu',
                 input_shape=(256,256,256, 1)))
</code>```

Body:
I am trying to train a convolutional neural network on google colab for a medical classification problem. The data set is 89 256x256x256 images for training and 11 for testing. When I try to make my model train it gives me the following error:

import keras
from keras import optimizers
import keras.models
from keras.models import Sequential
import keras.layers
from keras.layers.convolutional import Conv3D
from keras.layers.convolutional import MaxPooling3D
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers import Dense
from keras import metrics
model = Sequential()
model.add(Conv3D(64, kernel_size=(3,3,3),
                 activation='relu',
                 input_shape=(10,1,256,256,256)))
model.add(Conv3D(64, (2,2,2), activation='relu'))
model.add(MaxPooling3D(pool_size=(2,2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))

opt=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
model.compile(opt, loss='categorical_crossentropy', metrics=['mae','acc'])
model.fit(x=train_data, y=train_labels,epochs=100, batch_size=10, verbose=2 ,callbacks=None, validation_split=0.0, validation_data=(validation_data,validation_labels), shuffle=True)

This is the error i get:

ValueError: Input 0 is incompatible with layer conv3d_56: expected ndim=5, found ndim=6

Body:
Assuming you are using channels first data_format, your input_shape argugment to the first Conv3D layer  should be (CHANNELS, HEIGHT, WIDTH, DEPTH). But your input shape tuple has length of 5, and that is not what Conv3D layer expecting. Assuming the batch_size(of 10) is specified by mistake, making the following changes should fix the problem

model.add(Conv3D(64, kernel_size=(3,3,3),
                 activation='relu',
                 input_shape=(1,256,256,256)))

Edit

If you are using channels_last data-format your input_shape should be (HEIGHT, WIDTH, DEPTH, CHANNELS). And assuming your images have 1 channels, the above line should be,

model.add(Conv3D(64, kernel_size=(3,3,3),
                 activation='relu',
                 input_shape=(256,256,256, 1)))


问:
How to link routes list with store variable?
Is there any way to link routes list:

```<code>// router.js
export default new Router({
   routes: [
      { path: '/', component: Page },
      { path: '/page1', component: Page1 },
      { path: '/page2', component: Page2 },
   ]
})
</code>```

...to the variable in store:

```<code>// store.js
export default new Vuex.Store({
   state: {
      routes_list: []
   }
})
</code>```

?

答:
You would need to add a getter for your list. Something like:

```<code>export default new Vuex.Store({
   state: {
      routes_list: []
   },
  getters: {
    routesList: state => {
      return state.routes_list;
    }
  }
})
</code>```

Then you could import your Store in your router.js and use the created getter to receive the list:

```<code>// maybe your path is different
import Store from '@/store/index';
export default new Router({
   routes: Store.getters.routesList
})
</code>```

I've didn't tested the router code, maybe you need to do some correction.

Body:
Is there any way to link routes list:

// router.js
export default new Router({
   routes: [
      { path: '/', component: Page },
      { path: '/page1', component: Page1 },
      { path: '/page2', component: Page2 },
   ]
})

...to the variable in store:

// store.js
export default new Vuex.Store({
   state: {
      routes_list: []
   }
})

?

Body:
You would need to add a getter for your list. Something like:

export default new Vuex.Store({
   state: {
      routes_list: []
   },
  getters: {
    routesList: state => {
      return state.routes_list;
    }
  }
})

Then you could import your Store in your router.js and use the created getter to receive the list:

// maybe your path is different
import Store from '@/store/index';
export default new Router({
   routes: Store.getters.routesList
})

I've didn't tested the router code, maybe you need to do some correction.


问:
Running pod setup gives me "bad interpreter: No such file or directory" error
Recently I tried to do pod setup and I get this error:

```<code>-bash: /usr/local/bin/pod: /usr/local/opt/ruby/bin/ruby: bad interpreter: No such file or directory
</code>```

I followed Ray Wenderlich's guide to install CocoaPods and I get this issue so I have no idea what is going on.

答:
Same issue I was facing when I updated our system from Sierra to Mojave. Also works for Catalina

The following steps worked:

```<code>sudo gem update --system
sudo gem install -n /usr/local/bin cocoapods
</code>```

I got the help from the following link.

Body:
Recently I tried to do pod setup and I get this error:

-bash: /usr/local/bin/pod: /usr/local/opt/ruby/bin/ruby: bad interpreter: No such file or directory

I followed Ray Wenderlich's guide to install CocoaPods and I get this issue so I have no idea what is going on.

Body:
Same issue I was facing when I updated our system from Sierra to Mojave. Also works for Catalina

The following steps worked:

sudo gem update --system
sudo gem install -n /usr/local/bin cocoapods

I got the help from the following link.


问:
How to remove dark layer on video from BMPLayer iOS Swift?
I want to remove dark layer from BMPlayer. How to do it?</p>

答:
I found right answer:

```<code>player.controlView.mainMaskView.isHidden = true
</code>```

and use it like this:

```<code>func bmPlayer(player: BMPlayer, playerIsPlaying playing: Bool) {
    print("| BMPlayerDelegate | playerIsPlaying | playing - \(playing)")
    player.controlView.mainMaskView.isHidden = true
}

func bmPlayer(player: BMPlayer, playerStateDidChange state: BMPlayerState) {
    print("| BMPlayerDelegate | playerStateDidChange | state - \(state)")
    player.controlView.mainMaskView.isHidden = true
}

func bmPlayer(player: BMPlayer, playTimeDidChange currentTime: TimeInterval, totalTime: TimeInterval) {
    player.controlView.mainMaskView.isHidden = true
}

func bmPlayer(player: BMPlayer, loadedTimeDidChange loadedDuration: TimeInterval, totalDuration: TimeInterval) {
    player.controlView.mainMaskView.isHidden = true
}
</code>```

Body:
I found right answer:

player.controlView.mainMaskView.isHidden = true

and use it like this:

func bmPlayer(player: BMPlayer, playerIsPlaying playing: Bool) {
    print("| BMPlayerDelegate | playerIsPlaying | playing - \(playing)")
    player.controlView.mainMaskView.isHidden = true
}

func bmPlayer(player: BMPlayer, playerStateDidChange state: BMPlayerState) {
    print("| BMPlayerDelegate | playerStateDidChange | state - \(state)")
    player.controlView.mainMaskView.isHidden = true
}

func bmPlayer(player: BMPlayer, playTimeDidChange currentTime: TimeInterval, totalTime: TimeInterval) {
    player.controlView.mainMaskView.isHidden = true
}

func bmPlayer(player: BMPlayer, loadedTimeDidChange loadedDuration: TimeInterval, totalDuration: TimeInterval) {
    player.controlView.mainMaskView.isHidden = true
}


问:
How to fix 'Cannot read property of undefined' error in Angular post request
I'm getting these errors and I'm not sure how to fix it. I am making a form that will make a post request to an API.

ERROR TypeError: Cannot read property 'email' of undefined

ERROR TypeError: Cannot read property 'paymentMethod' of undefined

I am expecting:

```<code>createdBy: string from email input,
paymentMethod: string from paymentMethod select input,
</code>```

But what I get is:

```<code>createdBy: null,
paymentMethod: null
</code>```

Interfaces

```<code>export interface BillingForm {
    fullName: string;
    email: string;
    address: string;
    city: string;
    paymentMethod: string;

  }

export interface Order {
  id?: number;
  companyId: number;
  created: string;
  createdBy: string;
  paymentMethod: string;
  totalPrice: number;
  status: number;
  orderRows: OrderRows[];
}
</code>```

service.ts

```<code>public postOrder(order: Order): Observable<Order> {
      console.log(order);
      return this.http.post<Order>(this.ordersURL, order, httpOptions).pipe(
        catchError(this.handleError('postOrder', order))
      );
</code>```

component.ts

```<code>ngOnInit() {

    this.shippingForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      address: ['', Validators.required],
      paymentMethod: ['', Validators.required],
      city: ['', Validators.required],
    })
  }

  onSubmit(billingForm: BillingForm) {
    const order = this.newOrder(billingForm);

    this.productService.postOrder(order).subscribe (
      response => console.log('success', response),
      error => console.log('error', error)
    )

    this.submitted = true;

    if(this.shippingForm.invalid) {
      return;
    }
    this.success = true;

  }

  newOrder(billingForm: BillingForm ): Order {
    return {
      companyId: 6,
      created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
      createdBy: billingForm.email,
      paymentMethod: billingForm.paymentMethod,
      totalPrice: this.totalPrice,
      status: 0,
      orderRows: this.orderRows

    }
  }

  get email() {
    return this.shippingForm.get("email") as FormControl;
  }

  get paymentMethod() {
    return this.shippingForm.get("paymentMethod") as FormControl;
  }

</code>```

component.html

```<code><form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">
        <h5 *ngIf="success">Your form is valid!</h5>
          <div class="form-group col-md-6">
            <label for="inputEmail">Email</label>
            <input type="email" formControlName="email" class="form-control" id="inputEmail" placeholder="Email">
            <div *ngIf="submitted && shippingForm.controls.email.errors" class="error">
              <div *ngIf="shippingForm.controls.email.errors.required">Your email is required!</div>
            </div>
          </div>
        </div>
        <div class="form-group col-md-6">
            <label for="payment">Payment Method: </label>
            <select type="select" formControlName="paymentMethod" class="form-control" id="payment"
              aria-placeholder="Mastercard">
              <option selected> Choose...</option>
              <option *ngFor="let paymentMethod of paymentMethods">
                {{ paymentMethod }}
              </option>
            </select>
            <div *ngIf="submitted && shippingForm.controls.paymentMethod.errors" class="error">
              <div *ngIf="shippingForm.controls.paymentMethod.errors.required">Your preferred payment method is required!</div>
            </div>
          </div>
</form>
</code>```

答:
```<code>  newOrder(billingForm: BillingForm ): Order {
    return {
      companyId: 6,
      created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
      createdBy: billingForm.email, // <--- HERE
      paymentMethod: billingForm.paymentMethod, // <--- HERE
      totalPrice: this.totalPrice,
      status: 0,
      orderRows: this.orderRows

    }
  }
</code>```

The two lines depend on billingForm, and it seems that this billingForm doesn't have the email & paymentMethod values. Log it to be sure.

Body:
I'm getting these errors and I'm not sure how to fix it. I am making a form that will make a post request to an API.

ERROR TypeError: Cannot read property 'email' of undefined

ERROR TypeError: Cannot read property 'paymentMethod' of undefined

I am expecting:

createdBy: string from email input,
paymentMethod: string from paymentMethod select input,

But what I get is:

createdBy: null,
paymentMethod: null

Interfaces

export interface BillingForm {
    fullName: string;
    email: string;
    address: string;
    city: string;
    paymentMethod: string;

  }

export interface Order {
  id?: number;
  companyId: number;
  created: string;
  createdBy: string;
  paymentMethod: string;
  totalPrice: number;
  status: number;
  orderRows: OrderRows[];
}

service.ts

public postOrder(order: Order): Observable<Order> {
      console.log(order);
      return this.http.post<Order>(this.ordersURL, order, httpOptions).pipe(
        catchError(this.handleError('postOrder', order))
      );

component.ts

ngOnInit() {

    this.shippingForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      address: ['', Validators.required],
      paymentMethod: ['', Validators.required],
      city: ['', Validators.required],
    })
  }

  onSubmit(billingForm: BillingForm) {
    const order = this.newOrder(billingForm);

    this.productService.postOrder(order).subscribe (
      response => console.log('success', response),
      error => console.log('error', error)
    )

    this.submitted = true;

    if(this.shippingForm.invalid) {
      return;
    }
    this.success = true;

  }

  newOrder(billingForm: BillingForm ): Order {
    return {
      companyId: 6,
      created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
      createdBy: billingForm.email,
      paymentMethod: billingForm.paymentMethod,
      totalPrice: this.totalPrice,
      status: 0,
      orderRows: this.orderRows

    }
  }

  get email() {
    return this.shippingForm.get("email") as FormControl;
  }

  get paymentMethod() {
    return this.shippingForm.get("paymentMethod") as FormControl;
  }

component.html

<form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">

Your form is valid!

            Email
            <input type="email" formControlName="email" class="form-control" id="inputEmail" placeholder="Email">

Your email is required!

            Payment Method:
            <select type="select" formControlName="paymentMethod" class="form-control" id="payment"
              aria-placeholder="Mastercard">
              <option selected> Choose...</option>
              <option *ngFor="let paymentMethod of paymentMethods">
                {{ paymentMethod }}
              </option>
            </select>

Your preferred payment method is required!

</form>

Body:
  newOrder(billingForm: BillingForm ): Order {
    return {
      companyId: 6,
      created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
      createdBy: billingForm.email, // <--- HERE
      paymentMethod: billingForm.paymentMethod, // <--- HERE
      totalPrice: this.totalPrice,
      status: 0,
      orderRows: this.orderRows

    }
  }

The two lines depend on billingForm, and it seems that this billingForm doesn't have the email & paymentMethod values. Log it to be sure.


问:
C++ how to sort vector<class *> with operator <
i have

```<code> class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())
</code>```

why it dosent sort ?

but if we had

```<code> bool operator < (c1 w)
    {
        return number < w.number;
    }
</code>```

and

```<code>vector<c1> vec = { ... }
</code>```

it would have been sorted !

答: bool operator < (c1 *w) compares a c1 to a c1 * - Your sort compares a c1 * to a c1 *

ContentLicense: CC BY-SA 3.0

Body:
i have

 class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())

why it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !


问:
Is there a way for Protractor Cucumber to only rerun failed browser tests?
I'm using protractor flake and running browser tests in parallel using selenium grid. I don't want to rerun all the browser tests if one of the browser failed.

Is there a way to set in the configuration to only rerun the browser that failed?
Protractor config file

```<code>exports.config = {
        seleniumAddress: 'http://localhost:4444/wd/hub',
        getPageTimeout: 600000,
        allScriptsTimeout: 500000,
        defaultTimeoutInterval: 30000,
        framework: 'custom',
        // path relative to the current config file
        frameworkPath: require.resolve('protractor-cucumber-framework'),
        multiCapabilities:
        [{
          'browserName': 'chrome',
          specs: 'features/chrome/*.feature'
        },
        {
          'browserName': 'firefox',
          specs: 'features/firefox/*.feature'
        }],
        baseUrl: 'https://localhost:8080',
        ignoreSynchronization: true,
        cucumberOpts: {
          strict: true,
          require: [
            'hooks/hooks.js',
            'specs/*Spec.js'
          ],
          tags: [
            "@runThis",
            "~@ignoreThis"
          ],
          profile: false,
          format: 'json:e2e/reports/cucumber-report.json',
          resultJsonOutputFile: 'e2e/reports/cucumber-report.json'
        },
        onPrepare: async function() {

          const fs = require('fs');
          const path = require('path');

          const directory = 'e2e/reports';

          //cleans up the json results from the previous build when using node flake
          fs.readdir(directory, (err, files) => {
            if (err) throw err;

            for (const file of files) {
              fs.unlink(path.join(directory, file), err => {
                if (err) throw err;
              });
            }
          });

          var chai = require('chai');
          chai.use(require('chai-as-promised'));
          global.expect = chai.expect;
          browser.ignoreSynchronization = true;
          await browser.manage().window().maximize();
          browser.waitForAngular();
          browser.manage().timeouts().implicitlyWait(30000);

        },
        onComplete: function() {

        }
    }
</code>```

答:
Yes, for that you need to put the reporter rerun with the name of the file you want to give to the ouput:

```<code>format: ['pretty', 'rerun:@rerun.txt']
</code>```

then you have to run protractor with the cucumber options specifying the filename:

```<code>protractor test/cucumber/conf/cucumber1Conf.js --cucumberOpts.rerun test/cucumber/@rerun.txt
</code>```

More information about it can be found here: https://github.com/protractor-cucumber-framework/protractor-cucumber-framework/issues/89

Body:
I'm using protractor flake and running browser tests in parallel using selenium grid. I don't want to rerun all the browser tests if one of the browser failed.

Is there a way to set in the configuration to only rerun the browser that failed?
Protractor config file

exports.config = {
        seleniumAddress: 'http://localhost:4444/wd/hub',
        getPageTimeout: 600000,
        allScriptsTimeout: 500000,
        defaultTimeoutInterval: 30000,
        framework: 'custom',
        // path relative to the current config file
        frameworkPath: require.resolve('protractor-cucumber-framework'),
        multiCapabilities:
        [{
          'browserName': 'chrome',
          specs: 'features/chrome/*.feature'
        },
        {
          'browserName': 'firefox',
          specs: 'features/firefox/*.feature'
        }],
        baseUrl: 'https://localhost:8080',
        ignoreSynchronization: true,
        cucumberOpts: {
          strict: true,
          require: [
            'hooks/hooks.js',
            'specs/*Spec.js'
          ],
          tags: [
            "@runThis",
            "~@ignoreThis"
          ],
          profile: false,
          format: 'json:e2e/reports/cucumber-report.json',
          resultJsonOutputFile: 'e2e/reports/cucumber-report.json'
        },
        onPrepare: async function() {

          const fs = require('fs');
          const path = require('path');

          const directory = 'e2e/reports';

          //cleans up the json results from the previous build when using node flake
          fs.readdir(directory, (err, files) => {
            if (err) throw err;

            for (const file of files) {
              fs.unlink(path.join(directory, file), err => {
                if (err) throw err;
              });
            }
          });

          var chai = require('chai');
          chai.use(require('chai-as-promised'));
          global.expect = chai.expect;
          browser.ignoreSynchronization = true;
          await browser.manage().window().maximize();
          browser.waitForAngular();
          browser.manage().timeouts().implicitlyWait(30000);

        },
        onComplete: function() {

        }
    }

Body:
Yes, for that you need to put the reporter rerun with the name of the file you want to give to the ouput:

format: ['pretty', 'rerun:@rerun.txt']

then you have to run protractor with the cucumber options specifying the filename:

protractor test/cucumber/conf/cucumber1Conf.js --cucumberOpts.rerun test/cucumber/@rerun.txt

More information about it can be found here: https://github.com/protractor-cucumber-framework/protractor-cucumber-framework/issues/89


问:
JsonSerialize / JsonDeserialize not working in Apache Tomcat (TomEE)
LATER EDIT 2019-05-31

If I write a sample main method which instantiates an Item and then call String s = new ObjectMapper().writeValueAsString(item);, then the custom serializer is called correctly and has effect.

The issue only appears when the whole app is deployed in an Apache TomEE server.

LATER EDIT: it's not an issue with placement of annotation (on field vs. on getter), I tried various combinations of this (annotation on getter, annotation on private field, annotation on public field, etc...)

The code:

```<code>import com.fasterxml.jackson....
// YES, all JSON-related stuff is from fasterxml

@JsonAutoDetect
public class Item {
    private Date lastModified;

    @JsonSerialize(using = CSer.class)
    public Date getLastModified() {
        return lastModified;
    }

    public class CSer extends JsonSerializer<Date> {
        public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            gen.writeString(dateFormat.format(value));
        }
    }
}

// some place else, in a REST service class
    ...
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getItems(... {
        ...
        return Response.ok(result.getData()).build();
        // result.getData() is an ArrayList of "Item" objects.
    }
</code>```

The ISSUES:

from what I know, the default JSON output format of the date should be the timestamp. In my case, it's not, instead it's yyyyMMddHHmmssZ

the custom serializer has no effect, I cannot change the output format of the date, and the serialize method never gets called.

The jackson files in my lib folder: jackson-annotations-2.8.0.jar, jackson-core-2.8.8.jar, jackson-databind-2.8.8.1.jar.

What am I doing wrong ?

Thank you.

答:
It might have something to do with your annotation being placed on the getter - you might move it to reflect something similar to

```<code>public class Item {

    @JsonSerialize(using = CSer.class)
    private Date lastModified;

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

or you have to configure Jackson to only use getters for serialization.

Body:
LATER EDIT 2019-05-31

If I write a sample main method which instantiates an Item and then call String s = new ObjectMapper().writeValueAsString(item);, then the custom serializer is called correctly and has effect.

The issue only appears when the whole app is deployed in an Apache TomEE server.

LATER EDIT: it's not an issue with placement of annotation (on field vs. on getter), I tried various combinations of this (annotation on getter, annotation on private field, annotation on public field, etc...)

The code:

import com.fasterxml.jackson....
// YES, all JSON-related stuff is from fasterxml

@JsonAutoDetect
public class Item {
    private Date lastModified;

    @JsonSerialize(using = CSer.class)
    public Date getLastModified() {
        return lastModified;
    }

    public class CSer extends JsonSerializer<Date> {
        public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            gen.writeString(dateFormat.format(value));
        }
    }
}

// some place else, in a REST service class
    ...
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getItems(... {
        ...
        return Response.ok(result.getData()).build();
        // result.getData() is an ArrayList of "Item" objects.
    }

The ISSUES:

from what I know, the default JSON output format of the date should be the timestamp. In my case, it's not, instead it's yyyyMMddHHmmssZ

the custom serializer has no effect, I cannot change the output format of the date, and the serialize method never gets called.

The jackson files in my lib folder: jackson-annotations-2.8.0.jar, jackson-core-2.8.8.jar, jackson-databind-2.8.8.1.jar.

What am I doing wrong ?

Thank you.

Body:
It might have something to do with your annotation being placed on the getter - you might move it to reflect something similar to

public class Item {

    @JsonSerialize(using = CSer.class)
    private Date lastModified;

   // ...
}

or you have to configure Jackson to only use getters for serialization.


问:
ionic cordova run android adb command failed with exit code 137
i am new to ionic and i start basic tabs project using ionic cli. Everything is working fine, except when i tried "ionic cordova run android" command with redmi note 4 giving following error.

Error: Failed to execute shell command "input,keyevent,82"" on device: Error: adb: Command failed with exit code 137

it is working fine on redmi note 3, follow is log from terminal, Any help would be appreciated

```<code>[INFO] Running app-scripts build: --platform android --target cordova

[23:22:39]  build dev started ...
[23:22:39]  clean started ...
[23:22:39]  clean finished in 6 ms
[23:22:39]  copy started ...
[23:22:39]  deeplinks started ...
[23:22:39]  deeplinks finished in 64 ms
[23:22:39]  transpile started ...
[23:22:45]  transpile finished in 5.99 s
[23:22:45]  preprocess started ...
[23:22:45]  copy finished in 6.38 s
[23:22:46]  preprocess finished in 229 ms
[23:22:46]  webpack started ...
[23:23:08]  webpack finished in 22.92 s
[23:23:08]  sass started ...
[23:23:12]  sass finished in 3.52 s
[23:23:12]  postprocess started ...
[23:23:12]  postprocess finished in 11 ms
[23:23:12]  lint started ...
[23:23:12]  build dev finished in 32.98 s
> cordova run android --device
ANDROID_HOME=/home/rogers/android-sdk
JAVA_HOME=/usr/lib/jvm/java-8-oracle
Subproject Path: CordovaLib
[23:23:18]  lint finished in 5.77 s
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.

        at build_rbfqc9qtl315khhol1quvz1g.run(/home/rogers/workspace/practice/myApp/platforms/android/build.gradle:141)

The JavaCompile.setDependencyCacheDir() method has been deprecated and is scheduled to be removed in Gradle 4.0.

Incremental java compilation is an incubating feature.

The TaskInputs.source(Object) method has been deprecated and is scheduled to be removed in Gradle 4.0. Please use TaskInputs.file(Object).skipWhenEmpty() instead.

:preBuild UP-TO-DATE
:preDebugBuild
 UP-TO-DATE
:checkDebugManifest
:CordovaLib:preBuild UP-TO-DATE
:CordovaLib:preDebugBuild UP-TO-DATE
:CordovaLib:checkDebugManifest
:CordovaLib:prepareDebugDependencies

:CordovaLib:compileDebugAidl UP-TO-DATE
:CordovaLib:compileDebugNdk UP-TO-DATE
:CordovaLib:compileLint UP-TO-DATE
:CordovaLib:copyDebugLint UP-TO-DATE
:CordovaLib:mergeDebugShaders UP-TO-DATE
:CordovaLib:compileDebugShaders

UP-TO-DATE

:CordovaLib:generateDebugAssets

UP-TO-DATE

:CordovaLib:mergeDebugAssets
 UP-TO-DATE
:CordovaLib:mergeDebugProguardFiles
 UP-TO-DATE
:CordovaLib:packageDebugRenderscript
 UP-TO-DATE
:CordovaLib:compileDebugRenderscript

UP-TO-DATE

:CordovaLib:generateDebugResValues

UP-TO-DATE

:CordovaLib:generateDebugResources UP-TO-DATE
:CordovaLib:packageDebugResources

UP-TO-DATE

:CordovaLib:processDebugManifest
 UP-TO-DATE
:CordovaLib:generateDebugBuildConfig

UP-TO-DATE
:CordovaLib:processDebugResources UP-TO-DATE
:CordovaLib:generateDebugSources UP-TO-DATE
:CordovaLib:incrementalDebugJavaCompilationSafeguard

UP-TO-DATE

:CordovaLib:compileDebugJavaWithJavac
 UP-TO-DATE
:CordovaLib:processDebugJavaRes UP-TO-DATE
:CordovaLib:transformResourcesWithMergeJavaResForDebug UP-TO-DATE
:CordovaLib:transformClassesAndResourcesWithSyncLibJarsForDebug

UP-TO-DATE

:CordovaLib:mergeDebugJniLibFolders

UP-TO-DATE

:CordovaLib:transformNative_libsWithMergeJniLibsForDebug UP-TO-DATE
:CordovaLib:transformNative_libsWithSyncJniLibsForDebug UP-TO-DATE
:CordovaLib:bundleDebug

UP-TO-DATE

:prepareOrgApacheCordovaCordovaLib630DebugLibrary

UP-TO-DATE

:prepareDebugDependencies

:compileDebugAidl

UP-TO-DATE

:compileDebugRenderscript

UP-TO-DATE
:generateDebugBuildConfig
 UP-TO-DATE
:generateDebugResValues
 UP-TO-DATE
:generateDebugResources UP-TO-DATE
:mergeDebugResources

UP-TO-DATE

:processDebugManifest

UP-TO-DATE

:processDebugResources

UP-TO-DATE

:generateDebugSources
 UP-TO-DATE

:incrementalDebugJavaCompilationSafeguard UP-TO-DATE
:compileDebugJavaWithJavac

UP-TO-DATE
:compileDebugNdk

UP-TO-DATE

:compileDebugSources UP-TO-DATE
:mergeDebugShaders UP-TO-DATE
:compileDebugShaders UP-TO-DATE
:generateDebugAssets

UP-TO-DATE

:mergeDebugAssets
 UP-TO-DATE
:transformClassesWithDexForDebug
 UP-TO-DATE
:mergeDebugJniLibFolders
 UP-TO-DATE
:transformNative_libsWithMergeJniLibsForDebug UP-TO-DATE
:processDebugJavaRes
 UP-TO-DATE
:transformResourcesWithMergeJavaResForDebug
 UP-TO-DATE
:validateSigningDebug
:packageDebug
 UP-TO-DATE
:assembleDebug
 UP-TO-DATE
:cdvBuildDebug UP-TO-DATE

BUILD SUCCESSFUL

Total time: 3.045 secs
Built the following apk(s):
    /home/rogers/workspace/practice/myApp/platforms/android/build/outputs/apk/android-debug.apk

ANDROID_HOME=/home/rogers/android-sdk
JAVA_HOME=/usr/lib/jvm/java-8-oracle
Skipping build...

Built the following apk(s):
    /home/rogers/workspace/practice/myApp/platforms/android/build/outputs/apk/android-debug.apk

Using apk: /home/rogers/workspace/practice/myApp/platforms/android/build/outputs/apk/android-debug.apk

Package name: io.ionic.starter

Error: Failed to execute shell command "input,keyevent,82"" on device: Error: adb: Command failed with exit code 137

[ERROR] An error occurred while running cordova run android --device (exit code 1).
</code>```

答:
Turn On these both as shown in the Screenshot.
  For MI phones dont't forget to enable USB debugging (Security settings)

Body:
i am new to ionic and i start basic tabs project using ionic cli. Everything is working fine, except when i tried "ionic cordova run android" command with redmi note 4 giving following error.

Error: Failed to execute shell command "input,keyevent,82"" on device: Error: adb: Command failed with exit code 137

it is working fine on redmi note 3, follow is log from terminal, Any help would be appreciated

[INFO] Running app-scripts build: --platform android --target cordova

[23:22:39]  build dev started ...
[23:22:39]  clean started ...
[23:22:39]  clean finished in 6 ms
[23:22:39]  copy started ...
[23:22:39]  deeplinks started ...
[23:22:39]  deeplinks finished in 64 ms
[23:22:39]  transpile started ...
[23:22:45]  transpile finished in 5.99 s
[23:22:45]  preprocess started ...
[23:22:45]  copy finished in 6.38 s
[23:22:46]  preprocess finished in 229 ms
[23:22:46]  webpack started ...
[23:23:08]  webpack finished in 22.92 s
[23:23:08]  sass started ...
[23:23:12]  sass finished in 3.52 s
[23:23:12]  postprocess started ...
[23:23:12]  postprocess finished in 11 ms
[23:23:12]  lint started ...
[23:23:12]  build dev finished in 32.98 s
> cordova run android --device
ANDROID_HOME=/home/rogers/android-sdk
JAVA_HOME=/usr/lib/jvm/java-8-oracle
Subproject Path: CordovaLib
[23:23:18]  lint finished in 5.77 s
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.

        at build_rbfqc9qtl315khhol1quvz1g.run(/home/rogers/workspace/practice/myApp/platforms/android/build.gradle:141)

The JavaCompile.setDependencyCacheDir() method has been deprecated and is scheduled to be removed in Gradle 4.0.

Incremental java compilation is an incubating feature.

The TaskInputs.source(Object) method has been deprecated and is scheduled to be removed in Gradle 4.0. Please use TaskInputs.file(Object).skipWhenEmpty() instead.

:preBuild UP-TO-DATE
:preDebugBuild
 UP-TO-DATE
:checkDebugManifest
:CordovaLib:preBuild UP-TO-DATE
:CordovaLib:preDebugBuild UP-TO-DATE
:CordovaLib:checkDebugManifest
:CordovaLib:prepareDebugDependencies

:CordovaLib:compileDebugAidl UP-TO-DATE
:CordovaLib:compileDebugNdk UP-TO-DATE
:CordovaLib:compileLint UP-TO-DATE
:CordovaLib:copyDebugLint UP-TO-DATE
:CordovaLib:mergeDebugShaders UP-TO-DATE
:CordovaLib:compileDebugShaders

UP-TO-DATE

:CordovaLib:generateDebugAssets

UP-TO-DATE

:CordovaLib:mergeDebugAssets
 UP-TO-DATE
:CordovaLib:mergeDebugProguardFiles
 UP-TO-DATE
:CordovaLib:packageDebugRenderscript
 UP-TO-DATE
:CordovaLib:compileDebugRenderscript

UP-TO-DATE

:CordovaLib:generateDebugResValues

UP-TO-DATE

:CordovaLib:generateDebugResources UP-TO-DATE
:CordovaLib:packageDebugResources

UP-TO-DATE

:CordovaLib:processDebugManifest
 UP-TO-DATE
:CordovaLib:generateDebugBuildConfig

UP-TO-DATE
:CordovaLib:processDebugResources UP-TO-DATE
:CordovaLib:generateDebugSources UP-TO-DATE
:CordovaLib:incrementalDebugJavaCompilationSafeguard

UP-TO-DATE

:CordovaLib:compileDebugJavaWithJavac
 UP-TO-DATE
:CordovaLib:processDebugJavaRes UP-TO-DATE
:CordovaLib:transformResourcesWithMergeJavaResForDebug UP-TO-DATE
:CordovaLib:transformClassesAndResourcesWithSyncLibJarsForDebug

UP-TO-DATE

:CordovaLib:mergeDebugJniLibFolders

UP-TO-DATE

:CordovaLib:transformNative_libsWithMergeJniLibsForDebug UP-TO-DATE
:CordovaLib:transformNative_libsWithSyncJniLibsForDebug UP-TO-DATE
:CordovaLib:bundleDebug

UP-TO-DATE

:prepareOrgApacheCordovaCordovaLib630DebugLibrary

UP-TO-DATE

:prepareDebugDependencies

:compileDebugAidl

UP-TO-DATE

:compileDebugRenderscript

UP-TO-DATE
:generateDebugBuildConfig
 UP-TO-DATE
:generateDebugResValues
 UP-TO-DATE
:generateDebugResources UP-TO-DATE
:mergeDebugResources

UP-TO-DATE

:processDebugManifest

UP-TO-DATE

:processDebugResources

UP-TO-DATE

:generateDebugSources
 UP-TO-DATE

:incrementalDebugJavaCompilationSafeguard UP-TO-DATE
:compileDebugJavaWithJavac

UP-TO-DATE
:compileDebugNdk

UP-TO-DATE

:compileDebugSources UP-TO-DATE
:mergeDebugShaders UP-TO-DATE
:compileDebugShaders UP-TO-DATE
:generateDebugAssets

UP-TO-DATE

:mergeDebugAssets
 UP-TO-DATE
:transformClassesWithDexForDebug
 UP-TO-DATE
:mergeDebugJniLibFolders
 UP-TO-DATE
:transformNative_libsWithMergeJniLibsForDebug UP-TO-DATE
:processDebugJavaRes
 UP-TO-DATE
:transformResourcesWithMergeJavaResForDebug
 UP-TO-DATE
:validateSigningDebug
:packageDebug
 UP-TO-DATE
:assembleDebug
 UP-TO-DATE
:cdvBuildDebug UP-TO-DATE

BUILD SUCCESSFUL

Total time: 3.045 secs
Built the following apk(s):
    /home/rogers/workspace/practice/myApp/platforms/android/build/outputs/apk/android-debug.apk

ANDROID_HOME=/home/rogers/android-sdk
JAVA_HOME=/usr/lib/jvm/java-8-oracle
Skipping build...

Built the following apk(s):
    /home/rogers/workspace/practice/myApp/platforms/android/build/outputs/apk/android-debug.apk

Using apk: /home/rogers/workspace/practice/myApp/platforms/android/build/outputs/apk/android-debug.apk

Package name: io.ionic.starter

Error: Failed to execute shell command "input,keyevent,82"" on device: Error: adb: Command failed with exit code 137

[ERROR] An error occurred while running cordova run android --device (exit code 1).


问:
Angular 7 : How to fix value overwriting during dynamic field addition?
I am working on an Angular application, wherein I have to do some configuration setup using 4 fields:

Department Name (drop down)

Service Name (drop down)

Status (text field)

Level (text field).

I want to add multiple set of these fields and create a JSON structure.

'Department Name' and 'Service Name' values are fetched using API calls.

'Service Name' options is populated based on 'Department Name' selected.

Though I am able to add the fields dynamically, but when I select nth Department Name, corresponding Service Name overwrites all (n-1) 'Service Name' fields.

Here is my component.html file:

//mapFormGroup returns FormArray for given set of fields

        Department Name
        // getServices fetches all services for selected department
        <select class="form-control" formControlName="deptId" type="text" (change)="getServices($event.target.value)">
            // deptList contains list of all departments
            <option *ngFor="let dept of deptList" [value]="dept.id">{{dept.name}}</option>
        </select>
        Service Name
        <select class="form-control" formControlName="serviceName" type="text">
            // serviceList contains list of all services for given department
            <option *ngFor="let service of serviceList" [value]="service.wfName">{{service.description}}</option>
        </select>

```

I expect correct mapping of Department & Service Name fields. But the latest one is overwriting previous entries.

答:
I was able to resolve this issue by making below change:

In my component.html:

    //mapFormGroup returns FormArray for given set of fields

    Department Name
    // getServices fetches all services for selected department
    <select class="form-control" formControlName="deptId" type="text" (change)="getServices($event.target.value,**i** )">
    // deptList contains list of all departments
    <option *ngFor="let dept of deptList" [value]="dept.id">{{dept.name}}</option>
    </select>
    Service Name
    <select class="form-control" formControlName="serviceName" type="text">
    // serviceList contains list of all services for given department
    <option *ngFor="let service of **fnServiceList(i)**" [value]="service.wfName">{{service.description}}</option>
    </select>

```

<hr>

<h2>In my <code>component.ts</code>:</h2>

```// New function added to return array element of current index
**fnServiceList(row){
    return this.serviceList[row];
}**

// Added row as input to assign the output to current index of array
getServices = function (dept, **row**) {
    // Fetch the services for given department in "services" variable
    this.serviceList**[row]** = services;
    // Instead of: "this.serviceList = services;"
}
```

Body:
I am working on an Angular application, wherein I have to do some configuration setup using 4 fields:

Department Name (drop down)

Service Name (drop down)

Status (text field)

Level (text field).

I want to add multiple set of these fields and create a JSON structure.

'Department Name' and 'Service Name' values are fetched using API calls.

'Service Name' options is populated based on 'Department Name' selected.

Though I am able to add the fields dynamically, but when I select nth Department Name, corresponding Service Name overwrites all (n-1) 'Service Name' fields.

Here is my component.html file:

//mapFormGroup returns FormArray for given set of fields

        Department Name
        // getServices fetches all services for selected department
        <select class="form-control" formControlName="deptId" type="text" (change)="getServices($event.target.value)">
            // deptList contains list of all departments
            <option *ngFor="let dept of deptList" [value]="dept.id">{{dept.name}}</option>
        </select>
        Service Name
        <select class="form-control" formControlName="serviceName" type="text">
            // serviceList contains list of all services for given department
            <option *ngFor="let service of serviceList" [value]="service.wfName">{{service.description}}</option>
        </select>

I expect correct mapping of Department & Service Name fields. But the latest one is overwriting previous entries.

Body:
I was able to resolve this issue by making below change:

In my component.html:

    //mapFormGroup returns FormArray for given set of fields
    <div *ngFor="let map of mapFormGroup.controls; let i = index;">
    <div [formGroupName]="i" class="row">
    <label>Department Name</label>
    // getServices fetches all services for selected department
    <select class="form-control" formControlName="deptId" type="text" (change)="getServices($event.target.value,**i** )">
    // deptList contains list of all departments
    <option *ngFor="let dept of deptList" [value]="dept.id">{{dept.name}}</option>
    </select>
    <label>Service Name</label>
    <select class="form-control" formControlName="serviceName" type="text">
    // serviceList contains list of all services for given department
    <option *ngFor="let service of **fnServiceList(i)**" [value]="service.wfName">{{service.description}}</option>
    </select>
    </div>
    </div>

In my component.ts:

// New function added to return array element of current index
**fnServiceList(row){
    return this.serviceList[row];
}**

// Added row as input to assign the output to current index of array
getServices = function (dept, **row**) {
    // Fetch the services for given department in "services" variable
    this.serviceList**[row]** = services;
    // Instead of: "this.serviceList = services;"
}


问:
React Native get correct status bar height on android
I'm trying to get the status bar height on Android devices using React Native's StatusBar.currentHeight https://facebook.github.io/react-native/docs/statusbar. On a pixel 2, that variable is 24 when in fact the status bar height is 19. Does anyone know of a way to get the correct status bar height on all devices with React Native?</p>

答:
```<code>import { Dimensions, StatusBar } from 'react-native'

const { height: SCREEN_HEIGHT, width: SCREEN_WIDTH } = Dimensions.get('window');
const STATUSBAR_HEIGHT = StatusBar.currentHeight;
</code>```


问:
Implementing the __add__ Method in a Counter Class how?
I want to implement the add method in the Counter class. Without importing Counter.

I kinda had an idea as seen in the code but it always gives me an Error.

```<code>class MyCounter:
    def __init__(self, s=None):
        self.q = {}
        for x in s:
            self.add(x)
    def __repr__(self):
        return str(self.q)
    def add (self,x):
        if x in self.q:
            self.q[x] = self.q[x] + 1
        else:
            self.q[x]=1
    def __add__(self, args):
        new_dict = self.q
        for x in new_dict:
            if x in args:
                u=args.get(x)
                new_dict[x] = new_dict[x]+ u
            else:
                new_dict[x]=1
</code>```

this is what i want

```<code>a= MyCounter("hahahahha")
a+ MyCounter("hahhahahah")

new_dict = {'h': 11, 'a': 8}
</code>```

error code if i try it

TypeError: argument of type 'MyCounter' is not iterable

答:
Your line:

```<code>if x in args:
</code>```

Is essentially:

```<code>if x in MyCounter("hahhahahah"):
</code>```

But MyCounter doesn't support the in operator.

You probably wanna check against the q instead:

```<code>if x in args.q:
</code>```

You could also implement the in operator for your class (using the __contains__ method), or subclass from dict directly (this is what collections.Counter does).

You also have the same issue here:

```<code>u=args.get(x)
</code>```

MyCounter doesn't have get() method, you wanna use this instead:

```<code>u=args.q.get(x)
</code>```

Body:
I want to implement the add method in the Counter class. Without importing Counter.

I kinda had an idea as seen in the code but it always gives me an Error.

class MyCounter:
    def __init__(self, s=None):
        self.q = {}
        for x in s:
            self.add(x)
    def __repr__(self):
        return str(self.q)
    def add (self,x):
        if x in self.q:
            self.q[x] = self.q[x] + 1
        else:
            self.q[x]=1
    def __add__(self, args):
        new_dict = self.q
        for x in new_dict:
            if x in args:
                u=args.get(x)
                new_dict[x] = new_dict[x]+ u
            else:
                new_dict[x]=1

this is what i want

a= MyCounter("hahahahha")
a+ MyCounter("hahhahahah")

new_dict = {'h': 11, 'a': 8}

error code if i try it

TypeError: argument of type 'MyCounter' is not iterable

Body:
Your line:

if x in args:

Is essentially:

if x in MyCounter("hahhahahah"):

But MyCounter doesn't support the in operator.

You probably wanna check against the q instead:

if x in args.q:

You could also implement the in operator for your class (using the __contains__ method), or subclass from dict directly (this is what collections.Counter does).

You also have the same issue here:

u=args.get(x)

MyCounter doesn't have get() method, you wanna use this instead:

u=args.q.get(x)


问:
Can Objective-C code call Swift class extensions?
I searched some posts, I think I cannot write an extension under Swift, and call it from Objective-C code, right?

@objc like attributes only support methods, class, protocols ?

答: Import  "#import "ProductModuleName-Swift.h" header in objective-c file and add @objc infront of your extentsion in swift file. It will working fine in swift 4.2 and swift 5


问:
custom checkbox react only one to check
I have this checkbox component!

```<code>const CheckBox = props =>{
    var [show,setshow] = useState(false);
    const option = props.name.replace(/\s/g, '');
    return(
       <div className="filter-option" onClick={e=>setshow(!show)} data={option}>
          <div className={show?"check-bock checked":"check-bock"} >
              <i className="fa fa-check"></i>
          </div>
          <label className="font-20">{props.name}</label>
       </div>
     )
}
</code>```

The checked class will show checkmark, but if i want to render multiple checkboxes the problem is all checkboxes are checked at once!

I want only one checked and others unchecked!

答:
The solution is to keep in state which checkbox is checked and store this state in parent from where all checkboxes are rendered</p>

```<code>const CheckBox = props =>{
    const option = props.name.replace(/\s/g, '');
    return(
       <div className="filter-option" onClick={e=>props.setshow(prev => props.name == prev? '': props.name)} data={option}>
          <div className={props.show?"check-bock checked":"check-bock"} >
              <i className="fa fa-check"></i>
          </div>
          <label className="font-20">{props.name}</label>
       </div>
     )
}

const Parent = () => {

    var [show,setshow] = useState('');
    return (
       <>
         <Checkbox name="first" show={"first" === show} setShow={setShow}/>
         <Checkbox name="second" show={"second" === show} setShow={setShow}/>
       </>
    )

}
</code>```

Title: custom checkbox react only one to check

Body:
I have this checkbox component!

const CheckBox = props =>{
    var [show,setshow] = useState(false);
    const option = props.name.replace(/\s/g, '');
    return(

setshow(!show)} data={option}>

          {props.name}

     )
}

The checked class will show checkmark, but if i want to render multiple checkboxes the problem is all checkboxes are checked at once!

I want only one checked and others unchecked!

Body:
The solution is to keep in state which checkbox is checked and store this state in parent from where all checkboxes are rendered

const CheckBox = props =>{
    const option = props.name.replace(/\s/g, '');
    return(
       <div className="filter-option" onClick={e=>props.setshow(prev => props.name == prev? '': props.name)} data={option}>
          <div className={props.show?"check-bock checked":"check-bock"} >
              <i className="fa fa-check"></i>
          </div>
          <label className="font-20">{props.name}</label>
       </div>
     )
}

const Parent = () => {

    var [show,setshow] = useState('');
    return (
       <>
         <Checkbox name="first" show={"first" === show} setShow={setShow}/>
         <Checkbox name="second" show={"second" === show} setShow={setShow}/>
       </>
    )

}


问:
Merge two array of objects and added a new Key & Value
I have 2 arrays based on the "Form_Name" key value to merge an array with added new key&value "isChecked".

Array One

```<code>arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true}
{id: 11, Form_Name: "form name Two", isChecked: true}];
</code>```

Array Two

```<code>arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}];
</code>```

Expected merged array

```<code>mergedArray = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}]
</code>```

I tried like below

```<code>const mergedArray = [];
for (let i = 0; i < arrayTwo.length; i++) {
  mergedArray.push({
   ...arrayTwo[i],
   ...(arrayOne.find((itmInner) => itmInner.Form_Name === arrayTwo[i].Form_Name))}
  );
}
console.log('merged array result', mergedArray);
</code>```

答:
let arrayOne = [{
  id: 11,
  Form_Name: "form name One",
  isChecked: true
}, {
  id: 11,
  Form_Name: "form name Two",
  isChecked: true
}];

let arrayTwo = [{
  Form_Name: "form name One",
  Form_AddDate: "2019-05-15T11:03:18.05"
}, {
  Form_Name: "form name Two",
  Form_AddDate: "2019-05-15T11:03:18.05"
}, {
  Form_Name: "form name Three",
  Form_AddDate: "2019-05-15T11:03:18.05"
}, {
  Form_Name: "form name Four",
  Form_AddDate: "2019-05-15T11:03:18.05"
}];

let arrayOneObj = arrayOne.reduce((result, item) => {
  result[item.Form_Name] = item.isChecked
  return result;
}, {})

const result = arrayTwo.map((item) => ({ ...item,
  isChecked: !!arrayOneObj[item.Form_Name]
}))

console.log(result);```

Body:
I have 2 arrays based on the "Form_Name" key value to merge an array with added new key&value "isChecked".

Array One

arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true}
{id: 11, Form_Name: "form name Two", isChecked: true}];

Array Two

arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}];

Expected merged array

mergedArray = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}]

I tried like below

const mergedArray = [];
for (let i = 0; i < arrayTwo.length; i++) {
  mergedArray.push({
   ...arrayTwo[i],
   ...(arrayOne.find((itmInner) => itmInner.Form_Name === arrayTwo[i].Form_Name))}
  );
}
console.log('merged array result', mergedArray);


问:
Display validation message with duplicate StudentId one by one
I want to check duplicate Id validation in sql server, that validation grid display
row number , validation message & duplicate ID from sql server

I am not able to understand that how can I do it ?

Help is really appreciate

Create Table

```<code>    CREATE TEMPORARY TABLE IF NOT EXISTS Tbl_Student
    (RowID INT PRIMARY KEY auto_increment, StudentID BIGINT);
</code>```

Insert Records

```<code>Insert into Tbl_Student(RowID,StudentID) values (1,101)
Insert into Tbl_Student(RowID,StudentID) values (2,102)
Insert into Tbl_Student(RowID,StudentID) values (3,101)
Insert into Tbl_Student(RowID,StudentID) values (4,102)
Insert into Tbl_Student(RowID,StudentID) values (5,103)
</code>```

Please let share if any solution over there

Thank you

答:
You could use a join on the suquery having count of strundet id > 1</p>

```<code>  select id,  student_id, concat('Stundent id' , student_id, ' is duplicated')
  from  my_table m
  inner join  (
    select student_id
    from my_table
    group by student_id
    having count(*) > 1
  ) t on t.student_id  = m.student_id
</code>```

Body:
I want to check duplicate Id validation in sql server, that validation grid display
row number , validation message & duplicate ID from sql server

I am not able to understand that how can I do it ?

Help is really appreciate

Create Table

    CREATE TEMPORARY TABLE IF NOT EXISTS Tbl_Student
    (RowID INT PRIMARY KEY auto_increment, StudentID BIGINT);

Insert Records

Insert into Tbl_Student(RowID,StudentID) values (1,101)
Insert into Tbl_Student(RowID,StudentID) values (2,102)
Insert into Tbl_Student(RowID,StudentID) values (3,101)
Insert into Tbl_Student(RowID,StudentID) values (4,102)
Insert into Tbl_Student(RowID,StudentID) values (5,103)

Please let share if any solution over there

Thank you

Body:
You could use a join on the suquery having count of strundet id > 1

  select id,  student_id, concat('Stundent id' , student_id, ' is duplicated')
  from  my_table m
  inner join  (
    select student_id
    from my_table
    group by student_id
    having count(*) > 1
  ) t on t.student_id  = m.student_id


问:
create new instances or use public static methods?
Which one is the better way for a asp.net application in which i need to call methods from multiple pages? Or is there a third even better possibility?</p>

答: Either works just fine. Another alternative is to build your own base class for pages, and put the common functionality there. With that approach, you can make the methods virtual and allow concrete classes to override functionality where appropriate. </p>


问:
How can I play UNNotificationSound.default() by a player in my app?
I have a list of ringtones in iOS app, also, one of the options should be the system default ringtone, that the user can select and play.
How can I obtain the ringtone that user selected and how can I play this ringtone in-app with AVAudioPlayer, or at least get the name of the file that was selected by the user?

答:
Add import AudioToolbox, then AudioServicesPlaySystemSound(SystemSoundID(1000)) to play a system sound.

See Audio Services for a list of sounds. Hopefully, one of those sounds will be the as UNNotificationSound.default.

Edit

1002 seems to be the correct sound ID for the default notifcation.


问:
Load partial view in a div MVC
I have a button on my MVC view on click of it, it should add a partial view in a 'div', by calling an action which takes an object as a parameter

I tried out some thing like this:

```<code>$('#buttonId').onclick(function(){

$('#divid').load(@Html.Action("ActionName","ControllerName",new{parameterName = objectToPass}))

});
</code>```

but it loads the actionresult/partial view on page load itself not a click of button

Any Idea?

答:
On ajax call success function append result

ajax call=>

```<code>url: 'controllername/methodname'
 success: function (partialviewresult)
{
          $('#div').append(partialviewresult);
}

  // inside controller
 public ActionResult methodname()
{
    return PartialView("~/a/a.cshtml");
}
</code>```

and controller must return partialview as result

Title: Load partial view in a div MVC

Body:
I have a button on my MVC view on click of it, it should add a partial view in a 'div', by calling an action which takes an object as a parameter

I tried out some thing like this:

$('#buttonId').onclick(function(){

$('#divid').load(@Html.Action("ActionName","ControllerName",new{parameterName = objectToPass}))

});

but it loads the actionresult/partial view on page load itself not a click of button

Any Idea?

Body:
On ajax call success function append result

ajax call=>

url: 'controllername/methodname'
 success: function (partialviewresult)
{
          $('#div').append(partialviewresult);
}

  // inside controller
 public ActionResult methodname()
{
    return PartialView("~/a/a.cshtml");
}

and controller must return partialview as result


问:
UnityWebRequest POST not sending to ASP.NET API
I'm working on POSTing data by using UnityWebRequests. Unfortunately this isn't working, although I do not receive any errors.

I've made an API with ASP.NET Core which is working (tested with Postman). I tried multiple "solutions": sending bytes, JSON in string, request headers, WWW, but none of them seem to work.

POST part in API controller

```<code>    // POST: api/Todo
    [HttpPost]
    public async Task<ActionResult<LeaderboardItem>>
    PostLeaderboardItem(LeaderboardItem item)
    {
        _context.LeaderboardItems.Add(item);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetLeaderboardItem), new { id = item.Id }, item);
    }
</code>```

UnityWebRequest

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using UnityEngine.Networking;

[Serializable]
public class MiniGame
{
public int id;
public int teamId;
public int score;
}

public class JSON_Test : MonoBehaviour
{
void Start()
{
    MiniGame miniGame = new MiniGame();
    miniGame.id = 9999;
    miniGame.teamId = 10;
    miniGame.score = 10;

    StartCoroutine(PostRequest(miniGame));
}

public IEnumerator PostRequest(MiniGame miniGame)
{
    string jsonData = JsonUtility.ToJson(miniGame);
    Debug.Log(jsonData);

    using (UnityWebRequest request =
UnityWebRequest.Get("https://localhost:44326/api/leaderboard"))
    {
        request.method = UnityWebRequest.kHttpVerbGET;
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Accept", "application/json");
        yield return request.SendWebRequest();
        //if (!request.isNetworkError && request.responseCode == (int)responseCodes.OK)
        //{
        //    Debug.Log("Data succesfully sent to the server");
        //}
        //else
        //{
        //    Debug.Log("Error sending data to the server");
        //}
    }
   }
 }
</code>```

Any help?

答: I have some simular problem with get request from asp core web api. Solution for me was use http instead https for web api</p>

Body:
I'm working on POSTing data by using UnityWebRequests. Unfortunately this isn't working, although I do not receive any errors.

I've made an API with ASP.NET Core which is working (tested with Postman). I tried multiple "solutions": sending bytes, JSON in string, request headers, WWW, but none of them seem to work.

POST part in API controller

    // POST: api/Todo
    [HttpPost]
    public async Task<ActionResult<LeaderboardItem>>
    PostLeaderboardItem(LeaderboardItem item)
    {
        _context.LeaderboardItems.Add(item);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetLeaderboardItem), new { id = item.Id }, item);
    }

UnityWebRequest

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using UnityEngine.Networking;

[Serializable]
public class MiniGame
{
public int id;
public int teamId;
public int score;
}

public class JSON_Test : MonoBehaviour
{
void Start()
{
    MiniGame miniGame = new MiniGame();
    miniGame.id = 9999;
    miniGame.teamId = 10;
    miniGame.score = 10;

    StartCoroutine(PostRequest(miniGame));
}

public IEnumerator PostRequest(MiniGame miniGame)
{
    string jsonData = JsonUtility.ToJson(miniGame);
    Debug.Log(jsonData);

    using (UnityWebRequest request =
UnityWebRequest.Get("https://localhost:44326/api/leaderboard"))
    {
        request.method = UnityWebRequest.kHttpVerbGET;
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Accept", "application/json");
        yield return request.SendWebRequest();
        //if (!request.isNetworkError && request.responseCode == (int)responseCodes.OK)
        //{
        //    Debug.Log("Data succesfully sent to the server");
        //}
        //else
        //{
        //    Debug.Log("Error sending data to the server");
        //}
    }
   }
 }

Any help?


问:
How to tell sphinx to ignore the 'include' directive when building documentation?
I run sphinx-build command from the command line to build both latex and html documentation, since they have the same source .rst files:

$ sphinx-build -b html <source> <output>

$ sphinx-build -b latex <source> <output>

However, for the latex output I want to ignore all the "include" directives.

This can be done by adding a docutils.conf file in the same directory as the conf.py of sphinx with the following content:

```<code>[parsers]
[restructuredtext parser]
file-insertion-enabled:false
</code>```

This is a partial solution though, since I have to change the content (false or true) of the docutils.conf file every time I run the sphinx-build for both html and latex outputs.

It is possible to tell sphinx to ignore the 'include' directive without relying on docutils.conf file, specifying that I want no-file-insertion when running the sphinx-build command?

答:
After some time searching, I found a sphinx directive that include its content only when a expression is true (the only directive):

```<code>.. only:: html

    .. include:: <path/to/file.rst>
</code>```

This was a simple solution that works fine for me; the contents of file.rst are only included when making html documentation and not when making latex files.

Thanks!

Body:
I run sphinx-build command from the command line to build both latex and html documentation, since they have the same source .rst files:

$ sphinx-build -b html <source> <output>

$ sphinx-build -b latex <source> <output>

However, for the latex output I want to ignore all the "include" directives.

This can be done by adding a docutils.conf file in the same directory as the conf.py of sphinx with the following content:

[parsers]
[restructuredtext parser]
file-insertion-enabled:false

This is a partial solution though, since I have to change the content (false or true) of the docutils.conf file every time I run the sphinx-build for both html and latex outputs.

It is possible to tell sphinx to ignore the 'include' directive without relying on docutils.conf file, specifying that I want no-file-insertion when running the sphinx-build command?

Body:
After some time searching, I found a sphinx directive that include its content only when a expression is true (the only directive):

.. only:: html

    .. include:: <path/to/file.rst>

This was a simple solution that works fine for me; the contents of file.rst are only included when making html documentation and not when making latex files.

Thanks!


问:
How to set variables in local sass files that override settings in general sass when using webpack loader
I have a site that has a three underlying applications that uses many of the same components, but styles them slightly differently in each application.

So I have made a site styles that is imported using the sass loader in webpack

my path

```<code>const csspath = path.resolve(__dirname,  './src/styles/main.scss');
</code>```

my loaders

```<code>{
   loader: 'sass-loader',
   options: {
    sourceMap: true
   }
},
{
    loader: 'sass-resources-loader',
    options: {
      resources: [csspath]
    }
}
</code>```

inside of one of my sass files I have the following

```<code>$navBackground: $black;
$navForeground: $white;
$itemSize: 60px;

.NavHeader {
    position: sticky;
    top: 0;
    z-index: 1071;
    background-color: $navBackground;
    color: $navForeground;
    width: 100vw;
    height: $itemSize;
}
</code>```

I also have some css I import inside of my components, like so

```<code>import './Header.style.scss';
</code>```

If I put these variables into the header style

```<code>$navBackground: $black;
$navForeground: $white;
</code>```

it compiles fine, but if I remove those variables from the global sass files and keep the variables just in my local Header.style.scss I get the error message

Module build failed (from ./node_modules/sass-loader/lib/loader.js):

```<code>background-color: $navBackground;
                 ^
  Undefined variable: "$navBackground".
  in /Users/bryanrasmussen/projects/dc_frontend/src/styles/components/_header.scss (line 8, column 23)
</code>```

I suppose the obvious problem is that the local sass files in the components are loaded with the sass-loaders loader, and the resources that are global and not tied to a component are loaded by sass-resources-loader, so these loaders don't know anything about each other. So the question is if they can be merged in some way, or anyway that the sass-resources-loader can know about the sass files loaded with the sass-loader?

答:
I found a solution that I do not like particularly much as being somewhat inelegant, but I will put it here anyway in case someone has the same problem.

In the components that need to reuse the styles, for example the header I do

```<code>import './Header.style.scss';
</code>```

in the component, and in the sass I  set the variables that are needed and import the reusable sass

$

```<code>navBackground: $black;
$navForeground: $white;
$userColor: $white;
$navItemColor: $white;
$currentSelectedEmphasizeColor: $green;
$hamburgerCloserColor: $white;
$burgerMenuBackground: $black;
$navMenuLinkColor: $white;

@import '../../../styles/components/header';
</code>```

I remover the styles/components/header styles from the main loaded resource, so I still have the sass resource loader which gives the cross apps styles but anything that needs to be set in each individual app will have to load the reused component styles and set the variables locally so that no errors happen in the main.scss at compilation time.

Body:
I have a site that has a three underlying applications that uses many of the same components, but styles them slightly differently in each application.

So I have made a site styles that is imported using the sass loader in webpack

my path

const csspath = path.resolve(__dirname,  './src/styles/main.scss');

my loaders

{
   loader: 'sass-loader',
   options: {
    sourceMap: true
   }
},
{
    loader: 'sass-resources-loader',
    options: {
      resources: [csspath]
    }
}

inside of one of my sass files I have the following

$navBackground: $black;
$navForeground: $white;
$itemSize: 60px;

.NavHeader {
    position: sticky;
    top: 0;
    z-index: 1071;
    background-color: $navBackground;
    color: $navForeground;
    width: 100vw;
    height: $itemSize;
}

I also have some css I import inside of my components, like so

import './Header.style.scss';

If I put these variables into the header style

$navBackground: $black;
$navForeground: $white;

it compiles fine, but if I remove those variables from the global sass files and keep the variables just in my local Header.style.scss I get the error message

Module build failed (from ./node_modules/sass-loader/lib/loader.js):

background-color: $navBackground;
                 ^
  Undefined variable: "$navBackground".
  in /Users/bryanrasmussen/projects/dc_frontend/src/styles/components/_header.scss (line 8, column 23)

I suppose the obvious problem is that the local sass files in the components are loaded with the sass-loaders loader, and the resources that are global and not tied to a component are loaded by sass-resources-loader, so these loaders don't know anything about each other. So the question is if they can be merged in some way, or anyway that the sass-resources-loader can know about the sass files loaded with the sass-loader?

Body:
I found a solution that I do not like particularly much as being somewhat inelegant, but I will put it here anyway in case someone has the same problem.

In the components that need to reuse the styles, for example the header I do

import './Header.style.scss';

in the component, and in the sass I  set the variables that are needed and import the reusable sass

$

navBackground: $black;
$navForeground: $white;
$userColor: $white;
$navItemColor: $white;
$currentSelectedEmphasizeColor: $green;
$hamburgerCloserColor: $white;
$burgerMenuBackground: $black;
$navMenuLinkColor: $white;

@import '../../../styles/components/header';

I remover the styles/components/header styles from the main loaded resource, so I still have the sass resource loader which gives the cross apps styles but anything that needs to be set in each individual app will have to load the reused component styles and set the variables locally so that no errors happen in the main.scss at compilation time.


问:
display error if mail function not working
I'm building an Email verification script and i'm using ajax so whenever the user fill in a false or an invalid email, an error bar with the error name will be displayed, And when the email is true and belongs to an active account, an email will be sent to the user with instructions and the error bar says email sent.
The problem is even the mail function isn't working, the error bar keeps saying email sent.
So i wan't some lines to detect if the email wasn't sent to show "email was not sent" in the error bar.

This is my php file :

```<code>    <?php

include '../../app/init.php';

        /* Clean email */
    $recover_email = $_POST['recover_email'];

       /* check if email is valid */
    if(!filter_var($recover_email, FILTER_VALIDATE_EMAIL)) {

        /* email not valid */
        echo 3;

        /* Check if email exist */
    } else if(Database::exists('user_id', 'users', ['email' => $recover_email])) {

        /* Define some variables */
        $user_id            = Database::simple_get('user_id', 'users', ['email' => $recover_email]);
        $lost_password_code = md5($recover_email + microtime());

        /* Update the current activation email */
        $database->query("UPDATE `users` SET `lost_password_code` = '{$lost_password_code}' WHERE `user_id` = {$user_id}");

        /* Send the email */
        sendmail($recover_email,  $settings->contact_email, $language->lost_password->email->title, sprintf($language->lost_password->email->content, $settings->url, $recover_email, $lost_password_code));

        /* email exist */
        echo true;

    } else if(!Database::exists('user_id', 'users', ['email' => $email])) {

        /* email not exist */
        echo false;
    }

?>
</code>```

This is my mail functions :

```<code>function send_mail($to, $from, $title, $message) {

    $headers = "From: " . strip_tags($from) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    mail($to, $title, $message, $headers);
}

function sendmail($to, $from, $title, $message) {
    global $settings;

    if(!empty($settings->smtp_host) && !empty($settings->smtp_port) && !empty($settings->smtp_user) && !empty($settings->smtp_pass)) {

        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        $mail->SMTPSecure = 'tls';
        $mail->SMTPAuth = true;
        $mail->isHTML(true);

        $mail->Host = gethostbyname('tls://'.$settings->smtp_host);
        $mail->Port = $settings->smtp_port;
        $mail->Username = $settings->smtp_user;
        $mail->Password = $settings->smtp_pass;

        $mail->setFrom($from, $settings->title);
        $mail->addReplyTo($from, $settings->title);
        $mail->addAddress($to);
        $mail->Subject = $title;
        $mail->Body = $message;

        if (!$mail->send()) {
            send_mail($to, $from, $title, $message);
        }

    } else {
        send_mail($to, $from, $title, $message);
    }

}
</code>```

I only need some lines on the php file to return it as a response for the ajax file

答:
mail()Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.  So you need to run an if statement to check if the mail was accepted for delivery.

```<code><?php

function send_mail($to, $from, $title, $message)
{

    $headers = "From: " . strip_tags($from) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    if (mail($to, $title, $message, $headers)) {

        return true;
    } else {

        return false;
    }
}

function sendmail($to, $from, $title, $message)
{
    global $settings;

    if (!empty($settings->smtp_host) && !empty($settings->smtp_port) && !empty($settings->smtp_user) && !empty($settings->smtp_pass)) {

        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug  = 0;
        $mail->SMTPSecure = 'tls';
        $mail->SMTPAuth   = true;
        $mail->isHTML(true);

        $mail->Host     = gethostbyname('tls://' . $settings->smtp_host);
        $mail->Port     = $settings->smtp_port;
        $mail->Username = $settings->smtp_user;
        $mail->Password = $settings->smtp_pass;

        $mail->setFrom($from, $settings->title);
        $mail->addReplyTo($from, $settings->title);
        $mail->addAddress($to);
        $mail->Subject = $title;
        $mail->Body    = $message;

        if (!$mail->send()) {
            if (!send_mail($to, $from, $title, $message)) {

                echo "Error sending email, please try again later";
            }
        }

    } else {
        if (!send_mail($to, $from, $title, $message)) {

            echo "Error sending email, please try again later";
        }
    }

}
</code>```

Body:
I'm building an Email verification script and i'm using ajax so whenever the user fill in a false or an invalid email, an error bar with the error name will be displayed, And when the email is true and belongs to an active account, an email will be sent to the user with instructions and the error bar says email sent.
The problem is even the mail function isn't working, the error bar keeps saying email sent.
So i wan't some lines to detect if the email wasn't sent to show "email was not sent" in the error bar.

This is my php file :

    <?php

include '../../app/init.php';

        /* Clean email */
    $recover_email = $_POST['recover_email'];

       /* check if email is valid */
    if(!filter_var($recover_email, FILTER_VALIDATE_EMAIL)) {

        /* email not valid */
        echo 3;

        /* Check if email exist */
    } else if(Database::exists('user_id', 'users', ['email' => $recover_email])) {

        /* Define some variables */
        $user_id            = Database::simple_get('user_id', 'users', ['email' => $recover_email]);
        $lost_password_code = md5($recover_email + microtime());

        /* Update the current activation email */
        $database->query("UPDATE `users` SET `lost_password_code` = '{$lost_password_code}' WHERE `user_id` = {$user_id}");

        /* Send the email */
        sendmail($recover_email,  $settings->contact_email, $language->lost_password->email->title, sprintf($language->lost_password->email->content, $settings->url, $recover_email, $lost_password_code));

        /* email exist */
        echo true;

    } else if(!Database::exists('user_id', 'users', ['email' => $email])) {

        /* email not exist */
        echo false;
    }

?>

This is my mail functions :

function send_mail($to, $from, $title, $message) {

    $headers = "From: " . strip_tags($from) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    mail($to, $title, $message, $headers);
}

function sendmail($to, $from, $title, $message) {
    global $settings;

    if(!empty($settings->smtp_host) && !empty($settings->smtp_port) && !empty($settings->smtp_user) && !empty($settings->smtp_pass)) {

        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        $mail->SMTPSecure = 'tls';
        $mail->SMTPAuth = true;
        $mail->isHTML(true);

        $mail->Host = gethostbyname('tls://'.$settings->smtp_host);
        $mail->Port = $settings->smtp_port;
        $mail->Username = $settings->smtp_user;
        $mail->Password = $settings->smtp_pass;

        $mail->setFrom($from, $settings->title);
        $mail->addReplyTo($from, $settings->title);
        $mail->addAddress($to);
        $mail->Subject = $title;
        $mail->Body = $message;

        if (!$mail->send()) {
            send_mail($to, $from, $title, $message);
        }

    } else {
        send_mail($to, $from, $title, $message);
    }

}

I only need some lines on the php file to return it as a response for the ajax file

Body:
mail()Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.  So you need to run an if statement to check if the mail was accepted for delivery.

<?php

function send_mail($to, $from, $title, $message)
{

    $headers = "From: " . strip_tags($from) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    if (mail($to, $title, $message, $headers)) {

        return true;
    } else {

        return false;
    }
}

function sendmail($to, $from, $title, $message)
{
    global $settings;

    if (!empty($settings->smtp_host) && !empty($settings->smtp_port) && !empty($settings->smtp_user) && !empty($settings->smtp_pass)) {

        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug  = 0;
        $mail->SMTPSecure = 'tls';
        $mail->SMTPAuth   = true;
        $mail->isHTML(true);

        $mail->Host     = gethostbyname('tls://' . $settings->smtp_host);
        $mail->Port     = $settings->smtp_port;
        $mail->Username = $settings->smtp_user;
        $mail->Password = $settings->smtp_pass;

        $mail->setFrom($from, $settings->title);
        $mail->addReplyTo($from, $settings->title);
        $mail->addAddress($to);
        $mail->Subject = $title;
        $mail->Body    = $message;

        if (!$mail->send()) {
            if (!send_mail($to, $from, $title, $message)) {

                echo "Error sending email, please try again later";
            }
        }

    } else {
        if (!send_mail($to, $from, $title, $message)) {

            echo "Error sending email, please try again later";
        }
    }

}


问:
Find missing item in a list grouped
I have a list of objects dailySchedule with the properties Order, District, and other properties.

```<code>public class dailySchedule
{
        public int Order { get; set; }
        public string Title { get;  }
        public string District { get;  }
        ....
}
</code>```

the list is loaded with these values

Each district must have 6 orders,

var ordersValue = new List<int> {1, 2, 3, 4, 5, 6};

I want to find for each district, which order is missing.

The result must be
District 0  order {2,3,5,6}
District 12 order {5,6}

How can do that with linq c#?

答:
This is a case for Except():

you can achieve your desired result by "substracting two lists" like so:

```<code>var required = new List<int>() {1, 2, 3, 4, 5, 6};

var groupedByDistrict = orders.GroupBy(x => x.District);
foreach (var group in groupedByDistrict)
{
    var missing = required.Except(group.Select(x => x.Order).Distinct());

    // Do something with that informaton here
}
</code>```

This is mere non working pseudocode to get you on the right track
 actually it may work, but i haven't tested it.

Title: Find missing item in a list grouped

Body:
I have a list of objects dailySchedule with the properties Order, District, and other properties.

public class dailySchedule
{
        public int Order { get; set; }
        public string Title { get;  }
        public string District { get;  }
        ....
}

the list is loaded with these values

Each district must have 6 orders,

var ordersValue = new List<int> {1, 2, 3, 4, 5, 6};

I want to find for each district, which order is missing.

The result must be
District 0  order {2,3,5,6}
District 12 order {5,6}

How can do that with linq c#?

Body:
This is a case for Except():

you can achieve your desired result by "substracting two lists" like so:

var required = new List<int>() {1, 2, 3, 4, 5, 6};

var groupedByDistrict = orders.GroupBy(x => x.District);
foreach (var group in groupedByDistrict)
{
    var missing = required.Except(group.Select(x => x.Order).Distinct());

    // Do something with that informaton here
}

This is mere non working pseudocode to get you on the right track
 actually it may work, but i haven't tested it.