问:
Working with MultiLevel XML in C# and SQL Server
I have a client API which sends me an XML in the following format. I have to change few values and send the same XML to my client's another API. What is the best possible way to do it. We are currently using SQL Server 2014 and C#.

```<code><?xml version="1.0"?>
<JobPositionPostings>
    <JobPositionPosting>
        <JobAction>ADD</JobAction>
        <JobType>p</JobType>
        <JobPositionPostingID>27</JobPositionPostingID>
        <HiringOrg>
            <HiringOrgName>Company Name</HiringOrgName>
            <Industry>
                <SummaryText>Brief description of the hiring organization</SummaryText>
            </Industry>
            <Contact>
                <PersonName>
                    <FormattedName>Name of the Hiring Contact</FormattedName>
                </PersonName>
            </Contact>
        </HiringOrg>
        <JobDisplayOptions>
            <MicrositeName>Client Microsite Name</MicrositeName>
            <TemplateName>Client Template Name</TemplateName>
        </JobDisplayOptions>
        <JobPositionInformation>
            <JobPositionTitle>R and D manager #2 banglore</JobPositionTitle>
            <JobClassifications>
                <PrimaryJobCategory>
                    <JobIndustryCode>7</JobIndustryCode>
                    <JobFunctionCode>8</JobFunctionCode>
                    <JobRoleCode>8.31</JobRoleCode>
                </PrimaryJobCategory>
            </JobClassifications>
            <JobPositionDescription>
                <JobKeywords>Java</JobKeywords>
                <JobPositionLocation>
                    <InterNationalLoc></InterNationalLoc>
                    <InterNationalLocOther></InterNationalLocOther>
                    <IndianLoc>25.30.159</IndianLoc>
                    <IndianLocOther></IndianLocOther>
                </JobPositionLocation>
                <CompensationDescription>
                    <Pay>
                        <SalaryCurrency>Rupees</SalaryCurrency>
                        <MinimumSalary>250000</MinimumSalary>
                        <MaximumSalary>325000</MaximumSalary>
                        <DisplaySalary>Y</DisplaySalary>
                    </Pay>
                    <BenifitsDescription>Job Benefits Description</BenifitsDescription>
                </CompensationDescription>
                <SummaryText>Job Description(brief about JD)</SummaryText>
            </JobPositionDescription>
            <JobPositionRequirements>
                <SummaryText>Desired Candidate Profile Summary Text - Required Competencies/Skills/Leadership E-mail
         </SummaryText>
                <JobExperience>
                    <MinimumExperience>2</MinimumExperience>
                    <MaximumExperience>4</MaximumExperience>
                </JobExperience>
                <JobQualifications>
                    <UGQualifications />
                    <UGSpecializations />
                    <PGQualifications />
                    <PGSpecializations />
                </JobQualifications>
            </JobPositionRequirements>
            <AddJobsToRefSite>true</AddJobsToRefSite>
            <ReferenceCode>Your Unique Job Reference code</ReferenceCode>
        </JobPositionInformation>
        <HowToApply>
            <ApplicationMethods>
                <ByEmail>
                    <E-mail>Client E-mail for Response Management , in case not using ATS Integration
           </E-mail>
                </ByEmail>
                <ByWeb>
                    <URL></URL>
                    <ApplyIntegration>1</ApplyIntegration>
                </ByWeb>
                <QUESTIONNAIRE>Standard Questionnaire name if you know the same, else contact your Account manager</QUESTIONNAIRE>
            </ApplicationMethods>
        </HowToApply>
        <ReferralDetails>
            <Amount> 1000</Amount>
            <Benefit>  gift voucher</Benefit>
        </ReferralDetails>
    </JobPositionPosting>
    <JobFeedResponseEmail>Tech person's E-mail for receiving Feed Status</JobFeedResponseEmail>
</JobPositionPostings>
</code>```

I am following the below approach. I replaced all the value fields in my XML with some variables by separating them with pipe(|) symbols. Please find below the replaced one.

```<code><?xml version="1.0"?>
<JobPositionPostings>
   <JobPositionPosting>
                    <JobAction>|JAct_M|</JobAction>
                    <JobPositionPostingID>|JID_M|</JobPositionPostingID>
                    <JobType>|JType_M|</JobType>
   <HiringOrg>
                    <WebSite>|JWebSite_N|</WebSite>
                    <HiringOrgName>|JComp_M|</HiringOrgName>
        <Industry>
                    <SummaryText>|JCompDesc_M|</SummaryText>
        </Industry>
    <Contact>
            <PersonName>
                    <FormattedName>|JContactName_N|</FormattedName>
            </PersonName>
    </Contact>
   </HiringOrg>
   <JobDisplayOptions>
                    <MicrositeName>|JMSite_S|</MicrositeName>
                    <TemplateName>|JTempl_N|</TemplateName>
   </JobDisplayOptions>
   <JobPositionInformation>
                    <JobPositionTitle>|JTitle_M|</JobPositionTitle>
       <JobClassifications>
            <PrimaryJobCategory>
                    <JobIndustryCode>|JIndustryCode_M|</JobIndustryCode>
                    <JobFunctionCode>|JFunCode_M|</JobFunctionCode>
                    <JobRoleCode>|JRoleCode_M|</JobRoleCode>
            </PrimaryJobCategory>
       </JobClassifications>
       <JobPositionDescription>
                    <JobKeywords>|JSkills_M|</JobKeywords>
            <JobPositionLocation>
                    <InterNationalLoc>|JIntlCode_M|</InterNationalLoc>
                    <InterNationalLocOther>|JIntlCodeOther_N|</InterNationalLocOther>
                    <IndianLoc>|JLocCode_M|</IndianLoc>
                    <IndianLocOther>|JLocOther_N|</IndianLocOther>
            </JobPositionLocation>
            <CompensationDescription>
                <Pay>
                        <SalaryCurrency>|JCurr_M|</SalaryCurrency>
                        <MinimumSalary>|JMinSal_M|</MinimumSalary>
                        <MaximumSalary>|JMaxSal_M|</MaximumSalary>
                        <DisplaySalary>|JSalDisp_N|</DisplaySalary>
                </Pay>
                    <BenifitsDescription>|JBenefits_N|</BenifitsDescription>
            </CompensationDescription>
                    <SummaryText>|JJD_M|</SummaryText>
       </JobPositionDescription>
       <JobPositionRequirements>
                    <SummaryText>|JDesCand_N|</SummaryText>
            <JobExperience>
                    <MinimumExperience>|JMinExp_M|</MinimumExperience>
                    <MaximumExperience>|JMaxExp_M|</MaximumExperience>
            </JobExperience>
            <JobQualifications>
                    <UGQualifications>|JQual1_M|</UGQualifications>
                    <UGSpecializations>|JSpec1_M|</UGSpecializations>
                    <PGQualifications>|JQual2_M|</PGQualifications>
                    <PGSpecializations>|JSpec2_M|</PGSpecializations>
                    <DoctorateQualifications>|JQual3_M|</DoctorateQualifications>
                    <DoctorateSpecializations>|JSpec3_M|</DoctorateSpecializations>
            </JobQualifications>
       </JobPositionRequirements>
                <AddJobsToRefSite>|JRefSite_N|</AddJobsToRefSite>
                <ReferenceCode>|JRefCode_N|</ReferenceCode>
    </JobPositionInformation>
    <HowToApply>
            <ApplicationMethods>
                <ByEmail>
                    <E-mail>|JLntMail_M|</E-mail>
                </ByEmail>
            <ByEapps>
                <Eapps>|JeApps_M|</Eapps>
            </ByEapps>
                <ByWeb>
                    <URL>|JURL_M|</URL>
                    <ApplyIntegration>|JAppInt_M|</ApplyIntegration>
                </ByWeb>
                <QUESTIONNAIRE>|JQuest_N|</QUESTIONNAIRE>
            </ApplicationMethods>
     </HowToApply>
     <ReferralDetails>
                        <Benefit>|JBenefit_N|</Benefit>
                        <Amount>|JBAmt_N|</Amount>
     </ReferralDetails>
  </JobPositionPosting>
                <JobFeedResponseEmail>|JFeedRespEmail_N|</JobFeedResponseEmail>
</JobPositionPostings>
</code>```

After that in SQL server I am replacing them with desired values and forwarding that XML to my client.

```<code>set @Nxml = replace(@Nxml, '|JAct_M|','Add')
set @Nxml = replace(@Nxml, '|JID_M|',@reqmt_id)
set @Nxml = replace(@Nxml, '|JType_M|','P')
</code>```

Is this best method or is there any other easy approach.
Thanks in advance.

答:
To modify XML with SQL-Server you can use the XML data type's function .modify(). First you must cast/convert your XML to the real XML type.

Do not deal with XML on string level!

Check this (shortened for brevity):

```<code>DECLARE @xml XML=
N'<?xml version="1.0"?>
<JobPositionPostings>
    <JobPositionPosting>
        <JobAction>ADD</JobAction>
        <JobType>p</JobType>
        <JobPositionPostingID>27</JobPositionPostingID>
        <HiringOrg>
            <HiringOrgName>Company Name</HiringOrgName>
            <Industry>
                <SummaryText>Brief description of the hiring organization</SummaryText>
            </Industry>
            <Contact>
                <PersonName>
                    <FormattedName>Name of the Hiring Contact</FormattedName>
                </PersonName>
            </Contact>
        </HiringOrg>
        <JobDisplayOptions>
            <MicrositeName>Client Microsite Name</MicrositeName>
            <TemplateName>Client Template Name</TemplateName>
        </JobDisplayOptions>
        <!-- More nodes -->
    </JobPositionPosting>
    <JobFeedResponseEmail>Tech person''s E-mail for receiving Feed Status</JobFeedResponseEmail>
</JobPositionPostings>';
</code>```

--Replace one specific existing element's value with a hardcoded new value

```<code>SET @xml.modify(N'replace value of (/JobPositionPostings/JobPositionPosting/JobAction/text())[1] with "SomeNewValue"');
</code>```

--You can use sql:variable("@SomeVariable") or sql:column("SomeColumn") to take a value dynamically

```<code>DECLARE @NewJobType NVARCHAR(100)='NewType';
SET @xml.modify(N'replace value of (/JobPositionPostings/JobPositionPosting/JobType/text())[1] with sql:variable("@NewJobType")');
</code>```

