问:
How to collect output of several commands into one file in CMake?
I am trying to collect Git information into file and am doing

```<code>execute_process(
    COMMAND git log -1 --format=full && echo "Modified files:" && git ls-files -m
    OUTPUT_FILE "git_log"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
</code>```

or

```<code>execute_process(
    COMMAND git log -1 --format=full
    COMMAND echo "Modified files:"
    COMMAND git ls-files -m
    OUTPUT_FILE "git_log"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
</code>```

And in both cases don't see full content. In first case I see empty file and in second -- only output of last command.

How to gather all in one file?

答:
in first case I see empty file

Sure - no shell is used, and && is invalid argument to git, the command fails. See documentation No intermediate shell is used, so shell operators such as > are treated as normal arguments.

in second -- only output of last command.

Sure - see documentation Commands are executed concurrently as a pipeline, with the standard output of each process piped to the standard input of the next. git ... | echo ... | git ... will only output the last one - git and echo ignore standard input.

```<code>execute_process(
    COMMAND sh -c "
       git log -1 --format=full &&
       echo \"Modified files:\" &&
       git ls-files -m"
    OUTPUT_FILE "git_log1"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
</code>```

or

```<code>execute_process(
    COMMAND git log -1 --format=full
    OUTPUT_FILE "git_log1"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
execute_process(
    COMMAND echo ...
    OUTPUT_FILE "git_log2"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
execute_process(
    COMMAND git ...
    OUTPUT_FILE "git_log3"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
execute_process(
    COMMAND ${CMAKE_COMMAND} -E cat git_log1 git_log2 git_log3
    OUTPUT_FILE "git_log"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
</code>```

Body:
I am trying to collect Git information into file and am doing

execute_process(
    COMMAND git log -1 --format=full && echo "Modified files:" && git ls-files -m
    OUTPUT_FILE "git_log"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )

or

execute_process(
    COMMAND git log -1 --format=full
    COMMAND echo "Modified files:"
    COMMAND git ls-files -m
    OUTPUT_FILE "git_log"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )

And in both cases don't see full content. In first case I see empty file and in second -- only output of last command.

How to gather all in one file?

Body:
in first case I see empty file

Sure - no shell is used, and && is invalid argument to git, the command fails. See documentation No intermediate shell is used, so shell operators such as > are treated as normal arguments.

in second -- only output of last command.

Sure - see documentation Commands are executed concurrently as a pipeline, with the standard output of each process piped to the standard input of the next. git ... | echo ... | git ... will only output the last one - git and echo ignore standard input.

execute_process(
    COMMAND sh -c "
       git log -1 --format=full &&
       echo \"Modified files:\" &&
       git ls-files -m"
    OUTPUT_FILE "git_log1"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )

or

