问:
How to freeze the header of the girdview [gridview and column width are not fixed]
I am implementing Gridview freeze header with vertical scroll bar. I tried lot of solutions that has been suggested here. But the issues are,

The Gridview is inside a panel ,whose width is not fixed. Its 97% .

2.The columns don't have fixed width.

I tried solution suggested in GridviewScroll.js , but the problem is with fixed width and the Gridview doesn't resize as per the window size.

I tried too many solutions but nothing works without fixed width , so i can't present that here..

Below is my existing code

```<code>         <asp:Panel ID="panel_gridholder" runat="server"  style="position:absolute;left:10px;width:97%; min-width:1020px;margin-top:3px;margin-bottom:20px;overflow:auto;" >

            <asp:GridView ID="GridView_Vehicle" runat="server" AutoGenerateColumns="False" AllowSorting="true" PagerSettings-Position="TopAndBottom"
                OnPageIndexChanging="GridView_Vehicle_PageIndexChanging" OnSorting="GridView_Vehicle_Sorting" PageSize="100"
                GridLines="None" AllowPaging="true" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
                <Columns> </Columns>
           </asp:GridView>

            <div style="height: 400px"></div>
        </asp:Panel>
</code>```

Any suggestions ?

答:
I'd use DataTables.  Aside from doing what you want (as I far as I understand your requirements), it is mature, stable, and capable of much more besides.

I created a JsFiddle to demonstrate: https://jsfiddle.net/objo18f9/3/

