答:
It seems you are trying to sum-reduce the last axis of XYZ_to_sRGB_mat_D50 (axis=1) with the last one of XYZ_2 (axis=2). So, you can use np.tensordot like so -

```<code>np.tensordot(XYZ_2, XYZ_to_sRGB_mat_D50, axes=((2),(1)))
</code>```

Related post to understand tensordot.

For completeness, we can surely use np.matmul too after swappping last two axes of XYZ_2, like so -

```<code>np.matmul(XYZ_to_sRGB_mat_D50, XYZ_2.swapaxes(1,2)).swapaxes(1,2)
</code>```

This won't be as efficient as tensordot one.

Runtime test -

```<code>In [158]: XYZ_to_sRGB_mat_D50 = np.asarray([
     ...:     [3.1338561, -1.6168667, -0.4906146],
     ...:     [-0.9787684, 1.9161415, 0.0334540],
     ...:     [0.0719453, -0.2289914, 1.4052427],
     ...: ])
     ...:
     ...: XYZ_1 = np.asarray([0.25, 0.4, 0.1])
     ...: XYZ_2 = np.random.rand(100,100,3)

# @Julien's soln
In [159]: %timeit XYZ_2.dot(XYZ_to_sRGB_mat_D50.T)
1000 loops, best of 3: 450 µs per loop

In [160]: %timeit np.tensordot(XYZ_2, XYZ_to_sRGB_mat_D50, axes=((2),(1)))
10000 loops, best of 3: 73.1 µs per loop
</code>```

Generally speaking, when it comes to sum-reductions on tensors, tensordot is much more efficient. Since, the axis of sum-reduction is just one, we can make the tensor a 2D array by reshaping, use np.dot, get the result and reshape back to 3D.

Title: numpy - matrix multiple 3x3 and 100x100x3 arrays?

Body:
I have the following:

import numpy as np

XYZ_to_sRGB_mat_D50 = np.asarray([
    [3.1338561, -1.6168667, -0.4906146],
    [-0.9787684, 1.9161415, 0.0334540],
    [0.0719453, -0.2289914, 1.4052427],
])

XYZ_1 = np.asarray([0.25, 0.4, 0.1])
XYZ_2 = np.random.rand(100,100,3)

np.matmul(XYZ_to_sRGB_mat_D50, XYZ_1) # valid operation
np.matmul(XYZ_to_sRGB_mat_D50, XYZ_2) # makes no sense mathematically

How do I perform the same operation on XYZ_2 that I would on XYZ_2?  Do I somehow reshape the array first?

Body:
It seems you are trying to sum-reduce the last axis of XYZ_to_sRGB_mat_D50 (axis=1) with the last one of XYZ_2 (axis=2). So, you can use np.tensordot like so -

np.tensordot(XYZ_2, XYZ_to_sRGB_mat_D50, axes=((2),(1)))

Related post to understand tensordot.

For completeness, we can surely use np.matmul too after swappping last two axes of XYZ_2, like so -

np.matmul(XYZ_to_sRGB_mat_D50, XYZ_2.swapaxes(1,2)).swapaxes(1,2)

This won't be as efficient as tensordot one.

Runtime test -

In [158]: XYZ_to_sRGB_mat_D50 = np.asarray([
     ...:     [3.1338561, -1.6168667, -0.4906146],
     ...:     [-0.9787684, 1.9161415, 0.0334540],
     ...:     [0.0719453, -0.2289914, 1.4052427],
     ...: ])
     ...:
     ...: XYZ_1 = np.asarray([0.25, 0.4, 0.1])
     ...: XYZ_2 = np.random.rand(100,100,3)

# @Julien's soln
In [159]: %timeit XYZ_2.dot(XYZ_to_sRGB_mat_D50.T)
1000 loops, best of 3: 450 µs per loop

In [160]: %timeit np.tensordot(XYZ_2, XYZ_to_sRGB_mat_D50, axes=((2),(1)))
10000 loops, best of 3: 73.1 µs per loop

Generally speaking, when it comes to sum-reductions on tensors, tensordot is much more efficient. Since, the axis of sum-reduction is just one, we can make the tensor a 2D array by reshaping, use np.dot, get the result and reshape back to 3D.


来源: stackexchange

问:
Can I use a lambda function or std::function object in place of a function pointer?
I've got a library that I need to use that defines the following:

```<code>typedef void CallbackFunction(const int& i);
</code>```

and has a function to register your callback that looks like:

```<code>void registerCallback(CallbackFunction* pCallback);
</code>```

Because I'd like to capture the state of several variables to be used in the callback, I can't simply use a plain function. What I'd prefer to use is a lambda function, but the following doesn't compile:

```<code>auto fCallback = [](const int& i) {
    cout << i << endl;
};
registerCallback(fCallback);
</code>```

instead I get the error:

```<code>error C2664: 'registerCallback' : cannot convert parameter 1 from '`anonymous-namespace'::<lambda0>' to 'CallbackFunction (__cdecl *)'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
</code>```

I've been reading up on this topic a lot, and trying a few different (probably idiotic) approaches, but I can't seem to get this to work. Casting the function allows the code to compile, but (not surprisingly) it crashes. It may be that I've overlooked the solution either here on StackOverflow or elsewhere, so a link will suffice. (Though, since I'm a bit new to some of these techniques, please make sure that the correspondence is clear enough for a newbie. For instance, if this conversation contains my answer, I don't understand. Please simplify or explain the correspondence.) FYI, I'm using Visual C++ 2010.

Please let me know if there is anything I can do to clarify my question. Thanks in advance for the help!

答:
Short Answer: No

Long Answer:

Lamda's are just syntactic sugar for functors.

Functors are objects that act like functions.

A function pointer is not the same type of thing. In general you can not use functors where you need a function pointer.

Extra:

On the other hand it is easy to wrap a function to become a functor.

Historically:

Function pointers are generally used by C libraries. As C++ libraries will use an interface to achieve the same affect. Thus you can see why it is hard to pass functors where a function pointer is requried (the C code has no way to understand how to use the functor).

ContentLicense: CC BY-SA 2.5

Body:
I've got a library that I need to use that defines the following:

typedef void CallbackFunction(const int& i);

and has a function to register your callback that looks like:

void registerCallback(CallbackFunction* pCallback);

Because I'd like to capture the state of several variables to be used in the callback, I can't simply use a plain function. What I'd prefer to use is a lambda function, but the following doesn't compile:

auto fCallback = [](const int& i) {
    cout << i << endl;
};
registerCallback(fCallback);

instead I get the error:

error C2664: 'registerCallback' : cannot convert parameter 1 from '`anonymous-namespace'::<lambda0>' to 'CallbackFunction (__cdecl *)'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I've been reading up on this topic a lot, and trying a few different (probably idiotic) approaches, but I can't seem to get this to work. Casting the function allows the code to compile, but (not surprisingly) it crashes. It may be that I've overlooked the solution either here on StackOverflow or elsewhere, so a link will suffice. (Though, since I'm a bit new to some of these techniques, please make sure that the correspondence is clear enough for a newbie. For instance, if this conversation contains my answer, I don't understand. Please simplify or explain the correspondence.) FYI, I'm using Visual C++ 2010.

Please let me know if there is anything I can do to clarify my question. Thanks in advance for the help!


问:
Specify set of columns to be saved in each excel worksheet
I am working with a workbook containing multiple sheets and I have to export them on a regular basis. My sheets have thousands of rows, using an autofilter I would like to export only the filtered content and visible columns.

What I am missing is a way to export only the visible columns and rows. I think I need to use CellTypeVisible but have not found how to make it work in my code:

```<code>Sub SaveAllAsTsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim Filename As String

'Get folder to save to
With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Output Folder"
    .AllowMultiSelect = False
    If .Show <> -1 Then Exit Sub
    SaveToDirectory = .SelectedItems(1)
End With

'Choose which worksheets to save
For Each WS In ActiveWorkbook.Worksheets
    Select Case MsgBox("Save " & WS.Name & "?", vbQuestion + vbYesNoCancel)
        Case vbYes
            Filename = SaveToDirectory & "\" & WS.Name & ".txt"
            WS.SaveAs Filename, xlTextWindows, Local:=True
        Case vbCancel
            Exit Sub
        Case vbNo
    End Select
Next

End Sub
</code>```

答:
I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:</p>

```<code>Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working with a workbook containing multiple sheets and I have to export them on a regular basis. My sheets have thousands of rows, using an autofilter I would like to export only the filtered content and visible columns.

What I am missing is a way to export only the visible columns and rows. I think I need to use CellTypeVisible but have not found how to make it work in my code:

Sub SaveAllAsTsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim Filename As String

'Get folder to save to
With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Output Folder"
    .AllowMultiSelect = False
    If .Show <> -1 Then Exit Sub
    SaveToDirectory = .SelectedItems(1)
End With

'Choose which worksheets to save
For Each WS In ActiveWorkbook.Worksheets
    Select Case MsgBox("Save " & WS.Name & "?", vbQuestion + vbYesNoCancel)
        Case vbYes
            Filename = SaveToDirectory & "\" & WS.Name & ".txt"
            WS.SaveAs Filename, xlTextWindows, Local:=True
        Case vbCancel
            Exit Sub
        Case vbNo
    End Select
Next

End Sub

Body:
I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub


问:
How can I prevent duplicate charge using Stripe?
I'm using Stripe to allow my customer to save a credit card and pay invoices (that have a unique id). On payment, I use a form to send a POST request with the card id (provided by stripe) to my server, and the controller charges it. Then I marked the invoiced as payed on my side.

Turns out that if I double click my form's submit button quick enough, I send two POST request and the cards ends up being charged twice, because when the second POST request arrives on my server, the POST request from my server to Stripe API (from the first click) isn't finished, thus the invoice has not been marked as payed yet.

I'm considering disabling the form submit button after first click, but I feel there may be a cleaner way.

Is there on Stripe's side to prevent duplicating charges (maybe using my invoice id)? If not what would the best back-end method to do this on my side?

答:
Disabling the form submission after the first click is definitely the easiest way to implement this.

Another approach is to use idempotent requests as documented here. The idea is that you pass a unique identifier when making a request to Stripe's API that ensures you can only run this transaction once. If you re-run the query with the exact same idempotency key you will get the original response from the first call which ensures you never have 2 charges created for the same "transaction" on your website.


问:
How to extract Sentence from text with use of particular word in Rstudio?
I want to Extract Sentences which have a particular word in Text files which contains multiple Paragraphs.

For Example:
Digital India is an initiative by the Government of India to ensure that Government services are made available to citizens electronically by improving online infrastructure and by increasing Internet connectivity. It was launched on 1 July 2015 by Prime Minister Narendra Modi.

Now from This paragraph I need to Extract all those sentences that contains the word "India".

I tried to use substr and substring command in R but was not helpful.
Someone please help me in this Issue.

Thanks in Advance

答:
You can use grep like this

```<code>text <- c("Digital India is an initiative by the Government of India to ensure that Government services are made available to citizens electronically by improving online infrastructure and by increasing Internet connectivity. It was launched on 1 July 2015 by Prime Minister Narendra Modi.")
text <- unlist(strsplit(text, "\\."))

