问:
LINQ XML - Select all parent elements where a child has a given value
From the XML below,  I need to find information about all flights where  FlightSegmentReference ref equals BA2759,  and then pass some details from the parent elements to a class

```<code> If Len(inFlightNo) > 0 Then
     Dim xdoc As XDocument = XDocument.Parse(rawXML)
     Dim results As IEnumerable(Of Offer) =
         From offer In xdoc.Descendants(myns + "FlightSegmentReference")
             Where offer.Attribute("ref") = inFlightNo
                 Select New Offer With
                 {.FlightRef = offer.Attribute("ref")}
     'Return results
 End If
</code>```

This example works fine...  however I need to get more data to  pass to my class,  such as TotalAmount SimpleCurrancyPrice and OfferItemID

```<code> If Len(inFlightNo) > 0 Then
     Dim xdoc As XDocument = XDocument.Parse(rawXML)
     Dim results As IEnumerable(Of Offer) =
         From offer In xdoc.Descendants(myns + "FlightSegmentReference")
             Where offer.Attribute("ref") = inFlightNo
                 Select New Offer With
                 {.FlightRef = offer.Attribute("ref"),
                  .Price = ????,
                  .OfferItemID = ????
                 }
     'Return results
 End If
</code>```

What is the best practice method of getting SimpleCurrencyPrice and populating Price in my class

Here is the XML

```<code><AirlineOffers>
   <TotalOfferQuantity>1156</TotalOfferQuantity>
   <Owner>BA</Owner>
   <AirlineOffer RequestedDateInd="true">
      <OfferID Owner="BA">OFFER1</OfferID>
      <TotalPrice>
         <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
      </TotalPrice>
      <PricedOffer>
         <OfferPrice OfferItemID="1">
            <RequestedDate>
               <PriceDetail>
                  <TotalAmount>
                     <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
                  </TotalAmount>
                  <BaseAmount Code="GBP">84.00</BaseAmount>
                  <Taxes>
                     <Total Code="GBP">45.50</Total>
                  </Taxes>
               </PriceDetail>
               <Associations>
                  <AssociatedTraveler>
                     <TravelerReferences>SH1</TravelerReferences>
                  </AssociatedTraveler>
               </Associations>
            </RequestedDate>
         </OfferPrice>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2759">
                  <ClassOfService>
                     <Code>O</Code>
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2764">
                  <ClassOfService>
                     <Code>Q</Code>
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
      </PricedOffer>
   </AirlineOffer>
   <AirlineOffer RequestedDateInd="true">
      <OfferID Owner="BA">OFFER2</OfferID>
      <TotalPrice>
         <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
      </TotalPrice>
      <PricedOffer>
         <OfferPrice OfferItemID="1">
            <RequestedDate>
               <PriceDetail>
                  <TotalAmount>
                     <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
                  </TotalAmount>
                  <BaseAmount Code="GBP">84.00</BaseAmount>
                  <Taxes>
                     <Total Code="GBP">45.50</Total>
                  </Taxes>
               </PriceDetail>
               <Associations>
                  <AssociatedTraveler>
                     <TravelerReferences>SH1</TravelerReferences>
                  </AssociatedTraveler>
               </Associations>
            </RequestedDate>
         </OfferPrice>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2765">
                  <ClassOfService>
                     <Code>O</Code>
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2764">
                  <ClassOfService>
                     <Code>Q</Code>
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
      </PricedOffer>
   </AirlineOffer>
</AirlineOffers>
</code>```

答:
You could use Parent to navigate back up the tree from the FlightSegmentReference element:

Dim results As IEnumerable(Of Offer) =
    From ref In xdoc.Descendants(myns + "FlightSegmentReference")
    Where ref.Attribute("ref") = inFlightNo
    Let offer = ref.Parent.Parent.Parent.Parent
    Select New Offer With {
        .FlightRef = ref.Attribute("ref"),
        .Price = CDec(offer.Element(myns + "TotalPrice").Element(myns + "SimpleCurrencyPrice").Value),
        .OfferItemID = offer.Element(myns + "PricedOffer").Element(myns + "OfferPrice").Attribute("OfferItemID")
    }
```

<p>I like using VB.NET's XML syntax support - it seems more readable to me, although you will need to <code>Import</code> your namespace:</p>

<pre class="lang-vb prettyprint-override"><code>Dim results2 As IEnumerable(Of Offer) =
    From e In xdoc...<myns:FlightSegmentReference>
    Where e.@ref = inFlightNo
    Let offer = e.Parent.Parent.Parent.Parent
    Select New Offer() With {
        .FlightRef = e.@ref,
        .Price = CDec(offer.<myns:TotalPrice>.<myns:SimpleCurrencyPrice>.Value),
        .OfferItemID = offer.<myns:PricedOffer>.<myns:OfferPrice>.@OfferItemID
    }
</code>```

Body:
From the XML below,  I need to find information about all flights where  FlightSegmentReference ref equals BA2759,  and then pass some details from the parent elements to a class

 If Len(inFlightNo) > 0 Then
     Dim xdoc As XDocument = XDocument.Parse(rawXML)
     Dim results As IEnumerable(Of Offer) =
         From offer In xdoc.Descendants(myns + "FlightSegmentReference")
             Where offer.Attribute("ref") = inFlightNo
                 Select New Offer With
                 {.FlightRef = offer.Attribute("ref")}
     'Return results
 End If

This example works fine...  however I need to get more data to  pass to my class,  such as TotalAmount SimpleCurrancyPrice and OfferItemID

 If Len(inFlightNo) > 0 Then
     Dim xdoc As XDocument = XDocument.Parse(rawXML)
     Dim results As IEnumerable(Of Offer) =
         From offer In xdoc.Descendants(myns + "FlightSegmentReference")
             Where offer.Attribute("ref") = inFlightNo
                 Select New Offer With
                 {.FlightRef = offer.Attribute("ref"),
                  .Price = ????,
                  .OfferItemID = ????
                 }
     'Return results
 End If

What is the best practice method of getting SimpleCurrencyPrice and populating Price in my class

Here is the XML

<AirlineOffers>
   <TotalOfferQuantity>1156</TotalOfferQuantity>
   <Owner>BA</Owner>
   <AirlineOffer RequestedDateInd="true">
      <OfferID Owner="BA">OFFER1</OfferID>
      <TotalPrice>
         <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
      </TotalPrice>
      <PricedOffer>
         <OfferPrice OfferItemID="1">
            <RequestedDate>
               <PriceDetail>
                  <TotalAmount>
                     <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
                  </TotalAmount>
                  <BaseAmount Code="GBP">84.00</BaseAmount>
                  <Taxes>
                     <Total Code="GBP">45.50</Total>
                  </Taxes>
               </PriceDetail>
               <Associations>
                  <AssociatedTraveler>
                     <TravelerReferences>SH1</TravelerReferences>
                  </AssociatedTraveler>
               </Associations>
            </RequestedDate>
         </OfferPrice>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2759">
                  <ClassOfService>
                     O
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2764">
                  <ClassOfService>
                     Q
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
      </PricedOffer>
   </AirlineOffer>
   <AirlineOffer RequestedDateInd="true">
      <OfferID Owner="BA">OFFER2</OfferID>
      <TotalPrice>
         <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
      </TotalPrice>
      <PricedOffer>
         <OfferPrice OfferItemID="1">
            <RequestedDate>
               <PriceDetail>
                  <TotalAmount>
                     <SimpleCurrencyPrice Code="GBP">129.50</SimpleCurrencyPrice>
                  </TotalAmount>
                  <BaseAmount Code="GBP">84.00</BaseAmount>
                  <Taxes>
                     <Total Code="GBP">45.50</Total>
                  </Taxes>
               </PriceDetail>
               <Associations>
                  <AssociatedTraveler>
                     <TravelerReferences>SH1</TravelerReferences>
                  </AssociatedTraveler>
               </Associations>
            </RequestedDate>
         </OfferPrice>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2765">
                  <ClassOfService>
                     O
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
         <Associations>
            <ApplicableFlight>
               <FlightSegmentReference ref="BA2764">
                  <ClassOfService>
                     Q
                     <MarketingName>Euro Traveller</MarketingName>
                  </ClassOfService>
               </FlightSegmentReference>
            </ApplicableFlight>
            <PriceClass>
               <PriceClassReference>Plus</PriceClassReference>
            </PriceClass>
         </Associations>
      </PricedOffer>
   </AirlineOffer>
</AirlineOffers>

Body:
You could use Parent to navigate back up the tree from the FlightSegmentReference element:

Dim results As IEnumerable(Of Offer) =
    From ref In xdoc.Descendants(myns + "FlightSegmentReference")
    Where ref.Attribute("ref") = inFlightNo
    Let offer = ref.Parent.Parent.Parent.Parent
    Select New Offer With {
        .FlightRef = ref.Attribute("ref"),
        .Price = CDec(offer.Element(myns + "TotalPrice").Element(myns + "SimpleCurrencyPrice").Value),
        .OfferItemID = offer.Element(myns + "PricedOffer").Element(myns + "OfferPrice").Attribute("OfferItemID")
    }

I like using VB.NET's XML syntax support - it seems more readable to me, although you will need to Import your namespace:

Dim results2 As IEnumerable(Of Offer) =
    From e In xdoc...<myns:FlightSegmentReference>
    Where e.@ref = inFlightNo
    Let offer = e.Parent.Parent.Parent.Parent
    Select New Offer() With {
        .FlightRef = e.@ref,
        .Price = CDec(offer.<myns:TotalPrice>.<myns:SimpleCurrencyPrice>.Value),
        .OfferItemID = offer.<myns:PricedOffer>.<myns:OfferPrice>.@OfferItemID
    }


来源: stackexchange

问:
Default calendar id for android
I am trying to add event automatically but I need calendar id for this
If I add event to calendar with id = 1 sometimes it does not exist or does not depend to event I add

```<code>    ContentValues cv = new ContentValues();
    cv.put("calendar_id", 1);
</code>```

id = -1 does not work

how can I add event to default calendar. what id should I use?