In the Fiddle: the header is fixed with vertical scrolling of the contents; no specified column sizes (they will resize as you drag the middle divider (of the Fiddle) either left or right; and the table is surrounded by a div that is set to 97% of the page width (which from memory is what a Panel is rendered as in ASP.Net); and paging is turned on.

Here's the same example as a Code Snippet:

$(document).ready(function() {
  $('#example').DataTable({
    "scrollY": "200px",
    "scrollCollapse": true,
    "paging": true
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">

<div width="97%">
  <table id="example" class="display" width="100%" cellspacing="0">
    <thead>
      <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011/04/25</td>
        <td>$320,800</td>
      </tr>
      <tr>
        <td>Garrett Winters</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>63</td>
        <td>2011/07/25</td>
        <td>$170,750</td>
      </tr>
      <tr>
        <td>Ashton Cox</td>
        <td>Junior Technical Author</td>
        <td>San Francisco</td>
        <td>66</td>
        <td>2009/01/12</td>
        <td>$86,000</td>
      </tr>
      <tr>
        <td>Cedric Kelly</td>
        <td>Senior Javascript Developer</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2012/03/29</td>
        <td>$433,060</td>
      </tr>
      <tr>
        <td>Airi Satou</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>33</td>
        <td>2008/11/28</td>
        <td>$162,700</td>
      </tr>
      <tr>
        <td>Brielle Williamson</td>
        <td>Integration Specialist</td>
        <td>New York</td>
        <td>61</td>
        <td>2012/12/02</td>
        <td>$372,000</td>
      </tr>
      <tr>
        <td>Herrod Chandler</td>
        <td>Sales Assistant</td>
        <td>San Francisco</td>
        <td>59</td>
        <td>2012/08/06</td>
        <td>$137,500</td>
      </tr>
      <tr>
        <td>Rhona Davidson</td>
        <td>Integration Specialist</td>
        <td>Tokyo</td>
        <td>55</td>
        <td>2010/10/14</td>
        <td>$327,900</td>
      </tr>
      <tr>
        <td>Colleen Hurst</td>
        <td>Javascript Developer</td>
        <td>San Francisco</td>
        <td>39</td>
        <td>2009/09/15</td>
        <td>$205,500</td>
      </tr>
      <tr>
        <td>Sonya Frost</td>
        <td>Software Engineer</td>
        <td>Edinburgh</td>
        <td>23</td>
        <td>2008/12/13</td>
        <td>$103,600</td>
      </tr>
      <tr>
        <td>Jena Gaines</td>
        <td>Office Manager</td>
        <td>London</td>
        <td>30</td>
        <td>2008/12/19</td>
        <td>$90,560</td>
      </tr>
      <tr>
        <td>Quinn Flynn</td>
        <td>Support Lead</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2013/03/03</td>
        <td>$342,000</td>
      </tr>
      <tr>
        <td>Charde Marshall</td>
        <td>Regional Director</td>
        <td>San Francisco</td>
        <td>36</td>
        <td>2008/10/16</td>
        <td>$470,600</td>
      </tr>
      <tr>
        <td>Haley Kennedy</td>
        <td>Senior Marketing Designer</td>
        <td>London</td>
        <td>43</td>
        <td>2012/12/18</td>
        <td>$313,500</td>
      </tr>
      <tr>
        <td>Tatyana Fitzpatrick</td>
        <td>Regional Director</td>
        <td>London</td>
        <td>19</td>
        <td>2010/03/17</td>
        <td>$385,750</td>
      </tr>
      <tr>
        <td>Michael Silva</td>
        <td>Marketing Designer</td>
        <td>London</td>
        <td>66</td>
        <td>2012/11/27</td>
        <td>$198,500</td>
      </tr>
      <tr>
        <td>Paul Byrd</td>
        <td>Chief Financial Officer (CFO)</td>
        <td>New York</td>
        <td>64</td>
        <td>2010/06/09</td>
        <td>$725,000</td>
      </tr>
      <tr>
        <td>Gloria Little</td>
        <td>Systems Administrator</td>
        <td>New York</td>
        <td>59</td>
        <td>2009/04/10</td>
        <td>$237,500</td>
      </tr>
      <tr>
        <td>Bradley Greer</td>
        <td>Software Engineer</td>
        <td>London</td>
        <td>41</td>
        <td>2012/10/13</td>
        <td>$132,000</td>
      </tr>
      <tr>
        <td>Dai Rios</td>
        <td>Personnel Lead</td>
        <td>Edinburgh</td>
        <td>35</td>
        <td>2012/09/26</td>
        <td>$217,500</td>
      </tr>
    </tbody>
  </table>
</div></code>```

If you tell ASP.Net to use a static Id: <asp:GridView ID="GridView_Vehicle" ClientIDMode="static" ... then you should be able to refer to your table as: $('#GridView_Vehicle').DataTable({ ... });

Body:
I am implementing Gridview freeze header with vertical scroll bar. I tried lot of solutions that has been suggested here. But the issues are,

The Gridview is inside a panel ,whose width is not fixed. Its 97% .

2.The columns don't have fixed width.

I tried solution suggested in GridviewScroll.js , but the problem is with fixed width and the Gridview doesn't resize as per the window size.

I tried too many solutions but nothing works without fixed width , so i can't present that here..

Below is my existing code

         <asp:Panel ID="panel_gridholder" runat="server"  style="position:absolute;left:10px;width:97%; min-width:1020px;margin-top:3px;margin-bottom:20px;overflow:auto;" >

            <asp:GridView ID="GridView_Vehicle" runat="server" AutoGenerateColumns="False" AllowSorting="true" PagerSettings-Position="TopAndBottom"
                OnPageIndexChanging="GridView_Vehicle_PageIndexChanging" OnSorting="GridView_Vehicle_Sorting" PageSize="100"
                GridLines="None" AllowPaging="true" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
                <Columns> </Columns>
           </asp:GridView>

        </asp:Panel>

Any suggestions ?

Body:
I'd use DataTables.  Aside from doing what you want (as I far as I understand your requirements), it is mature, stable, and capable of much more besides.

I created a JsFiddle to demonstrate: https://jsfiddle.net/objo18f9/3/

In the Fiddle: the header is fixed with vertical scrolling of the contents; no specified column sizes (they will resize as you drag the middle divider (of the Fiddle) either left or right; and the table is surrounded by a div that is set to 97% of the page width (which from memory is what a Panel is rendered as in ASP.Net); and paging is turned on.

Here's the same example as a Code Snippet:

$(document).ready(function() {
  $('#example').DataTable({
    "scrollY": "200px",
    "scrollCollapse": true,
    "paging": true
  });
});

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">

<div width="97%">
  <table id="example" class="display" width="100%" cellspacing="0">
    <thead>
      <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011/04/25</td>
        <td>$320,800</td>
      </tr>
      <tr>
        <td>Garrett Winters</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>63</td>
        <td>2011/07/25</td>
        <td>$170,750</td>
      </tr>
      <tr>
        <td>Ashton Cox</td>
        <td>Junior Technical Author</td>
        <td>San Francisco</td>
        <td>66</td>
        <td>2009/01/12</td>
        <td>$86,000</td>
      </tr>
      <tr>
        <td>Cedric Kelly</td>
        <td>Senior Javascript Developer</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2012/03/29</td>
        <td>$433,060</td>
      </tr>
      <tr>
        <td>Airi Satou</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>33</td>
        <td>2008/11/28</td>
        <td>$162,700</td>
      </tr>
      <tr>
        <td>Brielle Williamson</td>
        <td>Integration Specialist</td>
        <td>New York</td>
        <td>61</td>
        <td>2012/12/02</td>
        <td>$372,000</td>
      </tr>
      <tr>
        <td>Herrod Chandler</td>
        <td>Sales Assistant</td>
        <td>San Francisco</td>
        <td>59</td>
        <td>2012/08/06</td>
        <td>$137,500</td>
      </tr>
      <tr>
        <td>Rhona Davidson</td>
        <td>Integration Specialist</td>
        <td>Tokyo</td>
        <td>55</td>
        <td>2010/10/14</td>
        <td>$327,900</td>
      </tr>
      <tr>
        <td>Colleen Hurst</td>
        <td>Javascript Developer</td>
        <td>San Francisco</td>
        <td>39</td>
        <td>2009/09/15</td>
        <td>$205,500</td>
      </tr>
      <tr>
        <td>Sonya Frost</td>
        <td>Software Engineer</td>
        <td>Edinburgh</td>
        <td>23</td>
        <td>2008/12/13</td>
        <td>$103,600</td>
      </tr>
      <tr>
        <td>Jena Gaines</td>
        <td>Office Manager</td>
        <td>London</td>
        <td>30</td>
        <td>2008/12/19</td>
        <td>$90,560</td>
      </tr>
      <tr>
        <td>Quinn Flynn</td>
        <td>Support Lead</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2013/03/03</td>
        <td>$342,000</td>
      </tr>
      <tr>
        <td>Charde Marshall</td>
        <td>Regional Director</td>
        <td>San Francisco</td>
        <td>36</td>
        <td>2008/10/16</td>
        <td>$470,600</td>
      </tr>
      <tr>
        <td>Haley Kennedy</td>
        <td>Senior Marketing Designer</td>
        <td>London</td>
        <td>43</td>
        <td>2012/12/18</td>
        <td>$313,500</td>
      </tr>
      <tr>
        <td>Tatyana Fitzpatrick</td>
        <td>Regional Director</td>
        <td>London</td>
        <td>19</td>
        <td>2010/03/17</td>
        <td>$385,750</td>
      </tr>
      <tr>
        <td>Michael Silva</td>
        <td>Marketing Designer</td>
        <td>London</td>
        <td>66</td>
        <td>2012/11/27</td>
        <td>$198,500</td>
      </tr>
      <tr>
        <td>Paul Byrd</td>
        <td>Chief Financial Officer (CFO)</td>
        <td>New York</td>
        <td>64</td>
        <td>2010/06/09</td>
        <td>$725,000</td>
      </tr>
      <tr>
        <td>Gloria Little</td>
        <td>Systems Administrator</td>
        <td>New York</td>
        <td>59</td>
        <td>2009/04/10</td>
        <td>$237,500</td>
      </tr>
      <tr>
        <td>Bradley Greer</td>
        <td>Software Engineer</td>
        <td>London</td>
        <td>41</td>
        <td>2012/10/13</td>
        <td>$132,000</td>
      </tr>
      <tr>
        <td>Dai Rios</td>
        <td>Personnel Lead</td>
        <td>Edinburgh</td>
        <td>35</td>
        <td>2012/09/26</td>
        <td>$217,500</td>
      </tr>
    </tbody>
  </table>
</div>

If you tell ASP.Net to use a static Id: <asp:GridView ID="GridView_Vehicle" ClientIDMode="static" ... then you should be able to refer to your table as: $('#GridView_Vehicle').DataTable({ ... });


来源: stackexchange

问:
Namespace is not Bound in Android Studio
If I create a new XML-file (using the default Android Studio "Create Linear Layout"), Studio makes a file with content:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>
```

If I (right)-click "Analyze... → Inspect Code" the result window throws 2 times:
"Namespace is not bound" and references to line 3 and 7 (the LinearLayout-tags). Is it a bug in Studio?

答:
try this:
in android studio 2.2.3 press F2 to jump between the warning then press Alt+Enter; this created the following reference:
xmlns:app="http://schemas.android.com/apk/res-auto"
and fixed the issue.
Moreover, I checked my XML files and all have this encoding version:
?xml version="1.0" encoding="utf-8"?

ContentLicense: CC BY-SA 3.0

Body:
If I create a new XML-file (using the default Android Studio "Create Linear Layout"), Studio makes a file with content:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>

If I (right)-click "Analyze... → Inspect Code" the result window throws 2 times:
"Namespace is not bound" and references to line 3 and 7 (the LinearLayout-tags). Is it a bug in Studio?


问:
Script laggy to load on older iOS devices only
Script takes a few seconds to load on older iOS devices. I tested on my iPhone 7 and works fine.

```<code>   $(document).scroll(function () {
   var y = $(this).scrollTop();

   if (y > 300) {
        $('#bottombadge').fadeIn;
   }

   else {
        /* (y <= 300) */
        $('#bottombadge').fadeOut();
   }

});
</code>```

It's mainly the fadeIn that is super slow. Any ideas please? Thank you

答:
The issue is because scroll fires for every pixel that's scrolled. Therefore if you scroll 200px you're potentially calling fadeIn() 200 times. To fix this you need to 'debounce' the scroll event so that it only happens N ms after scrolling has stopped:

```<code>var timer;

$(document).scroll(function () {
  var $doc = $(this);
  clearTimeout(timer);
  timer = setTimeout(function() {
    var y = $doc.scrollTop();
    $('#bottombadge')[y > 300 ? 'fadeIn' : 'fadeOut']();
  }, 150);
});
</code>```

Body:
Script takes a few seconds to load on older iOS devices. I tested on my iPhone 7 and works fine.

   $(document).scroll(function () {
   var y = $(this).scrollTop();

   if (y > 300) {
        $('#bottombadge').fadeIn;
   }

   else {
        /* (y <= 300) */
        $('#bottombadge').fadeOut();
   }

});

It's mainly the fadeIn that is super slow. Any ideas please? Thank you

Body:
The issue is because scroll fires for every pixel that's scrolled. Therefore if you scroll 200px you're potentially calling fadeIn() 200 times. To fix this you need to 'debounce' the scroll event so that it only happens N ms after scrolling has stopped:

var timer;

$(document).scroll(function () {
  var $doc = $(this);
  clearTimeout(timer);
  timer = setTimeout(function() {
    var y = $doc.scrollTop();
    $('#bottombadge')[y > 300 ? 'fadeIn' : 'fadeOut']();
  }, 150);
});


问:
Connecting to Boost Signals2 signal with anonymous or lambda function
I am trying to do the following in order to receive a string from a boost signal and post it to the display. The following syntax is incorrect.

```<code>signal<void (const char*)>                      UserMessageEvent;

// connect anonymous boost function to display message box on user message event
UserMessageEvent.connect(boost::bind(AfxMessageBox, _1));
</code>```

If this were C# I would do the following, leading me to believe I want to use a lambda function to convert between the calling type of the signal and the type of the AfxMessageBox arguments. However it is not clear to me how to do this.

```<code>UserMessageEvent += (c) => MessageBox.Show((some const char to LPCSTR conversion)c);
</code>```

Any suggestions?

Edit:
The error given by msvc10 is error C2914: 'boost::bind' : cannot deduce template argument as function argument is ambiguous

答:
AfxMessageBox has several overloads and default parameters, which makes your construct above ambigious. Write a small function taking exactly one LPCSTR, which forwards to AfxMessageBox, and bind that to the signal<>.

EDIT:
As some people seem not to like what I provided above (why downvote without a comment?) here some clarifying code for what I wrote above:

```<code>int MyMessageBox(LPCSTR msg)
{
    return AfxMessageBox(msg);
}

UserMessageEvent.connect(boost::bind(MyMessageBox, _1));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to do the following in order to receive a string from a boost signal and post it to the display. The following syntax is incorrect.

signal<void (const char*)>                      UserMessageEvent;

// connect anonymous boost function to display message box on user message event
UserMessageEvent.connect(boost::bind(AfxMessageBox, _1));

If this were C# I would do the following, leading me to believe I want to use a lambda function to convert between the calling type of the signal and the type of the AfxMessageBox arguments. However it is not clear to me how to do this.

UserMessageEvent += (c) => MessageBox.Show((some const char to LPCSTR conversion)c);

Any suggestions?

Edit:
The error given by msvc10 is error C2914: 'boost::bind' : cannot deduce template argument as function argument is ambiguous

Body:
AfxMessageBox has several overloads and default parameters, which makes your construct above ambigious. Write a small function taking exactly one LPCSTR, which forwards to AfxMessageBox, and bind that to the signal<>.

EDIT:
As some people seem not to like what I provided above (why downvote without a comment?) here some clarifying code for what I wrote above:

int MyMessageBox(LPCSTR msg)
{
    return AfxMessageBox(msg);
}

UserMessageEvent.connect(boost::bind(MyMessageBox, _1));


问:
How to draw shapes like circles, oval, ractangles dynamically in iOS?
I have a UICollectionView of showing shapes like circles, oval, ractangles. So when I clicked on Cell I need to draw same shape on UIView and after I need to move and resize that view which was drawn by clicking in Cell. How it can achieve in iOS ? Thanks in advance. </p>

答: study about bezier path. It is possible with this. hope it will work for you.</p>


问:
How to change SVN authentication details in AnkhSVN in Visual Studio 2010?
I want to change the username and password for SVN in Visual Studio 2010 AnkhSVN plugin. How can i do that?</p>

答:
Found it. To clear the cached username/passwords you can go to:

Tools > Options > Source Control > Subversion Environment > Authentication Cache


问:
Block doesn't execute
I am caching downloading and images in this way, but my problem is this queryDiskCacheForDisk block doesn't execute.

```<code>-(void)checkCache :(NSArray *)imgUrl
{
    float circleWidth=0.0;
    if (dm.screenWidth==320) {
        circleWidth=53.0;
    }

    else if(dm.screenWidth>320)
    {
        circleWidth=65.0;
    }
    CGRect circleFrame=CGRectMake(0, 0, circleWidth, circleWidth);
    __block UIImage *savedImage=[com circularScaleAndCropImage:[UIImage imageNamed:@"notFound"] frame:circleFrame];
    SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"TEAM_PROFILES"];
    [imageCache queryDiskCacheForKey:[imgUrl objectAtIndex:0] done:^(UIImage *image,SDImageCacheType cacheType) {
        // image is not nil if image was found

        if (image) {
            savedImage=[com circularScaleAndCropImage:image frame:circleFrame];

            NSLog(@"----image Cached------");
        }
        else
        {
            //[self performSelectorInBackground:@selector(getImageNew:) withObject:nil];
            savedImage=[self getImageNew:imgUrl];
            [imageCache storeImage:savedImage forKey:[imgUrl objectAtIndex:0]];
        }
    }];

    [arrayImages addObject:savedImage];
    [arrayTeamMemeberNames addObject:[imgUrl objectAtIndex:1]];
    [arrayEmpCodes addObject:[imgUrl objectAtIndex:2]];
    [arrEmpFullName addObject:[imgUrl objectAtIndex:3]];
    [arrEmpNumbers addObject:[imgUrl objectAtIndex:4]];
    if([arrayImages count]==[arrayTeamMembersUnfilter count])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"imagesFilledContact" object:nil];
        NSLog(@"------POST NOTIFICATION-----");

    }
}
</code>```

It always added the default image I assigned at the begining. How can I solve this issue?

答:
In you block, I didn't see any add operation.

Do you know your block is the last part to run?

ContentLicense: CC BY-SA 4.0

Title: Block doesn't execute

Body:
I am caching downloading and images in this way, but my problem is this queryDiskCacheForDisk block doesn't execute.

-(void)checkCache :(NSArray *)imgUrl
{
    float circleWidth=0.0;
    if (dm.screenWidth==320) {
        circleWidth=53.0;
    }

    else if(dm.screenWidth>320)
    {
        circleWidth=65.0;
    }
    CGRect circleFrame=CGRectMake(0, 0, circleWidth, circleWidth);
    __block UIImage *savedImage=[com circularScaleAndCropImage:[UIImage imageNamed:@"notFound"] frame:circleFrame];
    SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"TEAM_PROFILES"];
    [imageCache queryDiskCacheForKey:[imgUrl objectAtIndex:0] done:^(UIImage *image,SDImageCacheType cacheType) {
        // image is not nil if image was found

        if (image) {
            savedImage=[com circularScaleAndCropImage:image frame:circleFrame];

            NSLog(@"----image Cached------");
        }
        else
        {
            //[self performSelectorInBackground:@selector(getImageNew:) withObject:nil];
            savedImage=[self getImageNew:imgUrl];
            [imageCache storeImage:savedImage forKey:[imgUrl objectAtIndex:0]];
        }
    }];

    [arrayImages addObject:savedImage];
    [arrayTeamMemeberNames addObject:[imgUrl objectAtIndex:1]];
    [arrayEmpCodes addObject:[imgUrl objectAtIndex:2]];
    [arrEmpFullName addObject:[imgUrl objectAtIndex:3]];
    [arrEmpNumbers addObject:[imgUrl objectAtIndex:4]];
    if([arrayImages count]==[arrayTeamMembersUnfilter count])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"imagesFilledContact" object:nil];
        NSLog(@"------POST NOTIFICATION-----");

    }
}

It always added the default image I assigned at the begining. How can I solve this issue?


问:
How best to programmatically tell whether a TLabel's Caption is clipped (i.e. drawn using ellipsis)?
I have a TLabel with EllipsisPosition set to epEndEllipsis and I need to be able to tell whether the text is currently clipped or not. Besides calculating the area required to display the text myself and comparing it with the actual dimensions of the label, has anyone come up with an easier/more elegant way of doing this?

Actually, calculating the required area in a fail-safe manner also doesn't appear to be as straight forward as it sounds... For instance TCanvas.GetTextHeight does not take into account linebreaks.

TCustomLabel.DoDrawText internally uses either DrawTextW or DrawThemeTextExwith the DT_CALCRECT flag to determine whether it should use the ellipsis or not. There's quite a lot of code involved there, all of which is declared private. Simply duplicating all that code would not exactly qualify as "elegant" in my book...

Any ideas?

(I'm using Delphi 2010 in case anyone comes up with a Delphi-version-specific solution)

Update 1: I now figured out that I can simply call TCustomLabel.DoDrawText(lRect, DT_CALCRECT) directly (which is merely declared protected) to let the label perform the required size calculation without having to duplicate its code. I just have to make sure to either temporarily set EllipsisPosition to epNone or use a temporary label instance altogether. This is actually not that bad and I might just go with it if noone can think of an even simpler solution.

Update 2: I have now added my solution as a separate answer. It turned out to be rather more straight-forward than I anticipated so there probably is no easier/better way to do it but I'll leave this question open for a little while longer anyway just in case.

答:
As a starting point, you could use

```<code>function DrawStringEllipsis(const DC: HDC; const ARect: TRect; const AStr: string): boolean;
var
  r: TRect;
  s: PChar;
begin
  r := ARect;
  GetMem(s, length(AStr)*sizeof(char) + 8);
  StrCopy(s, PChar(AStr));
  DrawText(DC, PChar(s), length(AStr), r, DT_LEFT or DT_END_ELLIPSIS or DT_MODIFYSTRING);
  result := not SameStr(AStr, s);
  FreeMem(s);
end;
</code>```

Sample usage:

```<code>procedure TForm1.FormClick(Sender: TObject);
begin
  Caption := 'Clipped ' + BoolToStr(DrawStringEllipsis(Canvas.Handle, Rect(10, 100, 50, 50), 'This is a text.'), true);
end;
</code>```

It wouldn't be hard to write a TExtLabel component that has a WasClipped property using this technique. Indeed, the TLabel component is one of the simplest components in the VCL -- it just draws a string.

Body:
As a starting point, you could use

function DrawStringEllipsis(const DC: HDC; const ARect: TRect; const AStr: string): boolean;
var
  r: TRect;
  s: PChar;
begin
  r := ARect;
  GetMem(s, length(AStr)*sizeof(char) + 8);
  StrCopy(s, PChar(AStr));
  DrawText(DC, PChar(s), length(AStr), r, DT_LEFT or DT_END_ELLIPSIS or DT_MODIFYSTRING);
  result := not SameStr(AStr, s);
  FreeMem(s);
end;

Sample usage:

procedure TForm1.FormClick(Sender: TObject);
begin
  Caption := 'Clipped ' + BoolToStr(DrawStringEllipsis(Canvas.Handle, Rect(10, 100, 50, 50), 'This is a text.'), true);
end;

It wouldn't be hard to write a TExtLabel component that has a WasClipped property using this technique. Indeed, the TLabel component is one of the simplest components in the VCL -- it just draws a string.


问:
Are the terms Type and Class used interchangeably - Scala
I have been studying scala quite a bit now. However, I have a simple question in regards to few terms used on many learning materials I find.

Are the term Type used interchangeably with Class?

Could a Type be replaced by a Class? and vice versa?

Ex. a Scala programmer would/could call the following case class a Type

```<code>type ProductId = String
type Quantity = Int

case class ShoppingCart(items: Map[ProductId, Quantity])
</code>```

So, is ShoppingCart a Type, a class, or both, or depends on the paradigm ?

Also, does it have anything to do with Type Classes?

Thanks in advance.

答:
No there is difference between the two terms. A type doesn't have to belong to a certain class. For example,

```<code>  def fn[T <: Foo](t: T): Unit ={
  }
</code>```

fn takes a type that extends Foo, the number of classes that can confirm to this type is potentially infinity.

Or even simpler,

```<code>val s = "hi"
</code>```

Although s is instantiated as String, it still has 5 types: Any, Serializable,String, Comparable[String], CharSequence.

Body:
I have been studying scala quite a bit now. However, I have a simple question in regards to few terms used on many learning materials I find.

Are the term Type used interchangeably with Class?

Could a Type be replaced by a Class? and vice versa?

Ex. a Scala programmer would/could call the following case class a Type

type ProductId = String
type Quantity = Int

case class ShoppingCart(items: Map[ProductId, Quantity])

So, is ShoppingCart a Type, a class, or both, or depends on the paradigm ?

Also, does it have anything to do with Type Classes?

Thanks in advance.

Body:
No there is difference between the two terms. A type doesn't have to belong to a certain class. For example,

  def fn[T <: Foo](t: T): Unit ={
  }

fn takes a type that extends Foo, the number of classes that can confirm to this type is potentially infinity.

Or even simpler,

val s = "hi"

Although s is instantiated as String, it still has 5 types: Any, Serializable,String, Comparable[String], CharSequence.


问:
batch add leading zeroes filename
I've got a script that I'm using for all kinds of things, including renaming and repacking comics. Variants of this script are used by others as well.

I've been seeing a limitation in repacking comics, however; I've found that some comics don't have the leading zeroes at their pages, which makes the pages appear out of order. So, I've added a part that should add leading zeroes.

The file does the following:

loop over all subfolders of the current folder

rename comic archives to their proper extension (so I can see where it is)

loop over all archives, and extract them to a temporary folder

loop over all files in the temporary folder, and add leading zeroes

repack it as a 7zip

rename the file to a comic book extension

Somehow, it's not renaming the files properly, and the name of the archive appears as a subfolder in the archive. For example:
let's repack 'testfolder', which contains images from 1 to 100. It renames, extracts, packs, and renames again, without problem. However, the new archive contains the folder named 'testfolder' in the archive next to the images, which don't have the leading zeroes. I'm not sure what's going on, and I've been fighting with it for a while now, so I thought to put it online (it's a good script to share, anyway). Does anyone have an idea on what's going wrong here?

```<code>@ECHO ON
rem mode con: cols=80 lines=60
for /f "delims=" %%F in ('dir /ad/s/b') do (
    cd %%F

    IF EXIST *.cbr (
        RENAME *.cbr *.rar
    )

    IF EXIST *.cbz (
        RENAME *.cbz *.zip
    )

    IF EXIST *.cb7 (
        RENAME *.cb7 *.7z
    )

    FOR %%I IN (*.RAR, *.ZIP *.7Z) DO (
        ECHO Extracting %%I...
        "C:\Program Files\7-Zip\7z.exe" e "%%I" -oC:\TMPPACKDIR\* -y | FIND /V "ing  "

        echo %%~nI
        cd C:\TMPPACKDIR\%%~nI\

        FOR /f "delims=" %%P IN ('dir *.JPG, *.PNG, *.BMP') DO (
            SET %%N = %%P
            SET %%N = 00%%N
            SET %%N = %%N:~-2%
            echo %%P
            echo %%N
            pause
            rename 'C:\TMPPACKDIR\%%~nI\%%P' %%N
        )

        pause

        echo %%F

        cd %%F

        ECHO Repacking
        "C:\Program Files\7-Zip\7z.exe" a -t7z "%%~nI.7z" "C:\TMPPACKDIR\%%~nI*" -mx=9 | FIND /V "ing  "

        IF %ERRORLEVEL% EQU 0 RD /S /Q C:\TMPPACKDIR

        ECHO Renaming new file
        RENAME *.7z *.CB7

        ECHO Removing original file
        DEL "%%I"
        ECHO File %%I is done
    )
)

REM del /f/q "%~0" | exit
</code>```

答:
Yes, the problem is in the code portion between cd C:\TMPPACKDIR\%%~nI\ and pause. You are trying to set a for variable reference %%N, which does not work. You need to use a normal environment variable instead, like NAME, for example; you can only do sub-string expansion (like ~-2 in your code) using normal environment variables. In addition, since you are setting and reading the same environment variable within a single block of code, you need to use delayed expansion; otherwise, you would always receive the value present when the entire block is read.

The code portion should look like this:

        cd /D "C:\TMPPACKDIR\%%~nI"

        for /F "delims=" %%P in ('dir /B *.JPG, *.PNG, *.BMP') do (
            set "FILE=C:\TMPPACKDIR\%%~nI\%%P"
            set "NAME=00%%~nP"
            setlocal EnableDelayedExpansion
            set "NAME=!NAME:~-2!"
            rename "!FILE!" "!NAME!%%~xP"
            endlocal
        )

        pause
```

Title: batch add leading zeroes filename

Body:
I've got a script that I'm using for all kinds of things, including renaming and repacking comics. Variants of this script are used by others as well.

I've been seeing a limitation in repacking comics, however; I've found that some comics don't have the leading zeroes at their pages, which makes the pages appear out of order. So, I've added a part that should add leading zeroes.

The file does the following:

loop over all subfolders of the current folder

rename comic archives to their proper extension (so I can see where it is)

loop over all archives, and extract them to a temporary folder

loop over all files in the temporary folder, and add leading zeroes

repack it as a 7zip

rename the file to a comic book extension

Somehow, it's not renaming the files properly, and the name of the archive appears as a subfolder in the archive. For example:
let's repack 'testfolder', which contains images from 1 to 100. It renames, extracts, packs, and renames again, without problem. However, the new archive contains the folder named 'testfolder' in the archive next to the images, which don't have the leading zeroes. I'm not sure what's going on, and I've been fighting with it for a while now, so I thought to put it online (it's a good script to share, anyway). Does anyone have an idea on what's going wrong here?

@ECHO ON
rem mode con: cols=80 lines=60
for /f "delims=" %%F in ('dir /ad/s/b') do (
    cd %%F

    IF EXIST *.cbr (
        RENAME *.cbr *.rar
    )

    IF EXIST *.cbz (
        RENAME *.cbz *.zip
    )

    IF EXIST *.cb7 (
        RENAME *.cb7 *.7z
    )

    FOR %%I IN (*.RAR, *.ZIP *.7Z) DO (
        ECHO Extracting %%I...
        "C:\Program Files\7-Zip\7z.exe" e "%%I" -oC:\TMPPACKDIR\* -y | FIND /V "ing  "

        echo %%~nI
        cd C:\TMPPACKDIR\%%~nI\

        FOR /f "delims=" %%P IN ('dir *.JPG, *.PNG, *.BMP') DO (
            SET %%N = %%P
            SET %%N = 00%%N
            SET %%N = %%N:~-2%
            echo %%P
            echo %%N
            pause
            rename 'C:\TMPPACKDIR\%%~nI\%%P' %%N
        )

        pause

        echo %%F

        cd %%F

        ECHO Repacking
        "C:\Program Files\7-Zip\7z.exe" a -t7z "%%~nI.7z" "C:\TMPPACKDIR\%%~nI*" -mx=9 | FIND /V "ing  "

        IF %ERRORLEVEL% EQU 0 RD /S /Q C:\TMPPACKDIR

        ECHO Renaming new file
        RENAME *.7z *.CB7

        ECHO Removing original file
        DEL "%%I"
        ECHO File %%I is done
    )
)

REM del /f/q "%~0" | exit


问:
uinaviationcontroller pop animation become weird when status bar was hidden

as picture : when the white controller in popping out with a interactive pop gesture , the red controller (which make the status bar hide) will show, and during the animation : the navigation bar seems to move up , and the controller's view is still in its position (not move up with navigation bar) ,so the view seems divided into two pieces in the pop out animation . how to fix it ?

答:
In the first controller,add this code.</p>

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

    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

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

    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
</code>```

Body:
In the first controller,add this code.

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

    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

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

    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


问:
Datatable Methods not working after adding Row with append
Ive got a problem to solve. With .append() I do add new rows which have input fields. But the problem is, that after appending new rows no methods work on them. No methods like search, responsive button etc.

I tried a lot but I couldnt figure it out...After clicking on a button a new Row gets added to the #table.

```<code>var poAddRowTable = $('#table').DataTable();
$('button').on('click', function () {
    addRowFunc(true)
});

addRowFunc = function () {
    var previousRow = $('#table tr:last');
    var newRow = $(previousRow).clone(true, true);

    $('#table tbody').append(newRow);
    $("html, body").scrollTop($(document).height());
}
</code>```

答:
I guess you have to refresh your table after appending, the following link can help :

How to refresh a simple Datatables table when adding new rows with jQuery

Body:
Ive got a problem to solve. With .append() I do add new rows which have input fields. But the problem is, that after appending new rows no methods work on them. No methods like search, responsive button etc.

I tried a lot but I couldnt figure it out...After clicking on a button a new Row gets added to the #table.

var poAddRowTable = $('#table').DataTable();
$('button').on('click', function () {
    addRowFunc(true)
});

addRowFunc = function () {
    var previousRow = $('#table tr:last');
    var newRow = $(previousRow).clone(true, true);

    $('#table tbody').append(newRow);
    $("html, body").scrollTop($(document).height());
}


问:
How to pip-install Python package into virtual env and have CLI commands accessible in normal shell
For larger Python packages which might interfere with other packages it is recommended to install them into their own virtual environment and some Python packages expose CLI commands to the shell.

Is there a way to pip-install such a package into its own virtual environment,
but have the CLI commands accessible from a normal shell without switching
beforehand manually to this virtual environment?

Here an example: When I install csvkit via

```<code>pip install csvkit
</code>```

I have the commands csvcut, csvlook, csvgrep and others available in my
shell. However if I do not want to install cvskit in my System-Python and
install it in a virtual environment, say at ~/venvs/csvkit, I have
csvkit only available if I have manually activated the environment
csvkit.

Is there a way to create the virtual environment and install csvkit in it,
so that the commands like csvcut activate the environment themselves before
they run?

答:
You can create an aliases, such as csvcut and point them to source ~/venvs/csvkit/bin/activate && csvcut && source deactivate

If this programs accept parameters, you can use functions and defined the in the .bashrc file:

```<code>csvcut() {
    #do things with parameters like $1 such as
    source ~/venvs/csvkit/bin/activate
    csvcut $1 $2 $3 $4 $5
    deactivate
}
</code>```

To call the function, just use the csvcut <your_parameter> command.

Body:
For larger Python packages which might interfere with other packages it is recommended to install them into their own virtual environment and some Python packages expose CLI commands to the shell.

Is there a way to pip-install such a package into its own virtual environment,
but have the CLI commands accessible from a normal shell without switching
beforehand manually to this virtual environment?

Here an example: When I install csvkit via

pip install csvkit

I have the commands csvcut, csvlook, csvgrep and others available in my
shell. However if I do not want to install cvskit in my System-Python and
install it in a virtual environment, say at ~/venvs/csvkit, I have
csvkit only available if I have manually activated the environment
csvkit.

Is there a way to create the virtual environment and install csvkit in it,
so that the commands like csvcut activate the environment themselves before
they run?

Body:
You can create an aliases, such as csvcut and point them to source ~/venvs/csvkit/bin/activate && csvcut && source deactivate

If this programs accept parameters, you can use functions and defined the in the .bashrc file:

csvcut() {
    #do things with parameters like $1 such as
    source ~/venvs/csvkit/bin/activate
    csvcut $1 $2 $3 $4 $5
    deactivate
}

To call the function, just use the csvcut <your_parameter> command.


问:
UISearchBar resigns first responder when trying to select UICollectionViewCell
I have a UIViewController that functions as a sharing drawer, and slides up from the bottom of the screen.

I have a UISearchBar and UICollectionView below it, typing in the search bar updates the collection view without a problem.

When the search bar is active, I want to be able to select cells in the collection view. However, whenever I tap anything other than the search bar, the keyboard is dismissed. I am used to having to add a UITapGestureRecognizer or manually calling searchBar.resignFirstResponder(), but in this case I cannot figure out how to NOT dismiss the keyboard.

There are no other gesture recognizers on the view controller. Any ideas on allowing (multiple) selection of the collection view while the keyboard is present?

答:
To unhide keyboard

```<code>self.view.endEditing(false)
</code>```

are you looking for this?

as in case of

```<code>resignFirstResponder
</code>```

you cannot pass a boolean to hide or unhide

We can also do this with following methods by always adding cancel button programmatically to search bar

```<code>    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchBar.showsCancelButton = true;
    }
