问:
Extracting DCT coefficients from encoded images and video
Is there a way to easily extract the DCT coefficients (and quantization parameters) from encoded images and video?  Any decoder software must be using them to decode block-DCT encoded images and video.  So I'm pretty sure the decoder knows what they are.  Is there a way to expose them to whomever is using the decoder?

I'm implementing some video quality assessment algorithms that work directly in the DCT domain.  Currently, the majority of my code uses OpenCV, so it would be great if anyone knows of a solution using that framework.  I don't mind using other libraries (perhaps libjpeg, but that seems to be for still images only), but my primary concern is to do as little format-specific work as possible (I don't want to reinvent the wheel and write my own decoders).  I want to be able to open any video/image (H.264, MPEG, JPEG, etc) that OpenCV can open, and if it's block DCT-encoded, to get the DCT coefficients.

In the worst case, I know that I can write up my own block DCT code, run the decompressed frames/images through it and then I'd be back in the DCT domain.  That's hardly an elegant solution, and I hope I can do better.

Presently, I use the fairly common OpenCV boilerplate to open images:

```<code>IplImage *image = cvLoadImage(filename);
// Run quality assessment metric
</code>```

The code I'm using for video is equally trivial:

```<code>CvCapture *capture = cvCaptureFromAVI(filename);
while (cvGrabFrame(capture))
{
    IplImage *frame = cvRetrieveFrame(capture);
    // Run quality assessment metric on frame
}
cvReleaseCapture(&capture);
</code>```

In both cases, I get a 3-channel IplImage in BGR format.  Is there any way I can get the DCT coefficients as well?

答:
Well, I did a bit of reading and my original question seems to be an instance of wishful thinking.

Basically, it's not possible to get the DCT coefficients from H.264 video frames for the simple reason that H.264 doesn't use DCT.  It uses a different transform (integer transform).  Next, the coefficients for that transform don't necessarily change on a frame-by-frame basis -- H.264 is smarter cause it splits up frames into slices.  It should be possible to get those coefficients through a special decoder, but I doubt OpenCV exposes it for the user.

For JPEG, things are a bit more positive.  As I suspected, libjpeg exposes the DCT coefficients for you.  I wrote a small app to show that it works (source at the end).  It makes a new image using the DC term from each block.  Because the DC term is equal to the block average (after proper scaling), the DC images are downsampled versions of the input JPEG image.

EDIT: fixed scaling in source

Original image (512 x 512):

DC images (64x64): luma Cr Cb RGB

Source (C++):

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

#include <cv.h>
#include <highgui.h>

extern "C"
{
#include "jpeglib.h"
#include <setjmp.h>
}

#define DEBUG 0
#define OUTPUT_IMAGES 1

/*
 * Extract the DC terms from the specified component.
 */
IplImage *
extract_dc(j_decompress_ptr cinfo, jvirt_barray_ptr *coeffs, int ci)
{
    jpeg_component_info *ci_ptr = &cinfo->comp_info[ci];
    CvSize size = cvSize(ci_ptr->width_in_blocks, ci_ptr->height_in_blocks);
    IplImage *dc = cvCreateImage(size, IPL_DEPTH_8U, 1);
    assert(dc != NULL);

    JQUANT_TBL *tbl = ci_ptr->quant_table;
    UINT16 dc_quant = tbl->quantval[0];

#if DEBUG
    printf("DCT method: %x\n", cinfo->dct_method);
    printf
    (
        "component: %d (%d x %d blocks) sampling: (%d x %d)\n",
        ci,
        ci_ptr->width_in_blocks,
        ci_ptr->height_in_blocks,
        ci_ptr->h_samp_factor,
        ci_ptr->v_samp_factor
    );

    printf("quantization table: %d\n", ci);
    for (int i = 0; i < DCTSIZE2; ++i)
    {
        printf("% 4d ", (int)(tbl->quantval[i]));
        if ((i + 1) % 8 == 0)
            printf("\n");
    }

    printf("raw DC coefficients:\n");
#endif

    JBLOCKARRAY buf =
    (cinfo->mem->access_virt_barray)
    (
        (j_common_ptr)cinfo,
        coeffs[ci],
        0,
        ci_ptr->v_samp_factor,
        FALSE
    );
    for (int sf = 0; (JDIMENSION)sf < ci_ptr->height_in_blocks; ++sf)
    {
        for (JDIMENSION b = 0; b < ci_ptr->width_in_blocks; ++b)
        {
            int intensity = 0;

            intensity = buf[sf][b][0]*dc_quant/DCTSIZE + 128;
            intensity = MAX(0,   intensity);
            intensity = MIN(255, intensity);

            cvSet2D(dc, sf, (int)b, cvScalar(intensity));

#if DEBUG
            printf("% 2d ", buf[sf][b][0]);
#endif
        }
#if DEBUG
        printf("\n");
#endif
    }

    return dc;

}

IplImage *upscale_chroma(IplImage *quarter, CvSize full_size)
{
    IplImage *full = cvCreateImage(full_size, IPL_DEPTH_8U, 1);
    cvResize(quarter, full, CV_INTER_NN);
    return full;
}

GLOBAL(int)
read_JPEG_file (char * filename, IplImage **dc)
{
  /* This struct contains the JPEG decompression parameters and pointers to
   * working space (which is allocated as needed by the JPEG library).
   */
  struct jpeg_decompress_struct cinfo;

  struct jpeg_error_mgr jerr;
  /* More stuff */
  FILE * infile;        /* source file */

  /* In this example we want to open the input file before doing anything else,
   * so that the setjmp() error recovery below can assume the file is open.
   * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
   * requires it in order to read binary files.
   */

  if ((infile = fopen(filename, "rb")) == NULL) {
    fprintf(stderr, "can't open %s\n", filename);
    return 0;
  }

  /* Step 1: allocate and initialize JPEG decompression object */

  cinfo.err = jpeg_std_error(&jerr);

  /* Now we can initialize the JPEG decompression object. */
  jpeg_create_decompress(&cinfo);

  /* Step 2: specify data source (eg, a file) */

  jpeg_stdio_src(&cinfo, infile);

  /* Step 3: read file parameters with jpeg_read_header() */

  (void) jpeg_read_header(&cinfo, TRUE);
  /* We can ignore the return value from jpeg_read_header since
   *   (a) suspension is not possible with the stdio data source, and
   *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
   * See libjpeg.txt for more info.
   */

  /* Step 4: set parameters for decompression */

  /* In this example, we don't need to change any of the defaults set by
   * jpeg_read_header(), so we do nothing here.
   */

  jvirt_barray_ptr *coeffs = jpeg_read_coefficients(&cinfo);

  IplImage *y    = extract_dc(&cinfo, coeffs, 0);
  IplImage *cb_q = extract_dc(&cinfo, coeffs, 1);
  IplImage *cr_q = extract_dc(&cinfo, coeffs, 2);

  IplImage *cb = upscale_chroma(cb_q, cvGetSize(y));
  IplImage *cr = upscale_chroma(cr_q, cvGetSize(y));

  cvReleaseImage(&cb_q);
  cvReleaseImage(&cr_q);

#if OUTPUT_IMAGES
  cvSaveImage("y.png",   y);
  cvSaveImage("cb.png", cb);
  cvSaveImage("cr.png", cr);
#endif

  *dc = cvCreateImage(cvGetSize(y), IPL_DEPTH_8U, 3);
  assert(dc != NULL);

  cvMerge(y, cr, cb, NULL, *dc);

  cvReleaseImage(&y);
  cvReleaseImage(&cb);
  cvReleaseImage(&cr);

  /* Step 7: Finish decompression */

  (void) jpeg_finish_decompress(&cinfo);
  /* We can ignore the return value since suspension is not possible
   * with the stdio data source.
   */

  /* Step 8: Release JPEG decompression object */

  /* This is an important step since it will release a good deal of memory. */
  jpeg_destroy_decompress(&cinfo);

  fclose(infile);

  return 1;
}

int
main(int argc, char **argv)
{
    int ret = 0;
    if (argc != 2)
    {
        fprintf(stderr, "usage: %s filename.jpg\n", argv[0]);
        return 1;
    }
    IplImage *dc = NULL;
    ret = read_JPEG_file(argv[1], &dc);
    assert(dc != NULL);

    IplImage *rgb = cvCreateImage(cvGetSize(dc), IPL_DEPTH_8U, 3);
    cvCvtColor(dc, rgb, CV_YCrCb2RGB);

#if OUTPUT_IMAGES
    cvSaveImage("rgb.png", rgb);
#else
    cvNamedWindow("DC", CV_WINDOW_AUTOSIZE);
    cvShowImage("DC", rgb);
    cvWaitKey(0);
#endif

    cvReleaseImage(&dc);
    cvReleaseImage(&rgb);

    return 0;
}
</code>```

Body:
Is there a way to easily extract the DCT coefficients (and quantization parameters) from encoded images and video?  Any decoder software must be using them to decode block-DCT encoded images and video.  So I'm pretty sure the decoder knows what they are.  Is there a way to expose them to whomever is using the decoder?

I'm implementing some video quality assessment algorithms that work directly in the DCT domain.  Currently, the majority of my code uses OpenCV, so it would be great if anyone knows of a solution using that framework.  I don't mind using other libraries (perhaps libjpeg, but that seems to be for still images only), but my primary concern is to do as little format-specific work as possible (I don't want to reinvent the wheel and write my own decoders).  I want to be able to open any video/image (H.264, MPEG, JPEG, etc) that OpenCV can open, and if it's block DCT-encoded, to get the DCT coefficients.

In the worst case, I know that I can write up my own block DCT code, run the decompressed frames/images through it and then I'd be back in the DCT domain.  That's hardly an elegant solution, and I hope I can do better.

Presently, I use the fairly common OpenCV boilerplate to open images:

IplImage *image = cvLoadImage(filename);
// Run quality assessment metric

The code I'm using for video is equally trivial:

CvCapture *capture = cvCaptureFromAVI(filename);
while (cvGrabFrame(capture))
{
    IplImage *frame = cvRetrieveFrame(capture);
    // Run quality assessment metric on frame
}
cvReleaseCapture(&capture);

In both cases, I get a 3-channel IplImage in BGR format.  Is there any way I can get the DCT coefficients as well?

Body:
Well, I did a bit of reading and my original question seems to be an instance of wishful thinking.

Basically, it's not possible to get the DCT coefficients from H.264 video frames for the simple reason that H.264 doesn't use DCT.  It uses a different transform (integer transform).  Next, the coefficients for that transform don't necessarily change on a frame-by-frame basis -- H.264 is smarter cause it splits up frames into slices.  It should be possible to get those coefficients through a special decoder, but I doubt OpenCV exposes it for the user.

For JPEG, things are a bit more positive.  As I suspected, libjpeg exposes the DCT coefficients for you.  I wrote a small app to show that it works (source at the end).  It makes a new image using the DC term from each block.  Because the DC term is equal to the block average (after proper scaling), the DC images are downsampled versions of the input JPEG image.

EDIT: fixed scaling in source

Original image (512 x 512):

DC images (64x64): luma Cr Cb RGB

Source (C++):

#include <stdio.h>
#include <assert.h>

#include <cv.h>
#include <highgui.h>

extern "C"
{
#include "jpeglib.h"
#include <setjmp.h>
}

#define DEBUG 0
#define OUTPUT_IMAGES 1

/*
 * Extract the DC terms from the specified component.
 */
IplImage *
extract_dc(j_decompress_ptr cinfo, jvirt_barray_ptr *coeffs, int ci)
{
    jpeg_component_info *ci_ptr = &cinfo->comp_info[ci];
    CvSize size = cvSize(ci_ptr->width_in_blocks, ci_ptr->height_in_blocks);
    IplImage *dc = cvCreateImage(size, IPL_DEPTH_8U, 1);
    assert(dc != NULL);

    JQUANT_TBL *tbl = ci_ptr->quant_table;
    UINT16 dc_quant = tbl->quantval[0];

#if DEBUG
    printf("DCT method: %x\n", cinfo->dct_method);
    printf
    (
        "component: %d (%d x %d blocks) sampling: (%d x %d)\n",
        ci,
        ci_ptr->width_in_blocks,
        ci_ptr->height_in_blocks,
        ci_ptr->h_samp_factor,
        ci_ptr->v_samp_factor
    );

    printf("quantization table: %d\n", ci);
    for (int i = 0; i < DCTSIZE2; ++i)
    {
        printf("% 4d ", (int)(tbl->quantval[i]));
        if ((i + 1) % 8 == 0)
            printf("\n");
    }

    printf("raw DC coefficients:\n");
#endif

    JBLOCKARRAY buf =
    (cinfo->mem->access_virt_barray)
    (
        (j_common_ptr)cinfo,
        coeffs[ci],
        0,
        ci_ptr->v_samp_factor,
        FALSE
    );
    for (int sf = 0; (JDIMENSION)sf < ci_ptr->height_in_blocks; ++sf)
    {
        for (JDIMENSION b = 0; b < ci_ptr->width_in_blocks; ++b)
        {
            int intensity = 0;

            intensity = buf[sf][b][0]*dc_quant/DCTSIZE + 128;
            intensity = MAX(0,   intensity);
            intensity = MIN(255, intensity);

            cvSet2D(dc, sf, (int)b, cvScalar(intensity));

#if DEBUG
            printf("% 2d ", buf[sf][b][0]);
#endif
        }
#if DEBUG
        printf("\n");
#endif
    }

    return dc;

}

IplImage *upscale_chroma(IplImage *quarter, CvSize full_size)
{
    IplImage *full = cvCreateImage(full_size, IPL_DEPTH_8U, 1);
    cvResize(quarter, full, CV_INTER_NN);
    return full;
}

GLOBAL(int)
read_JPEG_file (char * filename, IplImage **dc)
{
  /* This struct contains the JPEG decompression parameters and pointers to
   * working space (which is allocated as needed by the JPEG library).
   */
  struct jpeg_decompress_struct cinfo;

  struct jpeg_error_mgr jerr;
  /* More stuff */
  FILE * infile;        /* source file */

  /* In this example we want to open the input file before doing anything else,
   * so that the setjmp() error recovery below can assume the file is open.
   * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
   * requires it in order to read binary files.
   */

  if ((infile = fopen(filename, "rb")) == NULL) {
    fprintf(stderr, "can't open %s\n", filename);
    return 0;
  }

  /* Step 1: allocate and initialize JPEG decompression object */

  cinfo.err = jpeg_std_error(&jerr);

  /* Now we can initialize the JPEG decompression object. */
  jpeg_create_decompress(&cinfo);

  /* Step 2: specify data source (eg, a file) */

  jpeg_stdio_src(&cinfo, infile);

  /* Step 3: read file parameters with jpeg_read_header() */

  (void) jpeg_read_header(&cinfo, TRUE);
  /* We can ignore the return value from jpeg_read_header since
   *   (a) suspension is not possible with the stdio data source, and
   *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
   * See libjpeg.txt for more info.
   */

  /* Step 4: set parameters for decompression */

  /* In this example, we don't need to change any of the defaults set by
   * jpeg_read_header(), so we do nothing here.
   */

  jvirt_barray_ptr *coeffs = jpeg_read_coefficients(&cinfo);

  IplImage *y    = extract_dc(&cinfo, coeffs, 0);
  IplImage *cb_q = extract_dc(&cinfo, coeffs, 1);
  IplImage *cr_q = extract_dc(&cinfo, coeffs, 2);

  IplImage *cb = upscale_chroma(cb_q, cvGetSize(y));
  IplImage *cr = upscale_chroma(cr_q, cvGetSize(y));

  cvReleaseImage(&cb_q);
  cvReleaseImage(&cr_q);

#if OUTPUT_IMAGES
  cvSaveImage("y.png",   y);
  cvSaveImage("cb.png", cb);
  cvSaveImage("cr.png", cr);
#endif

  *dc = cvCreateImage(cvGetSize(y), IPL_DEPTH_8U, 3);
  assert(dc != NULL);

  cvMerge(y, cr, cb, NULL, *dc);

  cvReleaseImage(&y);
  cvReleaseImage(&cb);
  cvReleaseImage(&cr);

  /* Step 7: Finish decompression */

  (void) jpeg_finish_decompress(&cinfo);
  /* We can ignore the return value since suspension is not possible
   * with the stdio data source.
   */

  /* Step 8: Release JPEG decompression object */

  /* This is an important step since it will release a good deal of memory. */
  jpeg_destroy_decompress(&cinfo);

  fclose(infile);

  return 1;
}

int
main(int argc, char **argv)
{
    int ret = 0;
    if (argc != 2)
    {
        fprintf(stderr, "usage: %s filename.jpg\n", argv[0]);
        return 1;
    }
    IplImage *dc = NULL;
    ret = read_JPEG_file(argv[1], &dc);
    assert(dc != NULL);

    IplImage *rgb = cvCreateImage(cvGetSize(dc), IPL_DEPTH_8U, 3);
    cvCvtColor(dc, rgb, CV_YCrCb2RGB);

#if OUTPUT_IMAGES
    cvSaveImage("rgb.png", rgb);
#else
    cvNamedWindow("DC", CV_WINDOW_AUTOSIZE);
    cvShowImage("DC", rgb);
    cvWaitKey(0);
#endif

    cvReleaseImage(&dc);
    cvReleaseImage(&rgb);

    return 0;
}


来源: stackexchange

问:
Insert text body and excel table body in email using VBA
The ideal format of the email I wish to automate. Certain parts blacked out for privacy.

I am trying to create an email template for business use that can be sent using VBA because the ultimate goal is that the user can only fill in the blanks via userform therefore the text remains unchanged. I already have the userform, and have coded in such a way that the proper blanks are filled in in the text portion and are included in the email body, however I have not figured out how to include the table as well.

Here is what I have so far as my attempt to add the table:

```<code>Sub SendEmail(what_address As String, subject_line As String, mail_body As String, claim_info As Range)

    Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")

    Dim olMail As Outlook.MailItem
    Set olMail = olApp.CreateItem(olMailItem)

    olMail.To = what_address
    olMail.Subject = subject_line
    olMail.Body = mail_body
    olMail.HTMLBody = RangeToHtml.claim_info
    olMail.Send

End Sub

Sub SendClaimsEmail()

    Dim mail_body_message As String
    Dim tracking_number As String
    Dim amount_paid As String
    Dim date_paid As String
    Dim payment_due As String
    Dim claim As Range

    Set claim = Nothing
    On Error Resume Next
    'Only send the visible cells in the selection.
    Set claim = Selection.SpecialCells(xlCellTypeVisible)
    Set claim = Sheets("Sheet1").RangeToHtml("B2:C9").SpecialCells(xlCellTypeVisible, xlTextValues)
    On Error GoTo 0

    mail_body_message = Sheet1.Range("A1")
    tracking_number = Sheet1.Range("G2")
    amount_paid = Sheet1.Range("G3")
    date_paid = Sheet1.Range("G4")
    payment_due = Sheet1.Range("G5")
    mail_body_message = Replace(mail_body_message, "replace_tracking", tracking_number)
    mail_body_message = Replace(mail_body_message, "replace_amountpaid", amount_paid)
    mail_body_message = Replace(mail_body_message, "replace_datepaid", date_paid)
    mail_body_message = Replace(mail_body_message, "replace_pmtdueto", payment_due)

    Call SendEmail("email@email.com", "Subject Line", mail_body_message, claim)

    MsgBox "Complete!"

End Sub
</code>```

答:
I believe your problem lies in trying to combine olMail.Body and olMail.HTMLBody in the same message. From my experience you need to choose one and the table will not work with olMail.Body.

I suggest converting mail_body to valid HTML and appending to olMail.HTMLBody:

```<code>Sub SendEmail(what_address As String, subject_line As String, mail_body As String, claim_info As Range)

Dim olApp As Outlook.Application Set olApp = CreateObject("Outlook.Application")
Dim olApp As Outlook.Application Set olApp =
CreateObject("Outlook.Application")

Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)