答:
```<code>int calenderId=-1;
        String calenderEmaillAddress="xxx@gmail.com";
        String[] projection = new String[]{
                CalendarContract.Calendars._ID,
                CalendarContract.Calendars.ACCOUNT_NAME};
        ContentResolver cr = activity.getContentResolver();
        Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
                CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
                        CalendarContract.Calendars.NAME + "=? or " +
                        CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
                new String[]{calenderEmaillAddress, calenderEmaillAddress,
                        calenderEmaillAddress}, null);

        if (cursor.moveToFirst()) {

            if (cursor.getString(1).equals(calenderEmaillAddress))
                 calenderId=cursor.getInt(0); //youre calender id to be insered in above your code

        }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Default calendar id for android

Body:
I am trying to add event automatically but I need calendar id for this
If I add event to calendar with id = 1 sometimes it does not exist or does not depend to event I add

    ContentValues cv = new ContentValues();
    cv.put("calendar_id", 1);

id = -1 does not work

how can I add event to default calendar. what id should I use?


问:
Select all duplicate values group by row
I have table as

```<code>Building    Stairs
A           Two
B.          Three
C.          Two
</code>```

I need output as

```<code>A,C.     Two
B.       Three
</code>```

答:
You can do something like this:</p>

```<code>SELECT DISTINCT  STUFF((    SELECT ', ' + b.Building
            FROM #table b
            WHERE b.Stairs = a.Stairs
            FOR XML PATH('') ), 1, 1, '' ) AS Building,
    Stairs
FROM #table a
</code>```

Body:
I have table as

Building    Stairs
A           Two
B.          Three
C.          Two

I need output as

A,C.     Two
B.       Three

Body:
You can do something like this:

SELECT DISTINCT  STUFF((    SELECT ', ' + b.Building
            FROM #table b
            WHERE b.Stairs = a.Stairs
            FOR XML PATH('') ), 1, 1, '' ) AS Building,
    Stairs
FROM #table a


问:
How should I write a regex to remove a specific word from a string?
I have been trying to come up with a suitable regrex to remove the word 'fries' from strings. However, it hasn't been very successful.

Ideally, the regrex expression should be able to remove the word 'fries' regardless of whether is it in upper case and/ or lower case and the word 'fries' shouldn't be removed under the following cases.

```<code>frenchfries
friesislove
ilovefriesverymuch
</code>```

This is what I have came up with so far

```<code>gsub('(?i)\\Wfries\\W','',string)
</code>```

One major flaw with the above is that regex expression isn't able to detect the word 'fries' if it's at either the start or the end of the string.

eg. 'I love fries', 'Fries is love'

答:
You can also try this:

```<code>gsub("\\<fries\\>",replacement = "",string ,ignore.case = TRUE)
</code>```

\\<fries\\> will make sure that only the exact word "fries" will be replaced

Body:
I have been trying to come up with a suitable regrex to remove the word 'fries' from strings. However, it hasn't been very successful.

Ideally, the regrex expression should be able to remove the word 'fries' regardless of whether is it in upper case and/ or lower case and the word 'fries' shouldn't be removed under the following cases.

frenchfries
friesislove
ilovefriesverymuch

This is what I have came up with so far

gsub('(?i)\\Wfries\\W','',string)

One major flaw with the above is that regex expression isn't able to detect the word 'fries' if it's at either the start or the end of the string.

eg. 'I love fries', 'Fries is love'

Body:
You can also try this:

gsub("\\<fries\\>",replacement = "",string ,ignore.case = TRUE)

\\<fries\\> will make sure that only the exact word "fries" will be replaced


问:
Could someone explain why my print statement isn't printing both variables on one line?
as the question states, I don't understand why the output is in two separate lines rather than one. Here's my code:

```<code>import os

items=os.listdir("C:/output")

for names in items:
    if names.endswith(".txt"):
        with open('C:/output/' + names, encoding="utf8") as currentFile:
            for i, line in enumerate(currentFile):
                if ('Date Released' in line):
                    print(line + names)
                else:
                    i = i + 1
                if i > 11:
                    break
</code>```

I've tried using a comma for the print statement like so: print(line, names), that did not work. I've also tried using .format(line, names) at the end of the print statement, no luck with that either.

The output looks like this:

```<code>Date Released:  12/14/2016
 1393-004IP_ B_ C2  filename.txt
Date Released:  4/11/2017
 1476-002 IP, filename.txt
Date Released:  9/25/2015
 1987-XXX IP_B_filename.txt
Date Released: 4/9/2015
 2044-002IP_A_C1  filename.txt
</code>```

etc.

It would be very helpful to get the date and filename in the same line so I can put it into excel very easily. Thanks for any input.

答:
That's because every line ends with a new line character '\n'. You need to strip them, using say str.rstrip:

```
<code>for i, line in enumerate(currentFile):
   <b>line = line.rstrip()</b>
   if 'Date Released' in line:
       print(line + ' ' + names)</code>
```

Body:
as the question states, I don't understand why the output is in two separate lines rather than one. Here's my code:

import os

items=os.listdir("C:/output")

for names in items:
    if names.endswith(".txt"):
        with open('C:/output/' + names, encoding="utf8") as currentFile:
            for i, line in enumerate(currentFile):
                if ('Date Released' in line):
                    print(line + names)
                else:
                    i = i + 1
                if i > 11:
                    break

I've tried using a comma for the print statement like so: print(line, names), that did not work. I've also tried using .format(line, names) at the end of the print statement, no luck with that either.

The output looks like this:

Date Released:  12/14/2016
 1393-004IP_ B_ C2  filename.txt
Date Released:  4/11/2017
 1476-002 IP, filename.txt
Date Released:  9/25/2015
 1987-XXX IP_B_filename.txt
Date Released: 4/9/2015
 2044-002IP_A_C1  filename.txt

etc.

It would be very helpful to get the date and filename in the same line so I can put it into excel very easily. Thanks for any input.

Body:
That's because every line ends with a new line character '\n'. You need to strip them, using say str.rstrip:

for i, line in enumerate(currentFile):
   line = line.rstrip()
   if 'Date Released' in line:
       print(line + ' ' + names)


问:
INSERT Flash Object Into MySql with PHP
I'm breaking my head over this.

I'm trying to insert embeddable video code, such as youtube/viddler/etc.. which all start with the object tag:

<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/Ahg6qcgoay4?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/Ahg6qcgoay4?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>

into MySQL with PHP. I've looked all over the internet and there was nothing solid to make that happen. Does anyone know how to INSERT that code successfully to the database as the value for $video?

UPDATE: I figured out how to store it but now, I'm trying to call it in php, but only get the text value back, basically, the entire embed code as text is displayed instead of the video itself. Here is my display code which shows text. How can I make it show the actual video instead?

```<code><?php
    //assuming a connection to the database exists
$sql = "SELECT * FROM table";
$result = mysql_query( $sql );
while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
    $html = array();  //create an array of html formated values.
    $html['video'] = nl2br( stripslashes( htmlentities( $row['video'], ENT_QUOTES, 'UTF-8' ) ) );
    echo "Video:<br />{$html['video']}<hr />";
}   ?>
</code>```

UPDATE: This is what the embed code looks like in the DB:

```<code><object width=\"450\" height=\"380\"><param name=\"movie\" value=\"http://www.youtube.com/v/Z5j3CORfxmw&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/Z5j3CORfxmw&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"450\" height=\"380\"></embed></object>
</code>```

The php code right above it pulls out this data, without the slashes and it displays the embed code perfectly as text, but the actual video does not form from that. Is there anyway to have the code displayed act as code and show the video instead of text?

答:
```<code>$var = embed code

echo htmlspecialchars_decode($var);
</code>```

ContentLicense: CC BY-SA 2.5

Title: INSERT Flash Object Into MySql with PHP

Body:
I'm breaking my head over this.

I'm trying to insert embeddable video code, such as youtube/viddler/etc.. which all start with the object tag:

<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/Ahg6qcgoay4?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/Ahg6qcgoay4?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>

into MySQL with PHP. I've looked all over the internet and there was nothing solid to make that happen. Does anyone know how to INSERT that code successfully to the database as the value for $video?

UPDATE: I figured out how to store it but now, I'm trying to call it in php, but only get the text value back, basically, the entire embed code as text is displayed instead of the video itself. Here is my display code which shows text. How can I make it show the actual video instead?

<?php
    //assuming a connection to the database exists
$sql = "SELECT * FROM table";
$result = mysql_query( $sql );
while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
    $html = array();  //create an array of html formated values.
    $html['video'] = nl2br( stripslashes( htmlentities( $row['video'], ENT_QUOTES, 'UTF-8' ) ) );
    echo "Video:
{$html['video']}
";
}   ?>

UPDATE: This is what the embed code looks like in the DB:

<object width=\"450\" height=\"380\"><param name=\"movie\" value=\"http://www.youtube.com/v/Z5j3CORfxmw&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/Z5j3CORfxmw&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"450\" height=\"380\"></embed></object>

The php code right above it pulls out this data, without the slashes and it displays the embed code perfectly as text, but the actual video does not form from that. Is there anyway to have the code displayed act as code and show the video instead of text?


问:
Using PowerMockito to mock Path.getParent()
I have been getting the following error:
org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) getParent were found in the class hierarchy of class java.lang.Object.

I'm not sure why.  I have tried creating some simple code to narrow down the error and don't understand why this mock isn't working.

The code to test:

```<code>public void forTest(File xmlFile){
    Path p = Paths.get(xmlFile.getAbsolutePath());
    p.getParent();
}
</code>```

The test Code:

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({XmlFileFunctions.class,Paths.class})
public class XmlFileFunctionsTest {
    @InjectMocks
    XmlFileFunctions xmlFileFunctionsMock;

    @Mock
    File xmlFileMock;
    @Mock
    Path pMock;

    @Test
    public void myTest(){
        when(xmlFileMock.getAbsolutePath()).thenReturn("abc");
        PowerMockito.mockStatic(Paths.class);
        when(Paths.get(Matchers.anyString())).thenReturn(pMock);

        xmlFileFunctionsMock.forTest(xmlFileMock);
        verify(pMock).getParent();
    }

}
</code>```

答:
After going down a different solution path, I found the following answer: Mockito and PowerMock MethodNotFoundException being thrown

It seems that changing the version of powermock from 1.6.6 to 1.6.5 fixes this issue.

Body:
I have been getting the following error:
org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) getParent were found in the class hierarchy of class java.lang.Object.

I'm not sure why.  I have tried creating some simple code to narrow down the error and don't understand why this mock isn't working.

The code to test:

public void forTest(File xmlFile){
    Path p = Paths.get(xmlFile.getAbsolutePath());
    p.getParent();
}

The test Code:

@RunWith(PowerMockRunner.class)
@PrepareForTest({XmlFileFunctions.class,Paths.class})
public class XmlFileFunctionsTest {
    @InjectMocks
    XmlFileFunctions xmlFileFunctionsMock;

    @Mock
    File xmlFileMock;
    @Mock
    Path pMock;

    @Test
    public void myTest(){
        when(xmlFileMock.getAbsolutePath()).thenReturn("abc");
        PowerMockito.mockStatic(Paths.class);
        when(Paths.get(Matchers.anyString())).thenReturn(pMock);

        xmlFileFunctionsMock.forTest(xmlFileMock);
        verify(pMock).getParent();
    }

}