</code>```

Also, should be trying by dropping an IBOutlet of the search bar as:

```<code>self.yourSearchBar.endEditing(false)
</code>```

Note: yourSearchBar is the name of your search bar provided on dropping IBOutlet.

Body:
To unhide keyboard

self.view.endEditing(false)

are you looking for this?

as in case of

resignFirstResponder

you cannot pass a boolean to hide or unhide

We can also do this with following methods by always adding cancel button programmatically to search bar

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchBar.showsCancelButton = true;
    }

Also, should be trying by dropping an IBOutlet of the search bar as:

self.yourSearchBar.endEditing(false)

Note: yourSearchBar is the name of your search bar provided on dropping IBOutlet.


问:
Python - Transform List to List of Lists with each entry containing unique combinations
I have a list of lists as follows:

```<code>mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]
</code>```

What I would like to do is iterate through mylist and produce a new list like this:

```<code>result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]
</code>```

In other words, make a list of lists, where each list contains unique combinations of entries of the initial list, so that a letter is not present twice in each entry of result list. Also each time an entry is added to result, we abstract it's sub elements from the set of available combinations of the initial list. (I guess the given example makes it more clear than the explanation).

答:
This does the job :</p>

```<code>myList=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
newList=[]

while len(myList) > 0:
    print 'my entry list' + str(myList)
    tmpList = []
    stop = 0
    toRemove = [0]
    i = 0
    alreadyUsed = []
    tmpList.append(myList[i])
    for j in range (len(myList[i])):
        alreadyUsed.append(myList[i][j])
    i+=1
    while stop != 1 :
        try :
            if myList[i][0] not in alreadyUsed and myList[i][1] not in alreadyUsed:
                tmpList.append(myList[i])
                print 'tmpList' + str(tmpList)
                for j in range (len(myList[i])):
                    alreadyUsed.append(myList[i][j])
                toRemove.append(i)
            i+=1
        except IndexError:
            print 'No more elements in the list'
            stop = 1
    newList.append(tmpList)
    while len(toRemove) > 0 :
        x = toRemove[-1]
        del myList[x]
        del toRemove[-1]