text[grep(pattern = "India", text, ignore.case = T)]

[1] "Digital India is an initiative by the Government of India ...
</code>```

Body:
You can use grep like this

text <- c("Digital India is an initiative by the Government of India to ensure that Government services are made available to citizens electronically by improving online infrastructure and by increasing Internet connectivity. It was launched on 1 July 2015 by Prime Minister Narendra Modi.")
text <- unlist(strsplit(text, "\\."))

text[grep(pattern = "India", text, ignore.case = T)]

[1] "Digital India is an initiative by the Government of India ...


问:
Repeat Heading to table in pdf
I am using the Itextsharp PDF tool to generate PDF using asp.net and C# , In that in one PDFPtable the last row data is repeating on next page means part of a table forwarded to next page. so want to show header for that Table on next page.

This is my code.

```<code>Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 20, 10);
string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf" + Guid.NewGuid().ToString("N") + ".pdf";
try
{
    //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
    FileStream fs = new FileStream(pdfFilePath, FileMode.Create);
    //
    PdfWriter wri = PdfWriter.GetInstance(doc, fs);

    //Header Section
    string strImagePath = Server.MapPath("Images");
    string strReportName = oReportDTO.strReportName + " " + oReportDTO.oDateRange.FromDate.ToString(DateFormat);
    Chunk headerchunk = new Chunk(strReportName, new Font(1, 8.0f));
    HeaderFooter oHeader = new HeaderFooter(new Phrase(headerchunk), false);
    oHeader.Border = Rectangle.NO_BORDER;
    oHeader.Alignment = 1;
    doc.Header = oHeader;

    //Footer Section
    string name ="Logged in as : " +currentLoggedInUser.UserName + new string(' ',70)+ "Page Number : " + doc.PageNumber;
    Chunk Footerchunk1 = new Chunk(name, new Font(1, 5.0f));
    HeaderFooter oFooter1 = new HeaderFooter(new Phrase(Footerchunk1), true);
    oFooter1.Border = Rectangle.NO_BORDER;
    oFooter1.Alignment = 1;
    doc.Footer = oFooter1;
    iTextSharp.text.Image imgFooter = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(strImagePath + "/TransRisk Logo168x97.png"), System.Drawing.Imaging.ImageFormat.Jpeg);
    imgFooter.ScaleAbsolute(80, 50);
    Chunk footerchunk = new Chunk(imgFooter, 260.0f, 0.0f);
    HeaderFooter oFooter = new HeaderFooter(new Phrase(name),new Phrase(footerchunk));
    oFooter.Border =Rectangle.NO_BORDER;
    doc.Footer = oFooter;

    doc.Open();//Open Document to write

    Font font8 = FontFactory.GetFont("ARIAL", 7);

    HtmlTable dt = customMatrixReport;

    if (dt.Rows.Count > 0)
    {
        //Craete instance of the pdf table and set the number of column in that table
        int startColumnPosition = 1;
        int endColumnPosition = 13;//End Column number in Pdf Page
        int NoOfReports = Convert.ToInt32(Math.Ceiling((decimal)(dt.Rows[0].Cells.Count - 1) / endColumnPosition));//Count How many Pages to show
        int pageRowCount = 0;
        List<PdfPCell> lstHeaderCells = new List<PdfPCell>();
        PdfPTable oPdfTable = null;
        PdfPCell oPdfPCell = null;
        for (int report = 1; report <= NoOfReports; ++report)
        {
            doc.Add(oHeader);
            //ColumnText.ShowTextAligned(

            int noOfColumns = -1;
            if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
            else
            {
                oPdfTable = new PdfPTable(14);
                //Widths Count
                noOfColumns = 14;
            }
            oPdfTable.TotalWidth = 650f;
            List<float> lstwidths = new List<float>();
            lstwidths.Add(100f);
            for (int i = 2; i <= noOfColumns; ++i)
            {
                lstwidths.Add(80f);
            }
            oPdfTable.SetTotalWidth(lstwidths.ToArray());
            pageRowCount = 0;

            for (int rows = 0; rows < dt.Rows.Count; rows++)
            {
                //PageRowCount
                pageRowCount = pageRowCount + 1;
                //Description celll
                if (rows == 0 )
                {
                    //Background color for table header
                    oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
                    oPdfPCell.BackgroundColor = new Color(118, 147, 199);
                    oPdfTable.AddCell(oPdfPCell);
                }
                else
                {
                    //background color for Table cells
                    oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText,new Font(1, 8.0f))));
                    oPdfPCell.BackgroundColor = new Color(232, 237, 255);
                    oPdfTable.AddCell(oPdfPCell);
                }

                //for header cel
                if (rows == 0)
                {
                    lstHeaderCells.Add(oPdfPCell);
                }
                for (int column = startColumnPosition; column <= endColumnPosition; column++)
                {

                    if (rows == 0)
                    {
                        oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
                        oPdfPCell.BackgroundColor = new Color(118, 147, 199);
                        oPdfTable.AddCell(oPdfPCell);
                    }
                    else
                    {
                        oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f))));
                        oPdfPCell.BackgroundColor = new Color(232, 237, 255);
                        oPdfPCell.Column.Alignment = 2;
                        oPdfTable.AddCell(oPdfPCell);
                    }

                    if (rows == 0)
                    {
                        lstHeaderCells.Add(oPdfPCell);
                    }
                }
                if (pageRowCount >= 40 && rows != (dt.Rows.Count - 1))
                {
                    pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
                }
            }
            startColumnPosition = endColumnPosition + 1;
            endColumnPosition = endColumnPosition + 13;
            oPdfTable.SpacingBefore = 10;
            oPdfTable.SpacingAfter = 10;
            doc.Add(oPdfTable);
            //doc.NewPage();
        }
    }
    else
        doc.Add(oHeader);
}