olMail.To = what_address
olMail.Subject = subject_line
'assuming your mail_body uses vbLf for linefeeds you can just do this
mail_body = "<p>" & replace(mail_body,vblf,"</br>") & "</p>"
olMail.HTMLBody = mail_body & "</br>" & RangeToHtml.claim_info
olMail.Send
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The ideal format of the email I wish to automate. Certain parts blacked out for privacy.

I am trying to create an email template for business use that can be sent using VBA because the ultimate goal is that the user can only fill in the blanks via userform therefore the text remains unchanged. I already have the userform, and have coded in such a way that the proper blanks are filled in in the text portion and are included in the email body, however I have not figured out how to include the table as well.

Here is what I have so far as my attempt to add the table:

Sub SendEmail(what_address As String, subject_line As String, mail_body As String, claim_info As Range)

    Dim olApp As Outlook.Application
    Set olApp = CreateObject("Outlook.Application")

    Dim olMail As Outlook.MailItem
    Set olMail = olApp.CreateItem(olMailItem)

    olMail.To = what_address
    olMail.Subject = subject_line
    olMail.Body = mail_body
    olMail.HTMLBody = RangeToHtml.claim_info
    olMail.Send

End Sub

Sub SendClaimsEmail()

    Dim mail_body_message As String
    Dim tracking_number As String
    Dim amount_paid As String
    Dim date_paid As String
    Dim payment_due As String
    Dim claim As Range

    Set claim = Nothing
    On Error Resume Next
    'Only send the visible cells in the selection.
    Set claim = Selection.SpecialCells(xlCellTypeVisible)
    Set claim = Sheets("Sheet1").RangeToHtml("B2:C9").SpecialCells(xlCellTypeVisible, xlTextValues)
    On Error GoTo 0

    mail_body_message = Sheet1.Range("A1")
    tracking_number = Sheet1.Range("G2")
    amount_paid = Sheet1.Range("G3")
    date_paid = Sheet1.Range("G4")
    payment_due = Sheet1.Range("G5")
    mail_body_message = Replace(mail_body_message, "replace_tracking", tracking_number)
    mail_body_message = Replace(mail_body_message, "replace_amountpaid", amount_paid)
    mail_body_message = Replace(mail_body_message, "replace_datepaid", date_paid)
    mail_body_message = Replace(mail_body_message, "replace_pmtdueto", payment_due)

    Call SendEmail("email@email.com", "Subject Line", mail_body_message, claim)

    MsgBox "Complete!"