问:
No tests executed JUNIT Netbeans 8.2
I have libraries imported JUNIT 4.12 and Hamcrest 1.3 and test folder setup. Sources pointing to the right test package folder. I would run test with Shift+F6 for each Java test file and it would execute all tests in that java file. After a restart of my computer, I followed same procedure to run tests only to get "No tests executed". What could be the reason and solution.

```<code>package test1;
import hello.*;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class hellotest {
private jj j1;

@Before
public void runBeforeEachTest(){
    j1 = new jj();
    j1.setName("cur");
    j1.setComp("goo");
}

@Test
public void testProp(){
    String name = j1.getName();
    String cmp = j1.getComp();
    assertEquals("cur", name);
    assertEquals("goo", cmp);
}

}
</code>```

Same project without any modification works fine on another computer. Trying to re-install Netbeans 8.2 , but it does not uninstall , it gives error "Java SE Development Kit(JDK) was not found on this computer" JDK 6 is required for uninstalling the Netbeans IDE.
This is strange since to install NetBeans 8.2 JDK 8 is installed but during uninstallation JDK 6 it is looking for. Question is how to uninstall Netbeans?

答:
Well, you have to right click your project and Test. The same tool is located on the navigation bar Run / Test Project (project) since you have selected a project as active.

You can either use the keyboard shortcut Alt + F6. Your shortcut using Shift is wrong and I have no idea what it should do (check the Options).

This guarantee to start all the tests. You can either create your test suite defining the "pack" of test instances.

Title: No tests executed JUNIT Netbeans 8.2

Body:
I have libraries imported JUNIT 4.12 and Hamcrest 1.3 and test folder setup. Sources pointing to the right test package folder. I would run test with Shift+F6 for each Java test file and it would execute all tests in that java file. After a restart of my computer, I followed same procedure to run tests only to get "No tests executed". What could be the reason and solution.

package test1;
import hello.*;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class hellotest {
private jj j1;

@Before
public void runBeforeEachTest(){
    j1 = new jj();
    j1.setName("cur");
    j1.setComp("goo");
}

@Test
public void testProp(){
    String name = j1.getName();
    String cmp = j1.getComp();
    assertEquals("cur", name);
    assertEquals("goo", cmp);
}

}

Same project without any modification works fine on another computer. Trying to re-install Netbeans 8.2 , but it does not uninstall , it gives error "Java SE Development Kit(JDK) was not found on this computer" JDK 6 is required for uninstalling the Netbeans IDE.
This is strange since to install NetBeans 8.2 JDK 8 is installed but during uninstallation JDK 6 it is looking for. Question is how to uninstall Netbeans?


问:
react-bootstrap modal override class not working
I'm trying to remove the shadow on a react-bootstrap modal. My modal code is

```<code>  <Modal show={this.props.modalDetails}
    onHide={this.props.close}
    animation={false}
    dialogClassName='trade-detail-dialog'
  >
    <Modal.Header closeButton>
      <Modal.Title>Modal heading</Modal.Title>
    </Modal.Header>
    <Modal.Body>
      <h4>Text in a modal</h4>
      <p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula.</p>

      <hr />
    </Modal.Body>
    <Modal.Footer>
      <Button onClick={this.props.close}>Close</Button>
    </Modal.Footer>
  </Modal>
</code>```

My CSS is

```<code>div.trade-detail-dialog div.modal-content {
  box-shadow: 0 !important;
  -webkit-box-shadow: 0 !important;
}

@media (min-width: 768px) {
  div.trade-detail-dialog div.modal-content {
    box-shadow: 0 !important;
    -webkit-box-shadow: 0 !important;
  }

}
</code>```

But the modal still has a box shadow:

Apparently my styles are not important, no matter how much I want them to be:

Any idea on how I can remove the shadow?

答:
Your css properties are invalid.

It should be

```<code>box-shadow: none;
-webkit-box-shadow: none;
</code>```

Body:
I'm trying to remove the shadow on a react-bootstrap modal. My modal code is

  <Modal show={this.props.modalDetails}
    onHide={this.props.close}
    animation={false}
    dialogClassName='trade-detail-dialog'
  >
    <Modal.Header closeButton>
      <Modal.Title>Modal heading</Modal.Title>
    </Modal.Header>
    <Modal.Body>

Text in a modal

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

    </Modal.Body>
    <Modal.Footer>
      <Button onClick={this.props.close}>Close</Button>
    </Modal.Footer>
  </Modal>

My CSS is

div.trade-detail-dialog div.modal-content {
  box-shadow: 0 !important;
  -webkit-box-shadow: 0 !important;
}

@media (min-width: 768px) {
  div.trade-detail-dialog div.modal-content {
    box-shadow: 0 !important;
    -webkit-box-shadow: 0 !important;
  }

}

But the modal still has a box shadow:

Apparently my styles are not important, no matter how much I want them to be:

Any idea on how I can remove the shadow?

Body:
Your css properties are invalid.

It should be

box-shadow: none;
-webkit-box-shadow: none;


问:
Count and group by query for counting rows in database table based on 3 to 4 conditions
I am running a market survey and all the survey data is saved in the database. I need a query for counting the number of rows in which option "1" is selected for question "1", option "2" for question "1" and so on for all questions and options… I need to specify few conditions here, I have to match distinct ID's of 3 tables and display the result for each particular ID.</p>

答:
I think you're going to have to do it the hard way:

```<code>SELECT COUNT(`keyfield`)
 WHERE `column` = '1'
</code>```

and,

```<code>SELECT COUNT(`keyfield`)
 WHERE `column` = '2'
</code>```

Else you'll need a script to run through all the iterations of the data/options.  What platform are you on?

OwnerDisplayName: Jyotsna

LastEditorDisplayName: Spoike

Body:
I think you're going to have to do it the hard way:

SELECT COUNT(`keyfield`)
 WHERE `column` = '1'

and,

SELECT COUNT(`keyfield`)
 WHERE `column` = '2'

Else you'll need a script to run through all the iterations of the data/options.  What platform are you on?

OwnerDisplayName: jedihawk


问:
Problem with Tail Recursion in g++
I'm was messing around with tail-recursive functions in C++, and I've run into a bit of  a snag with the g++ compiler.

The following code results in a stack overflow when numbers[] is over a couple hundred integers in size. Examining the assembly code generated by g++ for the following reveals that twoSum_Helper is executing a recursive call instruction to itself.

The question is which of the following is causing this?

A mistake in the following that I am overlooking which prevents tail-recursion.

A mistake with my usage of g++.

A flaw in the detection of tail-recursive functions within the g++ compiler.

I am compiling with g++ -O3 -Wall -fno-stack-protector test.c on Windows Vista x64 via MinGW with g++ 4.5.0.

```<code>struct result
{
    int i;
    int j;
    bool found;
};

struct result gen_Result(int i, int j, bool found)
{
    struct result r;
    r.i = i;
    r.j = j;
    r.found = found;
    return r;
}

// Return 2 indexes from numbers that sum up to target.
struct result twoSum_Helper(int numbers[], int size, int target, int i, int j)
{
    if (numbers[i] + numbers[j] == target)
        return gen_Result(i, j, true);
    if (i >= (size - 1))
        return gen_Result(i, j, false);
    if (j >= size)
        return twoSum_Helper(numbers, size, target, i + 1, i + 2);
    else
        return twoSum_Helper(numbers, size, target, i, j + 1);
}
</code>```

答:
Since the code of twoSum_Helper is calling itself it shouldn't come as a surprise that the assembly shows exactly that happening. That's the whole point of a recursion :-) So this hasn't got anything to do with g++.