finally
{
    doc.Close();
}
</code>```

help me..

答:
Change this line-

```<code>if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
</code>```

To this-

```<code>if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1;}
</code>```

After this line-

```<code>oPdfTable = new PdfPTable(14);
</code>```

Add this-

```<code>oPdfTable.HeaderRows = 1;
</code>```

Change this line-

```<code>pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
</code>```

To this-

```<code>pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1; oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
</code>```

Title: Repeat Heading to table in pdf

Body:
I am using the Itextsharp PDF tool to generate PDF using asp.net and C# , In that in one PDFPtable the last row data is repeating on next page means part of a table forwarded to next page. so want to show header for that Table on next page.

This is my code.

Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 20, 10);
string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf" + Guid.NewGuid().ToString("N") + ".pdf";
try
{
    //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
    FileStream fs = new FileStream(pdfFilePath, FileMode.Create);
    //
    PdfWriter wri = PdfWriter.GetInstance(doc, fs);

    //Header Section
    string strImagePath = Server.MapPath("Images");
    string strReportName = oReportDTO.strReportName + " " + oReportDTO.oDateRange.FromDate.ToString(DateFormat);
    Chunk headerchunk = new Chunk(strReportName, new Font(1, 8.0f));
    HeaderFooter oHeader = new HeaderFooter(new Phrase(headerchunk), false);
    oHeader.Border = Rectangle.NO_BORDER;
    oHeader.Alignment = 1;
    doc.Header = oHeader;

    //Footer Section
    string name ="Logged in as : " +currentLoggedInUser.UserName + new string(' ',70)+ "Page Number : " + doc.PageNumber;
    Chunk Footerchunk1 = new Chunk(name, new Font(1, 5.0f));
    HeaderFooter oFooter1 = new HeaderFooter(new Phrase(Footerchunk1), true);
    oFooter1.Border = Rectangle.NO_BORDER;
    oFooter1.Alignment = 1;
    doc.Footer = oFooter1;
    iTextSharp.text.Image imgFooter = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(strImagePath + "/TransRisk Logo168x97.png"), System.Drawing.Imaging.ImageFormat.Jpeg);
    imgFooter.ScaleAbsolute(80, 50);
    Chunk footerchunk = new Chunk(imgFooter, 260.0f, 0.0f);
    HeaderFooter oFooter = new HeaderFooter(new Phrase(name),new Phrase(footerchunk));
    oFooter.Border =Rectangle.NO_BORDER;
    doc.Footer = oFooter;

    doc.Open();//Open Document to write

    Font font8 = FontFactory.GetFont("ARIAL", 7);

    HtmlTable dt = customMatrixReport;

    if (dt.Rows.Count > 0)
    {
        //Craete instance of the pdf table and set the number of column in that table
        int startColumnPosition = 1;
        int endColumnPosition = 13;//End Column number in Pdf Page
        int NoOfReports = Convert.ToInt32(Math.Ceiling((decimal)(dt.Rows[0].Cells.Count - 1) / endColumnPosition));//Count How many Pages to show
        int pageRowCount = 0;
        List<PdfPCell> lstHeaderCells = new List<PdfPCell>();
        PdfPTable oPdfTable = null;
        PdfPCell oPdfPCell = null;
        for (int report = 1; report <= NoOfReports; ++report)
        {
            doc.Add(oHeader);
            //ColumnText.ShowTextAligned(

            int noOfColumns = -1;
            if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
            else
            {
                oPdfTable = new PdfPTable(14);
                //Widths Count
                noOfColumns = 14;
            }
            oPdfTable.TotalWidth = 650f;
            List<float> lstwidths = new List<float>();
            lstwidths.Add(100f);
            for (int i = 2; i <= noOfColumns; ++i)
            {
                lstwidths.Add(80f);
            }
            oPdfTable.SetTotalWidth(lstwidths.ToArray());
            pageRowCount = 0;

            for (int rows = 0; rows < dt.Rows.Count; rows++)
            {
                //PageRowCount
                pageRowCount = pageRowCount + 1;
                //Description celll
                if (rows == 0 )
                {
                    //Background color for table header
                    oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
                    oPdfPCell.BackgroundColor = new Color(118, 147, 199);
                    oPdfTable.AddCell(oPdfPCell);
                }
                else
                {
                    //background color for Table cells
                    oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText,new Font(1, 8.0f))));
                    oPdfPCell.BackgroundColor = new Color(232, 237, 255);
                    oPdfTable.AddCell(oPdfPCell);
                }

                //for header cel
                if (rows == 0)
                {
                    lstHeaderCells.Add(oPdfPCell);
                }
                for (int column = startColumnPosition; column <= endColumnPosition; column++)
                {

                    if (rows == 0)
                    {
                        oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
                        oPdfPCell.BackgroundColor = new Color(118, 147, 199);
                        oPdfTable.AddCell(oPdfPCell);
                    }
                    else
                    {
                        oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f))));
                        oPdfPCell.BackgroundColor = new Color(232, 237, 255);
                        oPdfPCell.Column.Alignment = 2;
                        oPdfTable.AddCell(oPdfPCell);
                    }

                    if (rows == 0)
                    {
                        lstHeaderCells.Add(oPdfPCell);
                    }
                }
                if (pageRowCount >= 40 && rows != (dt.Rows.Count - 1))
                {
                    pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
                }
            }
            startColumnPosition = endColumnPosition + 1;
            endColumnPosition = endColumnPosition + 13;
            oPdfTable.SpacingBefore = 10;
            oPdfTable.SpacingAfter = 10;
            doc.Add(oPdfTable);
            //doc.NewPage();
        }
    }
    else
        doc.Add(oHeader);
}

finally
{
    doc.Close();
}

help me..

Body:
Change this line-

if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }

To this-

if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1;}

After this line-

oPdfTable = new PdfPTable(14);

Add this-

oPdfTable.HeaderRows = 1;

Change this line-

pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }

To this-

pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1; oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }


问:
Arguments passed into for loop in bash script
I am trying to pass the argument as max limit for the for loop like this:

```<code>#!/bin/bash

for i in {1..$1}
do
    echo $i
done
</code>```

This however returns {1..2} when called with argument 2, instead of executing the script and giving me

```<code>1
2
</code>```

答:
...or in the unlikely event that you really just want sequential numbers:

```<code>seq $1
</code>```

:-)

Body:
I am trying to pass the argument as max limit for the for loop like this:

#!/bin/bash

for i in {1..$1}
do
    echo $i
done

This however returns {1..2} when called with argument 2, instead of executing the script and giving me

1
2

Body:
...or in the unlikely event that you really just want sequential numbers:

seq $1

:-)


问:
How to custom marker InfoWindow in googleMap on android
In my application I want to make custom marker InfoWindow and transparent background for this.

I wrote the code below but it shows me wrong background again. I want the transparent background, not white.

My code:

```<code>       this.infoWindow = (ViewGroup) getLayoutInflater().inflate(R.layout.custominfowindow_one_button, null);

    this.infoButton = (Button) infoWindow.findViewById(R.id.button);
    this.infoButton_cancel=(Button) infoWindow.findViewById(R.id.btn_close_infowindow) ;
    mapWrapperLayout = (MapWrapperLayout) findViewById(R.id.map_relative_layout);
    mapWrapperLayout.init(mMap, getPixelsFromDp(this, 39 + 20));
    infoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            infoWindowReady = !infoWindowReady;
        }
    });

    this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton, getResources().getDrawable(R.color.trans),
            getResources().getDrawable(R.color.trans),context) {
        @Override
        protected void onClickConfirmed(View v, Marker marker) {

        }
    };

    this.infoButton.setOnTouchListener(infoButtonListener);
    this.infoButton_cancelListener = new OnInfoWindowElemTouchListener(infoButton_cancel, getResources().getDrawable(R.drawable.ic_cancel3),
            getResources().getDrawable(R.drawable.ic_cancel3),context) {
        @Override
        protected void onClickConfirmed(View v, Marker marker) {
            addmarker_map.hideInfoWindow();

        }
    };

    this.infoButton_cancel.setOnTouchListener(infoButton_cancelListener );

    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {

            if (serviceName == "geocode" && !hasGeoInfo) {
                if (__counter == 1) {
                    infoButton.setText("نشانگر");
                    togglePopup();
                } else if (__counter + "" == null) {
                    __counter = 0;
                    __counter++;
                } else {
                    __counter++;
                }
            }
            infoButtonListener.setMarker(marker);
            mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
            return infoWindow;
        }
    });
</code>```

My XML codes:

```<code>    <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dfhdfthd">

    <Button
        android:id="@+id/btn_close_infowindow"
        android:layout_width="@dimen/size25dp"
        android:layout_height="@dimen/size25dp"
        android:layout_marginLeft="@dimen/size70dp"
        android:background="@drawable/ic_cancel3"
        android:backgroundTint="#868585" />

    <Button
        android:id="@+id/button"
        android:layout_width="@dimen/size100dp"
        android:layout_height="@dimen/size30dp"
        android:layout_below="@+id/btn_close_infowindow"
        android:layout_marginTop="-5dp"
        android:background="@color/trans" />

</RelativeLayout>
</code>```

please see this image to understand what i mean : https://image.ibb.co/bsx7W5/photo_2017_09_21_12_44_22.jpg

How can i make transparent background for infoWindows? Please help me.

答:
```<code>@Override

public View getInfoWindow(Marker args) {
   View v = getActivity().getLayoutInflater().inflate(R.layout.marker_tab_layout, null);

   return v;

}
</code>```

if your method returns null than it shows white infoWindow in Background return your custom_info_contents.xml instead null.

Body:
In my application I want to make custom marker InfoWindow and transparent background for this.

I wrote the code below but it shows me wrong background again. I want the transparent background, not white.

My code:

       this.infoWindow = (ViewGroup) getLayoutInflater().inflate(R.layout.custominfowindow_one_button, null);

    this.infoButton = (Button) infoWindow.findViewById(R.id.button);
    this.infoButton_cancel=(Button) infoWindow.findViewById(R.id.btn_close_infowindow) ;
    mapWrapperLayout = (MapWrapperLayout) findViewById(R.id.map_relative_layout);
    mapWrapperLayout.init(mMap, getPixelsFromDp(this, 39 + 20));
    infoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            infoWindowReady = !infoWindowReady;
        }
    });

    this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton, getResources().getDrawable(R.color.trans),
            getResources().getDrawable(R.color.trans),context) {
        @Override
        protected void onClickConfirmed(View v, Marker marker) {

        }
    };

    this.infoButton.setOnTouchListener(infoButtonListener);
    this.infoButton_cancelListener = new OnInfoWindowElemTouchListener(infoButton_cancel, getResources().getDrawable(R.drawable.ic_cancel3),
            getResources().getDrawable(R.drawable.ic_cancel3),context) {
        @Override
        protected void onClickConfirmed(View v, Marker marker) {
            addmarker_map.hideInfoWindow();

        }
    };

    this.infoButton_cancel.setOnTouchListener(infoButton_cancelListener );

    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {

            if (serviceName == "geocode" && !hasGeoInfo) {
                if (__counter == 1) {
                    infoButton.setText("نشانگر");
                    togglePopup();
                } else if (__counter + "" == null) {
                    __counter = 0;
                    __counter++;
                } else {
                    __counter++;
                }
            }
            infoButtonListener.setMarker(marker);
            mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
            return infoWindow;
        }
    });

My XML codes:

    <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dfhdfthd">

    <Button
        android:id="@+id/btn_close_infowindow"
        android:layout_width="@dimen/size25dp"
        android:layout_height="@dimen/size25dp"
        android:layout_marginLeft="@dimen/size70dp"
        android:background="@drawable/ic_cancel3"
        android:backgroundTint="#868585" />

    <Button
        android:id="@+id/button"
        android:layout_width="@dimen/size100dp"
        android:layout_height="@dimen/size30dp"
        android:layout_below="@+id/btn_close_infowindow"
        android:layout_marginTop="-5dp"
        android:background="@color/trans" />

</RelativeLayout>

please see this image to understand what i mean : https://image.ibb.co/bsx7W5/photo_2017_09_21_12_44_22.jpg

How can i make transparent background for infoWindows? Please help me.

Body:
@Override

public View getInfoWindow(Marker args) {
   View v = getActivity().getLayoutInflater().inflate(R.layout.marker_tab_layout, null);

   return v;

}

if your method returns null than it shows white infoWindow in Background return your custom_info_contents.xml instead null.


问:
Packaging Wear 2 application
I am new to application development for Android Wear. My company needs to deploy to the customer our Android Wear application without using Play Store.
I have read this

https://developer.android.com/training/wearables/apps/packaging.html

but I don't understand if it is possible to use the embedded method like wear 1.x on wear 2. I tried the embedded method but when I install the phone application and if I check the log of wear I can see this message:

I/PackageChangesService: App is not installed

Before posting this thread I read on Stack Overflow many possible solution for this, like using the same name space, same permission on phone and wear etc. But I can't find a solution that works.

So on an Android Wear 2 smartwatch it is not possible to use the packaging method?

答:
From this article,

A Wear 2.0 user must visit the Play Store on their watch to install apps. There is no auto-install like on Wear 1.X. Wear 2.0 apps
  get full network access and can be installed completely separately
  from the handheld app so the focus is much more on standalone Wear
  apps than the handheld centric 1.X Wear apps.

Title: Packaging Wear 2 application


问:
Best way to querying a list by group by in 1 to n relation entities
I wanted a query to show only the last position of all my workers in a list.
I know that I must use group by for this situation but I don't know what is the best way to do that. I used a lot of way to do that but I think something is wrong plus I had problems with ToListAsync() with group by and I prefer to using queryable for querying instead of enumerable for best performance.As I searched in two or three days ago, I figured out that group by doesn't work with includes and some other problems.
This my code :

 public class WorkerTaxi : Worker
    {
        #region MainProperties

        ........

        #endregion

        #region EFRelations

        ......

        [InverseProperty(property: "WorkerTaxi")]
        public virtual ICollection<Car> Cars { get; set; }
        [InverseProperty(property: "WorkerTaxi")]
        public virtual ICollection<Position> Positions { get; set; }

        #endregion
    }
```

   <pre class="lang-cs prettyprint-override"><code> public class Position
    {
        [Required]
        public Guid PositionId { get; set; }
        [Required]
        public double GeoLocationLat { get; set; }
        [Required]
        public double GeoLocationLong { get; set; }
        [Required]
        public DateTime Date { get; set; }
        [ForeignKey("PersonId")]
        [InverseProperty(property: "Positions")]
        public virtual WorkerTaxi WorkerTaxi{get; set; }
        [Required]
        public Guid PersonId { get; set; }

    }