print newList
</code>```

Body:
I have a list of lists as follows:

mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]

What I would like to do is iterate through mylist and produce a new list like this:

result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]

In other words, make a list of lists, where each list contains unique combinations of entries of the initial list, so that a letter is not present twice in each entry of result list. Also each time an entry is added to result, we abstract it's sub elements from the set of available combinations of the initial list. (I guess the given example makes it more clear than the explanation).

Body:
This does the job :

myList=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
newList=[]

while len(myList) > 0:
    print 'my entry list' + str(myList)
    tmpList = []
    stop = 0
    toRemove = [0]
    i = 0
    alreadyUsed = []
    tmpList.append(myList[i])
    for j in range (len(myList[i])):
        alreadyUsed.append(myList[i][j])
    i+=1
    while stop != 1 :
        try :
            if myList[i][0] not in alreadyUsed and myList[i][1] not in alreadyUsed:
                tmpList.append(myList[i])
                print 'tmpList' + str(tmpList)
                for j in range (len(myList[i])):
                    alreadyUsed.append(myList[i][j])
                toRemove.append(i)
            i+=1
        except IndexError:
            print 'No more elements in the list'
            stop = 1
    newList.append(tmpList)
    while len(toRemove) > 0 :
        x = toRemove[-1]
        del myList[x]
        del toRemove[-1]

print newList


问:
NewtonSoft JSON DeserializeXmlNode exception
I have a simple json body

```<code>   "widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": {
        "src": "Images/Sun.png",
        "name": "sun1",
        "horizontal@Offset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}
</code>```

So during deserialization using

```<code> xmldoc = JsonConvert.DeserializeXmlNode(jsonBody, "widget")
</code>```

I am getting this exception

```<code>The '@' character, hexadecimal value 0x40, cannot be included in a name.
</code>```

My question is there any naming convention for NewtonSoft JSON parser, as it is not able to convert '@' character? If not, how to get rid of this exception?

答: As the error says @ is not valid character in the xml element's name as per W3C https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Name .You might have to change horizontal@Offset</p>

Body:
I have a simple json body

   "widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": {
        "src": "Images/Sun.png",
        "name": "sun1",
        "horizontal@Offset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}

So during deserialization using

 xmldoc = JsonConvert.DeserializeXmlNode(jsonBody, "widget")

I am getting this exception

The '@' character, hexadecimal value 0x40, cannot be included in a name.

My question is there any naming convention for NewtonSoft JSON parser, as it is not able to convert '@' character? If not, how to get rid of this exception?


问:
Update records from MySQL to SQL Server
I have the same tables in two different databases, one is on MySQL and the other one on SQL Server. I want to run a query to get the data from a MySQL table to a SQL Server table to update the records on daily basis.

E.g. I have 200 record in MySQL today by tomorrow it might be 300. I want to update 200 records today and the only 100 new record tomorrow.

Can any one help me please?

Thanks in advance

答:
There is no straight forward way for this. But you can approach this way

Use mysqldump to create a dump of the table data.

restore that in your SQL Server in a temporary / auxiliary table.

perform the update to main table JOIN with that temporary table.

delete the temporary table

Title: Update records from MySQL to SQL Server


问:
How do i set the cursor in a html editor using IE (7-8)
Actually i am trying to set the cursor to a specific node inside a html editor (which uses a contenteditable iframe). For example i have several paragraphs and want the cursor to move to the start of the previous paragraph.
Unfortunatly, the Internet Explorers range object does not support setStartBefore and setStartAfter. The ierange project is not an option - the solution i am looking for needs to work with IE out of the box.

How do i set the cursor in IE?

In Firefox the solution is straight forward:

```<code>// sets the cursor position (start defines, if cursor is needed at the start or end of the node)
function setCursor(editor, node, start){

var tn = editor.getDoc().createTextNode("."); // gets the editors document
  if (start){
    node.insertBefore(tn, node.firstChild);
  }
  else node.appendChild(tn);

  rng = editor.selection.getRng();  // gets the browsers range object for the users selection
  rng.selectNode(tn);
  rng.setStartBefore(tn);
  rng.setStartAfter(tn);

  ed.selection.setRng(rng);
  node.removeChild(tn);  // removes the caret node - curser is placed now
}
</code>```

答:
You could use my Rangy project for this. The code would then be the same in all browsers:

```<code>function setCursor(element, start) {
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;

    rangy.init();
    var range = rangy.createRange(doc);
    range.selectNodeContents(element);
    range.collapse(start);
    rangy.getSelection(win).setSingleRange(range);
}
</code>```

Alternatively, this particular case isn't too tricky without a library:

```<code>function setCursor(element, start) {
    var doc = element.ownerDocument || element.document;
    if (typeof doc.createRange != "undefined") {
        var range = doc.createRange();
        range.selectNodeContents(element);
        range.collapse(start);
        var win = doc.defaultView || doc.parentWindow;
        var sel = win.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof doc.body.createTextRange != "undefined") {
        var textRange = doc.body.createTextRange();
        if (start) {
            textRange.moveToElementText(element);
            textRange.collapse(start);
        } else {
            var markerEl = doc.createElement("span");
            markerEl.innerHTML = "\u00A0";
            element.appendChild(markerEl);
            textRange.moveToElementText(markerEl);
            element.removeChild(markerEl);
        }
        textRange.select();
    }
}
</code>```

Body:
Actually i am trying to set the cursor to a specific node inside a html editor (which uses a contenteditable iframe). For example i have several paragraphs and want the cursor to move to the start of the previous paragraph.
Unfortunatly, the Internet Explorers range object does not support setStartBefore and setStartAfter. The ierange project is not an option - the solution i am looking for needs to work with IE out of the box.

How do i set the cursor in IE?

In Firefox the solution is straight forward:

// sets the cursor position (start defines, if cursor is needed at the start or end of the node)
function setCursor(editor, node, start){

var tn = editor.getDoc().createTextNode("."); // gets the editors document
  if (start){
    node.insertBefore(tn, node.firstChild);
  }
  else node.appendChild(tn);

  rng = editor.selection.getRng();  // gets the browsers range object for the users selection
  rng.selectNode(tn);
  rng.setStartBefore(tn);
  rng.setStartAfter(tn);

  ed.selection.setRng(rng);
  node.removeChild(tn);  // removes the caret node - curser is placed now
}

Body:
You could use my Rangy project for this. The code would then be the same in all browsers:

function setCursor(element, start) {
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;

    rangy.init();
    var range = rangy.createRange(doc);
    range.selectNodeContents(element);
    range.collapse(start);
    rangy.getSelection(win).setSingleRange(range);
}

Alternatively, this particular case isn't too tricky without a library:

function setCursor(element, start) {
    var doc = element.ownerDocument || element.document;
    if (typeof doc.createRange != "undefined") {
        var range = doc.createRange();
        range.selectNodeContents(element);
        range.collapse(start);
        var win = doc.defaultView || doc.parentWindow;
        var sel = win.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof doc.body.createTextRange != "undefined") {
        var textRange = doc.body.createTextRange();
        if (start) {
            textRange.moveToElementText(element);
            textRange.collapse(start);
        } else {
            var markerEl = doc.createElement("span");
            markerEl.innerHTML = "\u00A0";
            element.appendChild(markerEl);
            textRange.moveToElementText(markerEl);
            element.removeChild(markerEl);
        }
        textRange.select();
    }
}


问:
Difference between struct static func vs class static func in swift?
I am not able to find any difference between class static function to struct static function. As I know class static function can not be inherited and struct does not have an option for inheritance.

Please do not get confused by static func and class func in class.

```<code>class a {
    static func myMethod1() {
    }
}
</code>```

vs

```<code>struct a {
    static func myMethod1() {
    }
}
</code>```

答:
This is kind of a stretch, but due to the reference vs value semantics of class and struct types, respectively, there is subtle difference in in the realization of a case where you want to make use of a type method (static) to mutate a private property of the type, given an instance of the type has been supplied. Again, kind of a stretch, as this focuses on differences in implementation details, and not on a concrete difference between the two.

In the class case, an immutable reference can be supplied to the static method, which in turn can be used to mutate a private instance member of the type. In the case of the struct, the instance of the type naturally needs to be supplied as an inout parameter, as changing the value of an instance member of a value type also means changing the value of the instance itself.

```<code>class A {
    private(set) var i: Int = 0
    static func foo(_ bar: A) {
        bar.i = 42
    }
}

struct B {
    private(set) var i: Int = 0
    static func foo(_ bar: inout B) {
        bar.i = 42
    }
}

let a = A()
var b = B()

A.foo(a)
print(a.i) // 42
B.foo(&b)
print(b.i) // 42
</code>```

Body:
I am not able to find any difference between class static function to struct static function. As I know class static function can not be inherited and struct does not have an option for inheritance.

Please do not get confused by static func and class func in class.

class a {
    static func myMethod1() {
    }
}

vs

struct a {
    static func myMethod1() {
    }
}

Body:
This is kind of a stretch, but due to the reference vs value semantics of class and struct types, respectively, there is subtle difference in in the realization of a case where you want to make use of a type method (static) to mutate a private property of the type, given an instance of the type has been supplied. Again, kind of a stretch, as this focuses on differences in implementation details, and not on a concrete difference between the two.

In the class case, an immutable reference can be supplied to the static method, which in turn can be used to mutate a private instance member of the type. In the case of the struct, the instance of the type naturally needs to be supplied as an inout parameter, as changing the value of an instance member of a value type also means changing the value of the instance itself.

class A {
    private(set) var i: Int = 0
    static func foo(_ bar: A) {
        bar.i = 42
    }
}

struct B {
    private(set) var i: Int = 0
    static func foo(_ bar: inout B) {
        bar.i = 42
    }
}

let a = A()
var b = B()

A.foo(a)
print(a.i) // 42
B.foo(&b)
print(b.i) // 42


问:
How can I implement DbContext Connection String in .NET Core?
My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.

Pass connection string to code-first DbContext

My specific code is as follows:

```<code>public partial class CompanyFormsContext : DbContext
{
    public CompanyFormsContext()
        : base("name=CompanyFormsContext")
    {
    }

    public CompanyFormsContext(string connName)
        : base("name=" + connName)
    {
    }
    ...
}
</code>```

I get an error saying:

Error  CS1503  Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions'    CompanyForms..NETCoreApp,Version=v1.0

when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).

What is the correct way of implementing this functionality in .NET Core?

Edit:

I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)

```<code>  "Data": {
    "CompanyFormsContext": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    },
    "CompanyFormsContextQA": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    }
  }