Every recursion creates a new stack frame, and stack space is limited by default. You can increase the stack size (don't know how to do that on Windows, on UNIX the ulimit command is used), but that only defers the crash.

The real solution is to get rid of the recursion. See for example this question and this question.

Title: Problem with Tail Recursion in g++

Body:
I'm was messing around with tail-recursive functions in C++, and I've run into a bit of  a snag with the g++ compiler.

The following code results in a stack overflow when numbers[] is over a couple hundred integers in size. Examining the assembly code generated by g++ for the following reveals that twoSum_Helper is executing a recursive call instruction to itself.

The question is which of the following is causing this?

A mistake in the following that I am overlooking which prevents tail-recursion.

A mistake with my usage of g++.

A flaw in the detection of tail-recursive functions within the g++ compiler.

I am compiling with g++ -O3 -Wall -fno-stack-protector test.c on Windows Vista x64 via MinGW with g++ 4.5.0.

struct result
{
    int i;
    int j;
    bool found;
};

struct result gen_Result(int i, int j, bool found)
{
    struct result r;
    r.i = i;
    r.j = j;
    r.found = found;
    return r;
}

// Return 2 indexes from numbers that sum up to target.
struct result twoSum_Helper(int numbers[], int size, int target, int i, int j)
{
    if (numbers[i] + numbers[j] == target)
        return gen_Result(i, j, true);
    if (i >= (size - 1))
        return gen_Result(i, j, false);
    if (j >= size)
        return twoSum_Helper(numbers, size, target, i + 1, i + 2);
    else
        return twoSum_Helper(numbers, size, target, i, j + 1);
}


问:
clock skew detected: you build may be incomplete
I've seen a bunch of these questions, most notable this one, which all say pretty much the same thing:  This error is caused by the modification time of the source files being in the future, which usually occurs on a mounted NFS when the server clock and client clock are not in sync.

I've tried to touch all the files in my directory, as many have suggested.  when that didn't work, I actually attempted copying all files out of the mounted drive and into a local drive, touching them again, then rerunning the build, and I still get the same error.  Is there any other way to solve this problem?

答:
If you are using Windows check if you compiling on a FAT file-system and if so try to switch.

FAT has a 2 second resolution, so its possible for your build to add to an archive, compile the next file, but detect that the archive is already up to date. Time resolutions for other file systems are listed in another answer.

If you must FAT consider the .LOW_RESOLUTION_TIME special target.


问:
xpath to get column inside a table
I want to validate "img" properties from the following html code[please refer image]

enter image description here

Code Here

//table[@class='row header-logo' and @style='border-collapse:collapse;border-spacing:0;display:table;padding:0;position:relative;text-align:left;vertical-align:top;width:100%']

Kindly help me to get the exact xpath to validate "img" properties by title, alt,src

答:
First, locate the  with this XPath:

```<code>//img[@alt='Intel']
</code>```

Explained:

// - Selects first matching node

img[@alt='Intel'] - Select  where alt equals string 'Intel'

Then, use IWebElement.GetAttribute to get the  attributes to validate:

```<code>IWebDriver driver;

try
{
    // locate image
    IWebElement image = driver.FindElement(By.XPath("//img[@alt='Intel']"));

    // get image attributes
    string title = image.GetAttribute("title");
    string alt = image.GetAttribute("alt");
    string src = image.GetAttribute("src");

    // validate title, alt, and src
    // EX: Assert.AreEqual("Intel", title);
}
catch (NoSuchElementException)
{
    // image does not exist, handle accordingly
}
</code>```

Title: xpath to get column inside a table

Body:
First, locate the <img> with this XPath:

//img[@alt='Intel']

Explained:

// - Selects first matching node

img[@alt='Intel'] - Select <img> where alt equals string 'Intel'

Then, use IWebElement.GetAttribute to get the <img> attributes to validate:

IWebDriver driver;

try
{
    // locate image
    IWebElement image = driver.FindElement(By.XPath("//img[@alt='Intel']"));

    // get image attributes
    string title = image.GetAttribute("title");
    string alt = image.GetAttribute("alt");
    string src = image.GetAttribute("src");

    // validate title, alt, and src
    // EX: Assert.AreEqual("Intel", title);
}
catch (NoSuchElementException)
{
    // image does not exist, handle accordingly
}


问:
Nginx - Forwarding a request to the Server-App if 'alias' fails
For a project I implemented automatic serverside thumbnail-generation. If you request an Image with '_thumb' in its filename the server checks if there already is a thumbnail for the original image, if not it generates it and sends it back. Works fine.

Now I'd like to bring Nginx into the mix to serve the images directly from the harddrive without involving the server-app (the url itself would work fine and return the image if requested from the server-app itself).

The following Block works fine, if the thumbnail already exists. If there is no thumbnail already generated it just responds 404 - unsurprisingly.

How would I modify the following Nginx-Block to make another request to the server in case the thumbnail cant be found to create it?

Request

```<code>http://www.proj.com/files/images/234782348234/bunny_thumb.jpg
</code>```

Nginx-Block

```<code>location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   alias /srv/proj/data/uploads/images/temp/$1_thumb.$2;
   // No image found? Request it from the server directly on "files/images/234782348234/bunny_thumb.jpg"
}
</code>```

Actual File-Path

```<code>/srv/proj/data/uploads/images/temp/234782348234_thumb.jpg
</code>```

答:
So, finally had to tackle it again and found a pretty easy solution. RegexMatches stillt won't work in try_files. So I just used "alias" to direct to the actual file-path and defined a 'error_page 404' pointing to the expressapp:</p>

```<code>location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   error_page 404 @makethumb
   alias /srv/proj/data/uploads/images/temp/$1_thumb.$2;
 }

location @makethumb {
    proxy_pass http://localhost:3000$uri;
}
</code>```

Body:
For a project I implemented automatic serverside thumbnail-generation. If you request an Image with '_thumb' in its filename the server checks if there already is a thumbnail for the original image, if not it generates it and sends it back. Works fine.

Now I'd like to bring Nginx into the mix to serve the images directly from the harddrive without involving the server-app (the url itself would work fine and return the image if requested from the server-app itself).

The following Block works fine, if the thumbnail already exists. If there is no thumbnail already generated it just responds 404 - unsurprisingly.

How would I modify the following Nginx-Block to make another request to the server in case the thumbnail cant be found to create it?

Request

http://www.proj.com/files/images/234782348234/bunny_thumb.jpg

Nginx-Block

location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   alias /srv/proj/data/uploads/images/temp/$1_thumb.$2;
   // No image found? Request it from the server directly on "files/images/234782348234/bunny_thumb.jpg"
}

Actual File-Path

/srv/proj/data/uploads/images/temp/234782348234_thumb.jpg

Body:
So, finally had to tackle it again and found a pretty easy solution. RegexMatches stillt won't work in try_files. So I just used "alias" to direct to the actual file-path and defined a 'error_page 404' pointing to the expressapp:

location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   error_page 404 @makethumb
   alias /srv/proj/data/uploads/images/temp/$1_thumb.$2;
 }

location @makethumb {
    proxy_pass http://localhost:3000$uri;
}


问:
WRL: how to subscribe to events *without* using lambdas?
Subscribing to events in C++/CX goes something like this:

```<code>listener::ConnectionReceived +=
ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(this, &MyClass::OnConnectionReceived);
</code>```

All documentation I've found for how to subscribe to events in WRL shows examples using lambda expressions, like this:

```<code>auto connectionReceivedHandler = Callback<ITypedEventHandler<StreamSocketListener*, StreamSocketListenerConnectionReceivedEventArgs*>>
([&] (IStreamSocketListener* cbListener, IStreamSocketListenerConnectionReceivedEventArgs* args)
{
    this->doSomething();
});
hr = listener->add_ConnectionReceived(connectionReceivedHandler.Get(), &this->connectionReceivedToken);
</code>```

But how can I subscribe to an event in WRL and provide a class method instead of a lambda? Something like this:

```<code>hr = listener->add_ConnectionReceived(&MyClass::OnConnectionReceived, &this->connectionReceivedToken);
</code>```

答:
There is an overload of Callback that takes this + member function. here it is...</p>

```<code>ComPtr<typename Details::DelegateArgTraitsHelper<TDelegateInterface>::Interface> Callback(_In_ TCallbackObject *object, _In_ HRESULT(TCallbackObject::* method)(TArgs...)) throw()
</code>```

Body:
Subscribing to events in C++/CX goes something like this:

listener::ConnectionReceived +=
ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(this, &MyClass::OnConnectionReceived);

All documentation I've found for how to subscribe to events in WRL shows examples using lambda expressions, like this:

auto connectionReceivedHandler = Callback<ITypedEventHandler<StreamSocketListener*, StreamSocketListenerConnectionReceivedEventArgs*>>
([&] (IStreamSocketListener* cbListener, IStreamSocketListenerConnectionReceivedEventArgs* args)
{
    this->doSomething();
});
hr = listener->add_ConnectionReceived(connectionReceivedHandler.Get(), &this->connectionReceivedToken);

But how can I subscribe to an event in WRL and provide a class method instead of a lambda? Something like this:

hr = listener->add_ConnectionReceived(&MyClass::OnConnectionReceived, &this->connectionReceivedToken);

Body:
There is an overload of Callback that takes this + member function. here it is...

ComPtr<typename Details::DelegateArgTraitsHelper<TDelegateInterface>::Interface> Callback(_In_ TCallbackObject *object, _In_ HRESULT(TCallbackObject::* method)(TArgs...)) throw()


问:
issue with bootstrap specific nested grid layout to display pictures
I want a specific nested grid layout to display pictures.
But I have an issue that I am unable to solve : my offset for xs screen is applied on sm, md screen.
You can see it in action here :

https://www.bootply.com/lpeNg9CcG3

My template is wrong, and what is the good one to only apply an offset on XS screen ?
Or this is an issue of bootstrap ?

Thanks for your help !

答:
I found the solution:
I have to overwrite my col-xs-offset-1 with col-sm-offset-0 and col-md-offset-0.

Indeed, this is a strange behavior of Bootstrap...

Here is a working example.


问:
How can I write a UTF-8-encoded file to the user’s computer using JavaScript on IE?
I am writing a local file using JavaScript and I am using IE for the same.

My code is as follows:

```<code>function savefile( f,g){

var w = window.frames.w;
if( !w ) {
    w = document.createElement( 'iframe' );
    w.id = 'w';
    w.style.display = 'none';
    document.body.insertBefore( w );
    w = window.frames.w;
    if( !w ) {
        w = window.open( '', '_temp', 'width=100,height=100' );
        if( !w ) {
            window.alert( 'Sorry, could not create file.' );
            return false;
        }
    }
}

var d = w.document;
d.open( 'text/xml', 'replace');
d.charset = "UTF-8";

d.write(JWPFormToHTML(f));
d.close();
var name= g.filename.value;

if( d.execCommand( 'SaveAs', false , name ) )
{
    g.filename.value=name;
    //document.getElementById("filename").value="";
    alert('File has been saved.' );
}
else
{
    alert( 'The file has not been saved.\nIs there a problem?' );
}
w.close();
return false;
}
</code>```

The problem I am facing is the file is not getting saved as a UTF-8 encoded file, although I have added <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> to it.

Please help me on this or suggest some alternative to me.

NOTE: I would like a file manager to open before the file gets saved as in the case of execCommand.

答:
I think you are creating HTA?

For saving file as UTF8

Writing UTF8 text to file

Body:
I am writing a local file using JavaScript and I am using IE for the same.

My code is as follows:

function savefile( f,g){

var w = window.frames.w;
if( !w ) {
    w = document.createElement( 'iframe' );
    w.id = 'w';
    w.style.display = 'none';
    document.body.insertBefore( w );
    w = window.frames.w;
    if( !w ) {
        w = window.open( '', '_temp', 'width=100,height=100' );
        if( !w ) {
            window.alert( 'Sorry, could not create file.' );
            return false;
        }
    }
}

var d = w.document;
d.open( 'text/xml', 'replace');
d.charset = "UTF-8";

d.write(JWPFormToHTML(f));
d.close();
var name= g.filename.value;

if( d.execCommand( 'SaveAs', false , name ) )
{
    g.filename.value=name;
    //document.getElementById("filename").value="";
    alert('File has been saved.' );
}
else
{
    alert( 'The file has not been saved.\nIs there a problem?' );
}
w.close();
return false;
}

The problem I am facing is the file is not getting saved as a UTF-8 encoded file, although I have added <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> to it.

Please help me on this or suggest some alternative to me.

NOTE: I would like a file manager to open before the file gets saved as in the case of execCommand.


问:
How to append in different columns with running for loop in Python3?
I am trying to create a program to collect data from text files into one text file. I am having lots of issues for some reason.  One final output file is composed of 10 different starter files (Serial 1-10.txt).  This data needs to be placed in a file (text or csv) in different columns before moving on to the next Data folder holding ten more Serial files.

The following code outputs one long column in each final text file, and not 11 different columns (counting the "numbering" column).

```<code>for z in datarange:
    f = open('/home/pi/Desktop/Newdata/Data' + str(z) + '.csv', 'a')
   # print(f)
    therange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    thelist = (folder_list + "Data" + str(z))

    for i in therange:
        lines = open(thelist + "/Serial" + str(i) + ".txt", 'r+')#, encoding='utf-8')  #open that same text file (reading priviledges
        thedata = lines.readline()
        mylist = [int (x) for x in thedata.split(',') if x.strip().isdigit()]
        #locals()["text" + str(i)] = pd.DataFrame(mylist)
        df = pd.DataFrame(mylist)
        f.write(str(df))
</code>```