</code>```

public async Task<ReadOnlyCollection<PositionViewModel>>
   GetAllWorkerTaxiLastPositionByCityAsync(string cityName)
    {
        var hashing = new Hashing(text: cityName);
        var hash = hashing.GetHash();
        var workerList = await (from x in _workerTaxi.Include(x=>x.Positions)
                where hashing.GetHashFromEncryption(x.City.CityName) == hash && x.IsReadyForWork
                select x)
            .ToListAsync();
        var workerWithLastPositions = workerList.GroupBy(
            p => p.PersonId,
            p => p.Positions.OrderByDescending(x=>x.Date).FirstOrDefault(),
            (key, g) => new Position{ PersonId = key,GeoLocationLat= g.FirstOrDefault().GeoLocationLat,GeoLocationLong = g.FirstOrDefault().GeoLocationLong }).ToList();
        return _mapper.Map<ReadOnlyCollection<PositionViewModel>>(workerWithLastPositions);
    }
}
```

答:
Let's forget about Entity Framework and async and work with the data model.

Positions is an ICollection which implies no particular order.  So to get the last position of a taxi

```<code>Positions
  .Where(p => p.WorkerTax == ...)
  .OrderByDescending(p => p.Date)
  .First()
</code>```

As you stated, we can group the positions by taxis and then take the last position.

```<code>Positions
  .OrderByDescending(p => p.Date)
  .GroupBy(p => p.taxi)
  .Select(g => g.First())
</code>```

A position contains the taxi, so to that'all you need.  You have now obtained the last position of all taxis.

Body:
I wanted a query to show only the last position of all my workers in a list.
I know that I must use group by for this situation but I don't know what is the best way to do that. I used a lot of way to do that but I think something is wrong plus I had problems with ToListAsync() with group by and I prefer to using queryable for querying instead of enumerable for best performance.As I searched in two or three days ago, I figured out that group by doesn't work with includes and some other problems.
This my code :

 public class WorkerTaxi : Worker
    {
        #region MainProperties

        ........

        #endregion

        #region EFRelations

        ......

        [InverseProperty(property: "WorkerTaxi")]
        public virtual ICollection<Car> Cars { get; set; }
        [InverseProperty(property: "WorkerTaxi")]
        public virtual ICollection<Position> Positions { get; set; }

        #endregion
    }

 public class Position
    {
        [Required]
        public Guid PositionId { get; set; }
        [Required]
        public double GeoLocationLat { get; set; }
        [Required]
        public double GeoLocationLong { get; set; }
        [Required]
        public DateTime Date { get; set; }
        [ForeignKey("PersonId")]
        [InverseProperty(property: "Positions")]
        public virtual WorkerTaxi WorkerTaxi{get; set; }
        [Required]
        public Guid PersonId { get; set; }

    }

public async Task<ReadOnlyCollection<PositionViewModel>>
   GetAllWorkerTaxiLastPositionByCityAsync(string cityName)
    {
        var hashing = new Hashing(text: cityName);
        var hash = hashing.GetHash();
        var workerList = await (from x in _workerTaxi.Include(x=>x.Positions)
                where hashing.GetHashFromEncryption(x.City.CityName) == hash && x.IsReadyForWork
                select x)
            .ToListAsync();
        var workerWithLastPositions = workerList.GroupBy(
            p => p.PersonId,
            p => p.Positions.OrderByDescending(x=>x.Date).FirstOrDefault(),
            (key, g) => new Position{ PersonId = key,GeoLocationLat= g.FirstOrDefault().GeoLocationLat,GeoLocationLong = g.FirstOrDefault().GeoLocationLong }).ToList();
        return _mapper.Map<ReadOnlyCollection<PositionViewModel>>(workerWithLastPositions);
    }
}

Body:
Let's forget about Entity Framework and async and work with the data model.

Positions is an ICollection which implies no particular order.  So to get the last position of a taxi

Positions
  .Where(p => p.WorkerTax == ...)
  .OrderByDescending(p => p.Date)
  .First()

As you stated, we can group the positions by taxis and then take the last position.

Positions
  .OrderByDescending(p => p.Date)
  .GroupBy(p => p.taxi)
  .Select(g => g.First())

A position contains the taxi, so to that'all you need.  You have now obtained the last position of all taxis.


问:
Recurring event in FullCalendar
So I have spent the past 2 weeks trying to figure this out and tried all other previously proposed answers. I'm still not able to get it right.

I'm trying to setup a calendar where the recurring events are filtered within the specified date range.
Example: "My event" - every Thursday at 2:15PM - Between 2017/06/01 and 2017/06/30.

I've unsuccessfully tried the solutions proposed on this link:
Recurring Events in FullCalendar

In the end end I decided to follow this route:
https://github.com/c-trimm/moment-recur

It's a moments.js plugin (moment-recur) that should process the date range filter.

Please help!

My json feed returns:

```<code>  [{
    "title":"my event",
    "start":"2017-06-01T14:15",
    "dow":"4",
    "recurrence":"moment().recur[{
                 start:\"2017-06-01\",
                 end:\"2017-06-30\"}]"
  }]
</code>```

My calendar works except for the fact that it will not stop publishing the event on Thursdays forever. I don't want to have to manually duplicate the event.

```<code><link rel="stylesheet" type="text/css" href="/fullcalendar.css">
    <script src='/jquery.min.js'></script>
    <script src='/moment.min.js'></script>
    <script src='/moment-recur.js'></script>
    <script src='/fullcalendar.js'></script>

    <script>

        $(document).ready(function() {

            $('#calendar').fullCalendar({
                header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,listWeek,listDay'
                },
                validRange: function(nowDate) {
                        return {
                            start: nowDate.clone().subtract(2, 'months'),
                            end: nowDate.clone().add(2, 'months')
                        };
                    },

                // customize the button names,
                // otherwise they'd all just say "list"
                views: {
                listDay: { buttonText: 'Day' },
                listWeek: { buttonText: 'Week' },
                },
                hiddenDays: [ 5 ], // hide Fridays
                editable: true,
                eventLimit: true, // allow "more" link when too many events
                businessHours: [ // specify an array instead
                    {
                        dow: [ 1 ], // Monday,
                        start: '12:30', // 8am
                        end: '22:00' // 6pm
                    },
                    {
                        dow: [ 2, 3 ], // Tuesday, Wednesday
                        start: '9:30', // 8am
                        end: '22:00' // 6pm
                    },
                    {
                        dow: [ 4, ], // Thursday
                        start: '13:00', // 10am
                        end: '22:00' // 4pm
                    },
                    {
                        dow: [ 7 ], // Sunday
                        start: '11:00', // 10am
                        end: '18:30' // 4pm
                    }],
                events: 'my-event/feed',

       //THIS IS WHERE I GET STUCK!!!!!

                // I'm trying to implement this:
                eventRender:
                recurrence = moment().recur({
                start: "01/01/2014",
                end: "01/01/2015"
               });

            });
        });
    </script>

    <div id='calendar'></div>
</code>```

I believe i'm suppose to write it as a function but no mater what I try it either brakes the calendar or doesn't return any results. Thanks in advance to you all!

答:
Below is the fiddler link for recurring events in fullcalendar.

http://jsfiddle.net/slicedtoad/duu0dx2t/1/

You need to specify dow property in event as specified in example.

```<code>$('#calendar').fullCalendar({
    defaultDate: moment(),
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    defaultView: 'month',

    events: [{
        title:"My repeating event",
        start: '10:00', // a start time (10am in this example)
        end: '14:00', // an end time (6pm in this example)

        dow: [ 1, 4 ] // Repeat monday and thursday
    }],
});
</code>```

Title: Recurring event in FullCalendar

Body:
So I have spent the past 2 weeks trying to figure this out and tried all other previously proposed answers. I'm still not able to get it right.

I'm trying to setup a calendar where the recurring events are filtered within the specified date range.
Example: "My event" - every Thursday at 2:15PM - Between 2017/06/01 and 2017/06/30.

I've unsuccessfully tried the solutions proposed on this link:
Recurring Events in FullCalendar

In the end end I decided to follow this route:
https://github.com/c-trimm/moment-recur

It's a moments.js plugin (moment-recur) that should process the date range filter.