</code>```

and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?

From the link:

```<code>services.AddEntityFramework(Configuration)
    .AddSqlServer()
    .AddDbContext<MyDbContext>(
        options =>
        options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
    );
</code>```

Do I need this kind of a service in my Startup.cs?

答:
IMO best practice:

add to your configuration.json:

```<code>     "ConnectionStrings": {
    "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
  }
</code>```

and to initialize section:

```<code>services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));
</code>```

Body:
My situation is quite similar to this link or at least my code is similar and I am trying to find a way to apply this same method in .NET Core syntax.

Pass connection string to code-first DbContext

My specific code is as follows:

public partial class CompanyFormsContext : DbContext
{
    public CompanyFormsContext()
        : base("name=CompanyFormsContext")
    {
    }

    public CompanyFormsContext(string connName)
        : base("name=" + connName)
    {
    }
    ...
}

I get an error saying:

Error  CS1503  Argument 1: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions'    CompanyForms..NETCoreApp,Version=v1.0

when I go over the parenthesis in base("name=CompanyFormsContext") or base("name=" = connName).

What is the correct way of implementing this functionality in .NET Core?

Edit:

I wanted to share that I have the following information for database connection in my appsettings.json file: (However, I do not have settings in the startup.cs)

  "Data": {
    "CompanyFormsContext": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    },
    "CompanyFormsContextQA": {
      "ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
    }
  }

and I have found the following link Adding DbContextOptions in Startup.cs not registering data store in the website and I am wondering if a simple protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) will be enough to fix my connection or not?

From the link:

services.AddEntityFramework(Configuration)
    .AddSqlServer()
    .AddDbContext<MyDbContext>(
        options =>
        options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
    );

Do I need this kind of a service in my Startup.cs?

Body:
IMO best practice:

add to your configuration.json:

     "ConnectionStrings": {
    "BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
  }

and to initialize section:

services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));


问:
how to convert the new input non-numerical-data into numerical data
OUTLINE:
I want to know how to keep the new input non-numerical-data as the unique one!

DESCRIBE:
Namely, when we finish both train and test period, lot of new data that unions numerical and non-numerical data input into my model.

ISSUE(1):
 Thus, the first important matter is convert these new mixed data into a dataframe with all numerical format!!

TRIED METHOD:

How can we do that? I used LabelEncoder to transform every non-numerical data into float type, however, the member of SCIKIT-LEARN feedbacked me that LabelEncoder is only available for Label[Y] and I should use OneHotEncoder
convert feature.
[He answered me at URL: https://github.com/scikit-learn/scikit-learn/issues/8674], while misunderstanding my meaning

Unfortunately, OneHotEncoder is only available for integer feature by SCIKIT-LEARN Official documentation said in p.1829.

I know there is a title about 'Feature Union with Heterogeneous Data Sources', while it is not convenient as LabelEncoder does.
ISSUE(2):
The second reason why such issue confuses me is related to how we can ensure the input new non-numerical data can be transform into an unique value that differs from the previous-transformed-training-data or previous-transformed-test-data. Namely, although we can use LabelEncoder transform new input data into numerical data, there is a risk that the transformed data[in the new input data yield] might be equal to the transformed data[in the previous transformed data]

Thanks for your help in advance

答:
OK, I have been answered by the official guys. The follow URL maybe helpful for somebody who confused about this issue.

https://github.com/amueller/introduction_to_ml_with_python/blob/master/04-representing-data-feature-engineering.ipynb


问:
Excel Sheet SQL Table
I have an Excel sheet. The top row corresponds to column names while successive rows each represent an entry.

How can I convert this Excel sheet into a SQL Table?

I am using SQL Server 2005.

答: That depends on which program you use for SQL . If you have SQL-Server installed. SSIS Import and Export Wizard SSIS Import and Export Wizard  would be a good choice.</p>

Title: Excel Sheet SQL Table


问:
error in csproj - duplicate item
I have error from visual studio 2010:

Error 1   The item "CrossDomainService.svc.cs" was specified more than once in the "Sources" parameter.  Duplicate items are not supported by the "Sources" parameter.    WcfServiceDomain

and from msbuild

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.targets(160,9)
  : error MSB3105: The item "CrossDomainService.svc.cs" was specified more than o
  nce in the "Sources" parameter.  Duplicate items are not supported by the "Sources" parameter. [C:\inetpub\Wwwroot\axaptaWcfConnection\WcfServiceDomain\WcfSer
  viceDomain.csproj]

My file is csproj:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{8D40933A-E036-4CD0-9003-314A692724D5}</ProjectGuid>
    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>WcfServiceDomain</RootNamespace>
    <AssemblyName>WcfServiceDomain</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <TargetFrameworkProfile />
    <FileUpgradeFlags>
    </FileUpgradeFlags>
    <UpgradeBackupLocation>
    </UpgradeBackupLocation>
    <OldToolsVersion>4.0</OldToolsVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System.Web.ApplicationServices" />
    <Reference Include="System.Web.DynamicData" />
    <Reference Include="System.Web.Entity" />
    <Reference Include="System.Configuration" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.EnterpriseServices" />
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
    <Reference Include="System.ServiceModel.Web" />
    <Reference Include="System.Web.Services" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="ClientAccessPolicy.xml" />
    <Content Include="CrossDomainService.svc" />
    <Content Include="Service1.svc" />
    <Content Include="Web.config">
      <SubType>Designer</SubType>
    </Content>
    <Content Include="Web.Debug.config">
      <DependentUpon>Web.config</DependentUpon>
    </Content>
    <Content Include="Web.Release.config">
      <DependentUpon>Web.config</DependentUpon>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="CrossDomainService.svc.cs">
      <DependentUpon>CrossDomainService.svc</DependentUpon>
    </Compile>
    <Compile Include="ICrossDomainService.cs" />
    <Compile Include="Service1.svc.cs">
      <DependentUpon>Service1.svc</DependentUpon>
    </Compile>
    <Compile Include="IService1.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <UseIIS>False</UseIIS>
          <AutoAssignPort>True</AutoAssignPort>
          <DevelopmentServerPort>51421</DevelopmentServerPort>
          <DevelopmentServerVPath>/</DevelopmentServerVPath>
          <IISUrl>
          </IISUrl>
          <NTLMAuthentication>False</NTLMAuthentication>
          <UseCustomServer>False</UseCustomServer>
          <CustomServerUrl>
          </CustomServerUrl>
          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
        </WebProjectProperties>
      </FlavorProperties>
    </VisualStudio>
  </ProjectExtensions>
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
</Project>
</code>```