End Sub

Body:
I believe your problem lies in trying to combine olMail.Body and olMail.HTMLBody in the same message. From my experience you need to choose one and the table will not work with olMail.Body.

I suggest converting mail_body to valid HTML and appending to olMail.HTMLBody:

Sub SendEmail(what_address As String, subject_line As String, mail_body As String, claim_info As Range)

Dim olApp As Outlook.Application Set olApp = CreateObject("Outlook.Application")
Dim olApp As Outlook.Application Set olApp =
CreateObject("Outlook.Application")

Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)

olMail.To = what_address
olMail.Subject = subject_line
'assuming your mail_body uses vbLf for linefeeds you can just do this
mail_body = "<p>" & replace(mail_body,vblf,"</br>") & "</p>"
olMail.HTMLBody = mail_body & "</br>" & RangeToHtml.claim_info
olMail.Send
End Sub

ContentLicense: CC BY-SA 3.0


问:
What problems can arise when the program ends before fclose()
I understand that not closing a file is irresponsible, but under the following two conditions, what issues can arise if fclose() was not be called?

1) In the event that fclose() was not called when a program ends, does the OS communicate with the file descriptor to let it know that the file is not longer needed and closes it?

```<code>#include <stdio.h>
int main(){
    FILE* f = open("sample.txt","r");
    return 0;
};
</code>```

In the event of a explicit exit e.g. exit(1) does it differ in any way as to just returning in the previous example?

```<code>#include <stdio.h>
int main(){
    FILE* f = fopen("sample.txt","r");
    exit(1);
    return 0;
}
</code>```

2) A potential segmentation fault occurs before fclose() could be called?

```<code>#include <stdio.h>
int main(){
    FILE* f = fopen("sample.txt","r");
    int *ptr = NULL;
    *ptr = 1; //seg-fault
    fclose(f);
    return 0;
};
</code>```

答:
If the program has a seg fault, the file handler will eventually be released by the OS, just like when program exits normally. But I have seen cases where the file handler from the seg'ed program was not available right away.

More details on a previous answer What happens if I don't call fclose() in a C program?

Body:
I understand that not closing a file is irresponsible, but under the following two conditions, what issues can arise if fclose() was not be called?

1) In the event that fclose() was not called when a program ends, does the OS communicate with the file descriptor to let it know that the file is not longer needed and closes it?

#include <stdio.h>
int main(){
    FILE* f = open("sample.txt","r");
    return 0;
};

In the event of a explicit exit e.g. exit(1) does it differ in any way as to just returning in the previous example?

#include <stdio.h>
int main(){
    FILE* f = fopen("sample.txt","r");
    exit(1);
    return 0;
}

2) A potential segmentation fault occurs before fclose() could be called?

#include <stdio.h>
int main(){
    FILE* f = fopen("sample.txt","r");
    int *ptr = NULL;
    *ptr = 1; //seg-fault
    fclose(f);
    return 0;
};


问:
Manipulate values in pandas DataFrame columns based on matching IDs from another DataFrame
I have two dataframes like the following examples:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, 1],
                 'c': [np.nan, 1, 1]})
df_id = pd.DataFrame({'b': ['50', '4954', '93920', '20'],
                      'c': ['123', '100', '6', np.nan]})

print(df)
     a    b    c
0   20  1.0  NaN
1   50  NaN  1.0
2  100  1.0  1.0

print(df_id)
       b    c
0     50  123
1   4954  100
2  93920    6
3     20  NaN
</code>```

For each identifier in df['a'], I want to null the value in df['b'] if there is no matching identifier in any row in df_id['b']. I want to do the same for column df['c'].

My desired result is as follows:

```<code>result = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, np.nan],
                 'c': [np.nan, np.nan, 1]})
print(result)
     a    b    c
0   20  1.0  NaN
1   50  NaN  NaN    # df_id['c'] did not contain '50'
2  100  NaN  1.0    # df_id['b'] did not contain '100'
</code>```

My attempt to do this is here:

```<code>for i, letter in enumerate(['b','c']):
    df[letter] = (df.apply(lambda x: x[letter] if x['a']
                   .isin(df_id[letter].tolist()) else np.nan, axis = 1))
</code>```

The error I get:

```<code>AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')
</code>```

This is in Python 3.5.2, Pandas version 20.1

答:
You can solve your problem using this instead:

```<code>for letter in ['b','c']: # took off enumerate cuz i didn't need it here, maybe you do for the rest of your code
    df[letter] = df.apply(lambda row: row[letter] if row['a'] in (df_id[letter].tolist()) else np.nan,axis=1)
</code>```

just replace isin with in.

The problem is that when you use apply on df, x will represent df rows, so when you select x['a'] you're actually selecting one element.

However, isin is applicable for series or list-like structures which raises the error so instead we just use in to check if that element is in the list.

Hope that was helpful. If you have any questions please ask.

Body:
I have two dataframes like the following examples:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, 1],
                 'c': [np.nan, 1, 1]})
df_id = pd.DataFrame({'b': ['50', '4954', '93920', '20'],
                      'c': ['123', '100', '6', np.nan]})

print(df)
     a    b    c
0   20  1.0  NaN
1   50  NaN  1.0
2  100  1.0  1.0

print(df_id)
       b    c
0     50  123
1   4954  100
2  93920    6
3     20  NaN

For each identifier in df['a'], I want to null the value in df['b'] if there is no matching identifier in any row in df_id['b']. I want to do the same for column df['c'].

My desired result is as follows:

result = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, np.nan],
                 'c': [np.nan, np.nan, 1]})
print(result)
     a    b    c
0   20  1.0  NaN
1   50  NaN  NaN    # df_id['c'] did not contain '50'
2  100  NaN  1.0    # df_id['b'] did not contain '100'

My attempt to do this is here:

for i, letter in enumerate(['b','c']):
    df[letter] = (df.apply(lambda x: x[letter] if x['a']
                   .isin(df_id[letter].tolist()) else np.nan, axis = 1))

The error I get:

AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')

This is in Python 3.5.2, Pandas version 20.1

Body:
You can solve your problem using this instead:

for letter in ['b','c']: # took off enumerate cuz i didn't need it here, maybe you do for the rest of your code
    df[letter] = df.apply(lambda row: row[letter] if row['a'] in (df_id[letter].tolist()) else np.nan,axis=1)

just replace isin with in.

The problem is that when you use apply on df, x will represent df rows, so when you select x['a'] you're actually selecting one element.

However, isin is applicable for series or list-like structures which raises the error so instead we just use in to check if that element is in the list.

Hope that was helpful. If you have any questions please ask.


问:
Android BottomNavigationView Truncating Text
Is there a way to disable BottomNavigationView's implementation of slighting enlarging the text/icon of a selected item?

Thanks,
Otterman

答:
You can override some default values for Text :

```<code><dimen name="design_bottom_navigation_text_size" tools:override="true">24sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">24sp</dimen>
</code>```

For icons (32dp) :

```<code>    final DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    BottomNavigationView bottomNavigationView = (BottomNavigationView) configurationActivity.findViewById(R.id.bottom_navigation_view);
    BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
    for (int i = 0; i < menuView.getChildCount(); i++) {
        final View iconView = menuView.getChildAt(i).findViewById(android.support.design.R.id.icon);
        final ViewGroup.LayoutParams layoutParams = iconView.getLayoutParams();
        layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, displayMetrics);
        layoutParams.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, displayMetrics);
        iconView.setLayoutParams(layoutParams);
    }