Please help!

My json feed returns:

  [{
    "title":"my event",
    "start":"2017-06-01T14:15",
    "dow":"4",
    "recurrence":"moment().recur[{
                 start:\"2017-06-01\",
                 end:\"2017-06-30\"}]"
  }]

My calendar works except for the fact that it will not stop publishing the event on Thursdays forever. I don't want to have to manually duplicate the event.

<link rel="stylesheet" type="text/css" href="/fullcalendar.css">

I believe i'm suppose to write it as a function but no mater what I try it either brakes the calendar or doesn't return any results. Thanks in advance to you all!

Body:
Below is the fiddler link for recurring events in fullcalendar.

http://jsfiddle.net/slicedtoad/duu0dx2t/1/

You need to specify dow property in event as specified in example.

$('#calendar').fullCalendar({
    defaultDate: moment(),
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    defaultView: 'month',

    events: [{
        title:"My repeating event",
        start: '10:00', // a start time (10am in this example)
        end: '14:00', // an end time (6pm in this example)

        dow: [ 1, 4 ] // Repeat monday and thursday
    }],
});


问:
Can one iOS mobile app use sync tables from several Azure App Service Mobile APPs?
Is it possible to have one iOS App use synch tables from different Azure App Services Mobile App headends so that tables 1,2 and 3 comes from one App Service and tables 4,5 and 6 comes from another App Service?</p>

答:
Is it possible to have one iOS App use synch tables from different Azure App Services Mobile App headends

AFAIK, you could just create multiple MSClient instances as follows which point to your Azure Mobile Apps in your iOS App to sync tables from several Azure Mobile Apps.

```<code>MSClient *client = [MSClient clientWithApplicationURLString:@"https://{app1}.azurewebsites.net"];
</code>```

For more details about using iOS client library for Azure Mobile Apps, you could follow here and Enable offline sync.

Additionally, for authentication users with social providers (e.g. AAD, Facebook, Twitter, Google, Microsoft Account, etc.) supported by azure app service, I would recommend you use the Client-managed authentication flow, and you could just create a single application with your social provider platform and use the same App ID and App Secret in your several Azure Mobile Apps. After the client user logged, you could leverage the token from the social provider and login with your Azure Mobile Apps. Details about authentication users, you could follow here.

Body:
Is it possible to have one iOS App use synch tables from different Azure App Services Mobile App headends

AFAIK, you could just create multiple MSClient instances as follows which point to your Azure Mobile Apps in your iOS App to sync tables from several Azure Mobile Apps.

MSClient *client = [MSClient clientWithApplicationURLString:@"https://{app1}.azurewebsites.net"];

For more details about using iOS client library for Azure Mobile Apps, you could follow here and Enable offline sync.

Additionally, for authentication users with social providers (e.g. AAD, Facebook, Twitter, Google, Microsoft Account, etc.) supported by azure app service, I would recommend you use the Client-managed authentication flow, and you could just create a single application with your social provider platform and use the same App ID and App Secret in your several Azure Mobile Apps. After the client user logged, you could leverage the token from the social provider and login with your Azure Mobile Apps. Details about authentication users, you could follow here.


问:
Showing only specific fields of javascript object in the array doesn't work
I'm trying to show specific series of specific fields and value inside of the object but it's not working.

```<code>var objArray = [
    {id:1, photo:true, bol: true }, {id:2, photo: true, bol:true}
];

result = objArray.map((item) => return {id: item.id, photo: item.photo
}) // this doesn't work.. why??
</code>```

Expectd Output

```<code>[
    {id:1, photo:true}, {id:2, photo: true}
]
</code>```

答:
Create temporary Object;

Iterate through object and if key is not "bol", then push it to temp Object;

finally return the temporary Object

var objArray = [
    {id:1, photo:true, bol: true }, {id:2, photo: true, bol:true}
];

result = objArray.map((item) => {
let tempObj = {}
 Object.keys(item).map((key) => {
   if(key != "bol") {
      tempObj[key] = item[key]

   }
 })
 return tempObj;
 })

 console.log(result)```

Body:
I'm trying to show specific series of specific fields and value inside of the object but it's not working.

var objArray = [
    {id:1, photo:true, bol: true }, {id:2, photo: true, bol:true}
];

result = objArray.map((item) => return {id: item.id, photo: item.photo
}) // this doesn't work.. why??

Expectd Output

[
    {id:1, photo:true}, {id:2, photo: true}
]


问:
Make my UIViewController fullscreen in Objective-C
I have an Objective C project which uses XIB files (not storyboards).

I have a UIViewController view that I lunch from my AppDelegate.m file which plays a video.  I want to make it full screen but the title
bar at the top is showing and there is a thin white line down the left hand side of the screen.

How can I make the whole video play full screen.

AppDelegate.m

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    VideoIntroViewController *videoIntroViewController = [[VideoIntroViewController alloc] initWithNibName:@"VideoIntroViewController" bundle:nil];
    videoIntroViewController.managedObjectContext = self.managedObjectContext;

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:videoIntroViewController];
    self.window.rootViewController = self.navigationController;
    [self.window addSubview:self.navigationController.view];

    [self.window makeKeyAndVisible];

  return YES;
}
</code>```

VideoIntroViewController.m

```<code>- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.navigationController.toolbarHidden)
    {
        [self.navigationController setToolbarHidden:YES animated:animated];
    }
}

- (void)viewDidLoad
{
    [self createVideoPlayer];

    [super viewDidLoad];
}

- (void)createVideoPlayer
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player.volume = PLAYER_VOLUME;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.videoGravity = UIViewContentModeScaleToFill; <-- 'Null passed to a callee that requires a non-null argument'
    playerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:playerLayer];

    [self.player play];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}
</code>```

答:
Remove the following line,

```<code>[self.window addSubview:self.navigationController.view];
</code>```

You have already set rootViewController of self.window.

If you ever need to add subview (here you do not need) and you are using autoLayout on that view controller/view, you have to add constraint in storyboard/xib file or by writing code for that view.

Body:
I have an Objective C project which uses XIB files (not storyboards).

I have a UIViewController view that I lunch from my AppDelegate.m file which plays a video.  I want to make it full screen but the title
bar at the top is showing and there is a thin white line down the left hand side of the screen.

How can I make the whole video play full screen.

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    VideoIntroViewController *videoIntroViewController = [[VideoIntroViewController alloc] initWithNibName:@"VideoIntroViewController" bundle:nil];
    videoIntroViewController.managedObjectContext = self.managedObjectContext;

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:videoIntroViewController];
    self.window.rootViewController = self.navigationController;
    [self.window addSubview:self.navigationController.view];

    [self.window makeKeyAndVisible];

  return YES;
}

VideoIntroViewController.m

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.navigationController.toolbarHidden)
    {
        [self.navigationController setToolbarHidden:YES animated:animated];
    }
}

- (void)viewDidLoad
{
    [self createVideoPlayer];

    [super viewDidLoad];
}

- (void)createVideoPlayer
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player.volume = PLAYER_VOLUME;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.videoGravity = UIViewContentModeScaleToFill; <-- 'Null passed to a callee that requires a non-null argument'
    playerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:playerLayer];

    [self.player play];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

Body:
Remove the following line,

[self.window addSubview:self.navigationController.view];

You have already set rootViewController of self.window.

If you ever need to add subview (here you do not need) and you are using autoLayout on that view controller/view, you have to add constraint in storyboard/xib file or by writing code for that view.


问:
Getting Class Cast exception in Kafka Stream API
I am producing input data as json string .

For Topic - myinput

```<code>{"time":"2017-11-28T09:42:26.776Z","name":"Lane1","oclass"
     :"myClass","id":112553,"Scope":"198S"}
</code>```

My class looking like this:

```<code>public class App {
    static public class CountryMessage {

        public String time;
        public String Scope;
        public String id;
        public String oclass;
        public String name;
    }

    private static final String APP_ID = "countries-streaming-analysis-app";

    public static void main(String[] args) {
        System.out.println("Kafka Streams Demonstration");

        StreamsConfig config = new StreamsConfig(getProperties());
        final Serde < String > stringSerde = Serdes.String();
        final Serde < Long > longSerde = Serdes.Long();

        Map < String, Object > serdeProps = new HashMap < > ();
        final Serializer < CountryMessage > countryMessageSerializer = new JsonPOJOSerializer < > ();
        serdeProps.put("JsonPOJOClass", CountryMessage.class);
        countryMessageSerializer.configure(serdeProps, false);

        final Deserializer < CountryMessage > countryMessageDeserializer = new JsonPOJODeserializer < > ();
        serdeProps.put("JsonPOJOClass", CountryMessage.class);
        countryMessageDeserializer.configure(serdeProps, false);
        final Serde < CountryMessage > countryMessageSerde = Serdes.serdeFrom(countryMessageSerializer,countryMessageDeserializer);

        KStreamBuilder kStreamBuilder = new KStreamBuilder();
        KStream<String, CountryMessage> countriesStream = kStreamBuilder.stream(stringSerde, countryMessageSerde, "vanitopic");

        KGroupedStream<String, CountryMessage> countries = countriesStream.selectKey((k, traffic) -> traffic.Scope).groupByKey();

        KTable<Windowed<String>, Long> aggregatedStream = countries.count(TimeWindows.of(60 * 1000L), "UserCountStore");

        System.out.println("Starting Kafka Streams Countries Example");
        KafkaStreams kafkaStreams = new KafkaStreams(kStreamBuilder, config);
        kafkaStreams.start();
        System.out.println("Now started CountriesStreams Example");
    }

    private static Properties getProperties() {
        Properties settings = new Properties();

        settings.put(StreamsConfig.APPLICATION_ID_CONFIG, APP_ID);
        settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "10.106.9.235:9092,10.106.9.235:9093,10.106.9.235:9094");
        settings.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "10.106.9.235:2181");
        //settings.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        //settings.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        return settings;
    }
}
</code>```

I am getting bellow class cast exception:

Exception in thread
  "countries-streaming-analysis-app-f7f95119-4401-4a6e-8060-5a138ffaddb2-StreamThread-1"
  org.apache.kafka.streams.errors.StreamsException: Exception caught in
  process. taskId=0_0, processor=KSTREAM-SOURCE-0000000000,
  topic=vanitopic, partition=0, offset=2036     at
  org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:203)
    at
  org.apache.kafka.streams.processor.internals.StreamThread.processAndPunctuate(StreamThread.java:679)
    at
  org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:557)
    at
  org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:527)
  Caused by: org.apache.kafka.streams.errors.StreamsException: A
  serializer (key:
  org.apache.kafka.common.serialization.ByteArraySerializer / value:
  org.apache.kafka.common.serialization.ByteArraySerializer) is not
  compatible to the actual key or value type (key type: java.lang.String
  / value type: com.cisco.streams.countries.App$CountryMessage). Change
  the default Serdes in StreamConfig or provide correct Serdes via
  method parameters.    at
  org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:91)
    at
  org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:82)
    at
  org.apache.kafka.streams.kstream.internals.KStreamFilter$KStreamFilterProcessor.process(KStreamFilter.java:43)
    at
  org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:47)
    at
  org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:187)
    at
  org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:133)
    at
  org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:82)
    at
  org.apache.kafka.streams.kstream.internals.KStreamMap$KStreamMapProcessor.process(KStreamMap.java:42)
    at
  org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:47)
    at
  org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:187)
    at
  org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:133)
    at
  org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:82)
    at
  org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:80)
    at
  org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:189)
    ... 3 more Caused by: java.lang.ClassCastException: java.lang.String
  cannot be cast to [B  at
  org.apache.kafka.common.serialization.ByteArraySerializer.serialize(ByteArraySerializer.java:21)
    at
  org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:88)
    at
  org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:76)
    at
  org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:87)
    ... 16 more

I need help to understand how and where to apply custom Serdes those I have created

答:
In your code,

```<code>KGroupedStream<String, CountryMessage> countries = countriesStream.selectKey((k, traffic) -> traffic.Scope).groupByKey();
</code>```

the groupByKey() need to set both serializer as this will trigger a data repartitioning. Or you set default Serded to for String and CountryMessage types.

As mentioned in my comment, every operator that does not use default Serdes from StreamsConfig need to set the correct Serdes.

Thus, also the count() operation need to specify corresponding String and Long Serdes:

```<code>countries.count(TimeWindows.of(60 * 1000L), "UserCountStore");
</code>```

All operators that might need Serdes have appropriate overload. Just check out all overload of all operators you are using.

Check out the docs for more details: https://docs.confluent.io/current/streams/developer-guide/dsl-api.html

Body:
I am producing input data as json string .

For Topic - myinput

{"time":"2017-11-28T09:42:26.776Z","name":"Lane1","oclass"
     :"myClass","id":112553,"Scope":"198S"}

My class looking like this:

public class App {
    static public class CountryMessage {

        public String time;
        public String Scope;
        public String id;
        public String oclass;
        public String name;
    }

    private static final String APP_ID = "countries-streaming-analysis-app";

    public static void main(String[] args) {
        System.out.println("Kafka Streams Demonstration");

        StreamsConfig config = new StreamsConfig(getProperties());
        final Serde < String > stringSerde = Serdes.String();
        final Serde < Long > longSerde = Serdes.Long();

        Map < String, Object > serdeProps = new HashMap < > ();
        final Serializer < CountryMessage > countryMessageSerializer = new JsonPOJOSerializer < > ();
        serdeProps.put("JsonPOJOClass", CountryMessage.class);
        countryMessageSerializer.configure(serdeProps, false);

        final Deserializer < CountryMessage > countryMessageDeserializer = new JsonPOJODeserializer < > ();
        serdeProps.put("JsonPOJOClass", CountryMessage.class);
        countryMessageDeserializer.configure(serdeProps, false);
        final Serde < CountryMessage > countryMessageSerde = Serdes.serdeFrom(countryMessageSerializer,countryMessageDeserializer);

        KStreamBuilder kStreamBuilder = new KStreamBuilder();
        KStream<String, CountryMessage> countriesStream = kStreamBuilder.stream(stringSerde, countryMessageSerde, "vanitopic");

        KGroupedStream<String, CountryMessage> countries = countriesStream.selectKey((k, traffic) -> traffic.Scope).groupByKey();

        KTable<Windowed<String>, Long> aggregatedStream = countries.count(TimeWindows.of(60 * 1000L), "UserCountStore");

        System.out.println("Starting Kafka Streams Countries Example");
        KafkaStreams kafkaStreams = new KafkaStreams(kStreamBuilder, config);
        kafkaStreams.start();
        System.out.println("Now started CountriesStreams Example");
    }

    private static Properties getProperties() {
        Properties settings = new Properties();

        settings.put(StreamsConfig.APPLICATION_ID_CONFIG, APP_ID);
        settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "10.106.9.235:9092,10.106.9.235:9093,10.106.9.235:9094");
        settings.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "10.106.9.235:2181");
        //settings.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        //settings.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        return settings;
    }
}

I am getting bellow class cast exception:

Exception in thread
  "countries-streaming-analysis-app-f7f95119-4401-4a6e-8060-5a138ffaddb2-StreamThread-1"
  org.apache.kafka.streams.errors.StreamsException: Exception caught in
  process. taskId=0_0, processor=KSTREAM-SOURCE-0000000000,
  topic=vanitopic, partition=0, offset=2036     at
  org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:203)
    at
  org.apache.kafka.streams.processor.internals.StreamThread.processAndPunctuate(StreamThread.java:679)
    at
  org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:557)
    at
  org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:527)
  Caused by: org.apache.kafka.streams.errors.StreamsException: A
  serializer (key:
  org.apache.kafka.common.serialization.ByteArraySerializer / value:
  org.apache.kafka.common.serialization.ByteArraySerializer) is not
  compatible to the actual key or value type (key type: java.lang.String
  / value type: com.cisco.streams.countries.App$CountryMessage). Change
  the default Serdes in StreamConfig or provide correct Serdes via
  method parameters.    at
  org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:91)
    at
  org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:82)
    at
  org.apache.kafka.streams.kstream.internals.KStreamFilter$KStreamFilterProcessor.process(KStreamFilter.java:43)
    at
  org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:47)
    at
  org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:187)
    at
  org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:133)
    at
  org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:82)
    at
  org.apache.kafka.streams.kstream.internals.KStreamMap$KStreamMapProcessor.process(KStreamMap.java:42)
    at
  org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:47)
    at
  org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:187)
    at
  org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:133)
    at
  org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:82)
    at
  org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:80)
    at
  org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:189)
    ... 3 more Caused by: java.lang.ClassCastException: java.lang.String
  cannot be cast to [B  at
  org.apache.kafka.common.serialization.ByteArraySerializer.serialize(ByteArraySerializer.java:21)
    at
  org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:88)
    at
  org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:76)
    at
  org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:87)
    ... 16 more

I need help to understand how and where to apply custom Serdes those I have created

Body:
In your code,

KGroupedStream<String, CountryMessage> countries = countriesStream.selectKey((k, traffic) -> traffic.Scope).groupByKey();

the groupByKey() need to set both serializer as this will trigger a data repartitioning. Or you set default Serded to for String and CountryMessage types.

As mentioned in my comment, every operator that does not use default Serdes from StreamsConfig need to set the correct Serdes.

Thus, also the count() operation need to specify corresponding String and Long Serdes:

countries.count(TimeWindows.of(60 * 1000L), "UserCountStore");

All operators that might need Serdes have appropriate overload. Just check out all overload of all operators you are using.

Check out the docs for more details: https://docs.confluent.io/current/streams/developer-guide/dsl-api.html


问:
MongoDB filter for specific data in Array and return only specific fields in the output
I have a below structure maintained in a sample collection.

```<code>{
  "_id": "1",
  "name": "Stock1",
  "description": "Test Stock",
  "lines": [
    {
      "lineNumber": "1",
      "priceInfo": {
        "buyprice": 10,
        "sellprice": 15
      },
      "item": {
        "id": "BAT10001",
        "name": "CricketBat",
        "description": "Cricket bat"
      },
      "quantity": 10
    },
    {
      "lineNumber": "2",
      "priceInfo": {
        "buyprice": 10,
        "sellprice": 15
      },
      "item": {
        "id": "BAT10002",
        "name": "CricketBall",
        "description": "Cricket ball"
      },
      "quantity": 10
    },
    {
      "lineNumber": "3",
      "priceInfo": {
        "buyprice": 10,
        "sellprice": 15
      },
      "item": {
        "id": "BAT10003",
        "name": "CricketStumps",
        "description": "Cricket stumps"
      },
      "quantity": 10
    }
  ]
}
</code>```

I have a scenario where i will be given lineNumber and item.id, i need to filter the above collection based on lineNumber and item.id and i need to project only selected fields.

Expected output below:

```<code>{
  "_id": "1",
  "lines": [
    {
      "lineNumber": "1",
      "item": {
        "id": "BAT10001",
        "name": "CricketBat",
        "description": "Cricket bat"
      },
      "quantity": 10
    }
  ]
}
</code>```

Note: I may not get lineNumber all the times, if lineNumber is null then i should filter for item.id alone and get the above mentioned output.The main purpose is to reduce the number of fields in the output, as the collection is expected to hold huge number of fields.

I tried the below query,

```<code>db.sample.aggregate([
{ "$match" : { "_id" : "1"} ,
{ "$project" : { "lines" : { "$filter" : { "input" : "$lines" , "as" : "line" , "cond" :
    { "$and" : [ { "$eq" : [ "$$line.lineNumber" , "3"]} , { "$eq" : [ "$$line.item.id" , "BAT10001"]}]}}}}}
])
</code>```

But i got all the fields, i'm not able to exclude or include the required fields.

答:
I tried the below query and it worked for me,