I have also tried something like this:  (to get the same result.  one long column.

```<code>df = { 'Column1': [(text1)], 'Column2': [(text2)],
     'Column3': [(text4)],'Column5': [(text5)],
     'Column6': [(text6)], 'Column7': [(text7)], 'Column8': [(text8)],
     'Column9': [(text9)], 'Column10': [(text10)]}

f.write(str(df))
</code>```

The data output summary:

```<code>Column1
0     145
1     146
2     123
3     154
.
.
.
287   140
</code>```

```<code>Column2
0     145
1     144
.
.
.
287   128
</code>```

```<code>Column3
</code>```

and so on....

Any advice or things to try?

答:
Just in case anyone has a similar issue, here is what I ended up using.  This worked for my application.  I want to post it because it fit for an answer for my question to ultimately get what I wanted it to do.

Part of code for question:
    for z in datarange:
        f = open('/home/pi/Desktop/Newdata/Data' + str(z) + '.txt', 'a')

```<code>    therange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    thelist = (folder_list + "Data" + str(z))

    for i in therange:
        lines = open(thelist + "/Serial" + str(i) + ".txt", 'r+')#, encoding='utf-8')  #open that same text file (reading priviledges
        thedata = lines.readline()
        mylist = [int (x) for x in thedata.split(',') if x.strip().isdigit()]
        locals()["text" + str(i)] = mylist
        if i == 10:
            try:

               df = pd.DataFrame({ 'Column1': text1, 'Column2': text2, 'Column3': text4, 'Column5': text5,
          'Column6': text6, 'Column7': text7, 'Column8': text8,
         'Column9': text9, 'Column10': text10})
               pd.set_option('max_rows', 288)
               pd.set_option('max_colwidth', 11)

               data = df.to_string(index=False)
               f.write(str(data))
            except:
               os.remove('/home/pi/Desktop/Newdata/Data' + str(z) + '.txt')
               pass
</code>```

What I was trying to accomplish  (Averaging the rows), worked with this set-up.  I then was able to sum and divide each line of the created text files, also looping involved to reach each one.  **If placed in a csv file, the "Column1 Column2... and data below" was all in ONE COLUMN" in the csv output.  So, I decided to mess with a text file instead.

Body:
I am trying to create a program to collect data from text files into one text file. I am having lots of issues for some reason.  One final output file is composed of 10 different starter files (Serial 1-10.txt).  This data needs to be placed in a file (text or csv) in different columns before moving on to the next Data folder holding ten more Serial files.

The following code outputs one long column in each final text file, and not 11 different columns (counting the "numbering" column).

for z in datarange:
    f = open('/home/pi/Desktop/Newdata/Data' + str(z) + '.csv', 'a')
   # print(f)
    therange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    thelist = (folder_list + "Data" + str(z))

    for i in therange:
        lines = open(thelist + "/Serial" + str(i) + ".txt", 'r+')#, encoding='utf-8')  #open that same text file (reading priviledges
        thedata = lines.readline()
        mylist = [int (x) for x in thedata.split(',') if x.strip().isdigit()]
        #locals()["text" + str(i)] = pd.DataFrame(mylist)
        df = pd.DataFrame(mylist)
        f.write(str(df))

I have also tried something like this:  (to get the same result.  one long column.

df = { 'Column1': [(text1)], 'Column2': [(text2)],
     'Column3': [(text4)],'Column5': [(text5)],
     'Column6': [(text6)], 'Column7': [(text7)], 'Column8': [(text8)],
     'Column9': [(text9)], 'Column10': [(text10)]}

f.write(str(df))

The data output summary:

Column1
0     145
1     146
2     123
3     154
.
.
.
287   140

Column2
0     145
1     144
.
.
.
287   128

Column3

and so on....

Any advice or things to try?

Body:
Just in case anyone has a similar issue, here is what I ended up using.  This worked for my application.  I want to post it because it fit for an answer for my question to ultimately get what I wanted it to do.

Part of code for question:
    for z in datarange:
        f = open('/home/pi/Desktop/Newdata/Data' + str(z) + '.txt', 'a')

    therange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    thelist = (folder_list + "Data" + str(z))

    for i in therange:
        lines = open(thelist + "/Serial" + str(i) + ".txt", 'r+')#, encoding='utf-8')  #open that same text file (reading priviledges
        thedata = lines.readline()
        mylist = [int (x) for x in thedata.split(',') if x.strip().isdigit()]
        locals()["text" + str(i)] = mylist
        if i == 10:
            try:

               df = pd.DataFrame({ 'Column1': text1, 'Column2': text2, 'Column3': text4, 'Column5': text5,
          'Column6': text6, 'Column7': text7, 'Column8': text8,
         'Column9': text9, 'Column10': text10})
               pd.set_option('max_rows', 288)
               pd.set_option('max_colwidth', 11)

               data = df.to_string(index=False)
               f.write(str(data))
            except:
               os.remove('/home/pi/Desktop/Newdata/Data' + str(z) + '.txt')
               pass

What I was trying to accomplish  (Averaging the rows), worked with this set-up.  I then was able to sum and divide each line of the created text files, also looping involved to reach each one.  **If placed in a csv file, the "Column1 Column2... and data below" was all in ONE COLUMN" in the csv output.  So, I decided to mess with a text file instead.


问:
Bulk uploading images to SSRS
We have used the excellent RSBuild for bulk uploading reports to SQL Server Reporting Services (SSRS) but I find no way to bulk upload images.  Using the Report Manager to upload one image at a time is silly.  The difficulty is that the SQL Server Reporting web service that RSBuild uses doesn't support image uploads.  Is there a way to bulk upload images to SSRS in some other fashion?  </p>

答:
To load multiple images in a SSRS solution, I used the following method. It's pretty easy
First, create a new Images folder in the Report Manager where you want to link the external images in the report

Open Visual Studio

Navigate to File

Select Open

Select File

Create a New Folder called "Images" or whatever

Paste all images desired in this folder

Now, navigate to Solution Explorer

Select "Reports" and right-click

Select Add then "Existing Item"

Navigate to the new folder just created

Change the File Type at the bottom  to "All Files"

Select all the images desired. Short cut to select all is the Ctrl key plus the letter A

Click "add"

All images will be added beneath any reports in the Solution Explorer

Navigate to the "Debug" menu and select the Solution Properties as seen here
Solution Properties

Temporarily change the TargetReportFolder to match the name of a new images folder you created in Report Manager

In Solution Explorer, right-click on all the images (not the reports)

Select "Deploy"

Verify that the deployment was successful in Visual Studio then, navigate to the Report Manager folder and verify the images are there!

DON'T FORGET: Reset the TargetReportFolder to the previous value!

Report Manager Image Folder

Title: Bulk uploading images to SSRS


问:
Can Boost Container vector manage memory through non raw pointers?
I have a pointer-like struct that goes in the place of a pointer.
The difference with a pointer is that it has extra information that the (also special) allocator can use to deallocate the memory.

This pointer-like structure works well for all basic uses.
I can allocate and deallocate memory, dereferrence, increment,->, etc.

Now I want to use this pointers to be managed by a STL-like container.
Early on, I realized that STL vector basically cannot handle non-raw pointers.
T* is too hard coded, and the standard basically rules out anything that is not a pointer.

Inspired by Boost.Interprocess' offset_ptr<T> I decided to use Boost.Container vector, which is very customizable and in principle can manage anything, the allocator passed to the boost::container::vector can handle anything that is pointer-like.

Now the class boost::container::vector<T, myallocator_with_special_pointer<T>> can do anything... except resize()!!

Looking at the code in boost/container/vector.hpp it seems that the process of resizing (which is basically and allocation, followed by a copy (or move) and deallocation) involves raw pointers.

The offending line is:

```<code>  [line 2729:] T * const new_buf = container_detail::to_raw_pointer
     (allocator_traits_type::allocate(this->m_holder.alloc(), new_cap, this->m_holder.m_start));
</code>```

Which is later followed by

```<code>  [line 3022:] this->m_holder.start(new_start);  // new_start is the same as new_buf above.
  // member ::start(pointer&) will need to convert a raw pointer to the pointer typedef.
</code>```

Both lines absolutely kill the possibility of using anything that is not a raw_pointer. Even if I have a conversion operator to a raw pointer, other information about the special pointer will be lost.

It seems pretty silly that this small detail forbids the use of non-raw pointers. Given all the effort for the container to be general (e.g. defining the pointer typedef), why this portion of the code uses T* just for resizing?

In other words, why Boost Container doesn't use this line instead

```<code>  [alternative] pointer const new_buf =
     allocator_traits_type::allocate(this->m_holder.alloc(), new_cap, this->m_holder.m_start);
</code>```

Is there a workaround or an alternative way to use Boost Container vector to handle non-raw pointers?

Boost.Container says in its manual page http://www.boost.org/doc/libs/1_64_0/doc/html/container/history_and_reasons.html#container.history_and_reasons.Why_boost_container

Boost.Container is a product of a long development effort that started
  in 2004 with the experimental Shmem library, which pioneered the use
  of standard containers in shared memory. Shmem included modified SGI
  STL container code tweaked to support non-raw allocator::pointer types
  and stateful allocators. Once reviewed, Shmem was accepted as
  Boost.Interprocess and this library continued to refine and improve
  those containers.

The current implementation (in the context of resize) goes against this design goal.

I asked a less specific question here, about other traits of the allocators: Is it still possible to customize STL vector's "reference" type?

For reference the allocator that specifies the special pointer (which is propagated to the container) is something like this,

```<code>template<class T>
struct allocator{
    using value_type = T;
    using pointer = array_ptr<T>; // simulates T*
    using const_pointer = array_ptr<T const>; // simulates T const*
    using void_pointer = array_ptr<void>; // simulates void*
    using const_void_pointer = array_ptr<void const>; // simulates void const*
    some_managed_shared_memory& msm_;
    allocator(some_managed_shared_memory& msm) : msm_(msm){}
    array_ptr<T> allocate(mpi3::size_t n){
        auto ret = msm_.allocate(n*sizeof(T));
        return static_cast<array_ptr<T>>(ret);
    }
    void deallocate(array_ptr<T> ptr, mpi3::size_t = 0){
        msm_.deallocate(ptr);
    }
};
</code>```

Full working code http://coliru.stacked-crooked.com/a/f43b6096f9464cbf

```<code>#include<iostream>
#include <boost/container/vector.hpp>

template<typename T>
struct array_ptr;

template<>
struct array_ptr<void> {
    using T = void;
    T* p;
    int i; //some additional information

//    T& operator*() const { return *p; }
    T* operator->() const { return p; }

//    operator T*() const { return p; }
    template<class TT>
    operator array_ptr<TT>() const{return array_ptr<TT>((TT*)p, i);}
    operator bool() const{return p;}
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr){}
    array_ptr(T* ptr, int _i) : p(ptr), i(_i){}
    template<class Other>
    array_ptr(array_ptr<Other> other) : p(other.p), i(other.i){}
};

template<>
struct array_ptr<void const> {
    using T = void const;
    T* p;
    int i; //some additional information

//    T& operator*() const { return *p; }
    T* operator->() const { return p; }

    operator T*() const { return p; }
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr){}
    array_ptr(T* ptr, int _i) : p(ptr), i(_i){}
    template<class Other>
    array_ptr(array_ptr<Other> other) : p(other.p), i(other.i){}
};

template<typename T>
struct array_ptr {
    T* p;
    int i; //some additional information

    T& operator*() const { return *p; }
    T* operator->() const { return p; }
    T& operator[](std::size_t n) const{
        assert(i == 99);
        return *(p + n);
    }
    bool operator==(array_ptr const& other) const{return p == other.p and i == other.i;}
    bool operator!=(array_ptr const& other) const{return not((*this)==other);}

//    operator T*() const { return p; }
    array_ptr& operator++(){++p; return *this;}
    array_ptr& operator+=(std::ptrdiff_t n){p+=n; return *this;}
    array_ptr& operator-=(std::ptrdiff_t n){p-=n; return *this;}
    array_ptr operator+(std::size_t n) const{array_ptr ret(*this); ret+=n; return ret;}
    std::ptrdiff_t operator-(array_ptr const& other) const{return p - other.p;}
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr), i(0){}

    operator bool() const{return p;}

    array_ptr(T* ptr, int _i) : p(ptr), i(_i){}
    array_ptr(T* ptr) : p(ptr), i(0){}
    array_ptr(int) : p(nullptr), i(0){}
    array_ptr(array_ptr<void> const& other) : p(static_cast<T*>(other.p)), i(other.i){}
};

struct some_managed_shared_memory {
    array_ptr<void> allocate(size_t n) { return array_ptr<void>(::malloc(n), 99); }
    void  deallocate(array_ptr<void> ptr) { if (ptr) ::free(ptr.p); }
};

template<typename T>
struct allocator{
    using value_type = T;
    using pointer = array_ptr<T>; // simulates T*
    using const_pointer = array_ptr<T const>; // simulates T const*
    using void_pointer = array_ptr<void>; // simulates void*
    using const_void_pointer = array_ptr<void const>; // simulates void const*

    some_managed_shared_memory& msm_;
    allocator(some_managed_shared_memory& msm) : msm_(msm){}
    array_ptr<T> allocate(size_t n){
        auto ret = msm_.allocate(n*sizeof(T));
        return static_cast<array_ptr<T>>(ret);
    }
    void deallocate(array_ptr<T> ptr, std::size_t = 0){
        msm_.deallocate(ptr);
    }
};

int main() {
    some_managed_shared_memory realm;
    boost::container::vector<int, allocator<int> > v(10, realm);
    assert( v[4] == 0 );
    v[4] = 1;
    assert( v[4] == 1 );
    for(std::size_t i = 0; i != v.size(); ++i) std::cout << v[i] << std::endl;
    for(auto it = v.begin(); it != v.end(); ++it) std::cout << *it << std::endl;

    // none of these compile:
    v.push_back(8);
    assert(v.size() == 11);
    v.resize(100);
    std::cout << v[89] << std::endl; // will fail an assert because the allocator information is lost
    //v.assign({1,2,3,4,5});
}
</code>```

答:
I looked into things.

The TL;DR seems to be: non-raw pointers are supported, but they need a implicit conversion from raw in some operations. Whether or not this is by design, I don't know, but it doesn't seem to contradict the design goal.

In fact this is very analogous to the history of allocator support: STL containers had support for custom allocators, but not for stateful allocators (meaning, non-default-constructible allocator types).

Allocator Versions

At first I tried some of the allocator versions:

```<code>using version = boost::container::version_0; // seems unsupported, really
using version = boost::container::version_1;
using version = boost::container::version_2; // does different operations
</code>```

But it had no (decisive) effect. Maybe the documentation has clues.

Pointer Arithmetic

After that I looked into the specific errors. Looking at the cited line/error it dawned on me that the raw-pointer might have been an accident. Looking at the output of these:

```<code>std::cout << boost::container::container_detail::impl::version<allocator<int> >::value << "\n";

array_ptr<int> p;
auto rawp = boost::container::container_detail::to_raw_pointer(p);
std::cout << typeid(rawp).name() << "\n";

std::cout << typeid(p).name() << "\n";
std::cout << typeid(p + 5).name() << "\n";
std::cout << typeid(p - 5).name() << "\n";
</code>```

Shows something like¹

```<code>1
int*
array_ptr<int>
int*
int*
</code>```

¹ prettified with the help of c++filt -t

This lead me to define pointer arithmetic:

```<code>template <typename T, typename N>
array_ptr<T> operator+(array_ptr<T> const& p, N n) { return array_ptr<T>(p.p+n, p.i); }

template <typename T>
array_ptr<T>& operator++(array_ptr<T>& p) { return ++p.p, p; }

template <typename T>
array_ptr<T> operator++(array_ptr<T>& p, int) { auto q = p.p++; return array_ptr<T>(q, p.i); }

template <typename T, typename N>
array_ptr<T> operator-(array_ptr<T> const& p, N n) { return array_ptr<T>(p.p-n, p.i); }

template <typename T>
ptrdiff_t operator-(array_ptr<T> const& a, array_ptr<T> const& b) { return a.p - b.p; }
</code>```

Now the output becomes

```<code>1
int*
array_ptr<int>
array_ptr<int>
array_ptr<int>
</code>```

Many more use cases compile successfully with these definitions. Assuming that the "annotation" data inside the array_pointer is valid after increment, it should not lose any allocator information

The Real Culprit

With that out of the way, some things still don't compile. Specifically, in some spots the allocator's pointer type is constructed back from a raw-pointer. This fails because there's no suitable "default" conversion constructor. If you declare the constructors with the data value optional, everything compiles, but you could argue that this loses information as there is a path from

```<code> array_pointer<T> p;
 auto* rawp = to_raw_pointer(p);
 array_pointer<T> clone(rawp); // oops lost the extra info in p
</code>```

OBSERVATION

Note that, as you apparently realized (judging from the commented operators), adding the default constructor argument removes the need for the arithmetic operations (except pre-increment).

However, adding them makes sure that the lossy conversion path is taken less often, which could be important to your use case.

DEMO TIME

Live On Coliru

```<code>#if COMPILATION_INSTRUCTIONS
clang++ -std=c++14 -Wall -Wfatal-errors $0 -o $0x.x && $0x.x $@ && rm -f $0x.x; exit
#endif

#define DEFAULT_DATA = 0
#define DEFINE_ARITHMETIC_OPERATIONS

#include <iostream>
#include <boost/container/vector.hpp>
#include <typeinfo>

template<typename T>
struct array_ptr {
    T* p;
    int i; //some additional information

    T& operator*() const { return *p; }
    T* operator->() const { return p; }

    operator T*() const { return p; }

    array_ptr(){}
    //array_ptr(std::nullptr_t) : p(nullptr), i(0){}
    array_ptr(T* ptr, int _i DEFAULT_DATA) : p(ptr), i(_i){}

};

template<>
struct array_ptr<void> {
    using T = void;
    T* p;
    int i; //some additional information

//    T& operator*() const { return *p; }
    T* operator->() const { return p; }

    operator T*() const { return p; }
    template<class T>
    operator array_ptr<T>() const{return array_ptr<T>((T*)p, i);}
//    array_ptr& operator++(){++p; return *this;}
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr){}
    array_ptr(T* ptr, int _i DEFAULT_DATA) : p(ptr), i(_i){}
    template<class Other>
    array_ptr(array_ptr<Other> other) : p(other.p), i(other.i){}
};

template<>
struct array_ptr<void const> {
    using T = void const;
    T* p;
    int i; //some additional information

//    T& operator*() const { return *p; }
    T* operator->() const { return p; }

    operator T*() const { return p; }
//    array_ptr& operator++(){++p; return *this;}
//  template<class Other> array_ptr(array_ptr<Other> const& other) : p(other.p), i(other.i){}
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr){}
    array_ptr(T* ptr, int _i DEFAULT_DATA) : p(ptr), i(_i){}
    template<class Other>
    array_ptr(array_ptr<Other> other) : p(other.p), i(other.i){}
};

struct some_managed_shared_memory {
    array_ptr<void> allocate(size_t n) { return array_ptr<void>(::malloc(n), 99); }
    void  deallocate(array_ptr<void> ptr) { if (ptr) ::free(ptr.p); }
};

template<typename T>
struct allocator{
    using version = boost::container::version_1;

    using value_type = T;
    using pointer = array_ptr<T>; // simulates T*
    using const_pointer = array_ptr<T const>; // simulates T const*
    using void_pointer = array_ptr<void>; // simulates void*
    using const_void_pointer = array_ptr<void const>; // simulates void const*

    some_managed_shared_memory& msm_;
    allocator(some_managed_shared_memory& msm) : msm_(msm){}
    array_ptr<T> allocate(size_t n){
        auto ret = msm_.allocate(n*sizeof(T));
        return static_cast<array_ptr<T>>(ret);
    }
    void deallocate(array_ptr<T> ptr, std::size_t = 0){
        msm_.deallocate(ptr);
    }
};

#ifdef DEFINE_ARITHMETIC_OPERATIONS
    template <typename T, typename N>
    array_ptr<T> operator+(array_ptr<T> const& p, N n) { return array_ptr<T>(p.p+n, p.i); }

    template <typename T>
    array_ptr<T>& operator++(array_ptr<T>& p) { return ++p.p, p; }

    template <typename T>
    array_ptr<T> operator++(array_ptr<T>& p, int) { auto q = p.p++; return array_ptr<T>(q, p.i); }

    template <typename T, typename N>
    array_ptr<T> operator-(array_ptr<T> const& p, N n) { return array_ptr<T>(p.p-n, p.i); }

    template <typename T>
    ptrdiff_t operator-(array_ptr<T> const& a, array_ptr<T> const& b) { return a.p - b.p; }
#endif

int main() {
    std::cout << boost::container::container_detail::impl::version<allocator<int> >::value << "\n";

    if (1) { // some diagnostics
        array_ptr<int> p;
        auto rawp = boost::container::container_detail::to_raw_pointer(p);
        std::cout << typeid(rawp).name() << "\n";

        std::cout << typeid(p).name() << "\n";
        std::cout << typeid(p + 5).name() << "\n";
        std::cout << typeid(p - 5).name() << "\n";
    }

    some_managed_shared_memory realm;
    boost::container::vector<int, allocator<int> > v(10, realm);
    assert( v[4] == 0 );
    v[4] = 1;
    assert( v[4] == 1 );
    for(std::size_t i = 0; i != v.size(); ++i) std::cout << v[i] << std::endl;

    // these compile:
    v.push_back(12);
    v.resize(100);
    v.assign({1,2,3,4,5});
}
</code>```

Prints

```<code>1
Pi
9array_ptrIiE
9array_ptrIiE
9array_ptrIiE
0
0
0
0
1
0
0
0
0
0
</code>```

Body:
I have a pointer-like struct that goes in the place of a pointer.
The difference with a pointer is that it has extra information that the (also special) allocator can use to deallocate the memory.

This pointer-like structure works well for all basic uses.
I can allocate and deallocate memory, dereferrence, increment,->, etc.

Now I want to use this pointers to be managed by a STL-like container.
Early on, I realized that STL vector basically cannot handle non-raw pointers.
T* is too hard coded, and the standard basically rules out anything that is not a pointer.

Inspired by Boost.Interprocess' offset_ptr<T> I decided to use Boost.Container vector, which is very customizable and in principle can manage anything, the allocator passed to the boost::container::vector can handle anything that is pointer-like.

Now the class boost::container::vector<T, myallocator_with_special_pointer<T>> can do anything... except resize()!!

Looking at the code in boost/container/vector.hpp it seems that the process of resizing (which is basically and allocation, followed by a copy (or move) and deallocation) involves raw pointers.

The offending line is:

  [line 2729:] T * const new_buf = container_detail::to_raw_pointer
     (allocator_traits_type::allocate(this->m_holder.alloc(), new_cap, this->m_holder.m_start));

Which is later followed by

  [line 3022:] this->m_holder.start(new_start);  // new_start is the same as new_buf above.
  // member ::start(pointer&) will need to convert a raw pointer to the pointer typedef.

Both lines absolutely kill the possibility of using anything that is not a raw_pointer. Even if I have a conversion operator to a raw pointer, other information about the special pointer will be lost.

It seems pretty silly that this small detail forbids the use of non-raw pointers. Given all the effort for the container to be general (e.g. defining the pointer typedef), why this portion of the code uses T* just for resizing?

In other words, why Boost Container doesn't use this line instead

  [alternative] pointer const new_buf =
     allocator_traits_type::allocate(this->m_holder.alloc(), new_cap, this->m_holder.m_start);

Is there a workaround or an alternative way to use Boost Container vector to handle non-raw pointers?

Boost.Container says in its manual page http://www.boost.org/doc/libs/1_64_0/doc/html/container/history_and_reasons.html#container.history_and_reasons.Why_boost_container

Boost.Container is a product of a long development effort that started
  in 2004 with the experimental Shmem library, which pioneered the use
  of standard containers in shared memory. Shmem included modified SGI
  STL container code tweaked to support non-raw allocator::pointer types
  and stateful allocators. Once reviewed, Shmem was accepted as
  Boost.Interprocess and this library continued to refine and improve
  those containers.

The current implementation (in the context of resize) goes against this design goal.

I asked a less specific question here, about other traits of the allocators: Is it still possible to customize STL vector's "reference" type?

For reference the allocator that specifies the special pointer (which is propagated to the container) is something like this,

template<class T>
struct allocator{
    using value_type = T;
    using pointer = array_ptr<T>; // simulates T*
    using const_pointer = array_ptr<T const>; // simulates T const*
    using void_pointer = array_ptr<void>; // simulates void*
    using const_void_pointer = array_ptr<void const>; // simulates void const*
    some_managed_shared_memory& msm_;
    allocator(some_managed_shared_memory& msm) : msm_(msm){}
    array_ptr<T> allocate(mpi3::size_t n){
        auto ret = msm_.allocate(n*sizeof(T));
        return static_cast<array_ptr<T>>(ret);
    }
    void deallocate(array_ptr<T> ptr, mpi3::size_t = 0){
        msm_.deallocate(ptr);
    }
};

Full working code http://coliru.stacked-crooked.com/a/f43b6096f9464cbf

#include<iostream>
#include <boost/container/vector.hpp>

template<typename T>
struct array_ptr;

template<>
struct array_ptr<void> {
    using T = void;
    T* p;
    int i; //some additional information

//    T& operator*() const { return *p; }
    T* operator->() const { return p; }

//    operator T*() const { return p; }
    template<class TT>
    operator array_ptr<TT>() const{return array_ptr<TT>((TT*)p, i);}
    operator bool() const{return p;}
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr){}
    array_ptr(T* ptr, int _i) : p(ptr), i(_i){}
    template<class Other>
    array_ptr(array_ptr<Other> other) : p(other.p), i(other.i){}
};

template<>
struct array_ptr<void const> {
    using T = void const;
    T* p;
    int i; //some additional information

//    T& operator*() const { return *p; }
    T* operator->() const { return p; }

    operator T*() const { return p; }
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr){}
    array_ptr(T* ptr, int _i) : p(ptr), i(_i){}
    template<class Other>
    array_ptr(array_ptr<Other> other) : p(other.p), i(other.i){}
};