--Introduce a new element at a specific position

```<code>SET @xml.modify(N'insert <SomeNewElement>test</SomeNewElement> after (/JobPositionPostings/JobPositionPosting/JobType)[1]');
</code>```

--remove one (complete) element

```<code>SET @xml.modify(N'delete (/JobPositionPostings/JobPositionPosting/HiringOrg)[1]');
</code>```

--Check the modified result

```<code>SELECT @xml;

<JobPositionPostings>
  <JobPositionPosting>
    <JobAction>SomeNewValue</JobAction>
    <JobType>NewType</JobType>
    <SomeNewElement>test</SomeNewElement>
    <JobPositionPostingID>27</JobPositionPostingID>
    <JobDisplayOptions>
      <MicrositeName>Client Microsite Name</MicrositeName>
      <TemplateName>Client Template Name</TemplateName>
    </JobDisplayOptions>
    <!-- More nodes -->
  </JobPositionPosting>
  <JobFeedResponseEmail>Tech person's E-mail for receiving Feed Status</JobFeedResponseEmail>
</JobPositionPostings>
</code>```

Body:
I have a client API which sends me an XML in the following format. I have to change few values and send the same XML to my client's another API. What is the best possible way to do it. We are currently using SQL Server 2014 and C#.

<?xml version="1.0"?>
<JobPositionPostings>
    <JobPositionPosting>
        <JobAction>ADD</JobAction>
        <JobType>p</JobType>
        <JobPositionPostingID>27</JobPositionPostingID>
        <HiringOrg>
            <HiringOrgName>Company Name</HiringOrgName>
            <Industry>
                <SummaryText>Brief description of the hiring organization</SummaryText>
            </Industry>
            <Contact>
                <PersonName>
                    <FormattedName>Name of the Hiring Contact</FormattedName>
                </PersonName>
            </Contact>
        </HiringOrg>
        <JobDisplayOptions>
            <MicrositeName>Client Microsite Name</MicrositeName>
            <TemplateName>Client Template Name</TemplateName>
        </JobDisplayOptions>
        <JobPositionInformation>
            <JobPositionTitle>R and D manager #2 banglore</JobPositionTitle>
            <JobClassifications>
                <PrimaryJobCategory>
                    <JobIndustryCode>7</JobIndustryCode>
                    <JobFunctionCode>8</JobFunctionCode>
                    <JobRoleCode>8.31</JobRoleCode>
                </PrimaryJobCategory>
            </JobClassifications>
            <JobPositionDescription>
                <JobKeywords>Java</JobKeywords>
                <JobPositionLocation>
                    <InterNationalLoc></InterNationalLoc>
                    <InterNationalLocOther></InterNationalLocOther>
                    <IndianLoc>25.30.159</IndianLoc>
                    <IndianLocOther></IndianLocOther>
                </JobPositionLocation>
                <CompensationDescription>
                    <Pay>
                        <SalaryCurrency>Rupees</SalaryCurrency>
                        <MinimumSalary>250000</MinimumSalary>
                        <MaximumSalary>325000</MaximumSalary>
                        <DisplaySalary>Y</DisplaySalary>
                    </Pay>
                    <BenifitsDescription>Job Benefits Description</BenifitsDescription>
                </CompensationDescription>
                <SummaryText>Job Description(brief about JD)</SummaryText>
            </JobPositionDescription>
            <JobPositionRequirements>
                <SummaryText>Desired Candidate Profile Summary Text - Required Competencies/Skills/Leadership E-mail
         </SummaryText>
                <JobExperience>
                    <MinimumExperience>2</MinimumExperience>
                    <MaximumExperience>4</MaximumExperience>
                </JobExperience>
                <JobQualifications>
                    <UGQualifications />
                    <UGSpecializations />
                    <PGQualifications />
                    <PGSpecializations />
                </JobQualifications>
            </JobPositionRequirements>
            <AddJobsToRefSite>true</AddJobsToRefSite>
            <ReferenceCode>Your Unique Job Reference code</ReferenceCode>
        </JobPositionInformation>
        <HowToApply>
            <ApplicationMethods>
                <ByEmail>
                    <E-mail>Client E-mail for Response Management , in case not using ATS Integration
           </E-mail>
                </ByEmail>
                <ByWeb>
                    <URL></URL>
                    <ApplyIntegration>1</ApplyIntegration>
                </ByWeb>
                <QUESTIONNAIRE>Standard Questionnaire name if you know the same, else contact your Account manager</QUESTIONNAIRE>
            </ApplicationMethods>
        </HowToApply>
        <ReferralDetails>
            <Amount> 1000</Amount>
            <Benefit>  gift voucher</Benefit>
        </ReferralDetails>
    </JobPositionPosting>
    <JobFeedResponseEmail>Tech person's E-mail for receiving Feed Status</JobFeedResponseEmail>
</JobPositionPostings>

I am following the below approach. I replaced all the value fields in my XML with some variables by separating them with pipe(|) symbols. Please find below the replaced one.

<?xml version="1.0"?>
<JobPositionPostings>
   <JobPositionPosting>
                    <JobAction>|JAct_M|</JobAction>
                    <JobPositionPostingID>|JID_M|</JobPositionPostingID>
                    <JobType>|JType_M|</JobType>
   <HiringOrg>
                    <WebSite>|JWebSite_N|</WebSite>
                    <HiringOrgName>|JComp_M|</HiringOrgName>
        <Industry>
                    <SummaryText>|JCompDesc_M|</SummaryText>
        </Industry>
    <Contact>
            <PersonName>
                    <FormattedName>|JContactName_N|</FormattedName>
            </PersonName>
    </Contact>
   </HiringOrg>
   <JobDisplayOptions>
                    <MicrositeName>|JMSite_S|</MicrositeName>
                    <TemplateName>|JTempl_N|</TemplateName>
   </JobDisplayOptions>
   <JobPositionInformation>
                    <JobPositionTitle>|JTitle_M|</JobPositionTitle>
       <JobClassifications>
            <PrimaryJobCategory>
                    <JobIndustryCode>|JIndustryCode_M|</JobIndustryCode>
                    <JobFunctionCode>|JFunCode_M|</JobFunctionCode>
                    <JobRoleCode>|JRoleCode_M|</JobRoleCode>
            </PrimaryJobCategory>
       </JobClassifications>
       <JobPositionDescription>
                    <JobKeywords>|JSkills_M|</JobKeywords>
            <JobPositionLocation>
                    <InterNationalLoc>|JIntlCode_M|</InterNationalLoc>
                    <InterNationalLocOther>|JIntlCodeOther_N|</InterNationalLocOther>
                    <IndianLoc>|JLocCode_M|</IndianLoc>
                    <IndianLocOther>|JLocOther_N|</IndianLocOther>
            </JobPositionLocation>
            <CompensationDescription>
                <Pay>
                        <SalaryCurrency>|JCurr_M|</SalaryCurrency>
                        <MinimumSalary>|JMinSal_M|</MinimumSalary>
                        <MaximumSalary>|JMaxSal_M|</MaximumSalary>
                        <DisplaySalary>|JSalDisp_N|</DisplaySalary>
                </Pay>
                    <BenifitsDescription>|JBenefits_N|</BenifitsDescription>
            </CompensationDescription>
                    <SummaryText>|JJD_M|</SummaryText>
       </JobPositionDescription>
       <JobPositionRequirements>
                    <SummaryText>|JDesCand_N|</SummaryText>
            <JobExperience>
                    <MinimumExperience>|JMinExp_M|</MinimumExperience>
                    <MaximumExperience>|JMaxExp_M|</MaximumExperience>
            </JobExperience>
            <JobQualifications>
                    <UGQualifications>|JQual1_M|</UGQualifications>
                    <UGSpecializations>|JSpec1_M|</UGSpecializations>
                    <PGQualifications>|JQual2_M|</PGQualifications>
                    <PGSpecializations>|JSpec2_M|</PGSpecializations>
                    <DoctorateQualifications>|JQual3_M|</DoctorateQualifications>
                    <DoctorateSpecializations>|JSpec3_M|</DoctorateSpecializations>
            </JobQualifications>
       </JobPositionRequirements>
                <AddJobsToRefSite>|JRefSite_N|</AddJobsToRefSite>
                <ReferenceCode>|JRefCode_N|</ReferenceCode>
    </JobPositionInformation>
    <HowToApply>
            <ApplicationMethods>
                <ByEmail>
                    <E-mail>|JLntMail_M|</E-mail>
                </ByEmail>
            <ByEapps>
                <Eapps>|JeApps_M|</Eapps>
            </ByEapps>
                <ByWeb>
                    <URL>|JURL_M|</URL>
                    <ApplyIntegration>|JAppInt_M|</ApplyIntegration>
                </ByWeb>
                <QUESTIONNAIRE>|JQuest_N|</QUESTIONNAIRE>
            </ApplicationMethods>
     </HowToApply>
     <ReferralDetails>
                        <Benefit>|JBenefit_N|</Benefit>
                        <Amount>|JBAmt_N|</Amount>
     </ReferralDetails>
  </JobPositionPosting>
                <JobFeedResponseEmail>|JFeedRespEmail_N|</JobFeedResponseEmail>
</JobPositionPostings>

After that in SQL server I am replacing them with desired values and forwarding that XML to my client.

set @Nxml = replace(@Nxml, '|JAct_M|','Add')
set @Nxml = replace(@Nxml, '|JID_M|',@reqmt_id)
set @Nxml = replace(@Nxml, '|JType_M|','P')

Is this best method or is there any other easy approach.
Thanks in advance.

Body:
To modify XML with SQL-Server you can use the XML data type's function .modify(). First you must cast/convert your XML to the real XML type.

Do not deal with XML on string level!

Check this (shortened for brevity):