```<code>db.Collection.aggregate([
{ $match: { _id: '1' } },
{
  $project: {
    lines: {
      $map: {
        input: {
          $filter: {
            input: '$lines',
            as: 'line',
            cond: {
              $and: [
                { $eq: ['$$line.lineNumber', '3'] },
                { $eq: ['$$line.item.id', 'BAT10001'] },
              ],
            },
          },
        },
        as: 'line',
        in: {
          lineNumber: '$$line.lineNumber',
          item: '$$line.item',
          quantity: '$$line.quantity',
        },
      },
    },
  },
},
</code>```

])

Body:
I have a below structure maintained in a sample collection.

{
  "_id": "1",
  "name": "Stock1",
  "description": "Test Stock",
  "lines": [
    {
      "lineNumber": "1",
      "priceInfo": {
        "buyprice": 10,
        "sellprice": 15
      },
      "item": {
        "id": "BAT10001",
        "name": "CricketBat",
        "description": "Cricket bat"
      },
      "quantity": 10
    },
    {
      "lineNumber": "2",
      "priceInfo": {
        "buyprice": 10,
        "sellprice": 15
      },
      "item": {
        "id": "BAT10002",
        "name": "CricketBall",
        "description": "Cricket ball"
      },
      "quantity": 10
    },
    {
      "lineNumber": "3",
      "priceInfo": {
        "buyprice": 10,
        "sellprice": 15
      },
      "item": {
        "id": "BAT10003",
        "name": "CricketStumps",
        "description": "Cricket stumps"
      },
      "quantity": 10
    }
  ]
}

I have a scenario where i will be given lineNumber and item.id, i need to filter the above collection based on lineNumber and item.id and i need to project only selected fields.

Expected output below:

{
  "_id": "1",
  "lines": [
    {
      "lineNumber": "1",
      "item": {
        "id": "BAT10001",
        "name": "CricketBat",
        "description": "Cricket bat"
      },
      "quantity": 10
    }
  ]
}

Note: I may not get lineNumber all the times, if lineNumber is null then i should filter for item.id alone and get the above mentioned output.The main purpose is to reduce the number of fields in the output, as the collection is expected to hold huge number of fields.

I tried the below query,

db.sample.aggregate([
{ "$match" : { "_id" : "1"} ,
{ "$project" : { "lines" : { "$filter" : { "input" : "$lines" , "as" : "line" , "cond" :
    { "$and" : [ { "$eq" : [ "$$line.lineNumber" , "3"]} , { "$eq" : [ "$$line.item.id" , "BAT10001"]}]}}}}}
])

But i got all the fields, i'm not able to exclude or include the required fields.

Body:
I tried the below query and it worked for me,

db.Collection.aggregate([
{ $match: { _id: '1' } },
{
  $project: {
    lines: {
      $map: {
        input: {
          $filter: {
            input: '$lines',
            as: 'line',
            cond: {
              $and: [
                { $eq: ['$$line.lineNumber', '3'] },
                { $eq: ['$$line.item.id', 'BAT10001'] },
              ],
            },
          },
        },
        as: 'line',
        in: {
          lineNumber: '$$line.lineNumber',
          item: '$$line.item',
          quantity: '$$line.quantity',
        },
      },
    },
  },
},

])

ContentLicense: CC BY-SA 4.0


问:
SIM800L Blank SMS issue
I am using a SIM800L module with a Texas Instrument Launchpad, with a MSP430G2553 microcontroller, not using an external library for SIM800L.

Problem Statement:
A Simple text message (SMS with Text Mode) is sent, received as a blank message on cellphone.

SIM details:

1. SIM 1 : Location: India. Operator: AirTel, 4G compatible SIM Card.

 2. SIM 2 : Location: India. Operator: Tata Docomo, 3G compatible SIM card.

What I know already:

UART Drivers in firmware are tested and working, non-polling, interrupt driven.

No blocking time delays added as a substitute to read responses of AT commands. I read the response and proceed only if positive acknowledgement is received, <CR><LF>OK<CR><LF> for most of the commands.

I have confirmed the data bits transmitted and received on Tx-Rx pins by means of an oscilloscope. Everything seems as expected, including voltage levels.

What I have read:

Some speculation through unofficial sources (Of course forums) that SIM800L is only 2G compatible.

(Shallow reading from wikipedia) I have read through GSM 3.38 and GSM 3.40, and the Data Coding Scheme section for understanding how the encoding of text is handled in suited/relevant AT command (AT+CSMP).

Various forums including the ones for arduino with which SIM800L modules are very popularly used.

Related posts on Stackoverflow:

Recieving Blank SMS SIM800 using AT Commands and Python on Raspberry Pi 2

How to send SMS with GSM module SIM800 and Arduino Uno?

Sending GSM Character Set in SMS with SIM800L Module

The answer in the first one seemed to have worked for him, it didn't work for me.

What have I tried:

I have used the same module with an instance of Docklight serial terminal. SMS sent from Docklight are received on my cellphone and appear as expected, not blank.

On day 0, before integrating module with Launchpad hardware, I have tested the overall firmware state machine with exact copy of expected responses from SIM800L.

The results for both the SIM cards are same, except for some of the initial configurations, but I load a typical set of configuration in both of them before I initiate any SMS related task.

Typical values that I use are:

Echo Off

CSMP: 17, 167, 0, 0 (I have tried 17, 167, 0, 0, but no luck). Default from SIM 1 is 17,11,0,246, and that from SIM 2 is 17, 255, 0, 0.

CSCS: "IRA"

Failed combinations on serial port:  (SIM 1 and SIM 2)

CSMP: 17, 11, 0, 246 | CSCS: "IRA" - Sends a blank SMS

CSMP: 17, 11, 0, 246 | CSCS: "GSM" - Sends a blank SMS

CSMP: 17, 11, 0, 246 | CSCS: "HEX" - Sends a blank SMS

Successful combinations on serial port:  (SIM 1 and SIM 2)

CSMP: 17, 167, 0, 0  | CSCS: "IRA"

CSMP: 17, 167, 0, 8  | CSCS: "IRA"

CSMP: 17, 11, 0, 0   | CSCS: "GSM"

CSMP: 17, 167, 0, 0  | CSCS: "GSM"

CSMP: 17, 167, 0, 8  | CSCS: "GSM"

To be honest, I played hunch with these combinations before I studied what field reflects what change these combinations (which are poorly documented in the SIM800L User guide).

Any idea what I might be missing here? I am open to thinking that it is more of a RTFM (Read The Fat Manual) issue.

答:
Ok, managed to resolve the issue.

It was not about the SIM800L at all.
The whole payload was followed by a '\0' which is unexpected (I know, very poor on my side). The serial term has no issues with it whatsoever.
Debugging was fun!

Title: SIM800L Blank SMS issue


问:
Tracking how many hours users spend on my website
I am writing a usersystem and as a statistic available for all my users I want to be able to provide them with the amount of hours they've been active on my website.

my original idea as to how to do this was:
user loads a page, and a record for the user is stored in a SQL table called accessLog
*user loads another page, sql query runs to see when they last visited a page*
if the user visited a page within the past two minutes, update their user account and add the time spent online
*insert a new record into accessLog*

however this would mean adding a potential of 4 additional queries to every single page of my website, which seems slow. I was thinking, there has got to be a more efficient way of tracking user activity online that I'm clearly too stupid to see!

答:
first choose a duration beyond which a session is considered interrupted. (ex: 10 minutes)

log all page load with all ip in database

if time between 2 page load for one ip is more than duration don't add this time to the total time for this ip

if time between 2 page load for one ip is less than duration add this time to the total time for this ip

2 problem is :
- if user stay more than duration (10 minutes) in a page without refresh he's considered as disconnected.
- the last page duration is not saved

Piwik works like that


问:
How to use result of pattern matching in R
I have a dataframe with string values

```<code>id str
a  1
b  10
c  0
d  102
e  010
</code>```

I need to create a flag such that if there is a 0 in the str, the flag is 1 else, the flag is 0

I'm using the following code :

```<code>df$flag <-ifelse(grep('0', df$str) == "1", 1, 0)
</code>```

But this returns less rows than the number of total rows in df.

On inspection i found that

```<code>grep('0', df$str[1]) returns int(0)
</code>```

whereas
    grep('0', df$str[2]) returns 1

Any idea how I could use this

答:
```<code>#df$flag <- NULL #unneeded. skip it.
df$flag <- ifelse(grepl('0',df$str), 1, 0)
</code>```

You need grepl instead of grep

Body:
I have a dataframe with string values

id str
a  1
b  10
c  0
d  102
e  010

I need to create a flag such that if there is a 0 in the str, the flag is 1 else, the flag is 0

I'm using the following code :

df$flag <-ifelse(grep('0', df$str) == "1", 1, 0)

But this returns less rows than the number of total rows in df.

On inspection i found that

grep('0', df$str[1]) returns int(0)

whereas
    grep('0', df$str[2]) returns 1

Any idea how I could use this

Body:
#df$flag <- NULL #unneeded. skip it.
df$flag <- ifelse(grepl('0',df$str), 1, 0)

You need grepl instead of grep


问:
Programming style of method declaration of get/set method variables in C++?
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp. </p>

答: I pretty much always follow the division of declaring them in the header, and defining in the source. Every time I don't, I end up having to go back and do it any way later.</p>

LastEditorDisplayName: Eddie Parker

OwnerDisplayName: Adam


问:
Rails 2.3.x - how does this ActiveRecord scope work?
There's a named_scope in a project I'm working on that looks like the following:

```<code> # default product scope only lists available and non-deleted products
  ::Product.named_scope :active,      lambda { |*args|
    Product.not_deleted.available(args.first).scope(:find)
  }
</code>```

The initial named_scope makes sense. The confusing part here is how .scope(:find) works. This is clearly calling another named scope (not_deleted), and applying .scope(:find) afterwards. What/how does .scope(:find) work here?

答:
Scope is a method on ActiveRecord::Base that returns the current scope for the method passed in (what would actually be used to build the query if you were to run it at this moment).

```<code># Retrieve the scope for the given method and optional key.
def scope(method, key = nil) #:nodoc:
  if current_scoped_methods && (scope = current_scoped_methods[method])
    key ? scope[key] : scope
  end
end
</code>```

So in your example, the lambda returns the scope for a Product.find call after merging all the other named scopes.

I have a named_scope:

```<code>named_scope :active, {:conditions => {:active => true}}
</code>```

In my console output, Object.active.scope(:find) returns:

```<code>{:conditions => {:active => true}}
</code>```

Body:
There's a named_scope in a project I'm working on that looks like the following:

 # default product scope only lists available and non-deleted products
  ::Product.named_scope :active,      lambda { |*args|
    Product.not_deleted.available(args.first).scope(:find)
  }

The initial named_scope makes sense. The confusing part here is how .scope(:find) works. This is clearly calling another named scope (not_deleted), and applying .scope(:find) afterwards. What/how does .scope(:find) work here?

Body:
Scope is a method on ActiveRecord::Base that returns the current scope for the method passed in (what would actually be used to build the query if you were to run it at this moment).

# Retrieve the scope for the given method and optional key.
def scope(method, key = nil) #:nodoc:
  if current_scoped_methods && (scope = current_scoped_methods[method])
    key ? scope[key] : scope
  end
end

So in your example, the lambda returns the scope for a Product.find call after merging all the other named scopes.

I have a named_scope:

named_scope :active, {:conditions => {:active => true}}

In my console output, Object.active.scope(:find) returns:

{:conditions => {:active => true}}


问:
How to replace a ' from a String in python
I am trying to remove a " ' " character from a python string .
Below code gives a syntax error, How to achieve this task  </p>

```<code>final = string.replace(old_str, '\'', '')
</code>```

答:
To replace single quotes</p>

```<code>final = old_str.replace("'", "")
</code>```

Body:
I am trying to remove a " ' " character from a python string .
Below code gives a syntax error, How to achieve this task

final = string.replace(old_str, '\'', '')

Body:
To replace single quotes

final = old_str.replace("'", "")


问:
textFieldDidEndEditing not firing when pickerviiew used in swift3
The text field delegate method textFieldDidEndEditing is not firing when picker view is used in Swift 3. How can I call it? There is no button to dynamically call the delegate.

You can see my code below.

```<code>import UIKit

class ThroewViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate {

    @IBOutlet weak var pickerText: UITextField!

    let thePicker = UIPickerView()
    var dashTitle_Arr = ["One","Two","Three","Four","Five","Six"]

    override func viewDidLoad() {
        super.viewDidLoad()

        pickerText.delegate = self
       thePicker.dataSource = self
        thePicker.delegate = self
       pickerText.inputView = thePicker

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return dashTitle_Arr .count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return dashTitle_Arr [row]     }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        pickerText.text = dashTitle_Arr [row]

    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        addIntoArray(text: textField.text)
    }

    func addIntoArray(text: String?) {

        guard let text = text, text.characters.count > 0 else {

            return
        }

        dashTitle_Arr.append(text)
        thePicker.reloadAllComponents()
    }
}
</code>```

答:
There is a property of picker-view is accessoriesView. Create a tool bar with done or cancel button and set it in the picker view's assessoriesView.

In the toolbar button action write the textfield.resignFirstResponder()
After that the textFieldDidEndEditing delegate method fired

It works fine for me. Hope it will helps you. Thank you

Body:
The text field delegate method textFieldDidEndEditing is not firing when picker view is used in Swift 3. How can I call it? There is no button to dynamically call the delegate.

You can see my code below.

import UIKit

class ThroewViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate {

    @IBOutlet weak var pickerText: UITextField!

    let thePicker = UIPickerView()
    var dashTitle_Arr = ["One","Two","Three","Four","Five","Six"]

    override func viewDidLoad() {
        super.viewDidLoad()

        pickerText.delegate = self
       thePicker.dataSource = self
        thePicker.delegate = self
       pickerText.inputView = thePicker

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return dashTitle_Arr .count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return dashTitle_Arr [row]     }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        pickerText.text = dashTitle_Arr [row]

    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        addIntoArray(text: textField.text)
    }

    func addIntoArray(text: String?) {

        guard let text = text, text.characters.count > 0 else {

            return
        }

        dashTitle_Arr.append(text)
        thePicker.reloadAllComponents()
    }
}