template<typename T>
struct array_ptr {
    T* p;
    int i; //some additional information

    T& operator*() const { return *p; }
    T* operator->() const { return p; }
    T& operator[](std::size_t n) const{
        assert(i == 99);
        return *(p + n);
    }
    bool operator==(array_ptr const& other) const{return p == other.p and i == other.i;}
    bool operator!=(array_ptr const& other) const{return not((*this)==other);}

//    operator T*() const { return p; }
    array_ptr& operator++(){++p; return *this;}
    array_ptr& operator+=(std::ptrdiff_t n){p+=n; return *this;}
    array_ptr& operator-=(std::ptrdiff_t n){p-=n; return *this;}
    array_ptr operator+(std::size_t n) const{array_ptr ret(*this); ret+=n; return ret;}
    std::ptrdiff_t operator-(array_ptr const& other) const{return p - other.p;}
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr), i(0){}

    operator bool() const{return p;}

    array_ptr(T* ptr, int _i) : p(ptr), i(_i){}
    array_ptr(T* ptr) : p(ptr), i(0){}
    array_ptr(int) : p(nullptr), i(0){}
    array_ptr(array_ptr<void> const& other) : p(static_cast<T*>(other.p)), i(other.i){}
};

struct some_managed_shared_memory {
    array_ptr<void> allocate(size_t n) { return array_ptr<void>(::malloc(n), 99); }
    void  deallocate(array_ptr<void> ptr) { if (ptr) ::free(ptr.p); }
};