execute_process(
    COMMAND git log -1 --format=full
    OUTPUT_FILE "git_log1"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
execute_process(
    COMMAND echo ...
    OUTPUT_FILE "git_log2"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
execute_process(
    COMMAND git ...
    OUTPUT_FILE "git_log3"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )
execute_process(
    COMMAND ${CMAKE_COMMAND} -E cat git_log1 git_log2 git_log3
    OUTPUT_FILE "git_log"
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    )


来源: stackexchange

问:
Is There A Way To Improve Performance Of Data Dictionary Model To Dict Appraoch?
I am currently getting a bunch of records for formsets in my Django application with the method below...

```<code>    line_items = BudgetLineItem.objects.filter(budget_pk=dropdown)

    line_item_listofdicts = []
    for line_item in line_items:
        line_item_dict = model_to_dict(line_item)
        del line_item_dict['id']
        del line_item_dict['budget']
        del line_item_dict['archive_budget']
        del line_item_dict['new_budget']
        del line_item_dict['update_budget']
        line_item_listofdicts.append(line_item_dict)

    UpdateBudgetLineItemFormSet = inlineformset_factory(UpdateBudget,
                                                        UpdateBudgetLineItem,
                                                        form=UpdateBudgetLineItemForm,
                                                        extra=len(line_item_listofdicts),
                                                        can_delete=True,
                                                        can_order=True)
</code>```

The good news is that it works and does what I want it to.  However it's super slow.  It takes about 13 seconds to render the data back to my app.  Not optimal.  I've spent the morning trying to do various prefetches and select_relateds but nothing has worked to improve the time it takes to render these fields back to the screen.  The fields in question are largely DecimalFields and I've read that they can be a bit slower.  I'm trying to use this data as "input" to my formsets in a CreateView.  Again it works...but it's slow.  Any ideas on how to make this approach more performant?

Thanks in advance for any thoughts.

答:
Instead of retreiving the models and deleting the fields you dont need, you could just query the models specifying only the list of fields you want
using  the queryset values(*args) method which you specify the fields you need as str(s)

And it will Automatically return it as a list dictionary with the specified fields
#taking your  code for example, it me assume you only need the title and added_date from your model

Note just assuming your BudgetLineItem model has the fields title and added_date then you code could be like

```<code>line_items = BudgetLineItem.objects.filter(budget_pk=dropdown).values('title', 'added_on')

    UpdateBudgetLineItemFormSet = inlineformset_factory(UpdateBudget,
                                                        UpdateBudgetLineItem,
                                                        form=UpdateBudgetLineItemForm,
                                                        extra=line_items.count(),
                                                        can_delete=True,
                                                        can_order=True)
</code>```

From you code you are doing operations that you dont need

-Since it just the len of the items need you dont need to evaluate the query,  you could just call the count method of the queryset

-If there some peice od code that still needs to use your line_item_listofdicts variable then you could just replace it with the line_items as it is a list of dictionary containing only the fields you need,  instead of converting you model queryset to a list of of model instances and deleting the fields you don't need and again converting it to another list (these operations a expensive)

You could check out the document on value

ContentLicense: CC BY-SA 4.0

Body:
I am currently getting a bunch of records for formsets in my Django application with the method below...

    line_items = BudgetLineItem.objects.filter(budget_pk=dropdown)

    line_item_listofdicts = []
    for line_item in line_items:
        line_item_dict = model_to_dict(line_item)
        del line_item_dict['id']
        del line_item_dict['budget']
        del line_item_dict['archive_budget']
        del line_item_dict['new_budget']
        del line_item_dict['update_budget']
        line_item_listofdicts.append(line_item_dict)

    UpdateBudgetLineItemFormSet = inlineformset_factory(UpdateBudget,
                                                        UpdateBudgetLineItem,
                                                        form=UpdateBudgetLineItemForm,
                                                        extra=len(line_item_listofdicts),
                                                        can_delete=True,
                                                        can_order=True)

The good news is that it works and does what I want it to.  However it's super slow.  It takes about 13 seconds to render the data back to my app.  Not optimal.  I've spent the morning trying to do various prefetches and select_relateds but nothing has worked to improve the time it takes to render these fields back to the screen.  The fields in question are largely DecimalFields and I've read that they can be a bit slower.  I'm trying to use this data as "input" to my formsets in a CreateView.  Again it works...but it's slow.  Any ideas on how to make this approach more performant?

Thanks in advance for any thoughts.

Body:
Instead of retreiving the models and deleting the fields you dont need, you could just query the models specifying only the list of fields you want
using  the queryset values(*args) method which you specify the fields you need as str(s)

And it will Automatically return it as a list dictionary with the specified fields
#taking your  code for example, it me assume you only need the title and added_date from your model

Note just assuming your BudgetLineItem model has the fields title and added_date then you code could be like

line_items = BudgetLineItem.objects.filter(budget_pk=dropdown).values('title', 'added_on')

    UpdateBudgetLineItemFormSet = inlineformset_factory(UpdateBudget,
                                                        UpdateBudgetLineItem,
                                                        form=UpdateBudgetLineItemForm,
                                                        extra=line_items.count(),
                                                        can_delete=True,
                                                        can_order=True)

From you code you are doing operations that you dont need

-Since it just the len of the items need you dont need to evaluate the query,  you could just call the count method of the queryset

-If there some peice od code that still needs to use your line_item_listofdicts variable then you could just replace it with the line_items as it is a list of dictionary containing only the fields you need,  instead of converting you model queryset to a list of of model instances and deleting the fields you don't need and again converting it to another list (these operations a expensive)

You could check out the document on value


问:
React with Firebase - submitting Formik form data
I have a react app that uses Formik for forms and Cloud Firestore for the database.

I am trying to save the form data in Cloud Firestore. I get no errors in my console or react inspector tools, and when I press submit, I can see in the react inspect tool that the button goes to disabled and then enabled again, but the form doesn't clear the data and the data does not get sent to Cloud Firestore.

My handleSubmit function has:

```<code>handleSubmit = (formState, { resetForm }) => {
    // Now, you're getting form state here!
    const payload = {
        ...formState,
        fieldOfResearch: formState.fieldOfResearch.map(t => t.value),
        preregisterPlatform: formState.preregisterPlatform.value,
        resourceRequests: formState.resourceRequests.map(t => t.value),
        resourceOffers: formState.resourceOffers.map(t => t.value),
        ethicsIssue: formState.ethicsIssue.map(t => t.value),
        disclosureStatus: formState.disclosureStatus.value,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      }
      console.log("formvalues", payload);

    fsDB
      .collection("project")
      .add(payload)
      .then(docRef => {
        console.log("docRef>>>", docRef);
        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };
</code>```

My submit button has:

```<code><div className="form-group">
                            <Button
                                variant="outline-primary"
                                type="submit"
                                id="ProjectId"
                                onClick={handleSubmit}
                                disabled={!dirty || isSubmitting}
                            >
                                Save
                            </Button>
                        </div>
</code>```

The form is long - it has 39 questions, I can see from my Cloud Firestore data usage that I'm no where close to the limits for reads and writes. I don't know how to measure the size of my form submit data to know if the form data exceeds Cloud Firestore limits - is there a way to get Firestore to tell you if that's why the submit isn't working?

My console log to see the payload in the handleSubmit isn't running - so I think there must be another issue - I just can't find any information on what the problem might be.

Has anyone had an issue with long forms not posting to Cloud Firestore? If i keep the first 10 questions only, this form submits to the database.

I think I am well within my usage limits on firestore:

NEXT ATTEMPT

So, I took each of questions 11-39 out of the form and commented all of the Yup validations. I added the questions back one at a time and found that the form works and posts to firestore, until I uncommented the validations. They all pass - there are no errors. So - now I'm wondering if the time it costs to check them is counted by firestore for its process and maybe that's causing a time out? Is that possible? If so, is there any way to get an indication from Firestore that this is the problem?  My validations are below.

I tried commenting and then uncommenting the validations in batches of 10. The form posts to firebase successfully if I comment all the validations from video down to the end. There are no errors in these validations. I just can't have them as well as successful posting to the database.

```<code><Formik
            initialValues={initialValues}
            validationSchema={Yup.object().shape({
                title: Yup.string().required("Give your proposal a title"),
                subtitle: Yup.string().required("Now a subtitle"),
                fieldOfResearch: Yup.array().required("What is your field of research?"),
                disclosureStatus: Yup.string().nullable().required("Some projects are sensitive. Choose a disclosure setting."),
                overview: Yup.string().required("Outline your proposal"),
                objective: Yup.string().required("What is your objective?"),
                currentThinking: Yup.string().required("Outline the current thinking"),
                innovationStatement: Yup.string().required("If this proposal progresses previous research, what are the next steps that are being considered? If it is a paradigm shift, what has prompted it?"),
                influence: Yup.string().required("How is this proposal influenced by prevailing opinion?"),
                layperson: Yup.string().required("How would you describe this research to someone new to your field?"),
                elevator: Yup.string().required("Give it a try."),
                // video:
                resourcesConfirmation: Yup.string().required("Do you have access to research infrastructure you will need?"),
                participantPlan: Yup.string().required("Do you have a plan for how you will recruit participants for this research proposal? If your study does not require participants, then NA will do the job here."),
                resourceRequests: Yup.array().required('What sort of resources are you seeking?'),
                resourceOffers: Yup.array().required('What sort of resources will you bring to this project?'),
                technique: Yup.string().required("Ideally, this answer looks something close to 'Yes, because...' or a 'No, but this team is amazing and will master these techniques in no time, because...'"),
                pitfalls: Yup.string().required("If you've tried to look at this objectively, and can't see any pitfalls, then 'Not Applicable' will do here."),
                community: Yup.string().required("It can be a good idea to do this. If you do, you'll show sensitivity to the interests of others in your field and may open doors for potential collaborations and translation opportunities."),
                samplesize: Yup.string().required("These questions address research quality issues that funders are assessing in considering a proposal."),
                methodDescription: Yup.string().required("What approach will you take in this research?"),
                qualityControls: Yup.string().required("What controls will you put in place? These should address participants, comparators and any interventions."),
                sopAdoption: Yup.string().required("Describe at a summary level, any part of the Statement of Procedures that you have proposed that is noteworthy for reviewers."),
                participantNotification: Yup.string().required("Will you notify participants (if there are any) about the outcomes of this research? If so, describe how that will be done."),
                preregisterPlatform: Yup.string().nullable().required("Select preregistration intention"),
                teamOverview: Yup.string().required("Summarise the collective capabilities and experience of the team making this proposal"),
                proposalLead: Yup.string().required("Enter the name of the team leader"),
                indigenous: Yup.string().required("Either outline the contribution of indigenous team members or mark this field 'Not Applicable'"),
                teamSkillGap: Yup.string().required("Either outline the contribution of indigenous team members or mark this field 'Not Applicable'"),
                performanceIndicators: Yup.string().required("Either outline the performance indicators or mark this field 'Not Applicable'"),
                timeline: Yup.string().required("Either outline the milestones or mark this field 'Not Applicable'"),
                confirmationTeamLead: Yup.boolean().oneOf(
                    [true],
                    "Confirmation that you and each team member has reviewed each of the applicable policies is required"
                ),
                outcomeOverview: Yup.string().required("How might your study contribute to knowledge in the field?"),
                potentialApplications: Yup.string().required("Do you have any insight into potential applications for this research?"),
                potentialResearchAngles: Yup.string().required("Are there any tangential research questions that you think might follow from this study?"),
                budget: Yup.string().required("Attach a link to your project budget?"),
                ethicsIssue: Yup.array().required("Complete your ethics assessment"),
                ethicsManagementPlan: Yup.string().required("Add an ethics management plan, or if there are no issues, complete this field with 'Not Applicable'"),
                conflict: Yup.string().required("Are there any conflicts of interest?"),
                reproducibility: Yup.string().required("How will you approach reproducibility?"),
            })}
</code>```

答:
There is a param in Formik as errors. You can access it via

```<code><Formik>
  (handleSubmit,errors,touched){
     console.log(errors);
     return (<React.Fragement>
      // Put other elements in here
      </React.Fragement>);
  }
</Formik>
</code>```

After submitting the code you can see the errors which are occurred in your form. And use Formik like https://codesandbox.io/s/zkrk5yldz

And it is a good practice to use the validation schema out of the function as a separate object. Because it does not need to rebuild again and again. (

Body:
I have a react app that uses Formik for forms and Cloud Firestore for the database.

I am trying to save the form data in Cloud Firestore. I get no errors in my console or react inspector tools, and when I press submit, I can see in the react inspect tool that the button goes to disabled and then enabled again, but the form doesn't clear the data and the data does not get sent to Cloud Firestore.

My handleSubmit function has:

handleSubmit = (formState, { resetForm }) => {
    // Now, you're getting form state here!
    const payload = {
        ...formState,
        fieldOfResearch: formState.fieldOfResearch.map(t => t.value),
        preregisterPlatform: formState.preregisterPlatform.value,
        resourceRequests: formState.resourceRequests.map(t => t.value),
        resourceOffers: formState.resourceOffers.map(t => t.value),
        ethicsIssue: formState.ethicsIssue.map(t => t.value),
        disclosureStatus: formState.disclosureStatus.value,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      }
      console.log("formvalues", payload);

    fsDB
      .collection("project")
      .add(payload)
      .then(docRef => {
        console.log("docRef>>>", docRef);
        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };

My submit button has:

                            <Button
                                variant="outline-primary"
                                type="submit"
                                id="ProjectId"
                                onClick={handleSubmit}
                                disabled={!dirty || isSubmitting}
                            >
                                Save
                            </Button>

The form is long - it has 39 questions, I can see from my Cloud Firestore data usage that I'm no where close to the limits for reads and writes. I don't know how to measure the size of my form submit data to know if the form data exceeds Cloud Firestore limits - is there a way to get Firestore to tell you if that's why the submit isn't working?

My console log to see the payload in the handleSubmit isn't running - so I think there must be another issue - I just can't find any information on what the problem might be.

Has anyone had an issue with long forms not posting to Cloud Firestore? If i keep the first 10 questions only, this form submits to the database.

I think I am well within my usage limits on firestore:

NEXT ATTEMPT

So, I took each of questions 11-39 out of the form and commented all of the Yup validations. I added the questions back one at a time and found that the form works and posts to firestore, until I uncommented the validations. They all pass - there are no errors. So - now I'm wondering if the time it costs to check them is counted by firestore for its process and maybe that's causing a time out? Is that possible? If so, is there any way to get an indication from Firestore that this is the problem?  My validations are below.

I tried commenting and then uncommenting the validations in batches of 10. The form posts to firebase successfully if I comment all the validations from video down to the end. There are no errors in these validations. I just can't have them as well as successful posting to the database.

<Formik
            initialValues={initialValues}
            validationSchema={Yup.object().shape({
                title: Yup.string().required("Give your proposal a title"),
                subtitle: Yup.string().required("Now a subtitle"),
                fieldOfResearch: Yup.array().required("What is your field of research?"),
                disclosureStatus: Yup.string().nullable().required("Some projects are sensitive. Choose a disclosure setting."),
                overview: Yup.string().required("Outline your proposal"),
                objective: Yup.string().required("What is your objective?"),
                currentThinking: Yup.string().required("Outline the current thinking"),
                innovationStatement: Yup.string().required("If this proposal progresses previous research, what are the next steps that are being considered? If it is a paradigm shift, what has prompted it?"),
                influence: Yup.string().required("How is this proposal influenced by prevailing opinion?"),
                layperson: Yup.string().required("How would you describe this research to someone new to your field?"),
                elevator: Yup.string().required("Give it a try."),
                // video:
                resourcesConfirmation: Yup.string().required("Do you have access to research infrastructure you will need?"),
                participantPlan: Yup.string().required("Do you have a plan for how you will recruit participants for this research proposal? If your study does not require participants, then NA will do the job here."),
                resourceRequests: Yup.array().required('What sort of resources are you seeking?'),
                resourceOffers: Yup.array().required('What sort of resources will you bring to this project?'),
                technique: Yup.string().required("Ideally, this answer looks something close to 'Yes, because...' or a 'No, but this team is amazing and will master these techniques in no time, because...'"),
                pitfalls: Yup.string().required("If you've tried to look at this objectively, and can't see any pitfalls, then 'Not Applicable' will do here."),
                community: Yup.string().required("It can be a good idea to do this. If you do, you'll show sensitivity to the interests of others in your field and may open doors for potential collaborations and translation opportunities."),
                samplesize: Yup.string().required("These questions address research quality issues that funders are assessing in considering a proposal."),
                methodDescription: Yup.string().required("What approach will you take in this research?"),
                qualityControls: Yup.string().required("What controls will you put in place? These should address participants, comparators and any interventions."),
                sopAdoption: Yup.string().required("Describe at a summary level, any part of the Statement of Procedures that you have proposed that is noteworthy for reviewers."),
                participantNotification: Yup.string().required("Will you notify participants (if there are any) about the outcomes of this research? If so, describe how that will be done."),
                preregisterPlatform: Yup.string().nullable().required("Select preregistration intention"),
                teamOverview: Yup.string().required("Summarise the collective capabilities and experience of the team making this proposal"),
                proposalLead: Yup.string().required("Enter the name of the team leader"),
                indigenous: Yup.string().required("Either outline the contribution of indigenous team members or mark this field 'Not Applicable'"),
                teamSkillGap: Yup.string().required("Either outline the contribution of indigenous team members or mark this field 'Not Applicable'"),
                performanceIndicators: Yup.string().required("Either outline the performance indicators or mark this field 'Not Applicable'"),
                timeline: Yup.string().required("Either outline the milestones or mark this field 'Not Applicable'"),
                confirmationTeamLead: Yup.boolean().oneOf(
                    [true],
                    "Confirmation that you and each team member has reviewed each of the applicable policies is required"
                ),
                outcomeOverview: Yup.string().required("How might your study contribute to knowledge in the field?"),
                potentialApplications: Yup.string().required("Do you have any insight into potential applications for this research?"),
                potentialResearchAngles: Yup.string().required("Are there any tangential research questions that you think might follow from this study?"),
                budget: Yup.string().required("Attach a link to your project budget?"),
                ethicsIssue: Yup.array().required("Complete your ethics assessment"),
                ethicsManagementPlan: Yup.string().required("Add an ethics management plan, or if there are no issues, complete this field with 'Not Applicable'"),
                conflict: Yup.string().required("Are there any conflicts of interest?"),
                reproducibility: Yup.string().required("How will you approach reproducibility?"),
            })}

Body:
There is a param in Formik as errors. You can access it via

<Formik>
  (handleSubmit,errors,touched){
     console.log(errors);
     return (<React.Fragement>
      // Put other elements in here
      </React.Fragement>);
  }
</Formik>

After submitting the code you can see the errors which are occurred in your form. And use Formik like https://codesandbox.io/s/zkrk5yldz

And it is a good practice to use the validation schema out of the function as a separate object. Because it does not need to rebuild again and again. (


问:
Why does gcc throw warning about conditionally-supported offsetof?
I have two structures in c++

```<code>struct Vertex {
  float x,y,z;
  float nx, ny, nz;
};

struct SkinnedVertex : public Vertex {
  uint32_t j0, j1, j2, j3;
  float w0, w1, w2, w3;
}
</code>```

Now, when I use offsetof to get offset of Vertex, everything is fine but if I use offsetof in SkinnedVertex, I get the following warning when compiling with GCC:

warning: offsetof within non-standard-layout type ‘SkinnedVertex’ is conditionally-supported

My guess is that this happens because I am inheriting SkinnedVertex from Vertex, which makes this a non-standard-layout. But why does this happen? Does inheritance add additional information that makes this a non standard layout? Is thee a way to enforce it so that both of these structures are in standard layout?

EDIT: Changed jN types to uint32_t (was float)

答:
https://en.cppreference.com/w/cpp/named_req/StandardLayoutType

A standard layout type requires all data members be in the same type.

Standard layout is conservative in definition. Additional types could be made standard layout. The fact that a type is not standard layout doesn't mean there is a good reason that it isn't. It just means the standard committee and compilers haven't done the work to justify it. I mean, you could make classes with virtual functions standard layout if the committee really wanted (like, standardize how vtables work).

One concern is that the committee doesn't want to needlessly break existing code. So they try to standardize existing practice unless there is a good reason. If two compilers disagree on layout of a class, that makes standardizing their layout more costly and/or generate less benefits.

Standard layout is technically just a flag; semantically it means different compilers with similar options (like packing) are going to compile compatible data layouts.

Body:
I have two structures in c++

struct Vertex {
  float x,y,z;
  float nx, ny, nz;
};

struct SkinnedVertex : public Vertex {
  uint32_t j0, j1, j2, j3;
  float w0, w1, w2, w3;
}

Now, when I use offsetof to get offset of Vertex, everything is fine but if I use offsetof in SkinnedVertex, I get the following warning when compiling with GCC:

warning: offsetof within non-standard-layout type ‘SkinnedVertex’ is conditionally-supported

My guess is that this happens because I am inheriting SkinnedVertex from Vertex, which makes this a non-standard-layout. But why does this happen? Does inheritance add additional information that makes this a non standard layout? Is thee a way to enforce it so that both of these structures are in standard layout?

EDIT: Changed jN types to uint32_t (was float)


问:
How to improve the accuracy of Yolov4-tiny.tflite in flutter
I have trained the yolov4-tiny file and successfully converted it to tflite. There were no problems during the computer test, but I encountered difficulties in installing it on the phone.

As I put my tflite into the flutter, I had different test results from my computer. And the result is not good, the accuracy is much lower, and the recognition error is often. I think the problem appear at classierYOLOv4, but i'm not sure where is wrong.

Is there any suggestion for me to fix this problem?

Thanks a lot for your help!

Here is computer test image:

Here is the code:https://github.com/piggychu0w0/flutter-yolov4tiny-tflite

答:
I think the problem here is your input not being scaled to (0,1). You have to add a normalize layer into your model or scale your input first.

Edit:
Using this code to normalize image

```<code>TensorImage getProcessedImage(TensorImage inputImage) {
    padSize = max(inputImage.height, inputImage.width);
    if (imageProcessor == null) {
      imageProcessor = ImageProcessorBuilder()
          .add(ResizeWithCropOrPadOp(padSize, padSize))
          .add(ResizeOp(INPUT_SIZE, INPUT_SIZE, ResizeMethod.BILINEAR))
          .add(DequantizeOp(0, 255.0))
          .build();
    }
    inputImage = imageProcessor.process(inputImage);
    return inputImage;
  }
</code>```

and load the input image

```<code>TensorImage inputImage =  TensorImage(TfLiteType.float32);
inputImage.loadImage(image);
inputImage = getProcessedImage(inputImage);
</code>```

Body:
I think the problem here is your input not being scaled to (0,1). You have to add a normalize layer into your model or scale your input first.

Edit:
Using this code to normalize image

TensorImage getProcessedImage(TensorImage inputImage) {
    padSize = max(inputImage.height, inputImage.width);
    if (imageProcessor == null) {
      imageProcessor = ImageProcessorBuilder()
          .add(ResizeWithCropOrPadOp(padSize, padSize))
          .add(ResizeOp(INPUT_SIZE, INPUT_SIZE, ResizeMethod.BILINEAR))
          .add(DequantizeOp(0, 255.0))
          .build();
    }
    inputImage = imageProcessor.process(inputImage);
    return inputImage;
  }

and load the input image

TensorImage inputImage =  TensorImage(TfLiteType.float32);
inputImage.loadImage(image);
inputImage = getProcessedImage(inputImage);


问:
How to center scrollable content with header?
I'm trying to center some content. The content is larger than the parent and therefore requires scrolling. There is also a header at top. For some reason, the scroll height clips the scrollable content. Thoughts on how I should fix the issue?

Here's the fiddle: https://jsfiddle.net/xgsqyu45/

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

答:
easily with set align-items: flex-start; on .scroll you can prevent that.

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
  background-image: url(https://yari-demos.prod.mdn.mozit.cloud/en-US/docs/Web/HTML/Element/img/clock-demo-400px.png);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

Body:
easily with set align-items: flex-start; on .scroll you can prevent that.

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
  background-image: url(https://yari-demos.prod.mdn.mozit.cloud/en-US/docs/Web/HTML/Element/img/clock-demo-400px.png);
}

<div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div>


问:
Flink SQL Windows not Reporting Final Results
I'm using Flink SQL to compute event-time-based windowed analytics. Everything works fine until my data source becomes idle each evening, after which the results for the last minute aren't produced until the next day when data begins to flow again.

CREATE TABLE input
    id STRING,
    data BIGINT,
    rowtime TIMESTAMP(3) METADATA FROM 'timestamp',
    WATERMARK FOR rowtime AS rowtime - INTERVAL '1' SECOND
WITH (
    'connector' = 'kafka',
    'topic' = 'input',
    'properties.bootstrap.servers' = 'localhost:9092',
    'scan.startup.mode' = 'latest-offset',
    'format' = 'json'
)

SELECT ...
FROM
  (SELECT * FROM
     TABLE(TUMBLE(TABLE input, DESCRIPTOR(rowtime), INTERVAL '1' MINUTES)))
GROUP BY ..., window_start, window_end
```

I've tried setting table.exec.source.idle-timeout, but it didn't help. What can I do?

答:
table.exec.source.idle-timeout (and the corresponding withIdleness construct used with the DataStream API for WatermarkStrategy) detects idle input partitions and prevents them from holding back the progress of the overall watermark. However, for the overall watermark to advance, there must still be some input, somewhere.

Some options:

(1) Live with the problem, which means waiting until the watermark can advance normally, based on observing larger timestamps in the input stream. As you've indicated, in your use case this can require waiting several hours.

(2) Arrange for the input stream(s) to contain keep-alive messages. This way the watermark generator will have evidence (based on the timestamps in the keep-alive messages) that it can advance the watermark. You'll have to modify your queries to ignore these otherwise extraneous events.

(3) Upon reaching the point where the job has fully ingested all of the daily input, but hasn't yet produced the final set of results, stop the job and specify --drain. This will send a watermark with value MAX_WATERMARK through the pipeline, which will close all pending windows. You can then restart the job.

(4) Implement a custom watermark strategy that uses a processing-time timer to detect idleness and artificially advance the watermark based on the passage of wall clock time. This will require converting your table input to a DataStream, adding the watermarks there, and then converting back to a table for the windowing. See https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/table/data_stream_api/ for examples of these conversions.

Body:
I'm using Flink SQL to compute event-time-based windowed analytics. Everything works fine until my data source becomes idle each evening, after which the results for the last minute aren't produced until the next day when data begins to flow again.

CREATE TABLE input
    id STRING,
    data BIGINT,
    rowtime TIMESTAMP(3) METADATA FROM 'timestamp',
    WATERMARK FOR rowtime AS rowtime - INTERVAL '1' SECOND
WITH (
    'connector' = 'kafka',
    'topic' = 'input',
    'properties.bootstrap.servers' = 'localhost:9092',
    'scan.startup.mode' = 'latest-offset',
    'format' = 'json'
)

SELECT ...
FROM
  (SELECT * FROM
     TABLE(TUMBLE(TABLE input, DESCRIPTOR(rowtime), INTERVAL '1' MINUTES)))
GROUP BY ..., window_start, window_end

I've tried setting table.exec.source.idle-timeout, but it didn't help. What can I do?


问:
How to create library for v lang by c++
I would like to ask how to create a module on c++ for v lang.
For example

с++

int some_method() {
 return 6
}
```
<p>v</p>
```import my_c_module
my_c_module.some_method()
```

I will be grateful for any information

And can I call c++ class method in v lang?

答:
In V every file in the root of a folder is part of the same module. Simple programs don't need to specify module name, in which case it defaults to 'main'.

V is a very modular language. Creating reusable modules is encouraged and is quite easy to do. To create a new module, create a directory with your module's name containing .v files with code:

```<code>cd ~/code/modules
mkdir mymodule
vim mymodule/myfile.v
</code>```

Inside myfile.v

```<code>// myfile.v
module mymodule

// To export a function we have to use `pub`
pub fn say_hi() {
    println('hello from mymodule!')
}
</code>```

Now you can call your module

```<code>import mymodule

fn main() {
    mymodule.say_hi()
}
</code>```

You can create also your custom module, and here is the official docs

Title: How to create library for v lang by c++

Body:
I would like to ask how to create a module on c++ for v lang.
For example

с++

int some_method() {
 return 6
}

v

import my_c_module
my_c_module.some_method()

I will be grateful for any information

And can I call c++ class method in v lang?

Body:
In V every file in the root of a folder is part of the same module. Simple programs don't need to specify module name, in which case it defaults to 'main'.

V is a very modular language. Creating reusable modules is encouraged and is quite easy to do. To create a new module, create a directory with your module's name containing .v files with code:

cd ~/code/modules
mkdir mymodule
vim mymodule/myfile.v

Inside myfile.v

// myfile.v
module mymodule

// To export a function we have to use `pub`
pub fn say_hi() {
    println('hello from mymodule!')
}

Now you can call your module

import mymodule

fn main() {
    mymodule.say_hi()
}

You can create also your custom module, and here is the official docs


问:
C# Delegates to methods with different optional parameters
I know that I can declare delegates that have default constant parameters such as:

```<code>delegate void MyDelegate(int x, int y = 5);
</code>```

and then call it anywhere with any method that matches the signature.

Ok, I've got LOTS of methods declared like this way:

```<code>public Something FirstMethod(float val = 10, int skip = 0){ ... return sth; }
public Something SecondMethod(float val = 20, int skip = 0){ ... return sth; }
public Something ThirdMethod(float val = 5, int skip = 0){ ... return sth; }
</code>```

... this list goes up all the way down, anyway, they all have that signature structure. The point here is that, they all have floating point argument, that defaults to something different.

Then, I want to create a delegate that will point to one of these methods:

```<code>delegate Something ProblematicDelegateType(<<WHAT WILL GO HERE>>);
ProblematicDelegateType myFunc;
if(someValue == someParameter){
    myFunc = FirstMethod;
}else if(...){
    myFunc = SecondMethod;
}else...
...
}

myFunc();
myFunc(skip:100);
</code>```

I want to be able to call myFunc both parameterless or with the skip parameter. In this part of code, the first parameter, val, is NOT used. (they are used elsewhere).

What will go to the delegate's argument list? I want to preserve that method's default val argument, whatever it is.

答:
If I understand you correctly, your myFunc will leave out the val parameter entirely, always using the default for whichever method you're ultimately calling, correct?

If so, this should accomplish what you're looking for:

```<code>delegate Something ProblematicDelegateType(int skip = 0);
ProblematicDelegateType myFunc;
if (someValue == someParameter) {
    myFunc = skip => FirstMethod(skip: skip);
} else if (...) {
    myFunc = skip => SecondMethod(skip: skip);
} else ...
    ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know that I can declare delegates that have default constant parameters such as:

delegate void MyDelegate(int x, int y = 5);

and then call it anywhere with any method that matches the signature.

Ok, I've got LOTS of methods declared like this way:

public Something FirstMethod(float val = 10, int skip = 0){ ... return sth; }
public Something SecondMethod(float val = 20, int skip = 0){ ... return sth; }
public Something ThirdMethod(float val = 5, int skip = 0){ ... return sth; }

... this list goes up all the way down, anyway, they all have that signature structure. The point here is that, they all have floating point argument, that defaults to something different.

Then, I want to create a delegate that will point to one of these methods:

delegate Something ProblematicDelegateType(<<WHAT WILL GO HERE>>);
ProblematicDelegateType myFunc;
if(someValue == someParameter){
    myFunc = FirstMethod;
}else if(...){
    myFunc = SecondMethod;
}else...
...
}

myFunc();
myFunc(skip:100);

I want to be able to call myFunc both parameterless or with the skip parameter. In this part of code, the first parameter, val, is NOT used. (they are used elsewhere).

What will go to the delegate's argument list? I want to preserve that method's default val argument, whatever it is.

Body:
If I understand you correctly, your myFunc will leave out the val parameter entirely, always using the default for whichever method you're ultimately calling, correct?

If so, this should accomplish what you're looking for:

delegate Something ProblematicDelegateType(int skip = 0);
ProblematicDelegateType myFunc;
if (someValue == someParameter) {
    myFunc = skip => FirstMethod(skip: skip);
} else if (...) {
    myFunc = skip => SecondMethod(skip: skip);
} else ...
    ...
}


问:
jinja giving error on pillar variable with absolute folder path
I got a pillar item which looks something like below:

```<code> "fileabspath": [
"Z:\\customer\region\chicago"
]
</code>```

And on my sls file, I am trying to access the "filepath" pillar value with the below:

```<code>{% set fileabspath = salt['pillar.get']('fileabspath', None) %}

customer:
  region.filepath:
    - name: '{{fileabspath}}'
</code>```

As soon as job hits above last line, I get below error.

```<code>failed: while parsing a block mapping\n  in \"<unicode string>\", line 10, column 1\ndid not find expected key\n  in \"<unicode string>\"
</code>```

Any advice how to fix the issue ? Thank you.

答:
You need to escape the backslashes if you're using that data format

"fileabspath": [
  "Z:\\\\customer\\region\\chicago"
]
```

Body:
I got a pillar item which looks something like below:

 "fileabspath": [
"Z:\\customer\region\chicago"
]

And on my sls file, I am trying to access the "filepath" pillar value with the below:

{% set fileabspath = salt['pillar.get']('fileabspath', None) %}

customer:
  region.filepath:
    - name: '{{fileabspath}}'

As soon as job hits above last line, I get below error.

failed: while parsing a block mapping\n  in \"<unicode string>\", line 10, column 1\ndid not find expected key\n  in \"<unicode string>\"

Any advice how to fix the issue ? Thank you.


问:
riginal error was: DLL load failed while importing _multiarray_umath
i got a something weird situation with import packages.

when i use numpy on Jupyter notebook, it's fine and my all source codes are run without problem

but if i use numpy on Visual Studio Code i got a something error.

```<code>ImportError: Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.8 from "C:\Users\Mohw-IN\anaconda3\python.exe"
  * The NumPy version is: "1.18.5"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: DLL load failed while importing _multiarray_umath: The specified module cannot be used
다.
</code>```

and i found something weird.

```<code>import os
print("PYTHONPATH:", os.environ.get('PYTHONPATH'))
---------------
PYTHONPATH: None
</code>```

how can i do for use numpy in vscode?

答: Open Anaconda and Launch Visual Studio. Now run the program.</p>

Body:
i got a something weird situation with import packages.

when i use numpy on Jupyter notebook, it's fine and my all source codes are run without problem

but if i use numpy on Visual Studio Code i got a something error.

ImportError: Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.8 from "C:\Users\Mohw-IN\anaconda3\python.exe"
  * The NumPy version is: "1.18.5"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: DLL load failed while importing _multiarray_umath: The specified module cannot be used
다.

and i found something weird.

import os
print("PYTHONPATH:", os.environ.get('PYTHONPATH'))
---------------
PYTHONPATH: None

how can i do for use numpy in vscode?


问:
How Can I fix "Can only add LpConstraintVar, LpConstraint, LpAffineExpression or True objects" error
Currently I have an LP model and while I'm trying to run it, the constraint

```<code>for i in DEMANDPOINT:
    prob += (lpSum(z[i][j]) == 1 for j in FACILITY5)
</code>```

causes this error to pop up.

TypeError: Can only add LpConstraintVar, LpConstraint, LpAffineExpression or True objects

How can I fix this? Thanks in advance

答:
You get an error because are adding to your problem a generator of constraints, where each constraint is of the form z[i][j] == 1, which is probably not what you want.

In case you are trying to add a constraint on the z variables with the sum over all the values of j for a given i must be one, then you can write it as follows.

```<code>for i in DEMANDPOINT:
    prob += lpSum(z[i][j] for j in FACILITY5) == 1
</code>```

Body:
Currently I have an LP model and while I'm trying to run it, the constraint

for i in DEMANDPOINT:
    prob += (lpSum(z[i][j]) == 1 for j in FACILITY5)

causes this error to pop up.

TypeError: Can only add LpConstraintVar, LpConstraint, LpAffineExpression or True objects

How can I fix this? Thanks in advance

Body:
You get an error because are adding to your problem a generator of constraints, where each constraint is of the form z[i][j] == 1, which is probably not what you want.

In case you are trying to add a constraint on the z variables with the sum over all the values of j for a given i must be one, then you can write it as follows.

for i in DEMANDPOINT:
    prob += lpSum(z[i][j] for j in FACILITY5) == 1


问:
Flutter Integration test failed when using tester.enterText more than 2 times
If I run this code snippet:

```<code>await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');
</code>```

or this one:

```<code>await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');
</code>```

It both works.

But if I run the three:

```<code>await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');
</code>```

The test will fail and produce this error:

```<code>══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following StateError was thrown running a test:
Bad state: No element

When the exception was thrown, this was the stack:
#0      Iterable.single (dart:core/iterable.dart:654:25)
#1      WidgetController.state (package:flutter_test/src/controller.dart:156:42)
#2      WidgetTester.showKeyboard.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1042:42)
#3      WidgetTester.showKeyboard.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1041:39)
#6      TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#7      WidgetTester.showKeyboard (package:flutter_test/src/widget_tester.dart:1041:27)
#8      WidgetTester.enterText.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1077:13)
#9      WidgetTester.enterText.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1076:39)
#12     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#13     WidgetTester.enterText (package:flutter_test/src/widget_tester.dart:1076:27)
#14     AddAccountScreenRobot.enterAccountDetails (file:///C:/Users/Noyruto/sources/repos/account_saver/integration_test/robots/add_account_screen_robot.dart:25:18)
<asynchronous suspension>
<asynchronous suspension>
(elided 5 frames from dart:async and package:stack_trace)
</code>```

答:
There must have some settling time between two tester.enterText to work properly. Add these according to your need.

```<code>        await tester.pump();
        await tester.pumpAndSettle();
        await tester.pump(Duration(seconds: 3));
</code>```

Example

```<code>await tester.enterText(
    find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.pumpAndSettle();
await tester.enterText(find.byKey(Key('usernameControlKey')),'username1');
await tester.pumpAndSettle();
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');
await tester.pump(Duration(seconds: 3));
</code>```

Body:
If I run this code snippet:

await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');

or this one:

await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');

It both works.

But if I run the three:

await tester.enterText(
        find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.enterText(find.byKey(Key('usernameControlKey')), 'username1');
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');

The test will fail and produce this error:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following StateError was thrown running a test:
Bad state: No element

When the exception was thrown, this was the stack:
#0      Iterable.single (dart:core/iterable.dart:654:25)
#1      WidgetController.state (package:flutter_test/src/controller.dart:156:42)
#2      WidgetTester.showKeyboard.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1042:42)
#3      WidgetTester.showKeyboard.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1041:39)
#6      TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#7      WidgetTester.showKeyboard (package:flutter_test/src/widget_tester.dart:1041:27)
#8      WidgetTester.enterText.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1077:13)
#9      WidgetTester.enterText.<anonymous closure> (package:flutter_test/src/widget_tester.dart:1076:39)
#12     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#13     WidgetTester.enterText (package:flutter_test/src/widget_tester.dart:1076:27)
#14     AddAccountScreenRobot.enterAccountDetails (file:///C:/Users/Noyruto/sources/repos/account_saver/integration_test/robots/add_account_screen_robot.dart:25:18)
<asynchronous suspension>
<asynchronous suspension>
(elided 5 frames from dart:async and package:stack_trace)

Body:
There must have some settling time between two tester.enterText to work properly. Add these according to your need.

        await tester.pump();
        await tester.pumpAndSettle();
        await tester.pump(Duration(seconds: 3));

Example

await tester.enterText(
    find.byKey(Key('titleControlKey')), 'Sample Account 1');
await tester.pumpAndSettle();
await tester.enterText(find.byKey(Key('usernameControlKey')),'username1');
await tester.pumpAndSettle();
await tester.enterText(find.byKey(Key('passwordControlKey')), 'password1');
await tester.pump(Duration(seconds: 3));


问:
Converting pandas dataframe to dictionary with same keys over multiple rows
I'm trying to create a dictionary from a pandas data frame with key from a column and values from rest of columns. But the problem is I will have same keys in multiple rows and I've read through many other similar SO posts but couldn't find the answer. This is what I have:

df1:

```<code>pid  feature_id  feature_value
78          20            1.0
78        1130            3.0
...
91        1148            1.0
92        1153            4.0
92        1154            1.0
...
115       1162            1.0
115       1175            5.0
......
</code>```

This is what I tried:

```<code>df2 = df1.set_index('pid').agg(tuple, 1).to_dict()
</code>```

But problem is this seems to not take into account the same keys from multiple rows.

What I want is something like this:

```<code>{78: [(20, 1.0), (1130, 3.0)]..., 115: [(1162, 1.0), (1175, 5.0)], ...}
</code>```

Please advise.

答:
```<code>def df_to_dict(df):
    # create a dictionary
    d = {}
    # iterate over the rows
    for index, row in df.iterrows():
        # if the key is not in the dictionary, add it
        if row[0] not in d:
            d[int(row[0])] = []
        # add the tuple (row[1], row[2]) to the list associated with the key
        d[row[0]].append((row[1], row[2]))
    return d
print(df_to_dict(df))
</code>```

Body:
I'm trying to create a dictionary from a pandas data frame with key from a column and values from rest of columns. But the problem is I will have same keys in multiple rows and I've read through many other similar SO posts but couldn't find the answer. This is what I have:

df1:

pid  feature_id  feature_value
78          20            1.0
78        1130            3.0
...
91        1148            1.0
92        1153            4.0
92        1154            1.0
...
115       1162            1.0
115       1175            5.0
......

This is what I tried:

df2 = df1.set_index('pid').agg(tuple, 1).to_dict()

But problem is this seems to not take into account the same keys from multiple rows.

What I want is something like this:

{78: [(20, 1.0), (1130, 3.0)]..., 115: [(1162, 1.0), (1175, 5.0)], ...}

Please advise.


问:
How to save only the play recap of Ansible to a file?
The question is as the title said, how to save only the "play recap" of ansible to a file or variable?

I am trying to make a web UI using Flask to make the user use ansible easier without writing any script or playbook, just write some hosts' IP address and click on what you want to do and flask/python script will call and play the premade playbook. The problem is I can't really tell the user whether the task is successfully done or not, because it only shows on Linux terminal. Therefore I want to "catch" only the "play recap" of the playbook and show it on a web page to tell the user the result.

答:
Since the environment and setup isn't further described, it is assumed you are just running ansible-playbook ... from CLI and send the output to STDOUT.

In such case you could use commands like

```<code>ansible-playbook deployment.yml | tee deployment.log
sed -n '/PLAY RECAP/,$p' deployment.log
</code>```

and proceed further from there.

Thanks to

Linux - grep from certain lines to the end of file

Is there a way to print only Ansible PLAY RECAP into CSV or HTML file and mail it?

Regarding an own plugin, you may take advantage from Ansible Issue #14367 "Show aggregated playbook execution recap at the bottom of play recap" or Access Ansible playbook results after run.

Body:
Since the environment and setup isn't further described, it is assumed you are just running ansible-playbook ... from CLI and send the output to STDOUT.

In such case you could use commands like

ansible-playbook deployment.yml | tee deployment.log
sed -n '/PLAY RECAP/,$p' deployment.log

and proceed further from there.

Thanks to

Linux - grep from certain lines to the end of file

Is there a way to print only Ansible PLAY RECAP into CSV or HTML file and mail it?

Regarding an own plugin, you may take advantage from Ansible Issue #14367 "Show aggregated playbook execution recap at the bottom of play recap" or Access Ansible playbook results after run.


问:
Is it possible to develop WP7 application for sharepoint 2010?
I am developing window phone application. I am consuming the sharepoint web services exposed by the sharepoint 2010. So firstly I am authenticating with the authentication.asmx. I am able to authenticate with the authentication.asmx. Then I am trying to access the list data using the Lists.asmx. For this I am using the following link

http://blogs.msdn.com/b/pstubbs/archive/2010/10/04/developing-windows-phone-7-applications-for-sharepoint-2010.aspx

By following the above link in my code I am getting the System.ServiceModel.ProtocolException at following method

lists.GetListItemsAsync()

I am getting the following error

The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were:

For this scenario I have serached on the internet and I come across the following two link. These are the two link which I am thinking might be useful

http://social.technet.microsoft.com/Forums/en-US/sharepointadmin/thread/9003839f-ec0e-473f-b86d-1b325d5c1a18/

http://msdn.microsoft.com/en-us/library/dd456789.aspx

The first link says that MOSS 2010 doesnt support .NET Framework 4. It supports the .NET Framework 3.5. .NET Framework 4 provides the new CLR. The second link says that if we try to consume .NET 3.5 WCF Service from .NET 4 then we will get the ProtocolException.

Then I am finding me in dought whether I can consume the Sharepoint 2010 list services on my WP7 application or not ?

Can you please tell me whether this is possible or not ? Can you please provide me your suggestions. If I am doing anything wrong then please guide me.

答:
If your SharePoint 2010 installation supports OData, then you can use the technique outlined in Jan Tielens' blog:

http://weblogs.asp.net/jan/archive/2010/04/22/accessing-sharepoint-2010-data-with-rest-odata-on-windows-phone-7.aspx

I've used that technique before and so long as the server is configured correctly, it works like a champ.

/chris


问:
NPM Timeout on install while overseas
I'm on vacation outside of the US where the connection is quite slow and npm install is giving me some trouble.

```<code>› npm config list
; cli configs
user-agent = "npm/3.7.3 node/v5.8.0 darwin x64"

; userconfig /Users/lfender/.npmrc
registry = "http://registry.npmjs.org/"
strict-ssl = false

; globalconfig /Users/lfender/.nvm/versions/node/v5.8.0/etc/npmrc
strict-ssl = false

; node bin location = /Users/lfender/.nvm/versions/node/v5.8.0/bin/node
; cwd = /Users/lfender/source/ag.js
; HOME = /Users/lfender
; "npm config ls -l" to show all defaults.

npm install --verbose
npm info retry will retry, error on last attempt: Error: connect ETIMEDOUT 151.101.56.162:443
</code>```

I have tried setting the registry to http but it looks as though it is still trying to connect on 443 or ssl.

It continues to do this and retries over and over again. What else can I try to establish communication with the registry?

Even when connecting to corporate VPN housed in the US it still fails.

```<code>npm ERR! network connect ETIMEDOUT 151.101.56.162:443
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'
npm verb exit [ 1, true ]
</code>```

I suspect its an issue with the ISP

答: I was using node version 17.3.0 when I had this problem. I updated to node version 17.4.0 and it worked. Try to update your node if all else fails.</p>

Title: NPM Timeout on install while overseas

Body:
I'm on vacation outside of the US where the connection is quite slow and npm install is giving me some trouble.

› npm config list
; cli configs
user-agent = "npm/3.7.3 node/v5.8.0 darwin x64"

; userconfig /Users/lfender/.npmrc
registry = "http://registry.npmjs.org/"
strict-ssl = false

; globalconfig /Users/lfender/.nvm/versions/node/v5.8.0/etc/npmrc
strict-ssl = false

; node bin location = /Users/lfender/.nvm/versions/node/v5.8.0/bin/node
; cwd = /Users/lfender/source/ag.js
; HOME = /Users/lfender
; "npm config ls -l" to show all defaults.

npm install --verbose
npm info retry will retry, error on last attempt: Error: connect ETIMEDOUT 151.101.56.162:443

I have tried setting the registry to http but it looks as though it is still trying to connect on 443 or ssl.

It continues to do this and retries over and over again. What else can I try to establish communication with the registry?

Even when connecting to corporate VPN housed in the US it still fails.

npm ERR! network connect ETIMEDOUT 151.101.56.162:443
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'
npm verb exit [ 1, true ]

I suspect its an issue with the ISP


问:
Update statement from a join
I have this SELECT statement:

```<code>SELECT * FROM `all_uu_features`

INNER JOIN `all_video_names`
ON `all_video_names`.`video_id` = `all_uu_features`.`video_id`

WHERE `language` = 'en'
  AND `navigation` = 'laser-interface'
</code>```

I need to reverse this and UPDATE the database.  How do I do that?  Is there a better way than:

```<code>UPDATE `all_uu_features` SET ...
WHERE `language` = 'en'
  AND `navigation` = 'laser-interface'
</code>```

and

```<code>UPDATE `all_video_names' SET ...
WHERE video_id = ?
</code>```

Can this be done with one statement?

all_video_names:

```<code>video_id | video_name
-------------------
1        |  ABC
2        |  DEF
3   ....
</code>```

all_uu_features:

```<code>feature_name | video_id |  language | navigation
-----------------------------------------------
Hello 1      |  1       |   en      | laser-interface
Hello 2      |  2       |   fr      | laser-interface
</code>```

答:
There is a multi-table update syntax in MySQL. You can actually find an example in the docs of almost exactly what you're trying to do.

```<code>-- docs example
UPDATE TABLE_1 LEFT JOIN TABLE_2 ON TABLE_1.COLUMN_1= TABLE_2.COLUMN_2
SET TABLE_1.COLUMN = EXPR WHERE TABLE_2.COLUMN2 IS NULL
</code>```

In your case, it would be:

```<code>UPDATE
`all_uu_features` uu
INNER JOIN `all_video_names` vid
ON uu.`video_id` = vid.`video_id`
SET uu.column_name = 1, vid.column_name = 2
WHERE `language` = 'en'
  AND `navigation` = 'laser-interface';
</code>```

Title: Update statement from a join

Body:
I have this SELECT statement:

SELECT * FROM `all_uu_features`

INNER JOIN `all_video_names`
ON `all_video_names`.`video_id` = `all_uu_features`.`video_id`

WHERE `language` = 'en'
  AND `navigation` = 'laser-interface'

I need to reverse this and UPDATE the database.  How do I do that?  Is there a better way than:

UPDATE `all_uu_features` SET ...
WHERE `language` = 'en'
  AND `navigation` = 'laser-interface'

and

UPDATE `all_video_names' SET ...
WHERE video_id = ?

Can this be done with one statement?

all_video_names:

video_id | video_name
-------------------
1        |  ABC
2        |  DEF
3   ....

all_uu_features:

feature_name | video_id |  language | navigation
-----------------------------------------------
Hello 1      |  1       |   en      | laser-interface
Hello 2      |  2       |   fr      | laser-interface

Body:
There is a multi-table update syntax in MySQL. You can actually find an example in the docs of almost exactly what you're trying to do.

-- docs example
UPDATE TABLE_1 LEFT JOIN TABLE_2 ON TABLE_1.COLUMN_1= TABLE_2.COLUMN_2
SET TABLE_1.COLUMN = EXPR WHERE TABLE_2.COLUMN2 IS NULL

In your case, it would be:

UPDATE
`all_uu_features` uu
INNER JOIN `all_video_names` vid
ON uu.`video_id` = vid.`video_id`
SET uu.column_name = 1, vid.column_name = 2
WHERE `language` = 'en'
  AND `navigation` = 'laser-interface';


问:
How to get parameter name with C#
How can we get parameter name called by a method in C#?

Example:

```<code>public static void PrintList (List<string> list)
{
    Console.WriteLine("\n");
    foreach (var item in list)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine("\n");
}

PrintList(oxygenList);
</code>```

I need the method to print:

oxygenList

Thanks.

答:
You should use:

```<code>Console.WriteLine(nameof(list));
</code>```

See more: nameof

Update:
This is still not clear for me what do You want to achieve but the easiest way would be:

```<code>public static void PrintList (List<string> list, string nameOfList)
{
    Console.WriteLine(nameOfList);
    Console.WriteLine("\n");
    foreach (var item in list)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine("\n");
}

PrintList(oxygenList, nameof(oxygenList));
</code>```

You may also create a bit cleaner extension method, like this:

```<code>public static class ListPrinter
{
    public static void PrintListWithName(this List<string> list, string nameOfList)
    {
        Console.WriteLine(nameOfList);
        list.ForEach(element => Console.WriteLine(element));
    }
}
</code>```

called like this:

```<code>oxygenList.PrintListWithName(nameof(oxygenList));
</code>```

Title: How to get parameter name with C#

Body:
How can we get parameter name called by a method in C#?

Example:

public static void PrintList (List<string> list)
{
    Console.WriteLine("\n");
    foreach (var item in list)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine("\n");
}

PrintList(oxygenList);

I need the method to print:

oxygenList

Thanks.

Body:
You should use:

Console.WriteLine(nameof(list));

See more: nameof

Update:
This is still not clear for me what do You want to achieve but the easiest way would be:

public static void PrintList (List<string> list, string nameOfList)
{
    Console.WriteLine(nameOfList);
    Console.WriteLine("\n");
    foreach (var item in list)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine("\n");
}

PrintList(oxygenList, nameof(oxygenList));

You may also create a bit cleaner extension method, like this:

public static class ListPrinter
{
    public static void PrintListWithName(this List<string> list, string nameOfList)
    {
        Console.WriteLine(nameOfList);
        list.ForEach(element => Console.WriteLine(element));
    }
}

called like this:

oxygenList.PrintListWithName(nameof(oxygenList));


问:
OnHoverListener is not working on an android emulator?
I'm trying to add mouse/touchpad support to my app and that includes hover support. As per the android guidelines, which say:

Developers can make their app layouts feel polished and easier to use by handling hover events. This is especially true for custom views. The two most common examples of this are:

Indicating to users if an element has interactive behavior, such as being clickable or editable, by changing the mouse pointer icon.

Adding visual feedback to items in a large list or grid when the pointer is hovering over them

```<code>yourView.setOnHoverListener { view, _ ->
  addVisualHighlighting(true)
  view.pointerIcon =
    PointerIcon.getSystemIcon(view.context,
    PointerIcon.TYPE_HAND)
  false // listener did not consume the event.
}
</code>```

This is not working e.g. the pointer icon is not changing and a debug/print line is NOT being called, at least not on an emulator. I am unable to test on a real device so could this be a limitation of the android emulator or am I wrongly implementing this listener? Would it run correctly on the Windows 11 subsystem for android?

答: Well, I tried running my app on android x86 in VirtualBox and everything worked! Looks like the android studio emulator doesn't capture mouse pointers. I'm only wondering if this will work on the Windows 11 subsystem.</p>

Body:
I'm trying to add mouse/touchpad support to my app and that includes hover support. As per the android guidelines, which say:

Developers can make their app layouts feel polished and easier to use by handling hover events. This is especially true for custom views. The two most common examples of this are:

Indicating to users if an element has interactive behavior, such as being clickable or editable, by changing the mouse pointer icon.

Adding visual feedback to items in a large list or grid when the pointer is hovering over them

yourView.setOnHoverListener { view, _ ->
  addVisualHighlighting(true)
  view.pointerIcon =
    PointerIcon.getSystemIcon(view.context,
    PointerIcon.TYPE_HAND)
  false // listener did not consume the event.
}

This is not working e.g. the pointer icon is not changing and a debug/print line is NOT being called, at least not on an emulator. I am unable to test on a real device so could this be a limitation of the android emulator or am I wrongly implementing this listener? Would it run correctly on the Windows 11 subsystem for android?


问:
Why is this trait `impl` considered to leak a private trait?
The following code does not compile:

pub(crate) trait Private {}

pub trait Public {}

impl<T: Private> Public for T {}
```
<p>The error is:</p>
```error[E0445]: private trait `Private` in public interface
 --> src/main.rs:7:1
  |
3 | pub(crate) trait Private {}
  | ------------------------ `Private` declared as private
...
7 | impl<T: Private> Public for T {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't leak private trait
```
<p>I don't understand why the Private trait is considered leaked in this situation.</p>
<p>The linked error explanation lists similar examples which do leak a private trait by using it in a trait bound. However, those examples are different because the trait bounds are something external crates can use.</p>
<p>For example, I can see why this is considered to leak the Private trait:</p>
<pre class="lang-rust prettyprint-override"><code>pub trait Public : Private {} // error: private trait in public interface
</code>```

Here, external crates would be required to implement the Private trait (which they can't do) to implement the Public trait (which they can).

My first example is different in that external crates don't need to know anything about the Private trait – so I'm confused.

Where are the rules of leaking documented? What does leaking a private trait really mean?

Why does my example fail to compile? Is there a reason for guarding against such an impl?

答:
As @eggyal explained in the comments, even though users of Public don't need to know anything about the Private trait, it is still leaked through the documentation, which must include the head of the impl block to communicate which types implement Public.

The workaround is to mark the Private trait as pub. It may still be hidden away in a private mod if you wish to keep it effectively private.

mod hidden {
    pub trait Private {}
}

pub(crate) use hidden::Private;

pub trait Public {}

impl<T: Private> Public for T {}
```

Body:
The following code does not compile:

pub(crate) trait Private {}

pub trait Public {}

impl<T: Private> Public for T {}

The error is:

error[E0445]: private trait `Private` in public interface
 --> src/main.rs:7:1
  |
3 | pub(crate) trait Private {}
  | ------------------------ `Private` declared as private
...
7 | impl<T: Private> Public for T {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't leak private trait

I don't understand why the Private trait is considered leaked in this situation.

The linked error explanation lists similar examples which do leak a private trait by using it in a trait bound. However, those examples are different because the trait bounds are something external crates can use.

For example, I can see why this is considered to leak the Private trait:

pub trait Public : Private {} // error: private trait in public interface

Here, external crates would be required to implement the Private trait (which they can't do) to implement the Public trait (which they can).

My first example is different in that external crates don't need to know anything about the Private trait – so I'm confused.

Where are the rules of leaking documented? What does leaking a private trait really mean?

Why does my example fail to compile? Is there a reason for guarding against such an impl?


问:
Regex for ANY string except "www"? (subdomain)
I was wondering if someone out there could help me with a regex in C#. I think it's fairly simple but I've been wracking my brain over it and not quite sure why I'm having such a hard time.  :)

I've found a few examples around but I can't seem to manipulate them to do what I need.

I just need to match ANY alphanumeric+dashes subdomain string that is not "www", and just up to the "."

Also, ideally, if someone were to type "www.subdomain.domain.com" I would like the www to be ignored if possible. If not, it's not a huge issue.

In other words, I would like to match:

(test).domain.com

(test2).domain.com

(wwwasdf).domain.com

(asdfwww).domain.com

(w).domain.com

(wwwwww).domain.com

(asfd-12345-www-bananas).domain.com

www.(subdomain).domain.com

And I don't want to match:

(www).domain.com

It seems to me like it should be easy, but I'm having troubles with the "not match" part.

For what it's worth, this is for use in the IIS 7 URL Rewrite Module, to rewrite for all non-www subdomains.

Thanks!

答:
This:

```<code>^(?:www\.)?([^.]*)
</code>```

It matches exactly what you put in parentheses in your question.  You will find your answers sitting in group(1).  You have to anchor it to the beginning of the line.   Use this:

```<code>^(?:www\.)?(.*)
</code>```

If you want everything in the URL except the "www.".  One example you did not include in your test cases was "alpha.subdomain.domain.com".  In the event you need to match everything, except "www.", that is not in the "domain.com" part of the string, use this:

```<code>^(?:www\.)?(.+)((?:\.(?:[^./\?]+)){2})
</code>```

It will solve all of your cases, but in addition, will also return "alpha.subdomain" from my additional test case.  And, for an encore, places ".domain.com" in group 2 and will not match beyond that if there are directories or parameters in the url.

I verified all of these responses here.

Finally, for the sake of overkill, if you want to reject addresses that begin with "www.", you can use negative lookbehind:

```<code>^....(?<!www\.).*
</code>```

Body:
This:

^(?:www\.)?([^.]*)

It matches exactly what you put in parentheses in your question.  You will find your answers sitting in group(1).  You have to anchor it to the beginning of the line.   Use this:

^(?:www\.)?(.*)

If you want everything in the URL except the "www.".  One example you did not include in your test cases was "alpha.subdomain.domain.com".  In the event you need to match everything, except "www.", that is not in the "domain.com" part of the string, use this:

^(?:www\.)?(.+)((?:\.(?:[^./\?]+)){2})

It will solve all of your cases, but in addition, will also return "alpha.subdomain" from my additional test case.  And, for an encore, places ".domain.com" in group 2 and will not match beyond that if there are directories or parameters in the url.

I verified all of these responses here.

Finally, for the sake of overkill, if you want to reject addresses that begin with "www.", you can use negative lookbehind:

^....(?<!www\.).*


问:
Creating a 2 column df from a loop of unique values
I am looking to create a matrix babyList storing the number of unique names in the babynames package for every year in that package. I am only interested in using a loop to do this.

```<code>   library(babynames)
###### Here I create the matrix where I want my output to be in
    babyList <- data.frame(matrix(ncol=2,nrow=range(babynames$year[2]-range(babynames$year[1])),))
    colnames(babyList) <- c("years","unique names")
</code>```

The for loop is giving me trouble. Here is what I know it will need:

Pseudo code

```<code>for (i in babynames$year) {
length(unique(babynames$name[babynames$year == i]

}
</code>```

How can I put this all together in a correct structure?

答:
I would suggest using dplyr::summarise() instead:

```<code>library(babynames)
library(dplyr)

babynames %>%
  group_by(year) %>%
  summarise(unique_names = length(unique(name)))
</code>```

which gives the number of unique names for each year in the babynames dataset:

```<code># A tibble: 138 x 2
    year unique_names
 * <dbl>        <int>
 1  1880         1889
 2  1881         1830
 3  1882         2012
 4  1883         1962
 ...
</code>```

Body:
I am looking to create a matrix babyList storing the number of unique names in the babynames package for every year in that package. I am only interested in using a loop to do this.

   library(babynames)
###### Here I create the matrix where I want my output to be in
    babyList <- data.frame(matrix(ncol=2,nrow=range(babynames$year[2]-range(babynames$year[1])),))
    colnames(babyList) <- c("years","unique names")

The for loop is giving me trouble. Here is what I know it will need:

Pseudo code

for (i in babynames$year) {
length(unique(babynames$name[babynames$year == i]

}

How can I put this all together in a correct structure?

Body:
I would suggest using dplyr::summarise() instead:

library(babynames)
library(dplyr)

babynames %>%
  group_by(year) %>%
  summarise(unique_names = length(unique(name)))

which gives the number of unique names for each year in the babynames dataset:

# A tibble: 138 x 2
    year unique_names
 * <dbl>        <int>
 1  1880         1889
 2  1881         1830
 3  1882         2012
 4  1883         1962
 ...


问:
Detect if an image is negative
I'm trying to clean some chest X-ray data to feed to a CNN. In my dataset are currently many images where the bones are shown in white (higher pixel value than the background), like so:

While others show the bones in a darker color than the background, like this:

Can you show me a way to label the two? I have no other external info about the image, though it can be assumed they are the same size (

Assuming they have the same size (about 1000x2000) and that the first row of pixels has more than 1 different values (i.e. is not a blank border), I've written this simple code to compare a middle-ish pixel to the top-left one (likely to be part of the background).

```<code>if img[0,0] > img[500, 500]: # if background lighter than center
        img = 255 - img # make the image negative
</code>```

As you can see even from these samples I posted, this comparison is not always a good indicator (sometimes there is a halo round the background or pixel in [500,500] can be similar to background). Is there some more reliable other way to detect if an image of this kind is negative or not?

Consider that in the dataset are some images with very few details and shading, such as

答:
Following the suggestion from Christoph Rackwitz, I get good result with this approach:

Optionally normalize the image

Extract corners from the image, more likely to be background (I considered just the top corners)

Extract center from the image

Compare the regions with a threshold (fixed or average greyscale value of image), obtaining list of truth values

Compare amount of pixels above the threshold (in percentage) to decide if background is lighter or darker than the center of the image: hence decide to invert the values.

```<code>def invert_if_negative(img):
    img = my_contrast_stretch(img)
    # assuming image has fixed size of (1396, 1676)
    # corners
    top_left  = img[:200, :200].flatten()
    top_right = img[:200, 1250:].flatten()
    # more or less center
    center    = img[1000:1300, 500:800].flatten()
    threshold = 120 # or computed from average
    top_left  = top_left > threshold
    top_right = top_right > threshold
    center    = center > threshold
    perc_white_corners = (sum(top_left) + sum(top_right)) / (len(top_left) + len(top_right))
    perc_white_center = sum(center) / len(center)
    if perc_white_corners > perc_white_center:
        img = 255 - img
    return img
</code>```
```<code>def my_contrast_stretch(img):
    if img.dtype == np.float64:
        img = (img * 255).astype(np.uint8)
    M=np.max(img)
    m=np.min(img)
    res = img - m
    res = res * (255 / (M - m))
    return res.astype(np.uint8)
</code>```

Title: Detect if an image is negative

Body:
I'm trying to clean some chest X-ray data to feed to a CNN. In my dataset are currently many images where the bones are shown in white (higher pixel value than the background), like so:

While others show the bones in a darker color than the background, like this:

Can you show me a way to label the two? I have no other external info about the image, though it can be assumed they are the same size (

Assuming they have the same size (about 1000x2000) and that the first row of pixels has more than 1 different values (i.e. is not a blank border), I've written this simple code to compare a middle-ish pixel to the top-left one (likely to be part of the background).

if img[0,0] > img[500, 500]: # if background lighter than center
        img = 255 - img # make the image negative

As you can see even from these samples I posted, this comparison is not always a good indicator (sometimes there is a halo round the background or pixel in [500,500] can be similar to background). Is there some more reliable other way to detect if an image of this kind is negative or not?

Consider that in the dataset are some images with very few details and shading, such as

Body:
Following the suggestion from Christoph Rackwitz, I get good result with this approach:

Optionally normalize the image

Extract corners from the image, more likely to be background (I considered just the top corners)

Extract center from the image

Compare the regions with a threshold (fixed or average greyscale value of image), obtaining list of truth values

Compare amount of pixels above the threshold (in percentage) to decide if background is lighter or darker than the center of the image: hence decide to invert the values.

def invert_if_negative(img):
    img = my_contrast_stretch(img)
    # assuming image has fixed size of (1396, 1676)
    # corners
    top_left  = img[:200, :200].flatten()
    top_right = img[:200, 1250:].flatten()
    # more or less center
    center    = img[1000:1300, 500:800].flatten()
    threshold = 120 # or computed from average
    top_left  = top_left > threshold
    top_right = top_right > threshold
    center    = center > threshold
    perc_white_corners = (sum(top_left) + sum(top_right)) / (len(top_left) + len(top_right))
    perc_white_center = sum(center) / len(center)
    if perc_white_corners > perc_white_center:
        img = 255 - img
    return img

def my_contrast_stretch(img):
    if img.dtype == np.float64:
        img = (img * 255).astype(np.uint8)
    M=np.max(img)
    m=np.min(img)
    res = img - m
    res = res * (255 / (M - m))
    return res.astype(np.uint8)


问:
Printing character occurrence in string - Java
I'm trying to count how many times each character appears in a string but have a couple problems with the program printing out different counts for upper/lower case as well as it not printing out a count of 0 for characters that dont show up.

The desired output should be something along the lines of...

A = 0

B = 1

C = 2

...

X = 0

Y = 1

Z = 2

as well as listing the number of times 0-9 occurs or if it doesn't occur. I have figured out a working way to prevent characters that are upper/lower case not being counted together (p = 1, P = 1) but am not sure if it is the most efficient. The main problem though is getting the program to print characters that don't appear in the string. Most of the other posts I've come across deal with the user checking to see how many times a certain character appears rather than all characters.

The code I have so far is

```<code>import java.util.*;
import java.io.*;

public class LetterCount  {
public static void main(String[] args) throws FileNotFoundException{
    String myInput;

    Scanner fileIn = new Scanner(new File("input_test"));
    myInput = fileIn.nextLine();

    myInput=charAdjust(myInput);
    charCounter(myInput);
    fileIn.close();

}

public static String charAdjust(String s) throws FileNotFoundException {
    String str;
    Scanner fileIn = new Scanner(new File("input_test"));
    str=fileIn.nextLine();

    System.out.println("-----------");
    fileIn.close();
    return (str.toUpperCase());

}
public static String charCounter(String str) {
    int[]counter = new int[(int) Character.MAX_VALUE];

    for (int i=0; i<str.length(); i++){
        char charAt = str.charAt(i);
        counter[(int) charAt]++;
    }

        for (int i=0; i<counter.length; i++) {
            if (counter[i] > 0)
                System.out.println((char)i + " = " + counter[i]);

        }
        return str;
    }
}
</code>```

答:
```<code>    /* Most common string occurrence related solutions using java 8 */

    //find all character occurrences in a string
    String myString = "test";
    List<Character> list = myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
    list.stream().distinct().forEach(c -> System.out.println(c + " = " + Collections.frequency(list, c)));

    //find one specific character occurrence in a string
    String myString = "test";
    char search = 't';
    long count = myString.chars().filter(c -> c == search).count();
    System.out.println(count);

    //find all unique characters in a string
    String myString = "test";
    List<Character> list = myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
    list.stream().filter(c -> Collections.frequency(list,c) == 1).forEach(System.out::println);

    //find first unique character in a string
    String myString = "test";
    List<Character> list = myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
    char firstUniqueChar = list.stream().filter(c -> Collections.frequency(list,c) == 1).findFirst().get();
    System.out.println(firstUniqueChar);
</code>```

Body:
I'm trying to count how many times each character appears in a string but have a couple problems with the program printing out different counts for upper/lower case as well as it not printing out a count of 0 for characters that dont show up.

The desired output should be something along the lines of...

A = 0

B = 1

C = 2

...

X = 0

Y = 1

Z = 2

as well as listing the number of times 0-9 occurs or if it doesn't occur. I have figured out a working way to prevent characters that are upper/lower case not being counted together (p = 1, P = 1) but am not sure if it is the most efficient. The main problem though is getting the program to print characters that don't appear in the string. Most of the other posts I've come across deal with the user checking to see how many times a certain character appears rather than all characters.

The code I have so far is

import java.util.*;
import java.io.*;

public class LetterCount  {
public static void main(String[] args) throws FileNotFoundException{
    String myInput;

    Scanner fileIn = new Scanner(new File("input_test"));
    myInput = fileIn.nextLine();

    myInput=charAdjust(myInput);
    charCounter(myInput);
    fileIn.close();

}

public static String charAdjust(String s) throws FileNotFoundException {
    String str;
    Scanner fileIn = new Scanner(new File("input_test"));
    str=fileIn.nextLine();

    System.out.println("-----------");
    fileIn.close();
    return (str.toUpperCase());

}
public static String charCounter(String str) {
    int[]counter = new int[(int) Character.MAX_VALUE];

    for (int i=0; i<str.length(); i++){
        char charAt = str.charAt(i);
        counter[(int) charAt]++;
    }

        for (int i=0; i<counter.length; i++) {
            if (counter[i] > 0)
                System.out.println((char)i + " = " + counter[i]);

        }
        return str;
    }
}