I not see any duplicate :/ Any idea from this error ??

答:
The way that I fixed this issue was by going to the location where the file was which was included in the error and find that there was two of the same files. Delete one of them and it should work.

I had to undo the pending changes afterwards as the files then went missing, but after a re-build it worked.

Title: error in csproj - duplicate item

Body:
I have error from visual studio 2010:

Error 1   The item "CrossDomainService.svc.cs" was specified more than once in the "Sources" parameter.  Duplicate items are not supported by the "Sources" parameter.    WcfServiceDomain

and from msbuild

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.CSharp.targets(160,9)
  : error MSB3105: The item "CrossDomainService.svc.cs" was specified more than o
  nce in the "Sources" parameter.  Duplicate items are not supported by the "Sources" parameter. [C:\inetpub\Wwwroot\axaptaWcfConnection\WcfServiceDomain\WcfSer
  viceDomain.csproj]

My file is csproj:

    <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{8D40933A-E036-4CD0-9003-314A692724D5}</ProjectGuid>
    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>WcfServiceDomain</RootNamespace>
    <AssemblyName>WcfServiceDomain</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <TargetFrameworkProfile />
    <FileUpgradeFlags>
    </FileUpgradeFlags>
    <UpgradeBackupLocation>
    </UpgradeBackupLocation>
    <OldToolsVersion>4.0</OldToolsVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System.Web.ApplicationServices" />
    <Reference Include="System.Web.DynamicData" />
    <Reference Include="System.Web.Entity" />
    <Reference Include="System.Configuration" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.EnterpriseServices" />
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
    <Reference Include="System.ServiceModel.Web" />
    <Reference Include="System.Web.Services" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="ClientAccessPolicy.xml" />
    <Content Include="CrossDomainService.svc" />
    <Content Include="Service1.svc" />
    <Content Include="Web.config">
      <SubType>Designer</SubType>
    </Content>
    <Content Include="Web.Debug.config">
      <DependentUpon>Web.config</DependentUpon>
    </Content>
    <Content Include="Web.Release.config">
      <DependentUpon>Web.config</DependentUpon>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="CrossDomainService.svc.cs">
      <DependentUpon>CrossDomainService.svc</DependentUpon>
    </Compile>
    <Compile Include="ICrossDomainService.cs" />
    <Compile Include="Service1.svc.cs">
      <DependentUpon>Service1.svc</DependentUpon>
    </Compile>
    <Compile Include="IService1.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <UseIIS>False</UseIIS>
          <AutoAssignPort>True</AutoAssignPort>
          <DevelopmentServerPort>51421</DevelopmentServerPort>
          <DevelopmentServerVPath>/</DevelopmentServerVPath>
          <IISUrl>
          </IISUrl>
          <NTLMAuthentication>False</NTLMAuthentication>
          <UseCustomServer>False</UseCustomServer>
          <CustomServerUrl>
          </CustomServerUrl>
          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
        </WebProjectProperties>
      </FlavorProperties>
    </VisualStudio>
  </ProjectExtensions>
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
</Project>