template<typename T>
struct allocator{
    using value_type = T;
    using pointer = array_ptr<T>; // simulates T*
    using const_pointer = array_ptr<T const>; // simulates T const*
    using void_pointer = array_ptr<void>; // simulates void*
    using const_void_pointer = array_ptr<void const>; // simulates void const*

    some_managed_shared_memory& msm_;
    allocator(some_managed_shared_memory& msm) : msm_(msm){}
    array_ptr<T> allocate(size_t n){
        auto ret = msm_.allocate(n*sizeof(T));
        return static_cast<array_ptr<T>>(ret);
    }
    void deallocate(array_ptr<T> ptr, std::size_t = 0){
        msm_.deallocate(ptr);
    }
};

int main() {
    some_managed_shared_memory realm;
    boost::container::vector<int, allocator<int> > v(10, realm);
    assert( v[4] == 0 );
    v[4] = 1;
    assert( v[4] == 1 );
    for(std::size_t i = 0; i != v.size(); ++i) std::cout << v[i] << std::endl;
    for(auto it = v.begin(); it != v.end(); ++it) std::cout << *it << std::endl;

    // none of these compile:
    v.push_back(8);
    assert(v.size() == 11);
    v.resize(100);
    std::cout << v[89] << std::endl; // will fail an assert because the allocator information is lost
    //v.assign({1,2,3,4,5});
}

Body:
I looked into things.

The TL;DR seems to be: non-raw pointers are supported, but they need a implicit conversion from raw in some operations. Whether or not this is by design, I don't know, but it doesn't seem to contradict the design goal.

In fact this is very analogous to the history of allocator support: STL containers had support for custom allocators, but not for stateful allocators (meaning, non-default-constructible allocator types).

Allocator Versions

At first I tried some of the allocator versions:

using version = boost::container::version_0; // seems unsupported, really
using version = boost::container::version_1;
using version = boost::container::version_2; // does different operations

But it had no (decisive) effect. Maybe the documentation has clues.

Pointer Arithmetic

After that I looked into the specific errors. Looking at the cited line/error it dawned on me that the raw-pointer might have been an accident. Looking at the output of these:

std::cout << boost::container::container_detail::impl::version<allocator<int> >::value << "\n";

array_ptr<int> p;
auto rawp = boost::container::container_detail::to_raw_pointer(p);
std::cout << typeid(rawp).name() << "\n";

std::cout << typeid(p).name() << "\n";
std::cout << typeid(p + 5).name() << "\n";
std::cout << typeid(p - 5).name() << "\n";

Shows something like¹

1
int*
array_ptr<int>
int*
int*

¹ prettified with the help of c++filt -t

This lead me to define pointer arithmetic:

template <typename T, typename N>
array_ptr<T> operator+(array_ptr<T> const& p, N n) { return array_ptr<T>(p.p+n, p.i); }

template <typename T>
array_ptr<T>& operator++(array_ptr<T>& p) { return ++p.p, p; }

template <typename T>
array_ptr<T> operator++(array_ptr<T>& p, int) { auto q = p.p++; return array_ptr<T>(q, p.i); }

template <typename T, typename N>
array_ptr<T> operator-(array_ptr<T> const& p, N n) { return array_ptr<T>(p.p-n, p.i); }

template <typename T>
ptrdiff_t operator-(array_ptr<T> const& a, array_ptr<T> const& b) { return a.p - b.p; }

Now the output becomes

1
int*
array_ptr<int>
array_ptr<int>
array_ptr<int>

Many more use cases compile successfully with these definitions. Assuming that the "annotation" data inside the array_pointer is valid after increment, it should not lose any allocator information

The Real Culprit