</code>```

Body:
You can override some default values for Text :

<dimen name="design_bottom_navigation_text_size" tools:override="true">24sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">24sp</dimen>

For icons (32dp) :

    final DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    BottomNavigationView bottomNavigationView = (BottomNavigationView) configurationActivity.findViewById(R.id.bottom_navigation_view);
    BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
    for (int i = 0; i < menuView.getChildCount(); i++) {
        final View iconView = menuView.getChildAt(i).findViewById(android.support.design.R.id.icon);
        final ViewGroup.LayoutParams layoutParams = iconView.getLayoutParams();
        layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, displayMetrics);
        layoutParams.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, displayMetrics);
        iconView.setLayoutParams(layoutParams);
    }


问:
php search script
i need some help to search property searching like on

Zameen

what i am unaware of is that how would i send the query to the next page? eg my query is like this

```<code>$query = select * from xyz where city='a' and location='b' and price between 'c' and 'd' and area between 'e' and 'f' and bedrooms='g' and addedwithin 'h';
</code>```

considering this query on the basis of form on the above mentioned website, what should be the scenario for searching property listings.

Also how should i get this query again when i use paging with this page. should it be like this

```<code><a href="<?php echo $_SERVER['PHP_SELF'] . '?q=' . $query; ?>" > nextpage </a>
</code>```

or is there any other simpler solution?

Thanks

答: you may store user search phrase e.g. in session coockies or keep in  form parameters (e.g. with hidden type). then do db-request again with new offset</p>

ContentLicense: CC BY-SA 2.5

Title: php search script

Body:
i need some help to search property searching like on

Zameen

what i am unaware of is that how would i send the query to the next page? eg my query is like this

$query = select * from xyz where city='a' and location='b' and price between 'c' and 'd' and area between 'e' and 'f' and bedrooms='g' and addedwithin 'h';

considering this query on the basis of form on the above mentioned website, what should be the scenario for searching property listings.

Also how should i get this query again when i use paging with this page. should it be like this

<a href="<?php echo $_SERVER['PHP_SELF'] . '?q=' . $query; ?>" > nextpage

or is there any other simpler solution?

Thanks


问:
SQL Function to return sequential id's
Consider this simple INSERT

```<code>INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,123 FROM Customers
</code>```

That will obviously assign UserId=123 to all customers.

What I need to do is assign them to 3 userId's sequentially, so 3 users get one third of the accounts equally.

```<code>INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,fnGetNextId() FROM Customers
</code>```

Could I create a function to return sequentially from a list of 3 ID's?, i.e. each time the function is called it returns the next one in the list?

Thanks

答:
Could I create a function to return sequentially from a list of 3 ID's?,

If you create a SEQUENCE, then you can assign incremental numbers with the NEXT VALUE FOR (Transact-SQL) expression.

Title: SQL Function to return sequential id's

Body:
Consider this simple INSERT

INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,123 FROM Customers

That will obviously assign UserId=123 to all customers.

What I need to do is assign them to 3 userId's sequentially, so 3 users get one third of the accounts equally.

INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,fnGetNextId() FROM Customers

Could I create a function to return sequentially from a list of 3 ID's?, i.e. each time the function is called it returns the next one in the list?

Thanks


问:
AlamofireImage download into CoreData
i want to cache image and few data from json to make persistent I know Alamofire Image has it own chade method, but i guess is only while app is alive when app close and open again chache is cleared so i have to download again image. so
if my image are download like so

```<code>image.af_setImage(withURL: url)
</code>```

it posible to save

```<code>imageEntity.save(image.image)
</code>```

not sure to be exactly code but the idea is to save the image downloaded an set to image in CoreData.
and any idea behind the logic of this approach to cjeck if image exist in coreData and show from the if not download and save to coreData

答:
CoreData is not designed to store ImageData or large data (files) but only String, Dates, integer... Just like a normal database.

If you want to save a data you could use AlamofireImageCache and save the image identifier in the CoreData Entity as a string. It's the most easy way to do it.

```<code>let imageCache = AutoPurgingImageCache(
    memoryCapacity: 100_000_000,
    preferredMemoryUsageAfterPurge: 60_000_000
)
imageCache.add(yourImage, withIdentifier: "YourImageIdentifier")
imageEntity.identifier = "YourImageIdentifier"
</code>```

Then if you want to get your image you can do for example:

```<code>let cachedAvatar = imageCache.image(withIdentifier: imageEntity.identifier)
</code>```

please check AlamofireImage documentation for more information about cache: https://github.com/Alamofire/AlamofireImage

Update

If you want to make your own ImageCache on the hard-drive here you have an example of storing an Image:

```<code>func saveImage(image:UIImage){

     if let data = UIImagePNGRepresentation(image) {

            let documentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]!
            let filename = documentPath.appendingPathComponent("YourImageName")
            try? data.write(to: filename)
     }
}

func getImage(ForName name:String) -> UIImage?{
    let documentPath =    FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]!
    let filename = documentPath.appendingPathComponent("YourImageName")
     return UIImage(contentsOf:URL(fileURLWithPath: filename))
 }
</code>```

Hope it helps !
Pierre

Title: AlamofireImage download into CoreData

Body:
i want to cache image and few data from json to make persistent I know Alamofire Image has it own chade method, but i guess is only while app is alive when app close and open again chache is cleared so i have to download again image. so
if my image are download like so

image.af_setImage(withURL: url)

it posible to save

imageEntity.save(image.image)

not sure to be exactly code but the idea is to save the image downloaded an set to image in CoreData.
and any idea behind the logic of this approach to cjeck if image exist in coreData and show from the if not download and save to coreData

Body:
CoreData is not designed to store ImageData or large data (files) but only String, Dates, integer... Just like a normal database.

If you want to save a data you could use AlamofireImageCache and save the image identifier in the CoreData Entity as a string. It's the most easy way to do it.

let imageCache = AutoPurgingImageCache(
    memoryCapacity: 100_000_000,
    preferredMemoryUsageAfterPurge: 60_000_000
)
imageCache.add(yourImage, withIdentifier: "YourImageIdentifier")
imageEntity.identifier = "YourImageIdentifier"

Then if you want to get your image you can do for example:

let cachedAvatar = imageCache.image(withIdentifier: imageEntity.identifier)

please check AlamofireImage documentation for more information about cache: https://github.com/Alamofire/AlamofireImage

Update

If you want to make your own ImageCache on the hard-drive here you have an example of storing an Image:

func saveImage(image:UIImage){

     if let data = UIImagePNGRepresentation(image) {

            let documentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]!
            let filename = documentPath.appendingPathComponent("YourImageName")
            try? data.write(to: filename)
     }
}

func getImage(ForName name:String) -> UIImage?{
    let documentPath =    FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]!
    let filename = documentPath.appendingPathComponent("YourImageName")
     return UIImage(contentsOf:URL(fileURLWithPath: filename))
 }

Hope it helps !
Pierre


问:
Cannot find a file in my tempfile.TemporaryDirectory() for Python3
I'm having trouble working with Python3's tempfile library in general.

I need to write a file in a temporary directory, and make sure it's there. The third party software tool I use sometimes fails so I can't just open the file, I need to verify it's there first using a 'while loop' or other method before just opening it. So I need to search the tmp_dir (using os.listdir() or equivalent).

Specific help/solution and general help would be appreciated in comments.

Thank you.

Small sample code:

```<code>import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:

    print('tmp dir name', tmp_dir)

    # write file to tmp dir
    fout = open(tmp_dir + 'file.txt', 'w')
    fout.write('test write')
    fout.close()

    print('file.txt location', tmp_dir + 'lala.fasta')

    # working with the file is fine
    fin = open(tmp_dir + 'file.txt', 'U')
    for line in fin:
        print(line)

    # but I cannot find the file in the tmp dir like I normally use os.listdir()
    for file in os.listdir(tmp_dir):
        print('searching in directory')
        print(file)
</code>```

答:
That's expected because the temporary directory name doesn't end with path separator (os.sep, slash or backslash on many systems). So the file is created at the wrong level.

```<code>tmp_dir = D:\Users\foo\AppData\Local\Temp\tmpm_x5z4tx
tmp_dir + "file.txt"
=> D:\Users\foo\AppData\Local\Temp\tmpm_x5z4txfile.txt
</code>```

Instead, join both paths to get a file inside your temporary dir:

```<code>fout = open(os.path.join(tmp_dir,'file.txt'), 'w')
</code>```

note that fin = open(tmp_dir + 'file.txt', 'U') finds the file, that's expected, but it finds it in the same directory where tmp_dir was created.

Body:
I'm having trouble working with Python3's tempfile library in general.

I need to write a file in a temporary directory, and make sure it's there. The third party software tool I use sometimes fails so I can't just open the file, I need to verify it's there first using a 'while loop' or other method before just opening it. So I need to search the tmp_dir (using os.listdir() or equivalent).

Specific help/solution and general help would be appreciated in comments.

Thank you.

Small sample code:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:

    print('tmp dir name', tmp_dir)

    # write file to tmp dir
    fout = open(tmp_dir + 'file.txt', 'w')
    fout.write('test write')
    fout.close()

    print('file.txt location', tmp_dir + 'lala.fasta')

    # working with the file is fine
    fin = open(tmp_dir + 'file.txt', 'U')
    for line in fin:
        print(line)

    # but I cannot find the file in the tmp dir like I normally use os.listdir()
    for file in os.listdir(tmp_dir):
        print('searching in directory')
        print(file)

Body:
That's expected because the temporary directory name doesn't end with path separator (os.sep, slash or backslash on many systems). So the file is created at the wrong level.

tmp_dir = D:\Users\foo\AppData\Local\Temp\tmpm_x5z4tx
tmp_dir + "file.txt"
=> D:\Users\foo\AppData\Local\Temp\tmpm_x5z4txfile.txt

Instead, join both paths to get a file inside your temporary dir:

fout = open(os.path.join(tmp_dir,'file.txt'), 'w')

note that fin = open(tmp_dir + 'file.txt', 'U') finds the file, that's expected, but it finds it in the same directory where tmp_dir was created.


问:
what is the role of ob_start() in here
```<code>session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {
    $hasDB = true;
    mysql_select_db($db);
}
</code>```

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..

答: In this particular code ob_start seems useless. The benefit of output buffering is in either following code or does not exist. `In general, consult PHP manual about ob_start.

Title: what is the role of ob_start() in here

Body:
session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {
    $hasDB = true;
    mysql_select_db($db);
}

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..


问:
Argument labels for initialization parameters in Swift 3.1
Apple's book "The Swift Programming Language (Swift 3.1)" states the following:

As with function and method parameters, initialization parameters can have both a parameter name for use within the initializer’s body and an argument label for use when calling the initializer.

However, initializers do not have an identifying function name before their parentheses in the way that functions and methods do. Therefore, the names and types of an initializer’s parameters play a particularly important role in identifying which initializer should be called. Because of this, Swift provides an automatic argument label for every parameter in an initializer if you don’t provide one.

I don't understand the last sentence, as I didn't notice any difference between functions/methods and initializers when it comes to parameters names/labels. How is the argument label automatically provided for an initializer?

答:
The feature being described is this: Given a struct:

```<code>struct Point {
    let x: Double
    let y: Double
}
</code>```

Swift will automatically generate Point.init(x: Double, y: Double). If you add an init method of your own in the main struct definition, then Swift won't create that automatic init. (If you add an init in an extension, then you will get an automatic init. This is why people often add convenience init in an extension for structs.)

The point the last paragraph is trying to make is that Point(x:y:) is preferable to Point(_:_:). The labels in an initializer are even more valuable than labels in method names, because all initializers have the same "base" name ("init"). They're just explaining why they didn't choose a more implicit default that some people might expect coming from other languages.

In short, sometimes unlabeled parameters make sense in methods depending on what the name of the method is and how unambiguous that makes the first parameter. But in init, unlabeled parameters should be eyed with strong suspicion.

Body:
The feature being described is this: Given a struct:

struct Point {
    let x: Double
    let y: Double
}