I not see any duplicate :/ Any idea from this error ??


问:
Invalid signature for SetUp or TearDown method - What am I doing wrong?
I am trying to do some dependency injection for my tests using nUnit. I'm new to TDD and nUnit so it's possible I am missing something simple. So basically I've created a SetUp method for my interfaces. I originally was using a constructor but I read it's bad to do this when doing TDD so I now using a method.

When I run my test I construct an object and assign it to the interface and then I call a method using that interface. I want to test if it can parse a string decimal.

When I run my test it says test failed and the message is:Invalid signature for SetUp or TearDown method

See below for the actual code:

```<code> public class DonorTests
    {
        private IDonor _Donor;
        private IValidateInput _ValidInput;

        //DonorTests(IDonor donor, IValidateInput validInput)
        //{
        //    _Donor = donor;
        //    _ValidInput = validInput;
        //}

        [SetUp]
        void Setup(IDonor donor, IValidateInput validInput)
        {
            _Donor = donor;
            _ValidInput = validInput;
        }

        [Test]
        public void HandleStringNotDecimal()
        {
            _ValidInput = new ValidateInput();
            Assert.IsTrue(_ValidInput.IsDecimal("3445.3450"));
        }
    }
</code>```

My class that uses this interface

```<code> public class ValidateInput : IValidateInput
    {
        public decimal RoundTwoDecimalPlaces(decimal amount)
        {
            return Math.Round(amount);
        }

        public bool IsDecimal(string amount)
        {
            decimal ParsedDecimal;
            return Decimal.TryParse(amount, out ParsedDecimal);
        }

        public decimal ConvertToString(string value)
        {
            decimal ParsedDecimal;
            Decimal.TryParse(value, out ParsedDecimal);
            return ParsedDecimal;
        }
    }
</code>```