With that out of the way, some things still don't compile. Specifically, in some spots the allocator's pointer type is constructed back from a raw-pointer. This fails because there's no suitable "default" conversion constructor. If you declare the constructors with the data value optional, everything compiles, but you could argue that this loses information as there is a path from

 array_pointer<T> p;
 auto* rawp = to_raw_pointer(p);
 array_pointer<T> clone(rawp); // oops lost the extra info in p

OBSERVATION

Note that, as you apparently realized (judging from the commented operators), adding the default constructor argument removes the need for the arithmetic operations (except pre-increment).

However, adding them makes sure that the lossy conversion path is taken less often, which could be important to your use case.

DEMO TIME

Live On Coliru

#if COMPILATION_INSTRUCTIONS
clang++ -std=c++14 -Wall -Wfatal-errors $0 -o $0x.x && $0x.x $@ && rm -f $0x.x; exit
#endif

#define DEFAULT_DATA = 0
#define DEFINE_ARITHMETIC_OPERATIONS

#include <iostream>
#include <boost/container/vector.hpp>
#include <typeinfo>

template<typename T>
struct array_ptr {
    T* p;
    int i; //some additional information

    T& operator*() const { return *p; }
    T* operator->() const { return p; }

    operator T*() const { return p; }

    array_ptr(){}
    //array_ptr(std::nullptr_t) : p(nullptr), i(0){}
    array_ptr(T* ptr, int _i DEFAULT_DATA) : p(ptr), i(_i){}

};

template<>
struct array_ptr<void> {
    using T = void;
    T* p;
    int i; //some additional information

//    T& operator*() const { return *p; }
    T* operator->() const { return p; }

    operator T*() const { return p; }
    template<class T>
    operator array_ptr<T>() const{return array_ptr<T>((T*)p, i);}
//    array_ptr& operator++(){++p; return *this;}
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr){}
    array_ptr(T* ptr, int _i DEFAULT_DATA) : p(ptr), i(_i){}
    template<class Other>
    array_ptr(array_ptr<Other> other) : p(other.p), i(other.i){}
};

template<>
struct array_ptr<void const> {
    using T = void const;
    T* p;
    int i; //some additional information

//    T& operator*() const { return *p; }
    T* operator->() const { return p; }

    operator T*() const { return p; }
//    array_ptr& operator++(){++p; return *this;}
//  template<class Other> array_ptr(array_ptr<Other> const& other) : p(other.p), i(other.i){}
    array_ptr(){}
    array_ptr(std::nullptr_t) : p(nullptr){}
    array_ptr(T* ptr, int _i DEFAULT_DATA) : p(ptr), i(_i){}
    template<class Other>
    array_ptr(array_ptr<Other> other) : p(other.p), i(other.i){}
};

struct some_managed_shared_memory {
    array_ptr<void> allocate(size_t n) { return array_ptr<void>(::malloc(n), 99); }
    void  deallocate(array_ptr<void> ptr) { if (ptr) ::free(ptr.p); }
};

template<typename T>
struct allocator{
    using version = boost::container::version_1;

    using value_type = T;
    using pointer = array_ptr<T>; // simulates T*
    using const_pointer = array_ptr<T const>; // simulates T const*
    using void_pointer = array_ptr<void>; // simulates void*
    using const_void_pointer = array_ptr<void const>; // simulates void const*

    some_managed_shared_memory& msm_;
    allocator(some_managed_shared_memory& msm) : msm_(msm){}
    array_ptr<T> allocate(size_t n){
        auto ret = msm_.allocate(n*sizeof(T));
        return static_cast<array_ptr<T>>(ret);
    }
    void deallocate(array_ptr<T> ptr, std::size_t = 0){
        msm_.deallocate(ptr);
    }
};

#ifdef DEFINE_ARITHMETIC_OPERATIONS
    template <typename T, typename N>
    array_ptr<T> operator+(array_ptr<T> const& p, N n) { return array_ptr<T>(p.p+n, p.i); }

    template <typename T>
    array_ptr<T>& operator++(array_ptr<T>& p) { return ++p.p, p; }

    template <typename T>
    array_ptr<T> operator++(array_ptr<T>& p, int) { auto q = p.p++; return array_ptr<T>(q, p.i); }

    template <typename T, typename N>
    array_ptr<T> operator-(array_ptr<T> const& p, N n) { return array_ptr<T>(p.p-n, p.i); }

    template <typename T>
    ptrdiff_t operator-(array_ptr<T> const& a, array_ptr<T> const& b) { return a.p - b.p; }
#endif

int main() {
    std::cout << boost::container::container_detail::impl::version<allocator<int> >::value << "\n";

    if (1) { // some diagnostics
        array_ptr<int> p;
        auto rawp = boost::container::container_detail::to_raw_pointer(p);
        std::cout << typeid(rawp).name() << "\n";

        std::cout << typeid(p).name() << "\n";
        std::cout << typeid(p + 5).name() << "\n";
        std::cout << typeid(p - 5).name() << "\n";
    }

    some_managed_shared_memory realm;
    boost::container::vector<int, allocator<int> > v(10, realm);
    assert( v[4] == 0 );
    v[4] = 1;
    assert( v[4] == 1 );
    for(std::size_t i = 0; i != v.size(); ++i) std::cout << v[i] << std::endl;

    // these compile:
    v.push_back(12);
    v.resize(100);
    v.assign({1,2,3,4,5});
}

Prints

1
Pi
9array_ptrIiE
9array_ptrIiE
9array_ptrIiE
0
0
0
0
1
0
0
0
0
0


问:
Detect if running as Administrator with or without elevated privileges?
I have an application that needs to detect whether or not it is running with elevated privileges or not.  I currently have code set up like this:

```<code>static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole (WindowsBuiltInRole.Administrator);
}
</code>```

This works to detect if a user is an administrator or not, but doesn't work if running as an administrator without elevation.  (For example in vshost.exe).

How can I determine whether or not elevation is [already in force or] possible?

答:
Try this out:</p>

```<code>using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;

public static class UacHelper
{
    private const string uacRegistryKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
    private const string uacRegistryValue = "EnableLUA";

    private static uint STANDARD_RIGHTS_READ = 0x00020000;
    private static uint TOKEN_QUERY = 0x0008;
    private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);

    [DllImport("advapi32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);

    public enum TOKEN_INFORMATION_CLASS
    {
        TokenUser = 1,
        TokenGroups,
        TokenPrivileges,
        TokenOwner,
        TokenPrimaryGroup,
        TokenDefaultDacl,
        TokenSource,
        TokenType,
        TokenImpersonationLevel,
        TokenStatistics,
        TokenRestrictedSids,
        TokenSessionId,
        TokenGroupsAndPrivileges,
        TokenSessionReference,
        TokenSandBoxInert,
        TokenAuditPolicy,
        TokenOrigin,
        TokenElevationType,
        TokenLinkedToken,
        TokenElevation,
        TokenHasRestrictions,
        TokenAccessInformation,
        TokenVirtualizationAllowed,
        TokenVirtualizationEnabled,
        TokenIntegrityLevel,
        TokenUIAccess,
        TokenMandatoryPolicy,
        TokenLogonSid,
        MaxTokenInfoClass
    }

    public enum TOKEN_ELEVATION_TYPE
    {
        TokenElevationTypeDefault = 1,
        TokenElevationTypeFull,
        TokenElevationTypeLimited
    }

    public static bool IsUacEnabled
    {
        get
        {
            RegistryKey uacKey = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false);
            bool result = uacKey.GetValue(uacRegistryValue).Equals(1);
            return result;
        }
    }

    public static bool IsProcessElevated
    {
        get
        {
            if (IsUacEnabled)
            {
                IntPtr tokenHandle;
                if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle))
                {
                    throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
                }

                TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                int elevationResultSize = Marshal.SizeOf((int)elevationResult);
                uint returnedSize = 0;
                IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);

                bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                if (success)
                {
                    elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                    bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                    return isProcessAdmin;
                }
                else
                {
                    throw new ApplicationException("Unable to determine the current elevation.");
                }
            }
            else
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                bool result = principal.IsInRole(WindowsBuiltInRole.Administrator);
                return result;
            }
        }
    }
}
</code>```

Body:
I have an application that needs to detect whether or not it is running with elevated privileges or not.  I currently have code set up like this:

static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole (WindowsBuiltInRole.Administrator);
}

This works to detect if a user is an administrator or not, but doesn't work if running as an administrator without elevation.  (For example in vshost.exe).

How can I determine whether or not elevation is [already in force or] possible?

Body:
Try this out:

using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;

public static class UacHelper
{
    private const string uacRegistryKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
    private const string uacRegistryValue = "EnableLUA";

    private static uint STANDARD_RIGHTS_READ = 0x00020000;
    private static uint TOKEN_QUERY = 0x0008;
    private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);

    [DllImport("advapi32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);

    public enum TOKEN_INFORMATION_CLASS
    {
        TokenUser = 1,
        TokenGroups,
        TokenPrivileges,
        TokenOwner,
        TokenPrimaryGroup,
        TokenDefaultDacl,
        TokenSource,
        TokenType,
        TokenImpersonationLevel,
        TokenStatistics,
        TokenRestrictedSids,
        TokenSessionId,
        TokenGroupsAndPrivileges,
        TokenSessionReference,
        TokenSandBoxInert,
        TokenAuditPolicy,
        TokenOrigin,
        TokenElevationType,
        TokenLinkedToken,
        TokenElevation,
        TokenHasRestrictions,
        TokenAccessInformation,
        TokenVirtualizationAllowed,
        TokenVirtualizationEnabled,
        TokenIntegrityLevel,
        TokenUIAccess,
        TokenMandatoryPolicy,
        TokenLogonSid,
        MaxTokenInfoClass
    }

    public enum TOKEN_ELEVATION_TYPE
    {
        TokenElevationTypeDefault = 1,
        TokenElevationTypeFull,
        TokenElevationTypeLimited
    }

    public static bool IsUacEnabled
    {
        get
        {
            RegistryKey uacKey = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false);
            bool result = uacKey.GetValue(uacRegistryValue).Equals(1);
            return result;
        }
    }

    public static bool IsProcessElevated
    {
        get
        {
            if (IsUacEnabled)
            {
                IntPtr tokenHandle;
                if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle))
                {
                    throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
                }

                TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                int elevationResultSize = Marshal.SizeOf((int)elevationResult);
                uint returnedSize = 0;
                IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);

                bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                if (success)
                {
                    elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                    bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                    return isProcessAdmin;
                }
                else
                {
                    throw new ApplicationException("Unable to determine the current elevation.");
                }
            }
            else
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                bool result = principal.IsInRole(WindowsBuiltInRole.Administrator);
                return result;
            }
        }
    }
}