Swift will automatically generate Point.init(x: Double, y: Double). If you add an init method of your own in the main struct definition, then Swift won't create that automatic init. (If you add an init in an extension, then you will get an automatic init. This is why people often add convenience init in an extension for structs.)

The point the last paragraph is trying to make is that Point(x:y:) is preferable to Point(_:_:). The labels in an initializer are even more valuable than labels in method names, because all initializers have the same "base" name ("init"). They're just explaining why they didn't choose a more implicit default that some people might expect coming from other languages.

In short, sometimes unlabeled parameters make sense in methods depending on what the name of the method is and how unambiguous that makes the first parameter. But in init, unlabeled parameters should be eyed with strong suspicion.


问:
Counting string occurrences in list
I'm trying to work on a simple python problem hosted on hackerrankteam but I'm having difficulty with the count function for lists in Python. I've tried multiple test cases but my count function always returns 0.

Objective: count the number of occurrences that consecutive squares equals the number of days.

Is this an issue with the type of list? Is there an easier way for me count the values in one line instead of having to check the valued pairs and then count the sums?

```<code>import sys

def solve(size, squares, day, month):
    check = [sum(squares[nums:nums+month]) == day for nums in range(0,len(squares))]
    print (check)   #Test list output
    count = check.count('True')
    return count

#Test Cases 1
# size = 6
# squares = [1,1,1,1,1,1]
# day, month = (3,2)
#Output 0

#Test Cases 2
# size = 1
# squares = [4]
# day, month = (4,1)
#Output 1

#Test Cases 3
size = 5
squares = [1,2,1,3,2]
day, month = [3,2]
#Output 2

#Custom User Input:
# size = int(input().strip())
# squares = list(map(int, input().strip().split(' ')))
# day, month = input().strip().split(' ')
# day, month = [int(day), int(month)]
result = solve(size, squares, day, month)
print(result)
</code>```

答:
```<code>check.count('True')
</code>```

This code is counting the number of occurrences of the string 'True'.

It should instead be:

```<code>check.count(True)
</code>```

You could also simply use this:

```<code>sum(check)
</code>```

Title: Counting string occurrences in list

Body:
I'm trying to work on a simple python problem hosted on hackerrankteam but I'm having difficulty with the count function for lists in Python. I've tried multiple test cases but my count function always returns 0.

Objective: count the number of occurrences that consecutive squares equals the number of days.

Is this an issue with the type of list? Is there an easier way for me count the values in one line instead of having to check the valued pairs and then count the sums?

import sys

def solve(size, squares, day, month):
    check = [sum(squares[nums:nums+month]) == day for nums in range(0,len(squares))]
    print (check)   #Test list output
    count = check.count('True')
    return count

#Test Cases 1
# size = 6
# squares = [1,1,1,1,1,1]
# day, month = (3,2)
#Output 0

#Test Cases 2
# size = 1
# squares = [4]
# day, month = (4,1)
#Output 1

#Test Cases 3
size = 5
squares = [1,2,1,3,2]
day, month = [3,2]
#Output 2

#Custom User Input:
# size = int(input().strip())
# squares = list(map(int, input().strip().split(' ')))
# day, month = input().strip().split(' ')
# day, month = [int(day), int(month)]
result = solve(size, squares, day, month)
print(result)

Body:
check.count('True')

This code is counting the number of occurrences of the string 'True'.

It should instead be:

check.count(True)

You could also simply use this:

sum(check)


问:
UITableView is under the TabBar
I have a custom UITableView with custom cells (70px height for each cell).

I have also a 49px UITabBar, but it's hides the tableView.

I've tried to add this line to the TableView awakeFromNib method but it didn't work:

```<code>self.commentsTableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0)
</code>```

Any idea how can I solve this?

Thanks!

答:
This did the trick for me in Swift 3. </p>

```<code>if let tabBarController = tabBarController {
    self.tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, tabBarController.tabBar.frame.height, 0.0);
}
</code>```

Title: UITableView is under the TabBar

Body:
I have a custom UITableView with custom cells (70px height for each cell).

I have also a 49px UITabBar, but it's hides the tableView.

I've tried to add this line to the TableView awakeFromNib method but it didn't work:

self.commentsTableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0)

Any idea how can I solve this?

Thanks!

Body:
This did the trick for me in Swift 3.

if let tabBarController = tabBarController {
    self.tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, tabBarController.tabBar.frame.height, 0.0);
}


问:
Get list of GCS files in a bucket using Dataflow pipeline
Is there a way to get the list of all/required files from a GCS bucket in a Dataflow pipeline?

Thank You

答: You could use a DoFn that uses the GCS API to list the files in a bucket. Is there something more specific you are trying to doing?


问:
MyActivity implements Custom Listener from MyClass.java but Listener is always NULL
MyActivity implements a CustomListener defined in MyClass.java. I have a function defined in MyClass that should trigger the listener and do some action(finish() MyActivity) defined in the activity. Somehow, I am getting null reference to the listener. Where am I going wrong?

Please refer to the code below!

MyActivity.java

```<code>import com.project.MyClass.CustomListener;

public class MyActivity extends Activity implements CustomListener {

    Context context;
    CustomListener listener;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        context = this;

        myClass = new MyClass(context);
        myClass.setOnCustomListener(listener);

    }

    public void doThisWhenTriggered()
    {
    ...
    }

}
</code>```

MyClass.java

```<code>public class MyClass{

    private Contect ctx;
    ArrayList<CustomListener> listeners = new ArrayList<CustomListener>();

    public MyClass(Context context)
    {
        super();
        this.ctx = context
    }

public interface CustomListener
{
       public void doThisWhenTriggered();
}

public void setOnCustomListener(CustomListenerListener listener)
{
    this.listeners.add(listener);
}

    public void generateTrigger()
    {
        CustomListener listener = listeners.get(0);

        if(listener != null)
            listener.doThisWhenTriggered();
        else
            Log.d("MyAPP", "Listener is NULL");
    }

}
</code>```

MyBroadcastReceiver.java

```<code>public void onReceive(Context context, Intent intent) {
    ...
    callMyClass(Context context)
}

public void callMyClass(Context context)
{
    MyClass myClass= new myClass(context);
    myClass.generateTrigger(context);
}
</code>```

EDIT

The problem was BECAUSE of accessing different instances of MyClass in BroadcastReceiver and Listeners list as correctly pointed out by @Binyamin Sharet

The solution is to declare the listener list as static and also  public void generateTrigger() as static so that the receiver's callMyClass looks like :

```<code>public void callMyClass(Context context)
{
    MyClass.generateTrigger(context);
}
</code>```

答:
Its because

```<code> MyClass myClass = new myClass(context);
</code>```

in MyBroadcastReceiver.java. This will create a new instance.

So I think it will be better to use MyClass.java as Singleton.

```<code>public class MyClass {

    private Contect ctx;
    ArrayList<CustomListener> listeners = new ArrayList<CustomListener>();
    private static final MyClass singletonMyClass = new MyClass();

    private MyClass() {
    }

    public static CustomListner getInstance() {
        return singletonMyClass;
    }

    public interface CustomListener {
        public void doThisWhenTriggered();
    }

    public void setOnCustomListener(CustomListenerListener listener) {
        this.listeners.add(listener);
    }

    public void generateTrigger() {
        CustomListener listener = listeners.get(0);

        if (listener != null)
            listener.doThisWhenTriggered();
        else
            Log.d("MyAPP", "Listener is NULL");
    }

}
</code>```

from MyActivity.java you can call

```<code>MyClass myClass = MyClass.getInstance();
myClass.setOnCustomListener(listener);
</code>```

and similarly in MyBroadcastReceiver.java

```<code>public void callMyClass(Context context)
{

    MyClass myClass= MyClass.getInstance();
    myClass.generateTrigger();

}
</code>```

Hope this helps!!!.

Body:
MyActivity implements a CustomListener defined in MyClass.java. I have a function defined in MyClass that should trigger the listener and do some action(finish() MyActivity) defined in the activity. Somehow, I am getting null reference to the listener. Where am I going wrong?

Please refer to the code below!

MyActivity.java

import com.project.MyClass.CustomListener;

public class MyActivity extends Activity implements CustomListener {

    Context context;
    CustomListener listener;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        context = this;

        myClass = new MyClass(context);
        myClass.setOnCustomListener(listener);

    }

    public void doThisWhenTriggered()
    {
    ...
    }

}

MyClass.java

public class MyClass{

    private Contect ctx;
    ArrayList<CustomListener> listeners = new ArrayList<CustomListener>();

    public MyClass(Context context)
    {
        super();
        this.ctx = context
    }

public interface CustomListener
{
       public void doThisWhenTriggered();
}

public void setOnCustomListener(CustomListenerListener listener)
{
    this.listeners.add(listener);
}

    public void generateTrigger()
    {
        CustomListener listener = listeners.get(0);

        if(listener != null)
            listener.doThisWhenTriggered();
        else
            Log.d("MyAPP", "Listener is NULL");
    }

}

MyBroadcastReceiver.java

public void onReceive(Context context, Intent intent) {
    ...
    callMyClass(Context context)
}

public void callMyClass(Context context)
{
    MyClass myClass= new myClass(context);
    myClass.generateTrigger(context);
}

EDIT

The problem was BECAUSE of accessing different instances of MyClass in BroadcastReceiver and Listeners list as correctly pointed out by @Binyamin Sharet

The solution is to declare the listener list as static and also  public void generateTrigger() as static so that the receiver's callMyClass looks like :

public void callMyClass(Context context)
{
    MyClass.generateTrigger(context);
}

Body:
Its because

 MyClass myClass = new myClass(context);

in MyBroadcastReceiver.java. This will create a new instance.

So I think it will be better to use MyClass.java as Singleton.

public class MyClass {

    private Contect ctx;
    ArrayList<CustomListener> listeners = new ArrayList<CustomListener>();
    private static final MyClass singletonMyClass = new MyClass();

    private MyClass() {
    }

    public static CustomListner getInstance() {
        return singletonMyClass;
    }

    public interface CustomListener {
        public void doThisWhenTriggered();
    }

    public void setOnCustomListener(CustomListenerListener listener) {
        this.listeners.add(listener);
    }

    public void generateTrigger() {
        CustomListener listener = listeners.get(0);

        if (listener != null)
            listener.doThisWhenTriggered();
        else
            Log.d("MyAPP", "Listener is NULL");
    }

}

from MyActivity.java you can call

MyClass myClass = MyClass.getInstance();
myClass.setOnCustomListener(listener);

and similarly in MyBroadcastReceiver.java

public void callMyClass(Context context)
{

    MyClass myClass= MyClass.getInstance();
    myClass.generateTrigger();

}