DECLARE @xml XML=
N'<?xml version="1.0"?>
<JobPositionPostings>
    <JobPositionPosting>
        <JobAction>ADD</JobAction>
        <JobType>p</JobType>
        <JobPositionPostingID>27</JobPositionPostingID>
        <HiringOrg>
            <HiringOrgName>Company Name</HiringOrgName>
            <Industry>
                <SummaryText>Brief description of the hiring organization</SummaryText>
            </Industry>
            <Contact>
                <PersonName>
                    <FormattedName>Name of the Hiring Contact</FormattedName>
                </PersonName>
            </Contact>
        </HiringOrg>
        <JobDisplayOptions>
            <MicrositeName>Client Microsite Name</MicrositeName>
            <TemplateName>Client Template Name</TemplateName>
        </JobDisplayOptions>
        <!-- More nodes -->
    </JobPositionPosting>
    <JobFeedResponseEmail>Tech person''s E-mail for receiving Feed Status</JobFeedResponseEmail>
</JobPositionPostings>';

--Replace one specific existing element's value with a hardcoded new value

SET @xml.modify(N'replace value of (/JobPositionPostings/JobPositionPosting/JobAction/text())[1] with "SomeNewValue"');

--You can use sql:variable("@SomeVariable") or sql:column("SomeColumn") to take a value dynamically

DECLARE @NewJobType NVARCHAR(100)='NewType';
SET @xml.modify(N'replace value of (/JobPositionPostings/JobPositionPosting/JobType/text())[1] with sql:variable("@NewJobType")');

--Introduce a new element at a specific position

SET @xml.modify(N'insert <SomeNewElement>test</SomeNewElement> after (/JobPositionPostings/JobPositionPosting/JobType)[1]');

--remove one (complete) element

SET @xml.modify(N'delete (/JobPositionPostings/JobPositionPosting/HiringOrg)[1]');

--Check the modified result

SELECT @xml;

<JobPositionPostings>
  <JobPositionPosting>
    <JobAction>SomeNewValue</JobAction>
    <JobType>NewType</JobType>
    <SomeNewElement>test</SomeNewElement>
    <JobPositionPostingID>27</JobPositionPostingID>
    <JobDisplayOptions>
      <MicrositeName>Client Microsite Name</MicrositeName>
      <TemplateName>Client Template Name</TemplateName>
    </JobDisplayOptions>
    <!-- More nodes -->
  </JobPositionPosting>
  <JobFeedResponseEmail>Tech person's E-mail for receiving Feed Status</JobFeedResponseEmail>
</JobPositionPostings>


来源: stackexchange

问:
Store arrays in unique variables at each for loop iteration in python
Currently i am working on a python project using windows platform in which i need to deal with images.
Under this, i need to divide my image into several segments and then store them as unique images.
For this, i need to convert my image into floating point array which would then be segmented
The segmentation part is sorted.
But the point where i am stuck is storing of these newly generated arrays.

For example if my loop runs for 6 times, 6 new arrays would be generated (of large size say 300 X 420) and i need to store them in unique variables for each iteration such that they do not overlap each other.

How do i do that?

How can i store newly generated arrays of my loop into different arrays for each iteration? I need these arrays afterwards so it is important for me to store them.

The number of arrays generated would be dynamic too!

this is the code:

`

```<code>#read image and do its segmentation
 image = cv2.imread("Path to input image\\___.png")
 segments = slic(img_as_float(image), compactness=100.0, n_segments = 2,sigma = 5)
 #loop to generate individual segments and to store them individually
 for (i, segVal) in enumerate(np.unique(segments)):
    print "[x] inspecting segment %d" % (i)
    mask = np.zeros(image.shape[:2], dtype = "uint8")
    mask[segments == segVal] = 255
    s2 = np.array(segments);
    bb= (cv2.bitwise_and(image, image, mask = mask) )
    #above the unique array is generated
    #store the generated array as unique image at desired location
    cv2.imwrite('Path to store\\__.png', bb)
</code>```

`

NOTE: the arrays generated are already 2-D and of the size 327 X 500.
So please give me a solution to store 2-D arrays.
It does now matter what we use dictionary, list or new variables :)

EDIT

As per some solutions, i tried to insert the newly generated arrays into another big array. But still there are some errors which i am getting. The new code chunk is:

```<code>#read image and do its segmentation
 image = cv2.imread("Path to input image\\___.png")
 segments = slic(img_as_float(image), compactness=100.0, n_segments = 2,sigma = 5)
 #loop to generate individual segments and to store them individually
 for (i, segVal) in enumerate(np.unique(segments)):
    print "[x] inspecting segment %d" % (i)
    mask = np.zeros(image.shape[:2], dtype = "uint8")
    mask[segments == segVal] = 255
    s2 = np.array(segments);
    results= []
    bb= (cv2.bitwise_and(image, image, mask = mask) )
    results.append(bb)
    #above the unique array is generated and appended into a big array
    #store the generated array as unique image at desired location
    cv2.imwrite('Path to store\\__.png', results(i))
</code>```

The errors which i am getting are:

list object is not callable for this line cv2.imwrite('Path to store\\__.png', results(i))

What changes shall be done?

答:
You cannot store them in unique variables. You can, however, create a 2-dimensional array to store all of them. For example, if there are 3 generated arrays: [1,2,3], [4,5,6], and [7,8,9], the structure of the 2-dimensional array will be as follows:

```<code>[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
</code>```

Then, to access the individual arrays, you can simply access the desired index, followed by the index of the element you want. For example, to get the second element of the first array, you can say something like arr[0][1]. This will return 2.

EDIT

It doesn't matter if the individual arrays are already 2-D. Just add another dimension. For example,

```<code># make a big array
bigarray = []

#read image and do its segmentation
 image = cv2.imread("Path to input image\\___.png")
 segments = slic(img_as_float(image), compactness=100.0, n_segments = 2,sigma = 5)
 #loop to generate individual segments and to store them individually
 for (i, segVal) in enumerate(np.unique(segments)):
    print "[x] inspecting segment %d" % (i)
    mask = np.zeros(image.shape[:2], dtype = "uint8")
    mask[segments == segVal] = 255
    s2 = np.array(segments);
    bb= (cv2.bitwise_and(image, image, mask = mask) )
    #above the unique array is generated
    #store the generated array as unique image at desired location
    cv2.imwrite('Path to store\\__.png', bb)

    # push the generated 2d array to the big array
    bigarray.append(bb)
</code>```

Then, let's say you want to access the first 2-D array, you can say bigarray[0]. If you want to access the upper left pixel of the first 2-D array, you can say bigarray[0][0][0].

ContentLicense: CC BY-SA 3.0

Body:
Currently i am working on a python project using windows platform in which i need to deal with images.
Under this, i need to divide my image into several segments and then store them as unique images.
For this, i need to convert my image into floating point array which would then be segmented
The segmentation part is sorted.
But the point where i am stuck is storing of these newly generated arrays.

For example if my loop runs for 6 times, 6 new arrays would be generated (of large size say 300 X 420) and i need to store them in unique variables for each iteration such that they do not overlap each other.

How do i do that?

How can i store newly generated arrays of my loop into different arrays for each iteration? I need these arrays afterwards so it is important for me to store them.

The number of arrays generated would be dynamic too!

this is the code:

`

#read image and do its segmentation
 image = cv2.imread("Path to input image\\___.png")
 segments = slic(img_as_float(image), compactness=100.0, n_segments = 2,sigma = 5)
 #loop to generate individual segments and to store them individually
 for (i, segVal) in enumerate(np.unique(segments)):
    print "[x] inspecting segment %d" % (i)
    mask = np.zeros(image.shape[:2], dtype = "uint8")
    mask[segments == segVal] = 255
    s2 = np.array(segments);
    bb= (cv2.bitwise_and(image, image, mask = mask) )
    #above the unique array is generated
    #store the generated array as unique image at desired location
    cv2.imwrite('Path to store\\__.png', bb)

`

NOTE: the arrays generated are already 2-D and of the size 327 X 500.
So please give me a solution to store 2-D arrays.
It does now matter what we use dictionary, list or new variables :)

EDIT

As per some solutions, i tried to insert the newly generated arrays into another big array. But still there are some errors which i am getting. The new code chunk is:

#read image and do its segmentation
 image = cv2.imread("Path to input image\\___.png")
 segments = slic(img_as_float(image), compactness=100.0, n_segments = 2,sigma = 5)
 #loop to generate individual segments and to store them individually
 for (i, segVal) in enumerate(np.unique(segments)):
    print "[x] inspecting segment %d" % (i)
    mask = np.zeros(image.shape[:2], dtype = "uint8")
    mask[segments == segVal] = 255
    s2 = np.array(segments);
    results= []
    bb= (cv2.bitwise_and(image, image, mask = mask) )
    results.append(bb)
    #above the unique array is generated and appended into a big array
    #store the generated array as unique image at desired location
    cv2.imwrite('Path to store\\__.png', results(i))

The errors which i am getting are:

list object is not callable for this line cv2.imwrite('Path to store\\__.png', results(i))

What changes shall be done?

Body:
You cannot store them in unique variables. You can, however, create a 2-dimensional array to store all of them. For example, if there are 3 generated arrays: [1,2,3], [4,5,6], and [7,8,9], the structure of the 2-dimensional array will be as follows:

[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

Then, to access the individual arrays, you can simply access the desired index, followed by the index of the element you want. For example, to get the second element of the first array, you can say something like arr[0][1]. This will return 2.

EDIT

It doesn't matter if the individual arrays are already 2-D. Just add another dimension. For example,

# make a big array
bigarray = []

#read image and do its segmentation
 image = cv2.imread("Path to input image\\___.png")
 segments = slic(img_as_float(image), compactness=100.0, n_segments = 2,sigma = 5)
 #loop to generate individual segments and to store them individually
 for (i, segVal) in enumerate(np.unique(segments)):
    print "[x] inspecting segment %d" % (i)
    mask = np.zeros(image.shape[:2], dtype = "uint8")
    mask[segments == segVal] = 255
    s2 = np.array(segments);
    bb= (cv2.bitwise_and(image, image, mask = mask) )
    #above the unique array is generated
    #store the generated array as unique image at desired location
    cv2.imwrite('Path to store\\__.png', bb)

    # push the generated 2d array to the big array
    bigarray.append(bb)

Then, let's say you want to access the first 2-D array, you can say bigarray[0]. If you want to access the upper left pixel of the first 2-D array, you can say bigarray[0][0][0].


问:
Not getting click event in jQuery
Thanks in advance.
My html contains:

```<code>    <div class="help-link">
       <a href="">WHY?</a>
   </div>
</code>```

and

```<code>    <div class="modal-container">
    <div data-id="modal1" class="status-modal modal">
        <div class="modal-body">
            <header>Status</header>
            <p><span class="fnt-wt-500"></span> Lorem Ipsum is simply
                      dummy text of the printing and typesetting industry.</p>
            <p><span class="fnt-wt-500"></span> Lorem Ipsum has been
                     the industry's standard dummy text ever since the 1500s.</p>
            <p><span class="fnt-wt-500"> </span>Various versions have
                     evolved over the years, sometimes by accident.</p>
            <div class="modal-footer clearfix">
                <a href="#" class="close">OK</a>
            </div>
        </div>
    </div>
  </div>
  <div class="modal-backdrop">
  </div>
</code>```

JQuery code is like

```<code>       $(document).ready(function() {

        $(".help-link a").click(function(e) {
            console.log("help link a clicked ");
            e.preventDefault();
            if (!$(".modal-backdrop, .modal-container").hasClass("open")) {
                $(".modal-backdrop, .modal-container").addClass("open");
            } else {
                $(".modal-backdrop, .modal-container").removeClass("open");
            }
             });
         });
       }
</code>```

But I am not able to log event for the click on help-link a. Please help.
Did I miss something in jquery?

答:
You had an extra bracket at the end. Also, I have used on() instead of just click().

$(document).ready(function() {
  $(".help-link a").on('click', function(e) {
    console.log("help link a clicked ");
    e.preventDefault();
    var modalContainer = $(".modal-backdrop, .modal-container");
    if (!modalContainer.hasClass("open")) {
      modalContainer.addClass("open");
    } else {
      modalContainer.removeClass("open");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="help-link">
  WHY?
</div>

<div class="modal-container">
  <div data-id="modal1" class="status-modal modal">
    <div class="modal-body">
      <header>Status</header>
      <p><span class="fnt-wt-500"></span> Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
      <p><span class="fnt-wt-500"></span> Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
      <p><span class="fnt-wt-500"> </span>Various versions have evolved over the years, sometimes by accident.</p>
      <div class="modal-footer clearfix">
        OK
      </div>
    </div>
  </div>
</div>
<div class="modal-backdrop">
</div></code>```

Title: Not getting click event in jQuery

Body:
Thanks in advance.
My html contains:

       WHY?

and

            Status

 Lorem Ipsum is simply
                      dummy text of the printing and typesetting industry.

 Lorem Ipsum has been
                     the industry's standard dummy text ever since the 1500s.

 Various versions have
                     evolved over the years, sometimes by accident.

                OK

JQuery code is like

       $(document).ready(function() {

        $(".help-link a").click(function(e) {
            console.log("help link a clicked ");
            e.preventDefault();
            if (!$(".modal-backdrop, .modal-container").hasClass("open")) {
                $(".modal-backdrop, .modal-container").addClass("open");
            } else {
                $(".modal-backdrop, .modal-container").removeClass("open");
            }
             });
         });
       }

But I am not able to log event for the click on help-link a. Please help.
Did I miss something in jquery?

Body:
You had an extra bracket at the end. Also, I have used on() instead of just click().

$(document).ready(function() {
  $(".help-link a").on('click', function(e) {
    console.log("help link a clicked ");
    e.preventDefault();
    var modalContainer = $(".modal-backdrop, .modal-container");
    if (!modalContainer.hasClass("open")) {
      modalContainer.addClass("open");
    } else {
      modalContainer.removeClass("open");
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="help-link">
  <a href="">WHY?</a>
</div>

<div class="modal-container">
  <div data-id="modal1" class="status-modal modal">
    <div class="modal-body">
      <header>Status</header>
      <p><span class="fnt-wt-500"></span> Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
      <p><span class="fnt-wt-500"></span> Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
      <p><span class="fnt-wt-500"> </span>Various versions have evolved over the years, sometimes by accident.</p>
      <div class="modal-footer clearfix">
        <a href="#" class="close">OK</a>
      </div>
    </div>
  </div>
</div>
<div class="modal-backdrop">
</div>


问:
Start java web application under weblogic --> error
I have used jdk 1.6 to compile my java web application project.
After war file made, I upload this war to weblogic for deployment.
When I started this application, it show below error.

java.lang.UnsupportedClassVersionError:
  org/apache/struts2/dispatcher/filter/StrutsPrepareAndExecuteFilter :
  unsupported classversion 51.0

Do you know why??

答:
According to what is written in there:
How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version
your struts library is compiled by Java SE 7 = 51.

What you can do is:

get older library of struts compiled by Java 6

upgrade jrockit/jdk to 1.7


问:
Is it more performant to cache a selector in a function if that function's called multiple times?
Ok I think I know the answer to this, looking to confirm. So I have a selector that's only used once, but it's used inside a function that's called several times. From a performance perspective, since that selector is re-searched-for each time the function is called, it's probably (albeit marginally) better to cache the selector?

In other words, the below...

```<code>function testFunction() {
  alert($("#input").val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})
</code>```

...is not as performant as the below

```<code>input = $("#input")

function testFunction() {
  alert(input.val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})
</code>```

答:
Evidently, jQuery() call completes in less total time than variable reference to jQuery object. Last run logged

jQuery(): 16.580ms

cached jQuery() object: 22.885ms

(function() {

  function testFunction() {
    $("#input").val()
  }

  console.time("jQuery()");

  for (let i = 0; i < 10000; i++) {
    testFunction()
  }

  console.timeEnd("jQuery()");

})();

(function() {

  let input = $("input");

  function testFunction() {
    input.val()
  }

  console.time("cached jQuery() object");

  for (let i = 0; i < 10000; i++) {
    testFunction()
  }

  console.timeEnd("cached jQuery() object");

})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input></code>```

Body:
Ok I think I know the answer to this, looking to confirm. So I have a selector that's only used once, but it's used inside a function that's called several times. From a performance perspective, since that selector is re-searched-for each time the function is called, it's probably (albeit marginally) better to cache the selector?

In other words, the below...

function testFunction() {
  alert($("#input").val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})

...is not as performant as the below

input = $("#input")

function testFunction() {
  alert(input.val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})

Body:
Evidently, jQuery() call completes in less total time than variable reference to jQuery object. Last run logged

jQuery(): 16.580ms

cached jQuery() object: 22.885ms

(function() {

  function testFunction() {
    $("#input").val()
  }

  console.time("jQuery()");

  for (let i = 0; i < 10000; i++) {
    testFunction()
  }

  console.timeEnd("jQuery()");

})();

(function() {

  let input = $("input");

  function testFunction() {
    input.val()
  }

  console.time("cached jQuery() object");

  for (let i = 0; i < 10000; i++) {
    testFunction()
  }

  console.timeEnd("cached jQuery() object");

})();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input>


问:
How to change color of SVG image using CSS (jQuery SVG image replacement)?
This is a self Q&A of a handy piece of code I came up with.

Currently, there isn't an easy way to embed an SVG image and then have access to the SVG elements via CSS. There are various methods of using JS SVG frameworks, but they are overly complicated if all you are doing is making a simple icon with a rollover state.

So here is what I came up with, which I think is by far the easiest way to use SVG files on a website. It takes its concept from the early text-to-image replacement methods, but as far as I am aware has never been done for SVGs.

This is the question:

How do I embed an SVG and change its color in CSS without using a JS-SVG framework?

答:
The selected solution is fine if you want jQuery to process all svg elements in your DOM and your DOM is of reasonable size. But if your DOM is large and you decide to load parts of your DOM dynamically, it really makes no sense to have to rescan the entire DOM just to update svg elements. Instead, use a jQuery plugin to do this:

```<code>/**
 * A jQuery plugin that loads an svg file and replaces the jQuery object with its contents.
 *
 * The path to the svg file is specified in the src attribute (which normally does not exist for an svg element).
 *
 * The width, height and class attributes in the loaded svg will be replaced by those that exist in the jQuery object's
 * underlying html. Note: All other attributes in the original element are lost including the style attribute. Place
 * any styles in a style class instead.
 */
(function ($) {
    $.fn.svgLoader = function () {
        var src = $(this).attr("src");
        var width = this.attr("width");
        var height = this.attr("height");
        var cls = this.attr("class");
        var ctx = $(this);

        // Get the svg file and replace the <svg> element.
        $.ajax({
            url: src,
            cache: false
        }).done(function (html) {
            let svg = $(html);
            svg.attr("width", width);
            svg.attr("height", height);
            svg.attr("class", cls);
            var newHtml = $('<a></a>').append(svg.clone()).html();
            ctx.replaceWith(newHtml);
        });

        return this;
    };

}(jQuery));
</code>```

In your html, specify an svg element as follows:

```<code><svg src="images/someSvgFile.svg" height="45" width="45" class="mySVGClass"/>
</code>```

And apply the plugin:

```<code>$(".mySVGClass").svgLoader();
</code>```

Body:
The selected solution is fine if you want jQuery to process all svg elements in your DOM and your DOM is of reasonable size. But if your DOM is large and you decide to load parts of your DOM dynamically, it really makes no sense to have to rescan the entire DOM just to update svg elements. Instead, use a jQuery plugin to do this:

/**
 * A jQuery plugin that loads an svg file and replaces the jQuery object with its contents.
 *
 * The path to the svg file is specified in the src attribute (which normally does not exist for an svg element).
 *
 * The width, height and class attributes in the loaded svg will be replaced by those that exist in the jQuery object's
 * underlying html. Note: All other attributes in the original element are lost including the style attribute. Place
 * any styles in a style class instead.
 */
(function ($) {
    $.fn.svgLoader = function () {
        var src = $(this).attr("src");
        var width = this.attr("width");
        var height = this.attr("height");
        var cls = this.attr("class");
        var ctx = $(this);

        // Get the svg file and replace the <svg> element.
        $.ajax({
            url: src,
            cache: false
        }).done(function (html) {
            let svg = $(html);
            svg.attr("width", width);
            svg.attr("height", height);
            svg.attr("class", cls);
            var newHtml = $('<a></a>').append(svg.clone()).html();
            ctx.replaceWith(newHtml);
        });

        return this;
    };

}(jQuery));

In your html, specify an svg element as follows:

<svg src="images/someSvgFile.svg" height="45" width="45" class="mySVGClass"/>

And apply the plugin:

$(".mySVGClass").svgLoader();


问:
PHP: switch() default for all?
I have this:

```<code>case true:

    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
    break;

    default:
    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
    break;
</code>```

I am trying to ONLY if it's true, then show normal else do READONLY.

The switch is checking from a function

```<code>switch( ( check_friend_state($showU["id"], 'friend') ) )
</code>```

And I tried to echo the function, and it returned err2 and not true, so why does it run true?

I also tried if/else

```<code>if(check_friend_state($showU["id"], 'friend') == true){

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
}else{
echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
}
</code>```

But as said previously it returns "err2" and still it runs true?

My function at the return:

```<code>if($USER == $uID){ // not yourself
return "err1";
}elseif( $checkIsFriend->rowCount() == 1 ){  // already friends
return "err2";
}elseif( $checkAlready->rowCount() == 1 ){ // already send a request
return "err3";
}elseif( $checkBlock->rowCount() == 1 ){ // blocked
return "err4";
}else{
return true;
}
</code>```

答:
IMHO ternary if statements work better in these cases for brevity of code... with the benefit of having to fiddle with the rendered HTML only once.  But that may be a more personal preference..</p>

```<code>   $readOnly=check_friend_state($showU["id"], 'friend')?'readonly="readonly"':'';
   echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" '.$readOnly.'></textarea>';
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP: switch() default for all?

Body:
I have this:

case true:

    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
    break;

    default:
    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
    break;

I am trying to ONLY if it's true, then show normal else do READONLY.

The switch is checking from a function

switch( ( check_friend_state($showU["id"], 'friend') ) )

And I tried to echo the function, and it returned err2 and not true, so why does it run true?

I also tried if/else

if(check_friend_state($showU["id"], 'friend') == true){

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
}else{
echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
}

But as said previously it returns "err2" and still it runs true?

My function at the return:

if($USER == $uID){ // not yourself
return "err1";
}elseif( $checkIsFriend->rowCount() == 1 ){  // already friends
return "err2";
}elseif( $checkAlready->rowCount() == 1 ){ // already send a request
return "err3";
}elseif( $checkBlock->rowCount() == 1 ){ // blocked
return "err4";
}else{
return true;
}

Body:
IMHO ternary if statements work better in these cases for brevity of code... with the benefit of having to fiddle with the rendered HTML only once.  But that may be a more personal preference..

   $readOnly=check_friend_state($showU["id"], 'friend')?'readonly="readonly"':'';
   echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" '.$readOnly.'></textarea>';


问:
Getting error MsRestAzure::AzureOperationError: AuthorizationFailed while trying to create vm instance using Ruby api
I am new to Azure platform. I have followed this link to generate service principle : https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

When I reach to step : Assign application to role > point 6 (Search for your application, and select it.) I can't see my application in result of search.

After that I have tried to create VM using ruby api :

https://github.com/Azure/azure-sdk-for-ruby/tree/master/management/azure_mgmt_compute

When I implement code to create VM, I get following error :

```<code>"message": "MsRestAzure::AzureOperationError: AuthorizationFailed: The client 'xxxx' with object id 'xxxx' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/write' over scope '/subscriptions/xxxx/resourceGroups/my_group/providers/Microsoft.Compute/virtualMachines/test-ubuntu3'.",
</code>```

In above error message both client and object id is same. I don't know why and what is the meaning of object id.

How I can resolve this issue ? Where I should look at in portal ? Any help will be appreciated.

Thank you

答:
Also, you can follow the steps below to give a role for the service principal to add permission for your app on Azure portal, as the figure below.

Move to the Subscription category.

Select the currect subscription for your app.

Click the Access control (IAM) tab.

Click the + Add button.

Select the Contributor role in the Add permission dialog.

Search with your app name, and select the app in the searched list.

Click the Save button.

Body:
I am new to Azure platform. I have followed this link to generate service principle : https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

When I reach to step : Assign application to role > point 6 (Search for your application, and select it.) I can't see my application in result of search.

After that I have tried to create VM using ruby api :

https://github.com/Azure/azure-sdk-for-ruby/tree/master/management/azure_mgmt_compute

When I implement code to create VM, I get following error :

"message": "MsRestAzure::AzureOperationError: AuthorizationFailed: The client 'xxxx' with object id 'xxxx' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/write' over scope '/subscriptions/xxxx/resourceGroups/my_group/providers/Microsoft.Compute/virtualMachines/test-ubuntu3'.",

In above error message both client and object id is same. I don't know why and what is the meaning of object id.

How I can resolve this issue ? Where I should look at in portal ? Any help will be appreciated.

Thank you


答: You have an extra "}" at the end of your code please remove it and then try </p>

Title: Not getting click event in jQuery


问:
Display first 3 line from large paragraph from php mysql
I am using PHP and MySQL to get data from database. I have one description field in database. In description field contains large para.

For example: (In database description field contain this para)

The ‘Fox and the Grapes’ is often cited as an example for cognitive dissonance: the discomfort people experience when their beliefs/actions are at odds with other beliefs/actions. In the story, the fox sees some grapes on a vine and wants to eat them. He tries to jump up, but cannot reach them because they are too high. When he realizes he will not be able to eat any grapes, the fox becomes disdainful; he tells himself that those grapes were sour and not worthy of desire anyway.

Now I want only first three line from this para like that

The ‘Fox and the Grapes’ is often cited as an example for cognitive dissonance: the discomfort people experience when their beliefs/actions are at odds with other beliefs/actions.

答:
I would suggest you to put the entire paragraph  in the webpage i.e: inside a div / p tag and use web designing skills to achieve your goal.

Putting a paragraph in a table is not appropriate if you apply normalisation. Apart from that the performance will be hampered in the long run.

If you still want to go ahead then parsing will help you.


问:
optimize for loop in java
I am trying to print a square using for loop.
can the below code be improvised to print the square only using for loop instead of swing</p>

```<code>public class TestProgram {

    public static void main(String[] args) {

        TestProgram test = new TestProgram();
        test.draw(15, 4);
    }

    public void draw(int x, int y) {
        // System.out.println(".");
        System.out.println();
        int i = 0;
        int j = 0;
        for (i = 0; i < x; i++) {

            System.out.print(".");

            // continue;
        }
        for (j = x; j > y; j--) {

            System.out.println(".");
            System.out.print("\t\t");
            System.out.println(".");

        }

        for (int k = 0; k <= x; k++) {
            System.out.print(".");
        }

    }

}
</code>```

答:
You can do it in this way:</p>

```<code>void rectangleDraw(int x, int y) {

    String line1 = new String(new byte[x]).replaceAll("", ".");
    String line2 = "." + new String(new byte[x - 2]).replaceAll("", " ") + ".";

    System.out.println(line1);
    for (int i = x; i > y; i--) {
        System.out.println(line2);
    }

    System.out.println(line1);
}
</code>```

Title: optimize for loop in java

Body:
I am trying to print a square using for loop.
can the below code be improvised to print the square only using for loop instead of swing

public class TestProgram {

    public static void main(String[] args) {

        TestProgram test = new TestProgram();
        test.draw(15, 4);
    }

    public void draw(int x, int y) {
        // System.out.println(".");
        System.out.println();
        int i = 0;
        int j = 0;
        for (i = 0; i < x; i++) {

            System.out.print(".");

            // continue;
        }
        for (j = x; j > y; j--) {

            System.out.println(".");
            System.out.print("\t\t");
            System.out.println(".");

        }

        for (int k = 0; k <= x; k++) {
            System.out.print(".");
        }

    }

}

Body:
You can do it in this way:

void rectangleDraw(int x, int y) {

    String line1 = new String(new byte[x]).replaceAll("", ".");
    String line2 = "." + new String(new byte[x - 2]).replaceAll("", " ") + ".";

    System.out.println(line1);
    for (int i = x; i > y; i--) {
        System.out.println(line2);
    }

    System.out.println(line1);
}


问:
Alternative to mcrypt_encrypt?
As per the php 7.0 mcrypt_decrypt is deprecated.

I have following code.

```<code>$intSize= mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
$strSize = mcrypt_create_iv( $intSize, MCRYPT_RAND );
$strText = ( true == $boolTrimText ) ? trim( $strText ) : $strText;
$strResult = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, ( string ) $strKey, ( string ) $strText, MCRYPT_MODE_ECB, $strSize) );
</code>```

Now we are getting

```<code>mcrypt_encrypt(): Key of size 0 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported
</code>```

Any alternative to fix this warning?

答: You should use openssl_encrypt.  here the link : http://php.net/manual/en/function.openssl-encrypt.php</p>

Title: Alternative to mcrypt_encrypt?

Body:
As per the php 7.0 mcrypt_decrypt is deprecated.

I have following code.

$intSize= mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
$strSize = mcrypt_create_iv( $intSize, MCRYPT_RAND );
$strText = ( true == $boolTrimText ) ? trim( $strText ) : $strText;
$strResult = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, ( string ) $strKey, ( string ) $strText, MCRYPT_MODE_ECB, $strSize) );

Now we are getting

mcrypt_encrypt(): Key of size 0 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported

Any alternative to fix this warning?


问:
Drupal 7: Can I use a webform to submit a single record or upload CSV file for multiple records to database?
A client has asked that we come up with a solution to the following scenario.

They would like a webform that would allow for single/multi-line record submission, which is easy enough to do. They would also like to have the ability to have a file upload option that would allow them to upload a CSV file for bulk record submission.

Has anyone else run into something like this? Is this something that can be done using the Drupal Feeds module? If so, how have you done it? If not... how have you done it?

答: As per my understanding you want to upload multiple CSV files in webform. I don't know why you are going for Feeds module. You have webform specific modules that is webform_multiple  and webform_multiple_file. Please have a look into these modules it may resolve your problem.</p>


问:
How to check the text box value that exist in the database after submit the form
I have this HTML Code in a form, I would like to check whether this value that user input is already exist in the database or not.

```<code><tr height="50">
    <td valign="top"><label for="CINumber"><span style="color:red">*</span>CI Name:</label></td>
     <td><input type="text" id="CINumber" name="CINumber"></td>
</tr>
</code>```

I have this ``JavaScript function for sumbmit the form values:

```<code>function submit(){
    var cNumber = document.getElementById("CINumber").value;
     //many form value within this function but I showed this value only cause this value need to check when click submit button.
    $.ajax({
        url: 'PHPMethodCalls_AL.php',
        type: 'post',
        data: {'action':'AddNewCI', 'cNumber' : cNumber },
        success: function(data,status) {
            //alert(data);
            if(status == "success"){
                alert("CI Name can be assigned");
                alert("Successfully Register New CI Record.");
            } else {
                alert("CI Name is already present!");
                return ;
            }
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}
</code>```

And I call the PHPMethod Call in the 'PHPMethodCalls_AL.php' url..

```<code>if($_POST['action'] == "AddNewCI"){
    $cNumber = $_POST['cNumber'];
    $newCI = AddNewCI($cNumber);
    echo json_encode($newCI );
}
</code>```

After that I call the PHP function that connect with the database.

```<code>function AddNewCI($cNumber){
    global $DB;
    if(!empty($cNumber)){
        $namequery="SELECT Name from Item where Name='$cNumber'";
        $namecheck=mysql_query($namequery);
        $row=mysql_num_rows($namecheck);

        if($row==0){
            echo "success";
            $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
            $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);
        }
        else {
            echo "!success";
        }
    }
}
</code>```

After click submit, I only got the (status == "success") then pop up 2 alert box  even the data is already exist in the database. However, the duplicate value don't save in the database cause I made the UNIQUE for this fields. Please suggest me how should I do to get the the right alert box if the data was exist, show "Alredy exist" if not " show the success alert box"...

答:
Change your success function with this in ajax request :</p>

```<code>success:fucntion(data){
  if(data=="success"){
    alert("Your success message here.");
  }else{
    alert("Alert message whatever you want.");
  }
},
</code>```

Body:
I have this HTML Code in a form, I would like to check whether this value that user input is already exist in the database or not.

    *CI Name:
     <input type="text" id="CINumber" name="CINumber">

I have this ``JavaScript function for sumbmit the form values:

function submit(){
    var cNumber = document.getElementById("CINumber").value;
     //many form value within this function but I showed this value only cause this value need to check when click submit button.
    $.ajax({
        url: 'PHPMethodCalls_AL.php',
        type: 'post',
        data: {'action':'AddNewCI', 'cNumber' : cNumber },
        success: function(data,status) {
            //alert(data);
            if(status == "success"){
                alert("CI Name can be assigned");
                alert("Successfully Register New CI Record.");
            } else {
                alert("CI Name is already present!");
                return ;
            }
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}

And I call the PHPMethod Call in the 'PHPMethodCalls_AL.php' url..

if($_POST['action'] == "AddNewCI"){
    $cNumber = $_POST['cNumber'];
    $newCI = AddNewCI($cNumber);
    echo json_encode($newCI );
}

After that I call the PHP function that connect with the database.

function AddNewCI($cNumber){
    global $DB;
    if(!empty($cNumber)){
        $namequery="SELECT Name from Item where Name='$cNumber'";
        $namecheck=mysql_query($namequery);
        $row=mysql_num_rows($namecheck);

        if($row==0){
            echo "success";
            $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
            $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);
        }
        else {
            echo "!success";
        }
    }
}

After click submit, I only got the (status == "success") then pop up 2 alert box  even the data is already exist in the database. However, the duplicate value don't save in the database cause I made the UNIQUE for this fields. Please suggest me how should I do to get the the right alert box if the data was exist, show "Alredy exist" if not " show the success alert box"...

Body:
Change your success function with this in ajax request :

success:fucntion(data){
  if(data=="success"){
    alert("Your success message here.");
  }else{
    alert("Alert message whatever you want.");
  }
},


问:
Connection object is not null in contructor i which i invoked to get connection object but in other function to use cbject i am getting null
Connection object is not null in the constructor which i invoked to get connection object  but in other function to use object I am getting null.

```<code>package shoppings;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;`
import Filehandling.MyConnection;

public class Product {

    public static void main( String args[]){
        String sql = "select ProductID, ProductName from products ";
        ProductDetail ub = new ProductDetail(  );
        ub.getProductDetail();
    }
}

    class ProductDetail{
    Connection con=null;
    PreparedStatement st;
    ResultSet rs;

    public ProductDetail(){
        MyConnection mycon = new MyConnection();
         Connection con = mycon.getConnObject("");
         System.out.println(con);
         //o/t com.mysql.jdbc.Connection@7cca494b
    }

    public void getProductDetail( ){

         System.out.println(con);
        //o/t null

    }

}
</code>```

答:
You aren't setting the variable in your constructor to the instance variable. Try this:</p>

```<code>public ProductDetail(){
     MyConnection mycon = new MyConnection();
     con = mycon.getConnObject("");
     System.out.println(con);
}
</code>```

Body:
Connection object is not null in the constructor which i invoked to get connection object  but in other function to use object I am getting null.

package shoppings;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;`
import Filehandling.MyConnection;

public class Product {

    public static void main( String args[]){
        String sql = "select ProductID, ProductName from products ";
        ProductDetail ub = new ProductDetail(  );
        ub.getProductDetail();
    }
}

    class ProductDetail{
    Connection con=null;
    PreparedStatement st;
    ResultSet rs;

    public ProductDetail(){
        MyConnection mycon = new MyConnection();
         Connection con = mycon.getConnObject("");
         System.out.println(con);
         //o/t com.mysql.jdbc.Connection@7cca494b
    }

    public void getProductDetail( ){

         System.out.println(con);
        //o/t null

    }

}

Body:
You aren't setting the variable in your constructor to the instance variable. Try this:

public ProductDetail(){
     MyConnection mycon = new MyConnection();
     con = mycon.getConnObject("");
     System.out.println(con);
}


问:
Print from java to jsp
i am trying to create a Facebook oAuth code which in the end will print user's First Name, Last Name,Email etc on browser. This will be made with java and jsp. So here is my java code

```<code>public class MainMenu extends HttpServlet {

private static final long serialVersionUID = 1L;
private String code="";

public void service(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    code = req.getParameter("code");
    if (code == null || code.equals("")) {
        throw new RuntimeException(
                "ERROR: Didn't get code parameter in callback.");
    }
    FBConnection fbConnection = new FBConnection();
    String accessToken = fbConnection.getAccessToken(code);

    FBGraph fbGraph = new FBGraph(accessToken);
    String graph = fbGraph.getFBGraph();
    Map<String, String> fbProfileData = fbGraph.getGraphData(graph);
    ServletOutputStream out = res.getOutputStream();
    out.println("<h1>Facebook Login using Java</h1>");
    out.println("<h2>Application Main Menu</h2>");
    out.println("<div>Welcome "+fbProfileData.get("first_name"));
    out.println("<div>Your Email: "+fbProfileData.get("email"));
    out.println("<div>You are "+fbProfileData.get("gender"));

}
</code>```

}

and i have an empty jsp file.

答:
Yeah as Scary suggested, try using,

PrintWriter out = response.getWriter()

As this basically does the similar work of, System.out.println as in Java.

Title: Print from java to jsp

Body:
i am trying to create a Facebook oAuth code which in the end will print user's First Name, Last Name,Email etc on browser. This will be made with java and jsp. So here is my java code

public class MainMenu extends HttpServlet {

private static final long serialVersionUID = 1L;
private String code="";

public void service(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    code = req.getParameter("code");
    if (code == null || code.equals("")) {
        throw new RuntimeException(
                "ERROR: Didn't get code parameter in callback.");
    }
    FBConnection fbConnection = new FBConnection();
    String accessToken = fbConnection.getAccessToken(code);

    FBGraph fbGraph = new FBGraph(accessToken);
    String graph = fbGraph.getFBGraph();
    Map<String, String> fbProfileData = fbGraph.getGraphData(graph);
    ServletOutputStream out = res.getOutputStream();
    out.println("
Facebook Login using Java
");
    out.println("
Application Main Menu
");
    out.println("
Welcome "+fbProfileData.get("first_name"));
    out.println("
Your Email: "+fbProfileData.get("email"));
    out.println("
You are "+fbProfileData.get("gender"));

}

}

and i have an empty jsp file.


问:
NoClassDefFoundError with HikariCP
When trying to compile HikariCP with my application, I'm getting a java.lang.NoClassDefFoundError: com/zaxxer/hikari/HikariConfig error.

It does build into the .jar file, but it seems like at runtime the application can't find it.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.MyApp.App</groupId>
    <artifactId>App</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>me.MyApp.App</mainClass>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.6.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>
</code>```

I thought adding the Assembly plugin would fix it, but it didn't. What am I doing wrong?

答:
Because you have this:

```<code>                <archive>
                    <manifest>
                        <mainClass>me.MyApp.App</mainClass>
                    </manifest>
                    <manifestEntries>
                        <Class-Path>.</Class-Path>
                    </manifestEntries>
                </archive>
</code>```

...I would assume that this means that your Class-Path entry in MANIFEST.MF is just a "." (i.e. the current directory only - no JAR files).

I'd suggest you change it to:

```<code>                <archive>
                    <manifest>
                        <mainClass>me.MyApp.App</mainClass>
                        <addClasspath>true</addClasspath>
                    </manifest>
                </archive>
</code>```

Reference Link

Title: NoClassDefFoundError with HikariCP

Body:
When trying to compile HikariCP with my application, I'm getting a java.lang.NoClassDefFoundError: com/zaxxer/hikari/HikariConfig error.

It does build into the .jar file, but it seems like at runtime the application can't find it.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.MyApp.App</groupId>
    <artifactId>App</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>me.MyApp.App</mainClass>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.6.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>

I thought adding the Assembly plugin would fix it, but it didn't. What am I doing wrong?

Body:
Because you have this:

                <archive>
                    <manifest>
                        <mainClass>me.MyApp.App</mainClass>
                    </manifest>
                    <manifestEntries>
                        <Class-Path>.</Class-Path>
                    </manifestEntries>
                </archive>

...I would assume that this means that your Class-Path entry in MANIFEST.MF is just a "." (i.e. the current directory only - no JAR files).

I'd suggest you change it to:

                <archive>
                    <manifest>
                        <mainClass>me.MyApp.App</mainClass>
                        <addClasspath>true</addClasspath>
                    </manifest>
                </archive>

Reference Link


问:
tabindex stops in a particular element
I am using Angular JS in my application. I am using tabindex on certain clickable elements to support keyboard users for the application.

My understanding about tabindex is that suppose an element A gets tabindex = 1, element B gets tabindex = 3, element C with tabindex = 2, then the order of tabbing will be A -> C -> B. Then the loop continues.

I have provided the following code snippet. This part is actually a modal, which appears on top of another page:

```<code><div data-ng-if="true">
    <a tabindex="1" data-ng-click="function1()">Change Password</a>
</div>
<div>
    <a tabindex="2" data-ng-click="function2()">Manage</a>
</div>
</code>```

So when we start tabbing the expectation is that change password with tabindex 1 will be highlighted and then Manage with tabindex 2. Then the loop continues. However, the tab stops at Manage

Did anyone face a similar issue?

答: I think tabindex works in reverse order, i.e. if A = 1, B = 2 and C = 3, then the order is C>B>A.</p>

Title: tabindex stops in a particular element

Body:
I am using Angular JS in my application. I am using tabindex on certain clickable elements to support keyboard users for the application.

My understanding about tabindex is that suppose an element A gets tabindex = 1, element B gets tabindex = 3, element C with tabindex = 2, then the order of tabbing will be A -> C -> B. Then the loop continues.

I have provided the following code snippet. This part is actually a modal, which appears on top of another page:

    Change Password

    Manage

So when we start tabbing the expectation is that change password with tabindex 1 will be highlighted and then Manage with tabindex 2. Then the loop continues. However, the tab stops at Manage

Did anyone face a similar issue?


问:
What are the mandatory options for loading Excel file?
I have loaded an excel file from S3 using the below syntax, but I am wondering about the options that need to be set here.

Why is it mandatory to set all the below options for loading excel file? None of these options are mandatory for loading other file types like csv,del,json,avro etc.

```<code>val data = sqlContext.read.
format("com.crealytics.spark.excel").
option("location", s3path).
option("useHeader", "true").
option("treatEmptyValuesAsNulls", "true").
option("inferSchema","true").
option("addColorColumns", "true").
load(path)
</code>```

I get the below error if any of the above options(except location) are not set:

```<code>sqlContext.read.format("com.crealytics.spark.excel").option("location", s3path).load(s3path)
</code>```

Error message :

```<code>Name: java.lang.IllegalArgumentException
Message: Parameter "useHeader" is missing in options.
StackTrace:   at com.crealytics.spark.excel.DefaultSource.checkParameter(DefaultSource.scala:37)
          at com.crealytics.spark.excel.DefaultSource.createRelation(DefaultSource.scala:19)
          at com.crealytics.spark.excel.DefaultSource.createRelation(DefaultSource.scala:7)
          at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:345)
          at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:149)
          at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:132)
          at $anonfun$1.apply(<console>:47)
          at $anonfun$1.apply(<console>:47)
          at time(<console>:36)
</code>```

答:
Most of the options for spark-excel are mandatory except for userSchema and sheetName.

You can always check for that in the DataSource source code that you can find here.

You have to remember that this data source or data connector packages are implemented outside of the spark project and each comes with his rules and parameters.

Body:
I have loaded an excel file from S3 using the below syntax, but I am wondering about the options that need to be set here.

Why is it mandatory to set all the below options for loading excel file? None of these options are mandatory for loading other file types like csv,del,json,avro etc.

val data = sqlContext.read.
format("com.crealytics.spark.excel").
option("location", s3path).
option("useHeader", "true").
option("treatEmptyValuesAsNulls", "true").
option("inferSchema","true").
option("addColorColumns", "true").
load(path)

I get the below error if any of the above options(except location) are not set:

sqlContext.read.format("com.crealytics.spark.excel").option("location", s3path).load(s3path)

Error message :

Name: java.lang.IllegalArgumentException
Message: Parameter "useHeader" is missing in options.
StackTrace:   at com.crealytics.spark.excel.DefaultSource.checkParameter(DefaultSource.scala:37)
          at com.crealytics.spark.excel.DefaultSource.createRelation(DefaultSource.scala:19)
          at com.crealytics.spark.excel.DefaultSource.createRelation(DefaultSource.scala:7)
          at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:345)
          at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:149)
          at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:132)
          at $anonfun$1.apply(<console>:47)
          at $anonfun$1.apply(<console>:47)
          at time(<console>:36)


问:
QTimer with QDragEvent problems
I have a GUI application where you can drag widgets around in a QGraphicsView/Scene. You can also pan and zoom while you're not dragging a widget.

What I want:
I want to make it so that when you're dragging an item near the edge of the screen that it starts to pan in that direction and keeps panning even if the mouse isn't moving, but the mouse still needs to be in the top/left/right or bottom 10% of the screen.

What I've tried:
Inside the dragMoveEvent I check if the mouse is on the edge of the screen. If so I start a Qtimer with 15msec timeout. On timeout a function is slotted to pan the scene in the right direction by updating the center. This approach WORKS, BUT when i leave the mouse still on the edge the panning is choppy and if the mouse is moving around inside the edge then the panning is smooth as it should be.

Bottom Line:
Why is the panning only choppy/laggy when the mouse isn't moving? How do I fix it so that the panning is smooth like when you move the mouse around inside the edges?

答: What happens when you increase/decrease your timeout?</p>

Title: QTimer with QDragEvent problems


问:
Where are tor control go?
According to this tutorial, I could launch my network connection through Tor by Vidalia, as the image shown

But when I download latest tor(windows version, 6.5.2), I cannot find the Vidalia anymore, now tor is start with browser and end with browser. How could I do the same settings as the graph shown on recent tor?

I try to connect through tor by Qt5.6.2 but it always fail(not a recommend way to use QNetworkAccessManager like this)

```<code>    //9150, 9151 both fails
    QNetworkProxy proxy(QNetworkProxy::DefaultProxy, "127.0.0.1", 9150);
    QNetworkProxy::setApplicationProxy(proxy);
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    //setup the proxy on network manager do not work either
    //manager->setProxy(proxy);
    connect(manager, static_cast<void(QNetworkAccessManager::*)(QNetworkReply*)>(&QNetworkAccessManager::finished),
            [=](QNetworkReply *reply)
    {
        qDebug()<<"push reply";
        QFile file("tor_reply.html");
        QTextStream stream(&file);
        if(file.open(QIODevice::WriteOnly)){
            stream<<reply->readAll();
        }
    });
    connect(manager, static_cast<void(QNetworkAccessManager::*)(QNetworkReply*)>(&QNetworkAccessManager::finished),
            manager, &QNetworkAccessManager::deleteLater);
    manager->get(QNetworkRequest(QUrl("http://www.whatsmyip.org/")));
</code>```

I confirm torrc is up and running and do not change any settings of torrc, any suggestions?

答:
I've found out the answer just now, changing proxy settings works:

```<code>QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, "127.0.0.1", 9150);
</code>```

How to set this up?

Go to Tools

Click on options

Click Advance

Click Network

Click Settings (please refer image below for steps 3~5)

Adjust Manual proxy configuration. I use default option:

Title: Where are tor control go?

Body:
According to this tutorial, I could launch my network connection through Tor by Vidalia, as the image shown

But when I download latest tor(windows version, 6.5.2), I cannot find the Vidalia anymore, now tor is start with browser and end with browser. How could I do the same settings as the graph shown on recent tor?

I try to connect through tor by Qt5.6.2 but it always fail(not a recommend way to use QNetworkAccessManager like this)

    //9150, 9151 both fails
    QNetworkProxy proxy(QNetworkProxy::DefaultProxy, "127.0.0.1", 9150);
    QNetworkProxy::setApplicationProxy(proxy);
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    //setup the proxy on network manager do not work either
    //manager->setProxy(proxy);
    connect(manager, static_cast<void(QNetworkAccessManager::*)(QNetworkReply*)>(&QNetworkAccessManager::finished),
            [=](QNetworkReply *reply)
    {
        qDebug()<<"push reply";
        QFile file("tor_reply.html");
        QTextStream stream(&file);
        if(file.open(QIODevice::WriteOnly)){
            stream<<reply->readAll();
        }
    });
    connect(manager, static_cast<void(QNetworkAccessManager::*)(QNetworkReply*)>(&QNetworkAccessManager::finished),
            manager, &QNetworkAccessManager::deleteLater);
    manager->get(QNetworkRequest(QUrl("http://www.whatsmyip.org/")));

I confirm torrc is up and running and do not change any settings of torrc, any suggestions?

Body:
I've found out the answer just now, changing proxy settings works:

QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, "127.0.0.1", 9150);

How to set this up?

Go to Tools

Click on options

Click Advance

Click Network

Click Settings (please refer image below for steps 3~5)

Adjust Manual proxy configuration. I use default option:


问:
Pass parameter to class which inherits from DbContext
My application is an ASP.NET Core 1.0 Web API. I am using Entity framework.

I wan't to change the CommandTimeout like this:

```<code>public class MyDbContext: DbContext
{
   private const int Timeout = 180;

   public MyDbContext(DbContextOptions options): base(options)
   {
       this.Database.SetCommandTimeout(Timeout);
   }
}
</code>```

this works if Timeout is defined in my class.

However, I would like to have the value of my Timeout inside my appsettings.json file like this:

```<code>  "DbContextSettings": {
    "Timeout": "180"
  }
</code>```

so there are two ways to set the CommandTimeout now:

Pass the CommandTimeOutInSeconds as a parameter to the constructor.

Get the value out of appsettings.json inside the constructor of my class

I don't know how to achieve one of the ways.

Is this possible? or is there any known workaround?

Edit

Iam never really Initailizing MyDbContext. I do this in ConfigureServices in the Startup class like this:

```<code>services.AddDbContext<MyDbContext>(db => db.UseSqlServer("secret"));
</code>```

Edit 2

@dennisanberlin so let's say I have a controller calling the following method:

```<code>public class SomeRepository
{

  private MyDbContext context;

  public SomeRepository(MyDbContext myContext)
  {
     this.context = myContext;
  }

  public Person SomeMethodCalledByController(){
     return myContext.SomeTableWhichContainsPersons.FirstOrDefault(person => person.name == "Bob");
  }
}
</code>```

The class SomeRepository is never getting initialized by me. Iam doing this via dependency injection in the startup like this:

```<code>services.AddTransient<SomeRepository>();
</code>```

The class knows about MyDbContext from the above shown line:

```<code>services.AddDbContext<MyDbContext>(db => db.UseSqlServer("secret"));
</code>```

Therefore I never pass an object of MyDbContext directly to any of my classes working with the database.

答:
You can pass the timeout to your constructor like this:

```<code>public MyDbContext(DbContextOptions options, int timeout): base(options)
   {
       Timeout = timeout;
       this.Database.SetCommandTimeout(Timeout);
   }
</code>```

And here is an example on how to read settings from your App settings.json csharpcorner

EDIT

```<code>public MyDbContext(DbContextOptions options): base(options)
   {
       int timeout = //return timeout setting from appsettings.json
       this.Database.SetCommandTimeout(Timeout);
   }
</code>```

You can try to do it that way, that you read your appsettings.json inside your constructor.

Body:
My application is an ASP.NET Core 1.0 Web API. I am using Entity framework.

I wan't to change the CommandTimeout like this:

public class MyDbContext: DbContext
{
   private const int Timeout = 180;

   public MyDbContext(DbContextOptions options): base(options)
   {
       this.Database.SetCommandTimeout(Timeout);
   }
}

this works if Timeout is defined in my class.

However, I would like to have the value of my Timeout inside my appsettings.json file like this:

  "DbContextSettings": {
    "Timeout": "180"
  }

so there are two ways to set the CommandTimeout now:

Pass the CommandTimeOutInSeconds as a parameter to the constructor.

Get the value out of appsettings.json inside the constructor of my class

I don't know how to achieve one of the ways.

Is this possible? or is there any known workaround?

Edit

Iam never really Initailizing MyDbContext. I do this in ConfigureServices in the Startup class like this:

services.AddDbContext<MyDbContext>(db => db.UseSqlServer("secret"));

Edit 2

@dennisanberlin so let's say I have a controller calling the following method:

public class SomeRepository
{

  private MyDbContext context;

  public SomeRepository(MyDbContext myContext)
  {
     this.context = myContext;
  }

  public Person SomeMethodCalledByController(){
     return myContext.SomeTableWhichContainsPersons.FirstOrDefault(person => person.name == "Bob");
  }
}

The class SomeRepository is never getting initialized by me. Iam doing this via dependency injection in the startup like this:

services.AddTransient<SomeRepository>();

The class knows about MyDbContext from the above shown line:

services.AddDbContext<MyDbContext>(db => db.UseSqlServer("secret"));

Therefore I never pass an object of MyDbContext directly to any of my classes working with the database.

Body:
You can pass the timeout to your constructor like this:

public MyDbContext(DbContextOptions options, int timeout): base(options)
   {
       Timeout = timeout;
       this.Database.SetCommandTimeout(Timeout);
   }

And here is an example on how to read settings from your App settings.json csharpcorner

EDIT

public MyDbContext(DbContextOptions options): base(options)
   {
       int timeout = //return timeout setting from appsettings.json
       this.Database.SetCommandTimeout(Timeout);
   }

You can try to do it that way, that you read your appsettings.json inside your constructor.


答:
Yes of course, your connection object here:

```<code>public ProductDetail(){
    MyConnection mycon = new MyConnection();
     Connection con = mycon.getConnObject("");
     System.out.println(con);
}
</code>```

is locally scoped to the method ProductDetails and will no longer be avaliable after that method is done, so it is making shadow over the class connection member

do instead:

```<code> public ProductDetail(){
     MyConnection mycon = new MyConnection();
     con = mycon.getConnObject("");
     System.out.println(con);

}
</code>```

Title: Connection object is not null in contructor i which i invoked to get connection object but in other function to use cbject i am getting null

Body:
Yes of course, your connection object here:

public ProductDetail(){
    MyConnection mycon = new MyConnection();
     Connection con = mycon.getConnObject("");
     System.out.println(con);
}

is locally scoped to the method ProductDetails and will no longer be avaliable after that method is done, so it is making shadow over the class connection member

do instead:

 public ProductDetail(){
     MyConnection mycon = new MyConnection();
     con = mycon.getConnObject("");
     System.out.println(con);

}


答:
In the constructor you declare a Connection con local variable and you instantiate it :

```<code>public ProductDetail(){
       ...
     Connection con = mycon.getConnObject("");
       ...
 }
</code>```

But this local variable is a distinct variable from the Connection con variable field declared here :

```<code>class ProductDetail{
 ....
    Connection con=null;
}
</code>```

So assigning one of them doesn't change the value of the other one.

If you want to value the Connection con field, you don't need to declare another variable in the constructor.

Just change your constructor to assign the new created Connection to the instance field :

```<code>con = new MyConnection().getConnObject("");
</code>```

Body:
In the constructor you declare a Connection con local variable and you instantiate it :

public ProductDetail(){
       ...
     Connection con = mycon.getConnObject("");
       ...
 }

But this local variable is a distinct variable from the Connection con variable field declared here :

class ProductDetail{
 ....
    Connection con=null;
}

So assigning one of them doesn't change the value of the other one.

If you want to value the Connection con field, you don't need to declare another variable in the constructor.

Just change your constructor to assign the new created Connection to the instance field :

con = new MyConnection().getConnObject("");


答:
If tabindex is a negative value, you can't focus it by using
tab press.

If it is zero, that is the first focusable element in the document.

If it is positive number, elements will be focused in ascending
order

If elements contains same tabindex, order in html is matters. Focused
in the order in which they are created in html

for more info, read tabindex

Most importantly, the browser url box is with tabindex 0

Title: tabindex stops in a particular element


问:
Remove Auto-Generated advertisement script appended to the results returned by ajax requests
My site is hosted on somee.com.

I have used JQuery to send ajax requests.

On every ajax request the returned result is appended with the below text.

```<code>"<!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE-->
<center><a href="http://somee.com">Web hosting by Somee.com</a></center> </textarea>
</xml></script></noframes></noscript></object></layer></style></title></applet>
<script language="JavaScript"
src="http://ads.mgmt.somee.com/serveimages/ad2/WholeInsert4.js"></script>
<!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE-->"
</code>```

for example if on success of ajax call the server returns the following string : "Invalid Username and/or Password"

Then I get the following string :

```<code>"Invalid Username and/or Password <!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE-->
 <center><a href="http://somee.com">Web hosting by Somee.com</a></center> </textarea>
</xml></script></noframes></noscript></object></layer></style></title></applet>
<script language="JavaScript"
src="http://ads.mgmt.somee.com/serveimages/ad2/WholeInsert4.js"></script>
<!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE-->"
</code>```

Now I am comparing this string to the other string, So comparison returns false as this string contains the appended text.

Thus, my site is not functioning properly.

EDIT :

I counted the no. of characters and tried to use .slice(0, -no. of characters in advertisement). This works fine if the server returns string. But does not work while server returns 'JSON' because in the ajax call we have to declare dataType:'json' and after the addition of advertisement script the result is no more json object. So, Success is not called and as a result I did not get the output.

So, now my question is : If server returns JSON + String on AJAX call, on client side I want to delete the String part and get only the JSON object so that AJAX call returns in a success instead of failure/Error. (I know the no. of characters that the appended string contains.)

答:
Simply append a unique identifier with your ajax response.Then the return result should looks like YOUR_DESIRED_RESULT+"Uniqueidentifier"+"(Somee Auto-Generated advertisement)

e.g. var retUrl = "DESIRED_RESULT/Somee Auto-Generated advertisement".

Now split the result with unique identifier(here '/').

retUrl = retUrl.split('/')[0]; // this is your desired output; :)

Body:
My site is hosted on somee.com.

I have used JQuery to send ajax requests.

On every ajax request the returned result is appended with the below text.

"
Web hosting by Somee.com </textarea>
</xml></script></noframes></object></layer></style></title></applet>

"

for example if on success of ajax call the server returns the following string : "Invalid Username and/or Password"

Then I get the following string :

"Invalid Username and/or Password
 Web hosting by Somee.com </textarea>
</xml></script></noframes></object></layer></style></title></applet>

"

Now I am comparing this string to the other string, So comparison returns false as this string contains the appended text.

Thus, my site is not functioning properly.

EDIT :

I counted the no. of characters and tried to use .slice(0, -no. of characters in advertisement). This works fine if the server returns string. But does not work while server returns 'JSON' because in the ajax call we have to declare dataType:'json' and after the addition of advertisement script the result is no more json object. So, Success is not called and as a result I did not get the output.

So, now my question is : If server returns JSON + String on AJAX call, on client side I want to delete the String part and get only the JSON object so that AJAX call returns in a success instead of failure/Error. (I know the no. of characters that the appended string contains.)


问:
All job data lost when running Jenkins in Docker and when Jenkins container is stopped
On a VPS server I use the following command to run Jenkins:

```<code>docker run -d -p 8080:8080 jenkins
</code>```

But sometimes, my config error will stop the container, then all my jobs configured in Jenkins are lost.

I follow this video to run Jenkins in Docker.
Is this the right way to run Jenkin in Docker? How to save my jobs in my pulled Jenkins image?

答:
You have to attach a volume to the container that point to jenkins home directory. Usually I use:

docker run -d -p 80:8080 -v /my-absolute-path/where-is-jenkins_home:/var/jenkins_home jenkins

Body:
On a VPS server I use the following command to run Jenkins:

docker run -d -p 8080:8080 jenkins

But sometimes, my config error will stop the container, then all my jobs configured in Jenkins are lost.

I follow this video to run Jenkins in Docker.
Is this the right way to run Jenkin in Docker? How to save my jobs in my pulled Jenkins image?


问:
Cant Connect to MongoDB server from Client
I am trying to connect from my machine (client) to server, and it says I cant connect to server.
My machine is Windows 10 and Server machine is Windows Server 2016.

And I tried to connect from cmd and it gives me this error.

Help me with this problem please.

答: I will comment regarding Robomongo, seems like you are trying to connect to MongoDB 3.4 DB which only supported starting from the latest beta: Robomongo 1.1 - Beta version with MongoDB 3.4 Support</p>

ContentLicense: CC BY-SA 4.0