答:
Besides the cause mentioned in the accepted answer, I have met the same error when leaving method as non-public (private  or protected).

NUnit most probably relies on reflection and does not deal with non-public methods, so special methods (i.e. decorated with NUnit specific attributes) must be public.

Body:
I am trying to do some dependency injection for my tests using nUnit. I'm new to TDD and nUnit so it's possible I am missing something simple. So basically I've created a SetUp method for my interfaces. I originally was using a constructor but I read it's bad to do this when doing TDD so I now using a method.

When I run my test I construct an object and assign it to the interface and then I call a method using that interface. I want to test if it can parse a string decimal.

When I run my test it says test failed and the message is:Invalid signature for SetUp or TearDown method

See below for the actual code:

 public class DonorTests
    {
        private IDonor _Donor;
        private IValidateInput _ValidInput;

        //DonorTests(IDonor donor, IValidateInput validInput)
        //{
        //    _Donor = donor;
        //    _ValidInput = validInput;
        //}

        [SetUp]
        void Setup(IDonor donor, IValidateInput validInput)
        {
            _Donor = donor;
            _ValidInput = validInput;
        }

        [Test]
        public void HandleStringNotDecimal()
        {
            _ValidInput = new ValidateInput();
            Assert.IsTrue(_ValidInput.IsDecimal("3445.3450"));
        }
    }

My class that uses this interface

 public class ValidateInput : IValidateInput
    {
        public decimal RoundTwoDecimalPlaces(decimal amount)
        {
            return Math.Round(amount);
        }

        public bool IsDecimal(string amount)
        {
            decimal ParsedDecimal;
            return Decimal.TryParse(amount, out ParsedDecimal);
        }

        public decimal ConvertToString(string value)
        {
            decimal ParsedDecimal;
            Decimal.TryParse(value, out ParsedDecimal);
            return ParsedDecimal;
        }
    }


问:
Returns posts with most recent comments by user as well as posts with no comments
Using Rails and Postgres I'm working on a complex SQL query to return all posts with the following conditions:

The last comment published for each post was not authored by a specific user; OR

The post has no comments

I've built the query to return posts where the last comment published was not authored by that specific user, but I can't work out how to modify this to also return the posts which don't have a comment.

```<code> Post
  .joins(:comments)
  .joins(
    "INNER JOIN (
      SELECT DISTINCT ON (commentable_type, commentable_id) commentable_type, commentable_id, id
      FROM comments
      WHERE comments.author_id != #{user.id}
      ORDER BY commentable_type, commentable_id, created_at DESC, id
    ) most_recent_comments ON (
      most_recent_comments.id = comments.id
    )"
  )
</code>```

Any advice?

答:
Think I've figured it out actually. I need to use includes to do a left outer join on comments and then do the same in the second joins method:

```<code> Post
  .includes(:comments)
  .joins(
    "LEFT outer JOIN (
      SELECT DISTINCT ON (commentable_type, commentable_id) commentable_type, commentable_id, id
      FROM comments
      WHERE comments.author_id != #{user.id}
      ORDER BY commentable_type, commentable_id, created_at DESC, id
    ) most_recent_comments ON (
      most_recent_comments.id = comments.id
    )"
  )
</code>```

Body:
Using Rails and Postgres I'm working on a complex SQL query to return all posts with the following conditions:

The last comment published for each post was not authored by a specific user; OR

The post has no comments

I've built the query to return posts where the last comment published was not authored by that specific user, but I can't work out how to modify this to also return the posts which don't have a comment.

 Post
  .joins(:comments)
  .joins(
    "INNER JOIN (
      SELECT DISTINCT ON (commentable_type, commentable_id) commentable_type, commentable_id, id
      FROM comments
      WHERE comments.author_id != #{user.id}
      ORDER BY commentable_type, commentable_id, created_at DESC, id
    ) most_recent_comments ON (
      most_recent_comments.id = comments.id
    )"
  )

Any advice?

Body:
Think I've figured it out actually. I need to use includes to do a left outer join on comments and then do the same in the second joins method:

 Post
  .includes(:comments)
  .joins(
    "LEFT outer JOIN (
      SELECT DISTINCT ON (commentable_type, commentable_id) commentable_type, commentable_id, id
      FROM comments
      WHERE comments.author_id != #{user.id}
      ORDER BY commentable_type, commentable_id, created_at DESC, id
    ) most_recent_comments ON (
      most_recent_comments.id = comments.id
    )"
  )


问:
Determining which unique constraint caused INSERT failure in ArangoDB
I have a document collection in ArangoDB that has multiple unique indexes. When inserting a new document, the insert could fail because of any of the unique indexes. Is there a way to easily figure out which field(s) in the document caused the insert to fail?

For example, take a collection that stores user data. Unique indexes on both the "username" and "email" fields mean that an insert could fail if either of those fields are duplicated.

Error messages are non-specific:

```<code>{
    error: true,
    errorMessage: 'unique constraint violated (while executing)',
    code: 409,
    errorNum: 1210
}
</code>```

The long way around would be to input/update these unique fields separately to know for certain which field violated the unique constraint. Or try retrieving documents that match our input values to identify if there would be a collision before trying to insert. I just have a feeling that there must be a simpler way.

Is there a way to return the field name along with the error? Or am I approaching the problem from entirely the wrong angle?

Would really appreciate any thoughts or suggestions. Thanks.

答:
I'm sorry, there is currently no smart way to achieve this.
The only way to handle this today, is to do a subsequent select with a FILTER to the values you tried to insert:

```<code>FOR doc IN collection
  FILTER doc.firstindexed = 'firstvalue'
      OR doc.secondindexed = 'secondvalue'
    RETURN doc
</code>```

Body:
I have a document collection in ArangoDB that has multiple unique indexes. When inserting a new document, the insert could fail because of any of the unique indexes. Is there a way to easily figure out which field(s) in the document caused the insert to fail?

For example, take a collection that stores user data. Unique indexes on both the "username" and "email" fields mean that an insert could fail if either of those fields are duplicated.

Error messages are non-specific:

{
    error: true,
    errorMessage: 'unique constraint violated (while executing)',
    code: 409,
    errorNum: 1210
}

The long way around would be to input/update these unique fields separately to know for certain which field violated the unique constraint. Or try retrieving documents that match our input values to identify if there would be a collision before trying to insert. I just have a feeling that there must be a simpler way.

Is there a way to return the field name along with the error? Or am I approaching the problem from entirely the wrong angle?

Would really appreciate any thoughts or suggestions. Thanks.

Body:
I'm sorry, there is currently no smart way to achieve this.
The only way to handle this today, is to do a subsequent select with a FILTER to the values you tried to insert:

FOR doc IN collection
  FILTER doc.firstindexed = 'firstvalue'
      OR doc.secondindexed = 'secondvalue'
    RETURN doc