Hope this helps!!!.


问:
How to pass data from gRPC interceptor to service method call?
I need to pass some data from my ServerAuthIntereptor to call.

ServerAuthInterceptor:

```<code>// used in context parameters map
private static final String AUTH_CONTEXT = "authContext";
private static final Context.Key<Object> AUTH_CONTEXT_KEY = Context.key(AUTH_CONTEXT);

// ...

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {

    // check credentials from header

    // remember account and session token for usage later (eg. in logout)
    AuthContext authContext = new AuthContext();
    authContext.account = account;
    authContext.sessionToken = sessionToken;

    logger.info("Call {} allowed (account={}, authContext={})",
        new Object[] { call, account, authContext });

    Context context = Context
        .current()
        .withValue(AUTH_CONTEXT_KEY, authContext);

    return Contexts.interceptCall(context, call, headers, next);
}

// ...

/**
 * To be used from services
 * @return
 */
public static Account getCurrentContextAccount() {
    AuthContext authContext = (AuthContext) Context.current().key(AUTH_CONTEXT).get();
    return authContext.account;
}
</code>```

In some service method implementation i try to access that stored 'authContext' from current context:

```<code>@Override
public void list(ListRequest request, StreamObserver<ListResponse> responseObserver) {
    logger.info("Starting list({}) ...", request);

     // ...

     account = ServerAuthInterceptor.getCurrentContextAccount();
</code>```

But authContext is null.
It's working sometimes so i believe it's related to threads(locals).

What is proper way to do it?

答:
Context Keys use reference equality. Thus, you must use the same key instance for setting and getting.

This code re-created the key, so it wouldn't match:

```<code>Context.current().key(AUTH_CONTEXT).get();
</code>```

Instead it should have been:

```<code>AUTH_CONTEXT_KEY.get();
</code>```

Reference equality is used so you can apply normal Java visibility (public, protected, package-private, private) rules to the value, as you can do with ThreadLocal.

Body:
I need to pass some data from my ServerAuthIntereptor to call.

ServerAuthInterceptor:

// used in context parameters map
private static final String AUTH_CONTEXT = "authContext";
private static final Context.Key<Object> AUTH_CONTEXT_KEY = Context.key(AUTH_CONTEXT);

// ...

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {

    // check credentials from header

    // remember account and session token for usage later (eg. in logout)
    AuthContext authContext = new AuthContext();
    authContext.account = account;
    authContext.sessionToken = sessionToken;

    logger.info("Call {} allowed (account={}, authContext={})",
        new Object[] { call, account, authContext });

    Context context = Context
        .current()
        .withValue(AUTH_CONTEXT_KEY, authContext);

    return Contexts.interceptCall(context, call, headers, next);
}

// ...

/**
 * To be used from services
 * @return
 */
public static Account getCurrentContextAccount() {
    AuthContext authContext = (AuthContext) Context.current().key(AUTH_CONTEXT).get();
    return authContext.account;
}

In some service method implementation i try to access that stored 'authContext' from current context:

@Override
public void list(ListRequest request, StreamObserver<ListResponse> responseObserver) {
    logger.info("Starting list({}) ...", request);

     // ...

     account = ServerAuthInterceptor.getCurrentContextAccount();

But authContext is null.
It's working sometimes so i believe it's related to threads(locals).

What is proper way to do it?

Body:
Context Keys use reference equality. Thus, you must use the same key instance for setting and getting.

This code re-created the key, so it wouldn't match:

Context.current().key(AUTH_CONTEXT).get();

Instead it should have been:

AUTH_CONTEXT_KEY.get();

Reference equality is used so you can apply normal Java visibility (public, protected, package-private, private) rules to the value, as you can do with ThreadLocal.


问:
Unable to bind 'this' when passing a function as props in React
My Letter component needs to be reused multiple times, with minor changes in what happens in its constructor. My idea was to pass a function as props to Letter, so I can call it in the constructor. However, I'm having a problem with this.

In the code below, when I invoke this.props.setMessage.call(this), this refers to Container and not Letter, and so the state of Letter remains unchanged. I can see that this refers to Container by inserting console.log(this) in the body of the setMessage function in Container.

How do I bind this such that the state of Letter will change when I run this code?

Source:

```<code>export class Container extends React.component {

    ...

    setMessage = () => {
        this.state.message = 'hello';
    }

    render () {
        return (
            <div>
                <Letter setMessage={this.setMessage} />
            </div>
    }
}

export class Letter extends React.component {
    constructor (props) {
        super(props);
        this.props.setMessage.call(this); // doesn't work, 'this' should refer to Letter but refers to Container
    }

    render () {
        ...
    }
}
</code>```

答:
That's because you're using an arrow function.

Arrow functions immediately and permanently bind to the lexical context. Or to put it simply in this case, this will always be a Container.

To fix this, simply define it as a normal function.

```<code>export class Container extends React.Component {
  ...
  setMessage() {
    // As Mayank Shukla pointed out, this is how you should change state
    this.setState({ message: 'hello' });
  }
  ...
}
</code>```

In general, setState is the correct way of updating state. However, if you try to use setState immediately in the constructor then you will get an error.

So just know that if you're setting that state anywhere but the constructor, setState is the right way of doing so. In the constructor, you should assign the initial state directly, as you were doing before.

Body:
My Letter component needs to be reused multiple times, with minor changes in what happens in its constructor. My idea was to pass a function as props to Letter, so I can call it in the constructor. However, I'm having a problem with this.

In the code below, when I invoke this.props.setMessage.call(this), this refers to Container and not Letter, and so the state of Letter remains unchanged. I can see that this refers to Container by inserting console.log(this) in the body of the setMessage function in Container.

How do I bind this such that the state of Letter will change when I run this code?

Source:

export class Container extends React.component {

    ...

    setMessage = () => {
        this.state.message = 'hello';
    }

    render () {
        return (

                <Letter setMessage={this.setMessage} />

    }
}

export class Letter extends React.component {
    constructor (props) {
        super(props);
        this.props.setMessage.call(this); // doesn't work, 'this' should refer to Letter but refers to Container
    }

    render () {
        ...
    }
}

Body:
That's because you're using an arrow function.

Arrow functions immediately and permanently bind to the lexical context. Or to put it simply in this case, this will always be a Container.

To fix this, simply define it as a normal function.

export class Container extends React.Component {
  ...
  setMessage() {
    // As Mayank Shukla pointed out, this is how you should change state
    this.setState({ message: 'hello' });
  }
  ...
}

In general, setState is the correct way of updating state. However, if you try to use setState immediately in the constructor then you will get an error.

So just know that if you're setting that state anywhere but the constructor, setState is the right way of doing so. In the constructor, you should assign the initial state directly, as you were doing before.


问:
ios - Error when hiding button through code Objective-c
I'm trying to hide a button through code, but the program crashes every time I try to hide it.

The error I get:

```<code>'NSInvalidArgumentException', reason: '-[UIBarButtonItem setHidden:]: unrecognized selector sent to instance 0x14ef8f30'
</code>```

.h file code:

```<code>@property (strong) UIButton *takeAll;
</code>```

.m code:

```<code>    @synthesize takeAll;

// function

   [self.takeAll setHidden:YES];
</code>```

答:
The crash shown is in UIBarButtonItem.
In the interface file the declaration is for a UIButton. May be you are trying to link a UIButton to UIBarButtonItem.</p>

Body:
I'm trying to hide a button through code, but the program crashes every time I try to hide it.

The error I get:

'NSInvalidArgumentException', reason: '-[UIBarButtonItem setHidden:]: unrecognized selector sent to instance 0x14ef8f30'

.h file code:

@property (strong) UIButton *takeAll;

.m code:

    @synthesize takeAll;

// function

   [self.takeAll setHidden:YES];


问:
Get values of 2 columns as single value separated with '|'
```<code>DECLARE @mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO @mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');

SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
      +ISNULL(NULLIF(Column2,'-'),'')
FROM @mockup
</code>```

Above query result is as below,

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

I want the result as above only except row4, where 2| should be only as 2 .
'|' should not be there at before or end of the values.

答:
Simply join both fields and use REPLACE to remove |- and -|. Condition in WHERE clause avoids records where both fields are -:

```<code>select replace(replace(Column1+'|'+Column2,'-|',''),'|-','') as Result
from mockup
where coalesce(nullif(Column1,'-'),nullif(Column2,'-')) is not null
</code>```

Output:

```<code>Result
1|2
2
1|2
2
1|2
</code>```

See result here.

Body:
DECLARE @mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO @mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');

SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
      +ISNULL(NULLIF(Column2,'-'),'')
FROM @mockup

Above query result is as below,

1|2
2
1|2
2|
1|2

I want the result as above only except row4, where 2| should be only as 2 .
'|' should not be there at before or end of the values.

Body:
Simply join both fields and use REPLACE to remove |- and -|. Condition in WHERE clause avoids records where both fields are -:

select replace(replace(Column1+'|'+Column2,'-|',''),'|-','') as Result
from mockup
where coalesce(nullif(Column1,'-'),nullif(Column2,'-')) is not null

Output:

Result
1|2
2
1|2
2
1|2

See result here.


问:
Navigate to agent / agent's default view in AnyLogic?
When you double click on an Agent in AnyLogic it navigates to that Agent's internals so you can see its states, variables, etc. Is there a way to do this programmatically with a function call without adding a ViewArea? My current solution is to add a ViewArea and then use viewArea.navigateTo() whenever I need to navigate to the agent, but that seems excessive to do multiple times and in multiple agent types.

答: Each agent has default view area object, its name is _origin_VA. So, you may call something like agent._origin_VA.navigateTo(); This area is not visible in graphical editor, but you may find it with code completion.


问:
Manipulate values in pandas DataFrame columns based on matching IDs from another DataFrame
I have two dataframes like the following examples:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, 1],
                 'c': [np.nan, 1, 1]})
df_id = pd.DataFrame({'b': ['50', '4954', '93920', '20'],
                      'c': ['123', '100', '6', np.nan]})

print(df)
     a    b    c
0   20  1.0  NaN
1   50  NaN  1.0
2  100  1.0  1.0

print(df_id)
       b    c
0     50  123
1   4954  100
2  93920    6
3     20  NaN
</code>```

For each identifier in df['a'], I want to null the value in df['b'] if there is no matching identifier in any row in df_id['b']. I want to do the same for column df['c'].

My desired result is as follows:

```<code>result = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, np.nan],
                 'c': [np.nan, np.nan, 1]})
print(result)
     a    b    c