问:
How to expand allocated memory in place
Is there something like std::realloc but do nothing if it fails to expand the existing memory (of course it will let you know it failed)?

I mean truly expand in place. Not copy to a newly created memory chunk.

答:
No, there is no such function.

From your comments, I suppose that the following might be of interest to you: `std::realloc` for non-POD types and What is C++ version of realloc(), to allocate the new buffer and copy the contents from the old one?

PS: Re-approach your problem, since the existing methology is most usually enough.

Title: How to expand allocated memory in place


问:
Get back the changes after accidental checkout?
The following was the status of my repo.

```<code>[~/rails_apps/jekyll_apps/nepalonrails (design)⚡] ➔ gst
# On branch design
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   _layouts/default.html
#   deleted:    _site/blog/2010/04/07/welcome-to-niraj-blog/index.html
#   deleted:    _site/blog/2010/04/08/the-code-syntax-highlight/index.html
#   deleted:    _site/blog/2010/05/01/showing-demo-to-kalyan/index.html
#   deleted:    _site/config.ru
#   deleted:    _site/index.html
#   deleted:    _site/static/css/style.css
#   deleted:    _site/static/css/syntax.css
#   modified:   static/css/style.css
#
no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Accedently, I did git checkout -f and now the changes are gone which I wasnt supposed to do.

```<code>[~/rails_apps/jekyll_apps/nepalonrails (design)⚡] ➔ git co -f
[~/rails_apps/jekyll_apps/nepalonrails (design)] ➔ gst
# On branch design
nothing to commit (working directory clean)
[~/rails_apps/jekyll_apps/nepalonrails (design)] ➔
</code>```

Can I get back the changes back?

答:
There is nothing you can do with git commands but if you are using IDE then you can recover your changes.
I am using PhpStorm where we can see file changes history.
Simply right-click on file and click on show local history.
Under External changes tab, you can find your local changes which you have accidentally removed.</p>

Body:
The following was the status of my repo.

[~/rails_apps/jekyll_apps/nepalonrails (design)⚡] ➔ gst
# On branch design
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   _layouts/default.html
#   deleted:    _site/blog/2010/04/07/welcome-to-niraj-blog/index.html
#   deleted:    _site/blog/2010/04/08/the-code-syntax-highlight/index.html
#   deleted:    _site/blog/2010/05/01/showing-demo-to-kalyan/index.html
#   deleted:    _site/config.ru
#   deleted:    _site/index.html
#   deleted:    _site/static/css/style.css
#   deleted:    _site/static/css/syntax.css
#   modified:   static/css/style.css
#
no changes added to commit (use "git add" and/or "git commit -a")

Accedently, I did git checkout -f and now the changes are gone which I wasnt supposed to do.

[~/rails_apps/jekyll_apps/nepalonrails (design)⚡] ➔ git co -f
[~/rails_apps/jekyll_apps/nepalonrails (design)] ➔ gst
# On branch design
nothing to commit (working directory clean)
[~/rails_apps/jekyll_apps/nepalonrails (design)] ➔

Can I get back the changes back?


问:
How to automate git pull origin without needing to comment?
I have a remote server on which I run a number of scripts.
I just run my scripts on that server, and do my editing and saving and pushing to bitbucket cloud as my origin repository from other locations.

How do I automate the "git pull origin" command for that windows server.
This isnt about running a command or script in the Task Scheduler, but more like I have to manually comment everytime when I do a "git pull origin".

I just wish to run "git pull origin" to make sure my scripts are up to date on the server in the morning before running.

But I am having trouble doing it without being forced to manually enter a message or other manual behavior.

Maybe do I have a setting wrong?

答:
I think for this you use git pull origin --rebase right

No: weather you are doing a merge (pull) or a rebase (pull --rebase), any concurrent modification on the same set of files would potentially involve conflicts, to be resolved manually.

If you see the same conflict over and over again, do consider git rerere, that I detail here.

That, or maintain a separate clone of the repo, in which you make no modification, and can do a git pull without ever having to enter any comment.


问:
How to get the location of the DLL currently executing?
I have a config file that I need to load as part of the execution of a dll I am writing.

The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.

For example, I put the dll and xml file here:

D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins

But if I try to reference the xml file (in my dll) like this:

```<code>XDocument doc = XDocument.Load(@".\AggregatorItems.xml")
</code>```

then .\AggregatorItems.xml translates to:

C:\windows\system32\inetsrv\AggregatorItems.xml

So, I need to find a way (I hope) of knowing where the dll that is currently executing is located.  Basically I am looking for this:

```<code>XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")
</code>```

答:
You are looking for System.Reflection.Assembly.GetExecutingAssembly()

```<code>string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
</code>```

Note:

The .Location property returns the location of the currently running DLL file.

Under some conditions the DLL is shadow copied before execution, and the .Location property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase property instead.

.CodeBase contains a prefix (file:\), which you may need to remove.

Body:
I have a config file that I need to load as part of the execution of a dll I am writing.

The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.

For example, I put the dll and xml file here:

D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins

But if I try to reference the xml file (in my dll) like this:

XDocument doc = XDocument.Load(@".\AggregatorItems.xml")

then .\AggregatorItems.xml translates to:

C:\windows\system32\inetsrv\AggregatorItems.xml

So, I need to find a way (I hope) of knowing where the dll that is currently executing is located.  Basically I am looking for this:

XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")

Body:
You are looking for System.Reflection.Assembly.GetExecutingAssembly()

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");

Note:

The .Location property returns the location of the currently running DLL file.

Under some conditions the DLL is shadow copied before execution, and the .Location property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase property instead.

.CodeBase contains a prefix (file:\), which you may need to remove.