0   20  1.0  NaN
1   50  NaN  NaN    # df_id['c'] did not contain '50'
2  100  NaN  1.0    # df_id['b'] did not contain '100'
</code>```

My attempt to do this is here:

```<code>for i, letter in enumerate(['b','c']):
    df[letter] = (df.apply(lambda x: x[letter] if x['a']
                   .isin(df_id[letter].tolist()) else np.nan, axis = 1))
</code>```

The error I get:

```<code>AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')
</code>```

This is in Python 3.5.2, Pandas version 20.1

答:
Adapting a hard-to-find answer from Pandas New Column Calculation Based on Existing Columns Values:

```<code>for i, letter in enumerate(['b','c']):
    mask = df['a'].isin(df_id[letter])
    name = letter + '_new'
    # for some reason, df[letter] = df.loc[mask, letter] does not work
    df.loc[mask, name] = df.loc[mask, letter]
    df[letter] = df[name]
    del df[name]
</code>```

This isn't pretty, but seems to work.

Body:
I have two dataframes like the following examples:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, 1],
                 'c': [np.nan, 1, 1]})
df_id = pd.DataFrame({'b': ['50', '4954', '93920', '20'],
                      'c': ['123', '100', '6', np.nan]})

print(df)
     a    b    c
0   20  1.0  NaN
1   50  NaN  1.0
2  100  1.0  1.0

print(df_id)
       b    c
0     50  123
1   4954  100
2  93920    6
3     20  NaN

For each identifier in df['a'], I want to null the value in df['b'] if there is no matching identifier in any row in df_id['b']. I want to do the same for column df['c'].

My desired result is as follows:

result = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, np.nan],
                 'c': [np.nan, np.nan, 1]})
print(result)
     a    b    c
0   20  1.0  NaN
1   50  NaN  NaN    # df_id['c'] did not contain '50'
2  100  NaN  1.0    # df_id['b'] did not contain '100'

My attempt to do this is here:

for i, letter in enumerate(['b','c']):
    df[letter] = (df.apply(lambda x: x[letter] if x['a']
                   .isin(df_id[letter].tolist()) else np.nan, axis = 1))

The error I get:

AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')

This is in Python 3.5.2, Pandas version 20.1

Body:
Adapting a hard-to-find answer from Pandas New Column Calculation Based on Existing Columns Values:

for i, letter in enumerate(['b','c']):
    mask = df['a'].isin(df_id[letter])
    name = letter + '_new'
    # for some reason, df[letter] = df.loc[mask, letter] does not work
    df.loc[mask, name] = df.loc[mask, letter]
    df[letter] = df[name]
    del df[name]

This isn't pretty, but seems to work.


问:
php class extend approch vs static approch,which one is better
Approch 1：

```<code>class Storage extends SaeStorage {
public function save($data,$name){
    if (! $this->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $this->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}
</code>```

}

approach 2：

```<code>class Storage  {
public static  function save($data,$name){
    $SaeStorage = new SaeStorage();
    if (! $SaeStorage->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $SaeStorage->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}
</code>```

}

答: If you are going to use the SaeStorage class throughout the Storage class then approach 1 makes much more sense. It saves you having to instantiate a new object every time you want to use a method or property in the extended class.</p>

Body:
Approch 1：

class Storage extends SaeStorage {
public function save($data,$name){
    if (! $this->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $this->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}

}

approach 2：

class Storage  {
public static  function save($data,$name){
    $SaeStorage = new SaeStorage();
    if (! $SaeStorage->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $SaeStorage->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}

}


问:
WPF COMException Crashes Application At Startup (Started Today)
I have just today started seeing this Exception out in the wild on application launch with an app that has been in production for 3 years.

System.TypeInitializationException: The type initializer for 'MS.Win32.Penimc.UnsafeNativeMethods' threw an exception. ---> System.Runtime.InteropServices.COMException: Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
   at MS.Win32.Penimc.UnsafeNativeMethods.CoCreateInstance(Guid& clsid, Object punkOuter, Int32 context, Guid& iid)
   at MS.Win32.Penimc.UnsafeNativeMethods.CreatePimcManager()
   at MS.Win32.Penimc.UnsafeNativeMethods..cctor()
   --- End of inner exception stack trace ---
   at MS.Win32.Penimc.UnsafeNativeMethods.CreateResetEvent(IntPtr& handle)
   at System.Windows.Input.PenThreadWorker..ctor()
   at System.Windows.Input.PenThreadPool.GetPenThreadForPenContextHelper(PenContext penContext)
   at System.Windows.Input.PenThreadPool.GetPenThreadForPenContext(PenContext penContext)
   at System.Windows.Input.StylusWisp.WispTabletDeviceCollection.UpdateTabletsImpl()
   at System.Windows.Input.StylusWisp.WispTabletDeviceCollection.UpdateTablets()
   at System.Windows.Input.StylusWisp.WispTabletDeviceCollection..ctor()
   at System.Windows.Input.StylusWisp.WispLogic.get_WispTabletDevices()
   at System.Windows.Input.StylusWisp.WispLogic.RegisterHwndForInput(InputManager inputManager, PresentationSource inputSource)
   at System.Windows.Interop.HwndStylusInputProvider..ctor(HwndSource source)
   at System.Windows.Interop.HwndSource.Initialize(HwndSourceParameters parameters)
   at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
   at System.Windows.Window.CreateSourceWindowDuringShow()
   at System.Windows.Window.SafeCreateWindowDuringShow()
   at System.Windows.Window.ShowHelper(Object booleanBox)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at APSSSentinel.App.Main()```

Apparently, some developers using VS2017 who got a Windows update that installed .NET 4.7 have been getting this crash as well, it appears the recommended workaround for now is to turn touch support off.

https://developercommunity.visualstudio.com/content/problem/55303/visual-studio-may-terminate-unexpectedly-when-runn.html

With my application, this is not ideal.  Has anyone else run into this, and found any other sort of workaround?

答:
Microsoft has fixed the issue with .NET 4.7 meanwhile, see
https://support.microsoft.com/en-US/help/4033488/comexception-error-from-wpf-applications-after-the-net-framework-4-7-i</p>

Body:
I have just today started seeing this Exception out in the wild on application launch with an app that has been in production for 3 years.

System.TypeInitializationException: The type initializer for 'MS.Win32.Penimc.UnsafeNativeMethods' threw an exception. ---> System.Runtime.InteropServices.COMException: Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
   at MS.Win32.Penimc.UnsafeNativeMethods.CoCreateInstance(Guid& clsid, Object punkOuter, Int32 context, Guid& iid)
   at MS.Win32.Penimc.UnsafeNativeMethods.CreatePimcManager()
   at MS.Win32.Penimc.UnsafeNativeMethods..cctor()
   --- End of inner exception stack trace ---
   at MS.Win32.Penimc.UnsafeNativeMethods.CreateResetEvent(IntPtr& handle)
   at System.Windows.Input.PenThreadWorker..ctor()
   at System.Windows.Input.PenThreadPool.GetPenThreadForPenContextHelper(PenContext penContext)
   at System.Windows.Input.PenThreadPool.GetPenThreadForPenContext(PenContext penContext)
   at System.Windows.Input.StylusWisp.WispTabletDeviceCollection.UpdateTabletsImpl()
   at System.Windows.Input.StylusWisp.WispTabletDeviceCollection.UpdateTablets()
   at System.Windows.Input.StylusWisp.WispTabletDeviceCollection..ctor()
   at System.Windows.Input.StylusWisp.WispLogic.get_WispTabletDevices()
   at System.Windows.Input.StylusWisp.WispLogic.RegisterHwndForInput(InputManager inputManager, PresentationSource inputSource)
   at System.Windows.Interop.HwndStylusInputProvider..ctor(HwndSource source)
   at System.Windows.Interop.HwndSource.Initialize(HwndSourceParameters parameters)
   at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
   at System.Windows.Window.CreateSourceWindowDuringShow()
   at System.Windows.Window.SafeCreateWindowDuringShow()
   at System.Windows.Window.ShowHelper(Object booleanBox)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at APSSSentinel.App.Main()

Apparently, some developers using VS2017 who got a Windows update that installed .NET 4.7 have been getting this crash as well, it appears the recommended workaround for now is to turn touch support off.

https://developercommunity.visualstudio.com/content/problem/55303/visual-studio-may-terminate-unexpectedly-when-runn.html

With my application, this is not ideal.  Has anyone else run into this, and found any other sort of workaround?


问:
Concatenate variable name in python
I have a set of table names

```1. EOM
2.STMT
3.LOOKUP etc```

I want to associate these table names with some variables names such as

```1. start_time,
2. end_time,
3. total_time etc. ```

The way I want to write these variable names is something like

```1. start_time_EOM, end_time_EOM, total_time_EOM
2. start_time_STMT, end_time_STMT,total_time_STMT
3. start_time_LOOKUP,end_time_LOOKUP,total_time_LOOKUP```

Can this be done in python, and how?
(Note: I am new to Python, and still trying to learn).

答: You cannot change variables names the way you are looking to do, but you might try using a python dictionary to achieve what you're trying to accomplish.</p>

Title: Concatenate variable name in python

Body:
I have a set of table names

1. EOM
2.STMT
3.LOOKUP etc

I want to associate these table names with some variables names such as

1. start_time,
2. end_time,
3. total_time etc.

The way I want to write these variable names is something like

1. start_time_EOM, end_time_EOM, total_time_EOM
2. start_time_STMT, end_time_STMT,total_time_STMT
3. start_time_LOOKUP,end_time_LOOKUP,total_time_LOOKUP

Can this be done in python, and how?
(Note: I am new to Python, and still trying to learn).


问:
how to check if field is autoincrement or not in symfony2 using doctrine2?
I am getting type of field using classMedataData using below,

```<code>$em->getClassMetadata('AcmeDemoBundle:' . $entityName)->getTypeOfField($fieldName)),
</code>```

I want to check if the field is autoincrement or not. I tried using this,

```<code>$em->getClassMetadata('AcmeDemoBundle:' . $entityName)->isIdentifier($fieldName)),
</code>```

but it doesnt give whether it is autoincrement or not ? Basically I want

```<code>   generator: { strategy: AUTO }
</code>```

metadata from entity name.

答:
Late-answering to @vishal's question, about what type to use for the auto-increment - the GENERATOR_TYPE_IDENTITY is actually the correct one (see below).

Excerpt from Symfony v3.3 code, ClassMetaDataInfo.php:

```<code>/* The Id generator types. */
/**
 * AUTO means the generator type will depend on what the used platform prefers.
 * Offers full portability.
 */
const GENERATOR_TYPE_AUTO = 1;

/**
 * SEQUENCE means a separate sequence object will be used. Platforms that do
 * not have native sequence support may emulate it. Full portability is currently
 * not guaranteed.
 */
const GENERATOR_TYPE_SEQUENCE = 2;

/**
 * TABLE means a separate table is used for id generation.
 * Offers full portability.
 */
const GENERATOR_TYPE_TABLE = 3;

/**
 * IDENTITY means an identity column is used for id generation. The database
 * will fill in the id column on insertion. Platforms that do not support
 * native identity columns may emulate them. Full portability is currently
 * not guaranteed.
 */
const GENERATOR_TYPE_IDENTITY = 4;

/**
 * NONE means the class does not have a generated id. That means the class
 * must have a natural, manually assigned id.
 */
const GENERATOR_TYPE_NONE = 5;

/**
 * UUID means that a UUID/GUID expression is used for id generation. Full
 * portability is currently not guaranteed.
 */
const GENERATOR_TYPE_UUID = 6;

/**
 * CUSTOM means that customer will use own ID generator that supposedly work
 */
const GENERATOR_TYPE_CUSTOM = 7;
</code>```

So, you may use some function like this:

```<code>public function isPrimaryKeyAutoGenerated(): bool
{
    return $this->classMetaData && $this->classMetaData->generatorType == ClassMetadataInfo::GENERATOR_TYPE_IDENTITY;
}
</code>```

Body:
I am getting type of field using classMedataData using below,

$em->getClassMetadata('AcmeDemoBundle:' . $entityName)->getTypeOfField($fieldName)),

I want to check if the field is autoincrement or not. I tried using this,

$em->getClassMetadata('AcmeDemoBundle:' . $entityName)->isIdentifier($fieldName)),

but it doesnt give whether it is autoincrement or not ? Basically I want

   generator: { strategy: AUTO }

metadata from entity name.

Body:
Late-answering to @vishal's question, about what type to use for the auto-increment - the GENERATOR_TYPE_IDENTITY is actually the correct one (see below).

Excerpt from Symfony v3.3 code, ClassMetaDataInfo.php:

/* The Id generator types. */
/**
 * AUTO means the generator type will depend on what the used platform prefers.
 * Offers full portability.
 */
const GENERATOR_TYPE_AUTO = 1;

/**
 * SEQUENCE means a separate sequence object will be used. Platforms that do
 * not have native sequence support may emulate it. Full portability is currently
 * not guaranteed.
 */
const GENERATOR_TYPE_SEQUENCE = 2;

/**
 * TABLE means a separate table is used for id generation.
 * Offers full portability.
 */
const GENERATOR_TYPE_TABLE = 3;

/**
 * IDENTITY means an identity column is used for id generation. The database
 * will fill in the id column on insertion. Platforms that do not support
 * native identity columns may emulate them. Full portability is currently
 * not guaranteed.
 */
const GENERATOR_TYPE_IDENTITY = 4;

/**
 * NONE means the class does not have a generated id. That means the class
 * must have a natural, manually assigned id.
 */
const GENERATOR_TYPE_NONE = 5;

/**
 * UUID means that a UUID/GUID expression is used for id generation. Full
 * portability is currently not guaranteed.
 */
const GENERATOR_TYPE_UUID = 6;

/**
 * CUSTOM means that customer will use own ID generator that supposedly work
 */
const GENERATOR_TYPE_CUSTOM = 7;

So, you may use some function like this:

public function isPrimaryKeyAutoGenerated(): bool
{
    return $this->classMetaData && $this->classMetaData->generatorType == ClassMetadataInfo::GENERATOR_TYPE_IDENTITY;
}


问:
How many requests per second does libmemcached can handle?
I hava a linux server which has 2G memory/ Intel Core 2 Duo 2.4 GHz cpu, I am developing a networking system. I use

libmemcached/memcache to store and access packet info,  I want to know how many requests does

libmemcached can handle in a plain linux server ? thanks!

答:
There are too many things that could affect the request rate (CPU speed, other hardware drivers, exact kernel version, request size, cache hit rate, etc ad infinitum).  There's no such thing as a "plain linux server."

Since it sounds like you've got fixed hardware, your best bet is to test the hardware you've got, and see how well it performs under your desired load.


问:
How to view the origin of HTTP requests?
One of my company's internal HTTP endpoints are receiving a large number requests but we don't know where they are coming from. How can I trace the origin of these requests?

Update:
I forgot to mention that I want to view the origin of the requests using NewRelic. I also don't have the luxury of installing debugging tools like Fiddler in my production environment.

答: Maybe a tool like fiddler or postman.</p>

Body: Maybe a tool like fiddler or postman.


问:
Comparing two integer arrays without sorting in java
I am working on a piece of code which is used to create a multiple choice question exam. The purpose of the code I am working on is to enable a question to have multiple correct answers.

The way a user inputs an answer is choosing an integer corresponding to the choice they would like to submit.

The actual correct integer(s) is/are stored in an array called "correctedIndex" and the user stored responses are stored in an array called "response".

The error I am having is checking to see whether the user's answers are correct, regardless of the order he or she submitted them in. My current idea was to created a nested for loop to cycle through both arrays and check for matches, and if the matches equal to the amount of correct answers, then the student would be correct. This does not work when I run it.

Everything before that point works properly, I have made sure a user cannot enter invalid responses, duplicate responses, and automatically mark them incorrect if they submit more responses than there are correct responses.

Here is the part of the code which does not work:

```<code>for(int i = 0; i < correctIndex.length; i++){
            for(int j = 0; j < response.length; j++){
                if(correctIndex[i] == response[j]){
                    matches++;
                }
            }
        }
        if(matches == correctIndex.length){
            System.out.println("Correct, answer was: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) + ": " + choices[correctIndex[i]]);
            }
        }
        else{
            System.out.println("Your answer: ");
            for(int i = 0; i < response.length; i++){
                System.out.println(response[i] + ": " + choices[response[i]-1]);
            }
            System.out.println();
            System.out.println();
            System.out.println("Is incorrect, the correct answer is: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) +": " + choices[correctIndex[i]]);
            }
        }
</code>```

Here is an example of an output I get:

```<code>Please input the correct choice using its corresponding number

Which of these are visibilities?

1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Please enter how many answers you would like to select:
4
Enter your number for answer 1
1
Enter your number for answer 2
2
Enter your number for answer 3
4
Enter your number for answer 4
7
</code>```

And here are the results after using the result method (The one in question):

```<code>Question:
Which of these are visibilities?

Choices:
1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Your answer:
1: Public
2: Private
4: Protected
7: Package-Protected

Is incorrect, the correct answer is:
1: Public
2: Private
4: Protected
7: Package-Protected
</code>```

答:
Why not use a Set? Two sets will be equal if they have the same elements regardless of the order!

An example:

```<code>Set<Integer> correctIndex = new HashSet<>();
Set<Integer> response = new HashSet<>();

correctIndex.add(1);
correctIndex.add(2);
correctIndex.add(3);

response.add(3);
response.add(2);
response.add(1);

// This will print true!
System.out.println(correctIndex.equals(response));
</code>```

Body:
I am working on a piece of code which is used to create a multiple choice question exam. The purpose of the code I am working on is to enable a question to have multiple correct answers.

The way a user inputs an answer is choosing an integer corresponding to the choice they would like to submit.

The actual correct integer(s) is/are stored in an array called "correctedIndex" and the user stored responses are stored in an array called "response".

The error I am having is checking to see whether the user's answers are correct, regardless of the order he or she submitted them in. My current idea was to created a nested for loop to cycle through both arrays and check for matches, and if the matches equal to the amount of correct answers, then the student would be correct. This does not work when I run it.

Everything before that point works properly, I have made sure a user cannot enter invalid responses, duplicate responses, and automatically mark them incorrect if they submit more responses than there are correct responses.

Here is the part of the code which does not work:

for(int i = 0; i < correctIndex.length; i++){
            for(int j = 0; j < response.length; j++){
                if(correctIndex[i] == response[j]){
                    matches++;
                }
            }
        }
        if(matches == correctIndex.length){
            System.out.println("Correct, answer was: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) + ": " + choices[correctIndex[i]]);
            }
        }
        else{
            System.out.println("Your answer: ");
            for(int i = 0; i < response.length; i++){
                System.out.println(response[i] + ": " + choices[response[i]-1]);
            }
            System.out.println();
            System.out.println();
            System.out.println("Is incorrect, the correct answer is: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) +": " + choices[correctIndex[i]]);
            }
        }

Here is an example of an output I get:

Please input the correct choice using its corresponding number

Which of these are visibilities?

1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Please enter how many answers you would like to select:
4
Enter your number for answer 1
1
Enter your number for answer 2
2
Enter your number for answer 3
4
Enter your number for answer 4
7

And here are the results after using the result method (The one in question):

Question:
Which of these are visibilities?

Choices:
1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Your answer:
1: Public
2: Private
4: Protected
7: Package-Protected

Is incorrect, the correct answer is:
1: Public
2: Private
4: Protected
7: Package-Protected

Body:
Why not use a Set? Two sets will be equal if they have the same elements regardless of the order!

An example:

Set<Integer> correctIndex = new HashSet<>();
Set<Integer> response = new HashSet<>();

correctIndex.add(1);
correctIndex.add(2);
correctIndex.add(3);

response.add(3);
response.add(2);
response.add(1);

// This will print true!
System.out.println(correctIndex.equals(response));


问:
How to do select statement after THEN of SELECT CASE in SQL query?
Is it possible to write query which has select statement after THEN of SELECT CASE in SQL query?
Example of logic</p>

```<code>SELECT Id, CASE WHEN level=2 THEN
    (select something here)
    else 0 end as Grade FROM CLASS
</code>```

答:
You could declare the second select as a variable.

For example:

```<code>DECLARE @var as int
SET @var = (SELECT COUNT(*) FROM table)

SELECT
Id,
CASE WHEN level=2 THEN @var else 0 end as Grade
FROM CLASS
</code>```

Body:
Is it possible to write query which has select statement after THEN of SELECT CASE in SQL query?
Example of logic

SELECT Id, CASE WHEN level=2 THEN
    (select something here)
    else 0 end as Grade FROM CLASS

Body:
You could declare the second select as a variable.

For example:

DECLARE @var as int
SET @var = (SELECT COUNT(*) FROM table)

SELECT
Id,
CASE WHEN level=2 THEN @var else 0 end as Grade
FROM CLASS