问:
Responsive Grid layout issue with Dynamic content (issue with IE 11 only)
I am using bootstrap 4 beta and came across layout problem while generating Dynamic contents for Responsive Grid. All browser seems working fine except IE 11 (Edge work just fine).

If i keep Layout static, everything looks smooth as shown below and here is
bootply code.

Now if i change it to dynamically generate data and fill in div, it start giving me problem in layout IE 11 and here is bootply code.

Every thing is working just fine in Firefox, Chrome and Edge but only start showing issue with IE 11.

Adding code sample, you can save these files as html and test in IE11 and you will see the problem.

Static Code sample

```<code><html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        function openWindow()
        {
            $('#myModal').modal({show:true})
        }
        </script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" crossorigin="anonymous"></script>
</head>
<body>
    <a class="btn btn-default" id="openBtn" href="#" onclick="openWindow();">Open modal</a>

    <div tabindex="-1" class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
        <div class="modal-body">
          <h4 class="g-mb-10 g-color-primary g-font-weight-600 text-capitalize">Company Name INC. <span class="h5 g-color-black">123343244</span></h4><div><div class="row"><div class="col-xl-12 col-xs-12 g-mb-15"><ul class="list-unstyled g-color-gray-dark-v5 g-font-size-13"><li class="media"><i class="d-flex mt-1 mr-3 icon-hotel-restaurant-235 u-line-icon-pro"></i><div class="media-body">68 SOME AREA ST, QUEENS, NY, 11345 - 6345, United States</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-001 u-line-icon-pro"></i><div class="media-body">http://www.microsoft.com</div></li></ul></div></div><div class="row"><div class="col-xl-6 col-lg-6 col-md-12 col-xs-12 g-mb-5"><ul class="list-unstyled g-color-gray-dark-v5 g-font-size-13"><li class="g-color-black g-font-weight-600 text-capitalize">Bill CLINTON</li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-033 u-line-icon-pro"></i><div class="media-body">800 852 3543</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-155 u-line-icon-pro"></i><div class="media-body">800 852 3543</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-062 u-line-icon-pro"></i><div class="media-body">support@microsoft.com</div></li></ul></div><div class="col-xl-6 col-lg-6 col-md-12 col-xs-12 g-mb-5"><ul class="list-unstyled g-color-gray-dark-v5 g-font-size-13"><li class="g-color-black g-font-weight-600 text-capitalize">Bill CLINTON</li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-033 u-line-icon-pro"></i><div class="media-body">800 852 3543 ext 205</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-155 u-line-icon-pro"></i><div class="media-body">800 852 3543</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-062 u-line-icon-pro"></i><div class="media-body">support@microsoft.com</div></li></ul></div></div></div>
        </div>
        <div class="modal-footer">
            <button class="btn" data-dismiss="modal">Close</button>
        </div>
        </div>
    </div>
    </div>
<body>
</html>
</code>```

Dynamic Code sample

```<code><html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        function openWindow()
        {
          $('#innerData').html('<h4 class="g-mb-10 g-color-primary g-font-weight-600 text-capitalize">Company Name INC. <span class="h5 g-color-black">123343244</span></h4><div><div class="row"><div class="col-xl-12 col-xs-12 g-mb-15"><ul class="list-unstyled g-color-gray-dark-v5 g-font-size-13"><li class="media"><i class="d-flex mt-1 mr-3 icon-hotel-restaurant-235 u-line-icon-pro"></i><div class="media-body">68 SOME AREA ST, QUEENS, NY, 11345 - 6345, United States</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-001 u-line-icon-pro"></i><div class="media-body">http://www.microsoft.com</div></li></ul></div></div><div class="row"><div class="col-xl-6 col-lg-6 col-md-12 col-xs-12 g-mb-5"><ul class="list-unstyled g-color-gray-dark-v5 g-font-size-13"><li class="g-color-black g-font-weight-600 text-capitalize">Bill CLINTON</li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-033 u-line-icon-pro"></i><div class="media-body">800 852 3543</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-155 u-line-icon-pro"></i><div class="media-body">800 852 3543</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-062 u-line-icon-pro"></i><div class="media-body">support@microsoft.com</div></li></ul></div><div class="col-xl-6 col-lg-6 col-md-12 col-xs-12 g-mb-5"><ul class="list-unstyled g-color-gray-dark-v5 g-font-size-13"><li class="g-color-black g-font-weight-600 text-capitalize">Bill CLINTON</li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-033 u-line-icon-pro"></i><div class="media-body">800 852 3543 ext 205</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-155 u-line-icon-pro"></i><div class="media-body">800 852 3543</div></li><li class="media"><i class="d-flex mt-1 mr-3 icon-communication-062 u-line-icon-pro"></i><div class="media-body">support@microsoft.com</div></li></ul></div></div></div>');

            $('#myModal').modal({show:true})
        }
        </script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" crossorigin="anonymous">
    <script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" crossorigin="anonymous"></script>
</head>
<body>
    <a class="btn btn-default" id="openBtn" href="#" onclick="openWindow();">Open modal</a>

    <div tabindex="-1" class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
        <div class="modal-body">
          <label id="innerData"/>
        </div>
        <div class="modal-footer">
            <button class="btn" data-dismiss="modal">Close</button>
        </div>
        </div>
    </div>
    </div>
<body>
</html>
</code>```

答:
Alright, after finding no help on anywhere i kind of figured out by debugging css line by line.
Once added this in header problem goes away (at least for IE11, which was my primary concern)

```<code><style>
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
     .inblock_issue{display:block;}
}
</style>
</code>```

And don't forget to add class "inblock_issue" to div.

Body:
I am using bootstrap 4 beta and came across layout problem while generating Dynamic contents for Responsive Grid. All browser seems working fine except IE 11 (Edge work just fine).

If i keep Layout static, everything looks smooth as shown below and here is
bootply code.

Now if i change it to dynamically generate data and fill in div, it start giving me problem in layout IE 11 and here is bootply code.

Every thing is working just fine in Firefox, Chrome and Edge but only start showing issue with IE 11.

Adding code sample, you can save these files as html and test in IE11 and you will see the problem.

Static Code sample

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" crossorigin="anonymous">

    Open modal

Company Name INC. 123343244

68 SOME AREA ST, QUEENS, NY, 11345 - 6345, United States

http://www.microsoft.com

Bill CLINTON

800 852 3543

800 852 3543

support@microsoft.com

Bill CLINTON

800 852 3543 ext 205

800 852 3543

support@microsoft.com

            <button class="btn" data-dismiss="modal">Close</button>

Dynamic Code sample

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" crossorigin="anonymous">

    Open modal

            <button class="btn" data-dismiss="modal">Close</button>

Body:
Alright, after finding no help on anywhere i kind of figured out by debugging css line by line.
Once added this in header problem goes away (at least for IE11, which was my primary concern)

<style>
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
     .inblock_issue{display:block;}
}
</style>

And don't forget to add class "inblock_issue" to div.


来源: stackexchange

问:
time data does not match format
I get the following error:

```<code>time data '07/28/2014 18:54:55.099000' does not match format '%d/%m/%Y %H:%M:%S.%f'
</code>```

But I cannot see what parameter is wrong in %d/%m/%Y %H:%M:%S.%f ?

This is the code I use.

```<code>from datetime import datetime
time_value = datetime.strptime(csv_line[0] + '000', '%d/%m/%Y %H:%M:%S.%f')
</code>```

I have added and removed the 000 but I get the same error.

答:
While the above answer is 100% helpful and correct, I'd like to add the following since only a combination of the above answer and reading through the pandas doc helped me:

2-digit / 4-digit year

It is noteworthy, that in order to parse through a 2-digit year, e.g. '90' rather than '1990', a %y is required instead of a %Y.

Infer the datetime automatically

If parsing with a pre-defined format still doesn't work for you, try using the flag infer_datetime_format=True, for example:

```<code>yields_df['Date'] = pd.to_datetime(yields_df['Date'], infer_datetime_format=True)
</code>```

Be advised that this solution is slower than using a pre-defined format.

ContentLicense: CC BY-SA 3.0

Title: time data does not match format

Body:
I get the following error:

time data '07/28/2014 18:54:55.099000' does not match format '%d/%m/%Y %H:%M:%S.%f'

But I cannot see what parameter is wrong in %d/%m/%Y %H:%M:%S.%f ?

This is the code I use.

from datetime import datetime
time_value = datetime.strptime(csv_line[0] + '000', '%d/%m/%Y %H:%M:%S.%f')

I have added and removed the 000 but I get the same error.

Body:
While the above answer is 100% helpful and correct, I'd like to add the following since only a combination of the above answer and reading through the pandas doc helped me:

2-digit / 4-digit year

It is noteworthy, that in order to parse through a 2-digit year, e.g. '90' rather than '1990', a %y is required instead of a %Y.

Infer the datetime automatically

If parsing with a pre-defined format still doesn't work for you, try using the flag infer_datetime_format=True, for example:

yields_df['Date'] = pd.to_datetime(yields_df['Date'], infer_datetime_format=True)

Be advised that this solution is slower than using a pre-defined format.


问:
iOS - Not able to access Static method of swift class
I want to access Swift code in Objective-c.

I have written one class in swift which contains static method. I want to access that Static Method in objective C Class.

Here is Class declaration:

```<code>@objc class LocalizedResource: NSObject {

    /*!
    * @discussion This function will get localize string for key

    * @param key Localize key
    * @return String for locaized key
    * @code LocalizedResource.getStringForKey(key);
    */
    static func getStringForKey(key:String) -> String    {
        let frameworkBundle = NSBundle.mainBundle()
        let value = frameworkBundle.localizedStringForKey(key, value: nil, table: nil)
        return value;
    }
}
</code>```

I have made following settings for it:

Product Module Name : MyProject

Defines Module : YES

Embedded Content Contains Swift : YES

Install Objective-C Compatibility Header : YES

Objective-C Bridging Header : $(SRCROOT)/MySources/SwiftBridgingHeader.h

Also I have added @Obj before my class declaration in Swift class.

I have import MyProject-Swift.h in the .m file where I want to access that method.

But when I am trying to access it, it is not allowing me to access that static method.

Is any one having solution for it? Is there something missing?

Thnaks.

答: Note in Swift 4 and the build setting swift 3 @objc inference is default, we must explicitly mark function as @objc, or it will not generate class function in Swift bridge header.

Body:
I want to access Swift code in Objective-c.

I have written one class in swift which contains static method. I want to access that Static Method in objective C Class.

Here is Class declaration:

@objc class LocalizedResource: NSObject {

    /*!
    * @discussion This function will get localize string for key

    * @param key Localize key
    * @return String for locaized key
    * @code LocalizedResource.getStringForKey(key);
    */
    static func getStringForKey(key:String) -> String    {
        let frameworkBundle = NSBundle.mainBundle()
        let value = frameworkBundle.localizedStringForKey(key, value: nil, table: nil)
        return value;
    }
}

I have made following settings for it:

Product Module Name : MyProject

Defines Module : YES

Embedded Content Contains Swift : YES

Install Objective-C Compatibility Header : YES

Objective-C Bridging Header : $(SRCROOT)/MySources/SwiftBridgingHeader.h

Also I have added @Obj before my class declaration in Swift class.

I have import MyProject-Swift.h in the .m file where I want to access that method.

But when I am trying to access it, it is not allowing me to access that static method.

Is any one having solution for it? Is there something missing?

Thnaks.


问:
java.lang.NullPointerException: while take photo
Im getting this error, when click deny permission in  "Allow app to access photos, media and files on your device ? "

```<code>    FATAL EXCEPTION: main
   Process: com.viantti.app, PID: 12349
   java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
</code>```

java error line,

```<code>public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}
</code>```

答:
Try the following code, since it will proceed only when all the required permissions has been allowed by the user.</p>

```<code> @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&  grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
                chooseimage();
            } else {
                finish();
            }
            break;
    }
}
</code>```

Body:
Im getting this error, when click deny permission in  "Allow app to access photos, media and files on your device ? "

    FATAL EXCEPTION: main
   Process: com.viantti.app, PID: 12349
   java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)

java error line,

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

Body:
Try the following code, since it will proceed only when all the required permissions has been allowed by the user.

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&  grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
                chooseimage();
            } else {
                finish();
            }
            break;
    }
}


问:
matplotlib numbers in legend
I have a couple of lines and I want to show a legend. The problem is, I can't use different styles (--, :, -.) because there are too few of them, and I can't use markers (+, *, etc.) because I need them to show some points on the lines.

So the best idea I've come up with is to use numbers. But I can't figure how I can create legends with numbers. I can even draw numbers near lines myself (to place them in the best position), but how can I then draw a legend with the numbers?

I.e. instead of:

```<code>--  H
-.- Li
</code>```

I'd like something like:

```<code>1  H
2  Li
</code>```

答:
Perhaps a little Latex thrown into the mix?

```<code>#In which we make a legend; not with lines, but numbers!

import pylab as pl
pl.rc('text', usetex=True)

pl.figure(1)
pl.clf()
ax = pl.subplot(111)
pl.plot(range(0,10), 'k', label = r'\makebox[25]{1\hfill}Bla')
pl.plot(range(1,11), 'k', label = r'\makebox[25]{12\hfill}Bla12')
lgd = pl.legend(handlelength = -0.4)
for k in lgd.get_lines():
k.set_linewidth(0)
pl.draw()
pl.show()
</code>```

The numbers/labels are aligned by using \makebox with specific width and \hfill to take up the space not used by your labels. Numbers are not automatic, but if you use a loop to draw your lines then you could add a counter to keep track of the numbers.

Don't know if this is part of your requirement, but the lines are removed by setting their linewidth to 0 and making the space reserved in the legend negative. Couldn't find a neater way of doing this as I believe a legend is always meant to show a line (e.g. you can't set numpoints to 0).

You could of course also just add some text in the right spot in your plot and not use a legend at all.

ContentLicense: CC BY-SA 2.5

Title: matplotlib numbers in legend

Body:
I have a couple of lines and I want to show a legend. The problem is, I can't use different styles (--, :, -.) because there are too few of them, and I can't use markers (+, *, etc.) because I need them to show some points on the lines.

So the best idea I've come up with is to use numbers. But I can't figure how I can create legends with numbers. I can even draw numbers near lines myself (to place them in the best position), but how can I then draw a legend with the numbers?

I.e. instead of:

--  H
-.- Li

I'd like something like:

1  H
2  Li

Body:
Perhaps a little Latex thrown into the mix?

#In which we make a legend; not with lines, but numbers!

import pylab as pl
pl.rc('text', usetex=True)

pl.figure(1)
pl.clf()
ax = pl.subplot(111)
pl.plot(range(0,10), 'k', label = r'\makebox[25]{1\hfill}Bla')
pl.plot(range(1,11), 'k', label = r'\makebox[25]{12\hfill}Bla12')
lgd = pl.legend(handlelength = -0.4)
for k in lgd.get_lines():
k.set_linewidth(0)
pl.draw()
pl.show()

The numbers/labels are aligned by using \makebox with specific width and \hfill to take up the space not used by your labels. Numbers are not automatic, but if you use a loop to draw your lines then you could add a counter to keep track of the numbers.

Don't know if this is part of your requirement, but the lines are removed by setting their linewidth to 0 and making the space reserved in the legend negative. Couldn't find a neater way of doing this as I believe a legend is always meant to show a line (e.g. you can't set numpoints to 0).

You could of course also just add some text in the right spot in your plot and not use a legend at all.


问:
How To fix That Json JQuery Ajax Call undefined Issuse
Php:-

```<code>$data = array();

 while($row = mysqli_fetch_array($avatar)){
    $row_data = array(
            'image' => $row['image']
    );
    array_push($data, $row_data);
 }

while($row = mysqli_fetch_array($comments)){
    $row_data = array(
            'comment' => $row['comments']
    );
    array_push($data, $row_data);
}

echo json_encode($data);
</code>```

jQuery Ajax:-

```<code>$(".comment").click(function(){

    var id  =  $(this).data("id");
    var name = $("#username_"+id).val();

    function json(){
        alert('loading please wait');
    }

    if(name==''){
        alert("Please Fill All Fields");
    }else{
        $.ajax({
            type: "POST",
            url: "comments",
            data:{comments:name,parent:id},
            success: function(json){

                $(".cmt_output").html(""+json["comments"]+""+json["image"]+"");

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

json Array Format:-

```<code>[
    {"image":"1510553412_User_Avatar_2.png"},
    {"comment":"Welcome"},
    {"comment":"Nice"},
    {"comment":"Nice"},
    {"comment":"Nice too...."}
]
</code>```

Html:-

```<code><div class="cmt_output"></div>
</code>```

Output:-

```<code>undefined undefined
</code>```

Output i want:

```<code>1510553412_User_Avatar_2.png
Welcome
Nice
Nice
Nice too
</code>```

答:
Change your success function to:

```<code>success: function(json)
{
    json = JSON.parse(json);
    json.forEach(function (item, index){
        if(item.image !== undefined)
        {
            $(".cmt_output").append(item.image);
        }
            $(".cmt_output").append(item.comments);
        })

}
</code>```

Or instead of json = JSON.parse(json); use:

```<code>dataType: 'json',
success: function(json)
{
    json.forEach(function (item, index){
        if(item.image !== undefined)
        {
            $(".cmt_output").append(item.image);
        }
            $(".cmt_output").append(item.comments);
        })

}
</code>```

Body:
Php:-

$data = array();

 while($row = mysqli_fetch_array($avatar)){
    $row_data = array(
            'image' => $row['image']
    );
    array_push($data, $row_data);
 }

while($row = mysqli_fetch_array($comments)){
    $row_data = array(
            'comment' => $row['comments']
    );
    array_push($data, $row_data);
}

echo json_encode($data);

jQuery Ajax:-

$(".comment").click(function(){

    var id  =  $(this).data("id");
    var name = $("#username_"+id).val();

    function json(){
        alert('loading please wait');
    }

    if(name==''){
        alert("Please Fill All Fields");
    }else{
        $.ajax({
            type: "POST",
            url: "comments",
            data:{comments:name,parent:id},
            success: function(json){

                $(".cmt_output").html(""+json["comments"]+""+json["image"]+"");

            }
        });
    }
});

json Array Format:-

[
    {"image":"1510553412_User_Avatar_2.png"},
    {"comment":"Welcome"},
    {"comment":"Nice"},
    {"comment":"Nice"},
    {"comment":"Nice too...."}
]

Html:-

Output:-

undefined undefined

Output i want:

1510553412_User_Avatar_2.png
Welcome
Nice
Nice
Nice too

Body:
Change your success function to:

success: function(json)
{
    json = JSON.parse(json);
    json.forEach(function (item, index){
        if(item.image !== undefined)
        {
            $(".cmt_output").append(item.image);
        }
            $(".cmt_output").append(item.comments);
        })

}

Or instead of json = JSON.parse(json); use:

dataType: 'json',
success: function(json)
{
    json.forEach(function (item, index){
        if(item.image !== undefined)
        {
            $(".cmt_output").append(item.image);
        }
            $(".cmt_output").append(item.comments);
        })

}


问:
I don't know what I'm misssing(Turtle)
I'm using Trinket to run my python.

I have been tinkering with it for days and it keeps giving me this error:

```<code>Traceback (most recent call last):   File
"/tmp/sessions/5ecd67058b43cfc0/main.py", line 2, in
    setup(500, 500)   File "", line 6, in setup   File "/usr/lib/python3.5/turtle.py", line 3662, in Screen
    Turtle._screen = _Screen()   File "/usr/lib/python3.5/turtle.py", line 3678, in __init__
    _Screen._root = self._root = _Root()   File "/usr/lib/python3.5/turtle.py", line 434, in __init__
    TK.Tk.__init__(self)   File "/usr/lib/python3.5/tkinter/__init__.py", line 1871, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
</code>```

Here is the code so far:

```<code>from turtle import *
setup(500, 500)
Screen()
title("Turtle Keys")
move = Turtle()
showturtle()
def k1():
 move.forward(100)
 move.left(90)
 move.forward(100)
 move.left(90)
 move.forward(100)
 move.left(90)
 move.forward(100)
 move.left(90)
def k2():
 move.forward(320)
 move.left(120)
 move.forward(320)
 move.left(120)
 move.forward(320)
 move.left(120)

def k3():
    move.right(45)
def k4():
 move.forward(100)
 move.left(90)
 move.forward(50)
 move.left(90)
 move.forward(100)
 move.left(90)
 move.forward(50)
 move.left(90)

def k5():
 move.left(10)

def k6():
 move.forward(10)

def k7():
 move.backward(10)

onkey(k1, "Up")
onkey(k2, "Left")
onkey(k3, "Right")
onkey(k4, "Down")
onkey(k5, "1")
onkey(k6, "2")
onkey(k7, "3")
listen()
mainloop()
</code>```

The objective is to draw certain shapes when certain keys are pressed.

答:
repl.it at least supports graphics and tells you the errors in your program instead of the unhelpful $DISPLAY variable error - Try https://repl.it/languages/python_turtle.

But it still doesn't seem to support keyboard input that you are trying to use.  If you comment out setup() and title() and also remove the onkey() / listen() code,  replacing instead with some hard calls to your functions, you can at least get some output.

Install Python locally - https://www.python.org/downloads/ - to get a full-featured environment.

Title: I don't know what I'm misssing(Turtle)

Body:
I'm using Trinket to run my python.

I have been tinkering with it for days and it keeps giving me this error:

Traceback (most recent call last):   File
"/tmp/sessions/5ecd67058b43cfc0/main.py", line 2, in
    setup(500, 500)   File "", line 6, in setup   File "/usr/lib/python3.5/turtle.py", line 3662, in Screen
    Turtle._screen = _Screen()   File "/usr/lib/python3.5/turtle.py", line 3678, in __init__
    _Screen._root = self._root = _Root()   File "/usr/lib/python3.5/turtle.py", line 434, in __init__
    TK.Tk.__init__(self)   File "/usr/lib/python3.5/tkinter/__init__.py", line 1871, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

Here is the code so far:

from turtle import *
setup(500, 500)
Screen()
title("Turtle Keys")
move = Turtle()
showturtle()
def k1():
 move.forward(100)
 move.left(90)
 move.forward(100)
 move.left(90)
 move.forward(100)
 move.left(90)
 move.forward(100)
 move.left(90)
def k2():
 move.forward(320)
 move.left(120)
 move.forward(320)
 move.left(120)
 move.forward(320)
 move.left(120)

def k3():
    move.right(45)
def k4():
 move.forward(100)
 move.left(90)
 move.forward(50)
 move.left(90)
 move.forward(100)
 move.left(90)
 move.forward(50)
 move.left(90)

def k5():
 move.left(10)

def k6():
 move.forward(10)

def k7():
 move.backward(10)

onkey(k1, "Up")
onkey(k2, "Left")
onkey(k3, "Right")
onkey(k4, "Down")
onkey(k5, "1")
onkey(k6, "2")
onkey(k7, "3")
listen()
mainloop()

The objective is to draw certain shapes when certain keys are pressed.


问:
R: transforming specific rows into columns
I have quite messy data imported from json file, it looks like this:

```<code>raw_df <- data.frame(text = c(paste0('text', 1:3), '---------- OUTCOME LINE ----------', paste0('text', 4:6), '---------- OUTCOME LINE ----------'),
                              demand = c('cat1', rep('', 2), 'info', 'cat2', rep('', 2), 'info2')
                     )

raw_df
                                text demand
1                              text1   cat1
2                              text2
3                              text3
4 ---------- OUTCOME LINE ----------   info
5                              text4   cat2
6                              text5
7                              text6
8 ---------- OUTCOME LINE ----------  info2
</code>```

(BTW, ---------- OUTCOME LINE ---------- is the actual string that I have in text column)

I want to tidy it up so that it has the following format:

```<code>final_df
                  text demand outcome
1 text1. text2. text3.   cat1   info1
2 text4. text5. text6.   cat2   info2
</code>```

What would be the quickest and most efficient way to do this? thanks for the tips.

答:
Here we create a logical index using 'grepl' based on the presence of - in the 'text' column, subset the 'raw_df' to remove those rows, create a grouping column by getting cumulative sum of 'indx', aggregate to paste the 'text' column grouped by 'demand' after replacing the '' with NA and using na.locf to fill the non-NA previous values.  Then, create the 'outcome' from the 'demand' by subsetting with 'indx'

```<code>indx <- grepl("-", raw_df$text)
transform(aggregate(text~demand, transform(raw_df[!indx,],
  demand = zoo::na.locf(replace(demand, demand=="", NA))), toString),
    outcome = raw_df$demand[indx])
#  demand                text outcome
#1   cat1 text1, text2, text3    info
#2   cat2 text4, text5, text6   info2
</code>```

Or this can be done with data.table

```<code>library(data.table)
setDT(raw_df)[demand == "", demand := NA][!indx, .(text= paste(text, collapse='. ')),
          .(demand = zoo::na.locf(demand))][, outcome := raw_df$demand[indx]][]
</code>```

Body:
I have quite messy data imported from json file, it looks like this:

raw_df <- data.frame(text = c(paste0('text', 1:3), '---------- OUTCOME LINE ----------', paste0('text', 4:6), '---------- OUTCOME LINE ----------'),
                              demand = c('cat1', rep('', 2), 'info', 'cat2', rep('', 2), 'info2')
                     )

raw_df
                                text demand
1                              text1   cat1
2                              text2
3                              text3
4 ---------- OUTCOME LINE ----------   info
5                              text4   cat2
6                              text5
7                              text6
8 ---------- OUTCOME LINE ----------  info2

(BTW, ---------- OUTCOME LINE ---------- is the actual string that I have in text column)

I want to tidy it up so that it has the following format:

final_df
                  text demand outcome
1 text1. text2. text3.   cat1   info1
2 text4. text5. text6.   cat2   info2

What would be the quickest and most efficient way to do this? thanks for the tips.

Body:
Here we create a logical index using 'grepl' based on the presence of - in the 'text' column, subset the 'raw_df' to remove those rows, create a grouping column by getting cumulative sum of 'indx', aggregate to paste the 'text' column grouped by 'demand' after replacing the '' with NA and using na.locf to fill the non-NA previous values.  Then, create the 'outcome' from the 'demand' by subsetting with 'indx'

indx <- grepl("-", raw_df$text)
transform(aggregate(text~demand, transform(raw_df[!indx,],
  demand = zoo::na.locf(replace(demand, demand=="", NA))), toString),
    outcome = raw_df$demand[indx])
#  demand                text outcome
#1   cat1 text1, text2, text3    info
#2   cat2 text4, text5, text6   info2

Or this can be done with data.table

library(data.table)
setDT(raw_df)[demand == "", demand := NA][!indx, .(text= paste(text, collapse='. ')),
          .(demand = zoo::na.locf(demand))][, outcome := raw_df$demand[indx]][]


问:
Dependency Injection and new objects creation
I'm new to dependency injection. It seems I have a good understanding of it, but  I am getting a little bit confused about one thing. Suppose I have a bean:

```<code>@Bean
HttpClient {
  public void void POST(String url, Object payload) {
    .......
  }
}
</code>```

And have a class using that bean:

```<code>Message {

 public void send() {
  httpClient.POST(this);
 }
}
</code>```

Obviously I should just inject the HttpCLient into the Message.But....
The Message also has a constructor with params:

```<code>Message {

 private final String text;

 public Message(String text) {
   this.text = text;
 }

 public void send() {
  httpClient.POST(this);
 }
}
</code>```

And it will be used in such way:

```<code>SomeClient {

  if(....) {
    new Message("Case 1 text").send();
  } else {
      new Message("Case 2 text").send();
   }
}
</code>```

Thus the Message is an immutable object that is used per request with new constructor's params and in the same time it needs the heavyweight HttpClient to be inject.

Maybe this example is not quite correct, but I believe there is many similar issues you had come across.

So the question is: what should I do if I have to instantiate objects by hands but they require dependencies to be inject?

答:
Propagating dependencies is usually solved with Factories. You don't directly instantiate the Message, you use a Factory to do it, like this:

messageFactory.createMessage("Text").send();
```

<p>With the message factory being:</p>

<pre class="lang-java prettyprint-override"><code>public interface MessageFactory {
    Message createMessage(String text);
}
</code>```

And then the dependency to the HTTP Client is in the actual factory:

public final class HttpClientBasedMessageFactory {
    private final HttpClient httpClient;
    ...
    @Override
    public Message createMessage(String text) {
        return new Message(httpClient, text);
    }
}
```

That is now without any dependency injection "framework", but it can be adjusted to support whatever you are using.

Body:
I'm new to dependency injection. It seems I have a good understanding of it, but  I am getting a little bit confused about one thing. Suppose I have a bean:

@Bean
HttpClient {
  public void void POST(String url, Object payload) {
    .......
  }
}

And have a class using that bean:

Message {

 public void send() {
  httpClient.POST(this);
 }
}

Obviously I should just inject the HttpCLient into the Message.But....
The Message also has a constructor with params:

Message {

 private final String text;

 public Message(String text) {
   this.text = text;
 }

 public void send() {
  httpClient.POST(this);
 }
}

And it will be used in such way:

SomeClient {

  if(....) {
    new Message("Case 1 text").send();
  } else {
      new Message("Case 2 text").send();
   }
}

Thus the Message is an immutable object that is used per request with new constructor's params and in the same time it needs the heavyweight HttpClient to be inject.

Maybe this example is not quite correct, but I believe there is many similar issues you had come across.

So the question is: what should I do if I have to instantiate objects by hands but they require dependencies to be inject?

Body:
Propagating dependencies is usually solved with Factories. You don't directly instantiate the Message, you use a Factory to do it, like this:

messageFactory.createMessage("Text").send();

With the message factory being:

public interface MessageFactory {
    Message createMessage(String text);
}

And then the dependency to the HTTP Client is in the actual factory:

public final class HttpClientBasedMessageFactory {
    private final HttpClient httpClient;
    ...
    @Override
    public Message createMessage(String text) {
        return new Message(httpClient, text);
    }
}

That is now without any dependency injection "framework", but it can be adjusted to support whatever you are using.


问:
How to add an element to an existing XML files with StAX?
I have an XML file similar to the one below:

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>
</a>
</code>```

Is there a way to add an element (eg. ddd) after zzz with StAX parser?
The approach I have thought of is to write the first part of the XML into a new file as below.

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>
</code>```

But I cannot figure out a solution to write exactly after the last element (zzz). Do I need to open a new file for output again? Is it possible to do it using StAX?

答:
Yes, you need a temp file to write to. Here is an example how to do this with StAX: </p>

```<code>Path in = Paths.get("file.xml");
Path temp = Files.createTempFile(null, null);
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
try (FileWriter out = new FileWriter(temp.toFile())) {
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(new FileReader(in.toFile()));
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(out);
    int depth = 0;
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        int eventType = event.getEventType();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            depth++;
        } else if (eventType == XMLStreamConstants.END_ELEMENT) {
            depth--;
            if (depth == 0) {
                List<Attribute> attrs = new ArrayList<>(1);
                attrs.add(eventFactory.createAttribute("id", "4"));
                writer.add(eventFactory.createStartElement("", null, "b", attrs.iterator(), null));
                writer.add(eventFactory.createCharacters("ddd"));
                writer.add(eventFactory.createEndElement("", null, "b"));
                writer.add(eventFactory.createSpace(System.getProperty("line.separator")));
            }
        }
        writer.add(event);
    }
    writer.flush();
    writer.close();
} catch (XMLStreamException | FactoryConfigurationError e) {
    throw new IOException(e);
}
Files.move(temp, in, StandardCopyOption.REPLACE_EXISTING);
</code>```

Body:
I have an XML file similar to the one below:

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

xxx
yyy
zzz

Is there a way to add an element (eg. ddd) after zzz with StAX parser?
The approach I have thought of is to write the first part of the XML into a new file as below.

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

xxx
yyy
zzz

But I cannot figure out a solution to write exactly after the last element (zzz). Do I need to open a new file for output again? Is it possible to do it using StAX?

Body:
Yes, you need a temp file to write to. Here is an example how to do this with StAX:

Path in = Paths.get("file.xml");
Path temp = Files.createTempFile(null, null);
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
try (FileWriter out = new FileWriter(temp.toFile())) {
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(new FileReader(in.toFile()));
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(out);
    int depth = 0;
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        int eventType = event.getEventType();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            depth++;
        } else if (eventType == XMLStreamConstants.END_ELEMENT) {
            depth--;
            if (depth == 0) {
                List<Attribute> attrs = new ArrayList<>(1);
                attrs.add(eventFactory.createAttribute("id", "4"));
                writer.add(eventFactory.createStartElement("", null, "b", attrs.iterator(), null));
                writer.add(eventFactory.createCharacters("ddd"));
                writer.add(eventFactory.createEndElement("", null, "b"));
                writer.add(eventFactory.createSpace(System.getProperty("line.separator")));
            }
        }
        writer.add(event);
    }
    writer.flush();
    writer.close();
} catch (XMLStreamException | FactoryConfigurationError e) {
    throw new IOException(e);
}
Files.move(temp, in, StandardCopyOption.REPLACE_EXISTING);


问:
How to switch environment on Jupyter notebook for new notebook?
I have an instance with various environment and some notebooks are compatible with different environment for e.g. notebook1 is for MXNet and notebook2 is for Tensorflow.

How do I jump to new environment when I move from notebook1 to notebook2?
I tried doing that but this doesn't quite work with Jupyter notebook? Any suggestion?

So I need to do it from conda environment but looks like jupyter notebook  UI doesn't respect (calls right activation function) to set the path.

答:
You could use the nb_conda_kernels package, which provides a separate  jupyter kernel for each conda environment, along with the appropriate code to handle their setup. This makes switching conda environment as simple as switching jupyter kernel (e.g. from the kernel menu), which I find very convenient. You can get it from the conda-forge channel, using</p>

```<code>conda install -c conda-forge nb_conda_kernels
</code>```

Body:
You could use the nb_conda_kernels package, which provides a separate  jupyter kernel for each conda environment, along with the appropriate code to handle their setup. This makes switching conda environment as simple as switching jupyter kernel (e.g. from the kernel menu), which I find very convenient. You can get it from the conda-forge channel, using

conda install -c conda-forge nb_conda_kernels


问:
Remove data from a SQLite database inside a RecyclerAdapter
I want to remove the data from mydatabase inside my RecyclerAdapter.

I've also got a swipe class that deletes the items from the RecyclerView.

Now, I'm able to remove the items from the RecyclerView, but not from the database as my database can't be called on the RecyclerAdapter.

This is my ManagerActivity.

```<code>public class Manager2 extends AppCompatActivity  {
    MySQLiteHelper db = new MySQLiteHelper(this);
    RecyclerView recycler;
    RecyclerAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manager2);
        initializeViews();

        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(adapter);

        ItemTouchHelper.Callback callback = new Swipe(adapter);
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recycler);
    }

    public void initializeViews(){
        List<Password> myPasswords = db.getAllPasswords();
        adapter = new RecyclerAdapter(myPasswords);
        recycler = (RecyclerView)findViewById(R.id.recycler);
    }
}
</code>```

SQLite Database class

```<code>public class MySQLiteHelper extends SQLiteOpenHelper {

    // Passwords table name
    public static final String TABLE_BOOKS = "passwords";

    // Passwords Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_PASSWORD = "password";

    public static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_PASSWORD};

    // Database Version
    public static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "PasswordDB";

    public MySQLiteHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // SQL statement to create password table
        String CREATE_PASSWORD_TABLE = "CREATE TABLE passwords ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "title TEXT, "+
                "password TEXT )";

        // create books table
        db.execSQL(CREATE_PASSWORD_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older passwords table if existed
        db.execSQL("DROP TABLE IF EXISTS passwords");
        // create fresh passwords table
        this.onCreate(db);
    }

    public void addPassword(Password password){
        //for logging
        Log.d("addBook", password.toString());

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, password.getTitle()); // get title
        values.put(KEY_PASSWORD, password.getPassword()); // get password

        // 3. insert
        db.insert(TABLE_BOOKS, // table
                null, //nullColumnHack
                values); // key/value -> keys = column names/ values = column values

        // 4. close
        db.close();
    }

    public Password getPassword(int id){

        // 1. get reference to readable DB
        SQLiteDatabase db = this.getReadableDatabase();

        // 2. build query
        Cursor cursor =
                db.query(TABLE_BOOKS, // a. table
                        COLUMNS, // b. column names
                        " id = ?", // c. selections
                        new String[] { String.valueOf(id) }, // d. selections args
                        null, // e. group by
                        null, // f. having
                        null, // g. order by
                        null); // h. limit

        // 3. if we got results get the first one
        if (cursor != null)
            cursor.moveToFirst();

        // 4. build password object
        Password password = new Password();
        password.setId(Integer.parseInt(cursor.getString(0)));
        password.setTitle(cursor.getString(1));
        password.setPassword(cursor.getString(2));

        //log
        Log.d("getPassword("+id+")", password.toString());

        // 5. return book
        return password;
    }

    public List<Password> getAllPasswords() {
        List<Password> passwords = new LinkedList<Password>();

        // 1. build the query
        String query = "SELECT * FROM " + TABLE_BOOKS;

        // 2. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query, null);

        // 3. go over each row, build book and add it to list
        Password password = null;
        if (cursor.moveToFirst()) {
            do {
                password = new Password();
                password.setId(Integer.parseInt(cursor.getString(0)));
                password.setTitle(cursor.getString(1));
                password.setPassword(cursor.getString(2));

                // Add password to passwords
                passwords.add(password);
            } while (cursor.moveToNext());
        }

        Log.d("getAllPasswords()", passwords.toString());

        // return passwords
        return passwords;
    }

    public int updatePassword(Password password) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, password.getTitle()); // get title
        values.put(KEY_PASSWORD, password.getPassword()); // get password

        // 3. updating row
        int i = db.update(TABLE_BOOKS, //table
                values, // column/value
                KEY_ID+" = ?", // selections
                new String[] { String.valueOf(password.getId()) }); //selection args

        // 4. close
        db.close();

        return i;
    }

    public boolean updatePass(int id, String title, String password ){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID,id);
        values.put(KEY_TITLE,title);// get title
        values.put(KEY_PASSWORD, password); // get password
        db.update(TABLE_BOOKS,values,"id = ?",new String[] {String.valueOf(id)});
        return true;
    }

    public void deletePassword(Password password) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. delete
        db.delete(TABLE_BOOKS, //table name
                KEY_ID+" = ?",  // selections
                new String[] { String.valueOf(password.getId()) }); //selections args

        // 3. close
        db.close();

        //log
        Log.d("deletePassword", password.toString());
    }
}
</code>```

This is my RecyclerAdapter class

```<code>public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    List<Password> myPasswords;
    public RecyclerAdapter(List<Password> myPasswords) {
        this.myPasswords = myPasswords;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_recycler_layout,parent,false));

    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Password myPass = getItem(position);
        holder.recImage.setImageResource(R.drawable.ic_menu_camera);
        holder.recTitle.setText(myPass.getTitle());
        holder.recPassword.setText(myPass.getPassword());
    }

    @Override
    public int getItemCount() {
        return myPasswords.size();
    }

    public Password getItem(int position){
        return myPasswords.get(position);
    }

    //swipe to delete-dismiss
    public void dismissItem(int position){
        myPasswords.remove(position);
        notifyItemRemoved(position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder  {
        TextView recTitle,recPassword;
        ImageView recImage;
        public ViewHolder(View itemView) {
            super(itemView);
            recTitle = (TextView)itemView.findViewById(R.id.recTitle);
            recPassword = (TextView)itemView.findViewById(R.id.recPassword);
            recImage = (ImageView)itemView.findViewById(R.id.recImage);
        }
    }

}
</code>```

答:
You execute detele  query in Recyclerview in adapter </p>

```<code>    //swipe to delete-dismiss
public void dismissItem(int position){
    myPasswords.remove(position);
    Here you want excute the query
    ////deletePassword(Password password)(your query)

    notifyItemRemoved(position);
}
</code>```

Body:
I want to remove the data from mydatabase inside my RecyclerAdapter.

I've also got a swipe class that deletes the items from the RecyclerView.

Now, I'm able to remove the items from the RecyclerView, but not from the database as my database can't be called on the RecyclerAdapter.

This is my ManagerActivity.

public class Manager2 extends AppCompatActivity  {
    MySQLiteHelper db = new MySQLiteHelper(this);
    RecyclerView recycler;
    RecyclerAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manager2);
        initializeViews();

        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(adapter);

        ItemTouchHelper.Callback callback = new Swipe(adapter);
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recycler);
    }

    public void initializeViews(){
        List<Password> myPasswords = db.getAllPasswords();
        adapter = new RecyclerAdapter(myPasswords);
        recycler = (RecyclerView)findViewById(R.id.recycler);
    }
}

SQLite Database class

public class MySQLiteHelper extends SQLiteOpenHelper {

    // Passwords table name
    public static final String TABLE_BOOKS = "passwords";

    // Passwords Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_PASSWORD = "password";

    public static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_PASSWORD};

    // Database Version
    public static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "PasswordDB";

    public MySQLiteHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // SQL statement to create password table
        String CREATE_PASSWORD_TABLE = "CREATE TABLE passwords ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "title TEXT, "+
                "password TEXT )";

        // create books table
        db.execSQL(CREATE_PASSWORD_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older passwords table if existed
        db.execSQL("DROP TABLE IF EXISTS passwords");
        // create fresh passwords table
        this.onCreate(db);
    }

    public void addPassword(Password password){
        //for logging
        Log.d("addBook", password.toString());

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, password.getTitle()); // get title
        values.put(KEY_PASSWORD, password.getPassword()); // get password

        // 3. insert
        db.insert(TABLE_BOOKS, // table
                null, //nullColumnHack
                values); // key/value -> keys = column names/ values = column values

        // 4. close
        db.close();
    }

    public Password getPassword(int id){

        // 1. get reference to readable DB
        SQLiteDatabase db = this.getReadableDatabase();

        // 2. build query
        Cursor cursor =
                db.query(TABLE_BOOKS, // a. table
                        COLUMNS, // b. column names
                        " id = ?", // c. selections
                        new String[] { String.valueOf(id) }, // d. selections args
                        null, // e. group by
                        null, // f. having
                        null, // g. order by
                        null); // h. limit

        // 3. if we got results get the first one
        if (cursor != null)
            cursor.moveToFirst();

        // 4. build password object
        Password password = new Password();
        password.setId(Integer.parseInt(cursor.getString(0)));
        password.setTitle(cursor.getString(1));
        password.setPassword(cursor.getString(2));

        //log
        Log.d("getPassword("+id+")", password.toString());

        // 5. return book
        return password;
    }

    public List<Password> getAllPasswords() {
        List<Password> passwords = new LinkedList<Password>();

        // 1. build the query
        String query = "SELECT * FROM " + TABLE_BOOKS;

        // 2. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query, null);

        // 3. go over each row, build book and add it to list
        Password password = null;
        if (cursor.moveToFirst()) {
            do {
                password = new Password();
                password.setId(Integer.parseInt(cursor.getString(0)));
                password.setTitle(cursor.getString(1));
                password.setPassword(cursor.getString(2));

                // Add password to passwords
                passwords.add(password);
            } while (cursor.moveToNext());
        }

        Log.d("getAllPasswords()", passwords.toString());

        // return passwords
        return passwords;
    }

    public int updatePassword(Password password) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, password.getTitle()); // get title
        values.put(KEY_PASSWORD, password.getPassword()); // get password

        // 3. updating row
        int i = db.update(TABLE_BOOKS, //table
                values, // column/value
                KEY_ID+" = ?", // selections
                new String[] { String.valueOf(password.getId()) }); //selection args

        // 4. close
        db.close();

        return i;
    }

    public boolean updatePass(int id, String title, String password ){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID,id);
        values.put(KEY_TITLE,title);// get title
        values.put(KEY_PASSWORD, password); // get password
        db.update(TABLE_BOOKS,values,"id = ?",new String[] {String.valueOf(id)});
        return true;
    }

    public void deletePassword(Password password) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. delete
        db.delete(TABLE_BOOKS, //table name
                KEY_ID+" = ?",  // selections
                new String[] { String.valueOf(password.getId()) }); //selections args

        // 3. close
        db.close();

        //log
        Log.d("deletePassword", password.toString());
    }
}

This is my RecyclerAdapter class

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    List<Password> myPasswords;
    public RecyclerAdapter(List<Password> myPasswords) {
        this.myPasswords = myPasswords;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_recycler_layout,parent,false));

    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Password myPass = getItem(position);
        holder.recImage.setImageResource(R.drawable.ic_menu_camera);
        holder.recTitle.setText(myPass.getTitle());
        holder.recPassword.setText(myPass.getPassword());
    }

    @Override
    public int getItemCount() {
        return myPasswords.size();
    }

    public Password getItem(int position){
        return myPasswords.get(position);
    }

    //swipe to delete-dismiss
    public void dismissItem(int position){
        myPasswords.remove(position);
        notifyItemRemoved(position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder  {
        TextView recTitle,recPassword;
        ImageView recImage;
        public ViewHolder(View itemView) {
            super(itemView);
            recTitle = (TextView)itemView.findViewById(R.id.recTitle);
            recPassword = (TextView)itemView.findViewById(R.id.recPassword);
            recImage = (ImageView)itemView.findViewById(R.id.recImage);
        }
    }

}

Body:
You execute detele  query in Recyclerview in adapter

    //swipe to delete-dismiss
public void dismissItem(int position){
    myPasswords.remove(position);
    Here you want excute the query
    ////deletePassword(Password password)(your query)

    notifyItemRemoved(position);
}


问:
How can I checkout only modified files from cvs-server using tortoiseCVS
I need to checkout the files modified by developers. I tried Date command but it check-out the whole project. But i need only modified file for my patch with directory structure. Is there any way to checkout those files.</p>

答:
It's not clear what precisely what you want to do here - if you really do want to checkout a new copy of the project which only contains the files that are modified relative to your current copy, then I don't think TortoiseCVS has a way to do it. In principle I imagine you could do it manually (e.g. checkout a new copy of the project, compare it with your existing copy and then delete any files which are the same), but it would surely be tedious to do for any realistically-sized project.

However I'm wondering if what you actually want is to patch a local checked-out copy of the files with the latest changes committed to the repository by other developers? If so then use the CVS "update" command, which will merge those changes into your local copies while still preserving any uncommitted modifications you might have there. (Be aware of any conflicts arising from the merging process - TortoiseCVS should warn you during the update, but they have to be resolved with manual editing.)


问:
Sed substitute: make a group operator optional
Let's say I want to use sed to substitute expressions like "foo", "foo(1 1)", "foo(42 1)" by "bar". I tried :

```<code>sed -i ':a;N;$!ba;s/foo([0-9]\+ [0-9]\+)\{0,1\}/bar/g' input.file
</code>```

But only replaced expressions with parenthesis after foo, not foo with no parenthesis.

Do you have any idea why ?

Example of I wish:

INPUT

```<code>foo
foo(236 124)
</code>```

OUPUT

```<code>bar
bar
</code>```

答:
You can use this sed:

```<code>sed 's/foo\(([0-9]\+ [0-9]\+)\)\{0,1\}/bar/g' file
           ^                  ^
           Here, I have added grouping. So that, {0,1} would work exactly.
</code>```

Test:

```<code>$ sed 's/foo\(([0-9]\+ [0-9]\+)\)\{0,1\}/bar/g' file
bar
bar
</code>```

Body:
Let's say I want to use sed to substitute expressions like "foo", "foo(1 1)", "foo(42 1)" by "bar". I tried :

sed -i ':a;N;$!ba;s/foo([0-9]\+ [0-9]\+)\{0,1\}/bar/g' input.file

But only replaced expressions with parenthesis after foo, not foo with no parenthesis.

Do you have any idea why ?

Example of I wish:

INPUT

foo
foo(236 124)

OUPUT

bar
bar

Body:
You can use this sed:

sed 's/foo\(([0-9]\+ [0-9]\+)\)\{0,1\}/bar/g' file
           ^                  ^
           Here, I have added grouping. So that, {0,1} would work exactly.

Test:

$ sed 's/foo\(([0-9]\+ [0-9]\+)\)\{0,1\}/bar/g' file
bar
bar


问:
Compiling OpenCV 3.3 : C++11 is not supported
I'm trying to compile the new version of OpenCV 3.3 (released on Aug 3, 2017) but I'm getting an error of C++11

This is my cmake command line:

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_CUDA=ON \
-D ENABLE_FAST_MATH=1 \
-D CUDA_FAST_MATH=1 \
-D WITH_CUBLAS=1 \
-DINSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-3.3/modules \
-D BUILD_SHARED_LIBS=ON \
-D WITH_GTK=ON /
-D BUILD_EXAMPLES=ON ..
</code>```

I've edited CMakeLists by turning ON some components (even without making any changes, the error remain the same):

```<code>OCV_OPTION(WITH_OPENGL         "Include OpenGL support"                      ON  IF (NOT ANDROID AND NOT WINRT) )
OCV_OPTION(WITH_OPENVX         "Include OpenVX support"                      ON)
OCV_OPTION(WITH_OPENNI         "Include OpenNI support"                      ON  IF (NOT ANDROID AND NOT IOS AND NOT WINRT) )
OCV_OPTION(WITH_OPENNI2        "Include OpenNI2 support"                     ON  IF (NOT ANDROID AND NOT IOS AND NOT WINRT) )
OCV_OPTION(WITH_OPENMP         "Include OpenMP support"                      ON)
OCV_OPTION(WITH_OPENCL_SVM     "Include OpenCL Shared Virtual Memory support" ON ) # experimental
</code>```

And here my CMakeError.log file:

```<code>Compilation failed:
    source file: '/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp'
    check option: ''
===== BUILD LOG =====
Change Dir: /home/jhros/opencv-3.3.0/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_f915e/fast"
/usr/bin/make -f CMakeFiles/cmTC_f915e.dir/build.make CMakeFiles/cmTC_f915e.dir/build
make[1]: Entering directory '/home/jhros/opencv-3.3.0/build/CMakeFiles/CMakeTmp'
Building CXX object CMakeFiles/cmTC_f915e.dir/cxx11.cpp.o
/usr/bin/c++      -o CMakeFiles/cmTC_f915e.dir/cxx11.cpp.o -c /home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp
/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp:4:2: error: #error "C++11 is not supported"
 #error "C++11 is not supported"
  ^
/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp: In function ‘int main()’:
/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp:11:10: error: ‘res’ does not name a type
     auto res = test();
          ^
/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp:12:12: error: ‘res’ was not declared in this scope
     return res;
            ^
CMakeFiles/cmTC_f915e.dir/build.make:65: recipe for target 'CMakeFiles/cmTC_f915e.dir/cxx11.cpp.o' failed
make[1]: *** [CMakeFiles/cmTC_f915e.dir/cxx11.cpp.o] Error 1
make[1]: Leaving directory '/home/jhros/opencv-3.3.0/build/CMakeFiles/CMakeTmp'
Makefile:126: recipe for target 'cmTC_f915e/fast' failed
make: *** [cmTC_f915e/fast] Error 2
</code>```

And my CMakeLists (not all of it):

```<code># ----------------------------------------------------------------------------
#  Root CMake file for OpenCV
#
#    From the off-tree build directory, invoke:
#      $ cmake <PATH_TO_OPENCV_ROOT>
#
# ----------------------------------------------------------------------------

# Disable in-source builds to prevent source tree corruption.
if(" ${CMAKE_SOURCE_DIR}" STREQUAL " ${CMAKE_BINARY_DIR}")
  message(FATAL_ERROR "
FATAL: In-source builds are not allowed.
       You should create separate directory for build files.
")
endif()

include(cmake/OpenCVMinDepVersions.cmake)

if(CMAKE_GENERATOR MATCHES Xcode AND XCODE_VERSION VERSION_GREATER 4.3)
  cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
elseif(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore)
  cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
  #Required to resolve linker error issues due to incompatibility with CMake v3.0+ policies.
  #CMake fails to find _fseeko() which leads to subsequent linker error.
  #See details here: http://www.cmake.org/Wiki/CMake/Policies
  cmake_policy(VERSION 2.8)
else()
  cmake_minimum_required(VERSION "${MIN_VER_CMAKE}" FATAL_ERROR)
endif()

# Following block can broke build in case of cross-compilng
# but CMAKE_CROSSCOMPILING variable will be set only on project(OpenCV) command
# so we will try to detect crosscompiling by presense of CMAKE_TOOLCHAIN_FILE
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  if(NOT CMAKE_TOOLCHAIN_FILE)
    # it _must_ go before project(OpenCV) in order to work
    if(WIN32)
      set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Installation Directory")
    else()
      set(CMAKE_INSTALL_PREFIX "/usr/local" CACHE PATH "Installation Directory")
    endif()
  else(NOT CMAKE_TOOLCHAIN_FILE)
    #Android: set output folder to ${CMAKE_BINARY_DIR}
    set( LIBRARY_OUTPUT_PATH_ROOT ${CMAKE_BINARY_DIR} CACHE PATH "root for library output, set this to change where android libs are compiled to" )
    # any crosscompiling
    set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Installation Directory")
  endif(NOT CMAKE_TOOLCHAIN_FILE)
endif()

if(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore)
  set(WINRT TRUE)
endif(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore)

if(WINRT)
  add_definitions(-DWINRT -DNO_GETENV)

  # Making definitions available to other configurations and
  # to filter dependency restrictions at compile time.
  if(CMAKE_SYSTEM_NAME MATCHES WindowsPhone)
    set(WINRT_PHONE TRUE)
    add_definitions(-DWINRT_PHONE)
  elseif(CMAKE_SYSTEM_NAME MATCHES WindowsStore)
    set(WINRT_STORE TRUE)
    add_definitions(-DWINRT_STORE)
  endif()

  if(CMAKE_SYSTEM_VERSION MATCHES 10)
    set(WINRT_10 TRUE)
    add_definitions(-DWINRT_10)
  elseif(CMAKE_SYSTEM_VERSION MATCHES 8.1)
    set(WINRT_8_1 TRUE)
    add_definitions(-DWINRT_8_1)
  elseif(CMAKE_SYSTEM_VERSION MATCHES 8.0)
    set(WINRT_8_0 TRUE)
    add_definitions(-DWINRT_8_0)
  endif()
endif()

if(POLICY CMP0020)
  cmake_policy(SET CMP0020 OLD)
endif()

if(POLICY CMP0022)
  cmake_policy(SET CMP0022 OLD)
endif()

if(POLICY CMP0023)
  cmake_policy(SET CMP0023 NEW)
endif()

if(POLICY CMP0026)
  # silence cmake 3.0+ warnings about reading LOCATION attribute
  cmake_policy(SET CMP0026 OLD)
endif()

if(POLICY CMP0042)
  cmake_policy(SET CMP0042 NEW)
endif()

if(POLICY CMP0046)
  cmake_policy(SET CMP0046 OLD)
endif()

if(POLICY CMP0051)
  cmake_policy(SET CMP0051 NEW)
endif()

if(POLICY CMP0056)
  cmake_policy(SET CMP0056 NEW)
endif()

if(POLICY CMP0067)
  cmake_policy(SET CMP0067 NEW)
endif()

include(cmake/OpenCVUtils.cmake)

# must go before the project command
ocv_update(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE)
if(DEFINED CMAKE_BUILD_TYPE)
  set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS ${CMAKE_CONFIGURATION_TYPES} )
endif()

enable_testing()

project(OpenCV CXX C)

if(MSVC)
  set(CMAKE_USE_RELATIVE_PATHS ON CACHE INTERNAL "" FORCE)
endif()

ocv_cmake_eval(DEBUG_PRE ONCE)

ocv_clear_vars(OpenCVModules_TARGETS)

include(cmake/OpenCVDownload.cmake)

# ----------------------------------------------------------------------------
# Break in case of popular CMake configuration mistakes
# ----------------------------------------------------------------------------
if(NOT CMAKE_SIZEOF_VOID_P GREATER 0)
  message(FATAL_ERROR "CMake fails to deterimine the bitness of target platform.
  Please check your CMake and compiler installation. If you are crosscompiling then ensure that your CMake toolchain file correctly sets the compiler details.")
endif()

# ----------------------------------------------------------------------------
# Detect compiler and target platform architecture
# ----------------------------------------------------------------------------
OCV_OPTION(ENABLE_CXX11 "Enable C++11 compilation mode" "${OPENCV_CXX11}")
include(cmake/OpenCVDetectCXXCompiler.cmake)

# Add these standard paths to the search paths for FIND_LIBRARY
# to find libraries from these locations first
if(UNIX AND NOT ANDROID)
  if(X86_64 OR CMAKE_SIZEOF_VOID_P EQUAL 8)
    if(EXISTS /lib64)
      list(APPEND CMAKE_LIBRARY_PATH /lib64)
    else()
      list(APPEND CMAKE_LIBRARY_PATH /lib)
    endif()
    if(EXISTS /usr/lib64)
      list(APPEND CMAKE_LIBRARY_PATH /usr/lib64)
    else()
      list(APPEND CMAKE_LIBRARY_PATH /usr/lib)
    endif()
  elseif(X86 OR CMAKE_SIZEOF_VOID_P EQUAL 4)
    if(EXISTS /lib32)
      list(APPEND CMAKE_LIBRARY_PATH /lib32)
    else()
      list(APPEND CMAKE_LIBRARY_PATH /lib)
    endif()
    if(EXISTS /usr/lib32)
      list(APPEND CMAKE_LIBRARY_PATH /usr/lib32)
    else()
      list(APPEND CMAKE_LIBRARY_PATH /usr/lib)
    endif()
  endif()
endif()

# Add these standard paths to the search paths for FIND_PATH
# to find include files from these locations first
if(MINGW)
  if(EXISTS /mingw)
      list(APPEND CMAKE_INCLUDE_PATH /mingw)
  endif()
  if(EXISTS /mingw32)
      list(APPEND CMAKE_INCLUDE_PATH /mingw32)
  endif()
  if(EXISTS /mingw64)
      list(APPEND CMAKE_INCLUDE_PATH /mingw64)
  endif()
endif()
</code>```

EDIT

CMake version -3.5

Compiler GNU 5.4.1

EDIT2

I'm compiling with GNU 7.1.0 now but I get different error

```<code>Build output check failed:
    Regex: 'command line option .* is valid for .* but not for C\+\+'
    Output line: 'cc1plus: warning: command line option ‘-Wmissing-prototypes’ is valid for C/ObjC but not for C++'
Compilation failed:
    source file: '/home/jhros/opencv-3.3.0/build/CMakeFiles/CMakeTmp/src.cxx'
    check option: ' -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations  -Wmissing-prototypes'
</code>```

答:
I installed OpenCV 3.3.1 on Linux Mint 18.2, followed this article (https://www.learnopencv.com/install-opencv3-on-ubuntu/) and I had the same problem. I changed cmake command from

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE \
  -D CMAKE_INSTALL_PREFIX=/usr/local \
  -D INSTALL_C_EXAMPLES=ON \
  -D INSTALL_PYTHON_EXAMPLES=ON \
  -D WITH_TBB=ON \
  -D WITH_V4L=ON \
  -D WITH_QT=ON \
  -D WITH_OPENGL=ON \
  -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
  -D BUILD_EXAMPLES=ON ..
</code>```

to

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE \
  -DCMAKE_INSTALL_PREFIX=/usr/local \
  -D INSTALL_C_EXAMPLES=OFF \
  -D INSTALL_PYTHON_EXAMPLES=OFF \
  -D WITH_TBB=ON \
  -D WITH_V4L=ON \
  -D WITH_QT=ON \
  -D WITH_OPENGL=ON \
  -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
  -D BUILD_EXAMPLES=OFF ..
</code>```

(changed from -D CMAKE_INSTALL_PREFIX=/usr/local \ to -DCMAKE_INSTALL_PREFIX=/usr/local \) and it worked for me. Hope useful.
Note: 3.3.0 is not work.
(Sorry about my English)

Body:
I'm trying to compile the new version of OpenCV 3.3 (released on Aug 3, 2017) but I'm getting an error of C++11

This is my cmake command line:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_CUDA=ON \
-D ENABLE_FAST_MATH=1 \
-D CUDA_FAST_MATH=1 \
-D WITH_CUBLAS=1 \
-DINSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-3.3/modules \
-D BUILD_SHARED_LIBS=ON \
-D WITH_GTK=ON /
-D BUILD_EXAMPLES=ON ..

I've edited CMakeLists by turning ON some components (even without making any changes, the error remain the same):

OCV_OPTION(WITH_OPENGL         "Include OpenGL support"                      ON  IF (NOT ANDROID AND NOT WINRT) )
OCV_OPTION(WITH_OPENVX         "Include OpenVX support"                      ON)
OCV_OPTION(WITH_OPENNI         "Include OpenNI support"                      ON  IF (NOT ANDROID AND NOT IOS AND NOT WINRT) )
OCV_OPTION(WITH_OPENNI2        "Include OpenNI2 support"                     ON  IF (NOT ANDROID AND NOT IOS AND NOT WINRT) )
OCV_OPTION(WITH_OPENMP         "Include OpenMP support"                      ON)
OCV_OPTION(WITH_OPENCL_SVM     "Include OpenCL Shared Virtual Memory support" ON ) # experimental

And here my CMakeError.log file:

Compilation failed:
    source file: '/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp'
    check option: ''
===== BUILD LOG =====
Change Dir: /home/jhros/opencv-3.3.0/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_f915e/fast"
/usr/bin/make -f CMakeFiles/cmTC_f915e.dir/build.make CMakeFiles/cmTC_f915e.dir/build
make[1]: Entering directory '/home/jhros/opencv-3.3.0/build/CMakeFiles/CMakeTmp'
Building CXX object CMakeFiles/cmTC_f915e.dir/cxx11.cpp.o
/usr/bin/c++      -o CMakeFiles/cmTC_f915e.dir/cxx11.cpp.o -c /home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp
/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp:4:2: error: #error "C++11 is not supported"
 #error "C++11 is not supported"
  ^
/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp: In function ‘int main()’:
/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp:11:10: error: ‘res’ does not name a type
     auto res = test();
          ^
/home/jhros/opencv-3.3.0/cmake/checks/cxx11.cpp:12:12: error: ‘res’ was not declared in this scope
     return res;
            ^
CMakeFiles/cmTC_f915e.dir/build.make:65: recipe for target 'CMakeFiles/cmTC_f915e.dir/cxx11.cpp.o' failed
make[1]: *** [CMakeFiles/cmTC_f915e.dir/cxx11.cpp.o] Error 1
make[1]: Leaving directory '/home/jhros/opencv-3.3.0/build/CMakeFiles/CMakeTmp'
Makefile:126: recipe for target 'cmTC_f915e/fast' failed
make: *** [cmTC_f915e/fast] Error 2

And my CMakeLists (not all of it):

# ----------------------------------------------------------------------------
#  Root CMake file for OpenCV
#
#    From the off-tree build directory, invoke:
#      $ cmake <PATH_TO_OPENCV_ROOT>
#
# ----------------------------------------------------------------------------

# Disable in-source builds to prevent source tree corruption.
if(" ${CMAKE_SOURCE_DIR}" STREQUAL " ${CMAKE_BINARY_DIR}")
  message(FATAL_ERROR "
FATAL: In-source builds are not allowed.
       You should create separate directory for build files.
")
endif()

include(cmake/OpenCVMinDepVersions.cmake)

if(CMAKE_GENERATOR MATCHES Xcode AND XCODE_VERSION VERSION_GREATER 4.3)
  cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
elseif(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore)
  cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
  #Required to resolve linker error issues due to incompatibility with CMake v3.0+ policies.
  #CMake fails to find _fseeko() which leads to subsequent linker error.
  #See details here: http://www.cmake.org/Wiki/CMake/Policies
  cmake_policy(VERSION 2.8)
else()
  cmake_minimum_required(VERSION "${MIN_VER_CMAKE}" FATAL_ERROR)
endif()

# Following block can broke build in case of cross-compilng
# but CMAKE_CROSSCOMPILING variable will be set only on project(OpenCV) command
# so we will try to detect crosscompiling by presense of CMAKE_TOOLCHAIN_FILE
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  if(NOT CMAKE_TOOLCHAIN_FILE)
    # it _must_ go before project(OpenCV) in order to work
    if(WIN32)
      set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Installation Directory")
    else()
      set(CMAKE_INSTALL_PREFIX "/usr/local" CACHE PATH "Installation Directory")
    endif()
  else(NOT CMAKE_TOOLCHAIN_FILE)
    #Android: set output folder to ${CMAKE_BINARY_DIR}
    set( LIBRARY_OUTPUT_PATH_ROOT ${CMAKE_BINARY_DIR} CACHE PATH "root for library output, set this to change where android libs are compiled to" )
    # any crosscompiling
    set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Installation Directory")
  endif(NOT CMAKE_TOOLCHAIN_FILE)
endif()

if(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore)
  set(WINRT TRUE)
endif(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore)

if(WINRT)
  add_definitions(-DWINRT -DNO_GETENV)

  # Making definitions available to other configurations and
  # to filter dependency restrictions at compile time.
  if(CMAKE_SYSTEM_NAME MATCHES WindowsPhone)
    set(WINRT_PHONE TRUE)
    add_definitions(-DWINRT_PHONE)
  elseif(CMAKE_SYSTEM_NAME MATCHES WindowsStore)
    set(WINRT_STORE TRUE)
    add_definitions(-DWINRT_STORE)
  endif()

  if(CMAKE_SYSTEM_VERSION MATCHES 10)
    set(WINRT_10 TRUE)
    add_definitions(-DWINRT_10)
  elseif(CMAKE_SYSTEM_VERSION MATCHES 8.1)
    set(WINRT_8_1 TRUE)
    add_definitions(-DWINRT_8_1)
  elseif(CMAKE_SYSTEM_VERSION MATCHES 8.0)
    set(WINRT_8_0 TRUE)
    add_definitions(-DWINRT_8_0)
  endif()
endif()

if(POLICY CMP0020)
  cmake_policy(SET CMP0020 OLD)
endif()

if(POLICY CMP0022)
  cmake_policy(SET CMP0022 OLD)
endif()

if(POLICY CMP0023)
  cmake_policy(SET CMP0023 NEW)
endif()

if(POLICY CMP0026)
  # silence cmake 3.0+ warnings about reading LOCATION attribute
  cmake_policy(SET CMP0026 OLD)
endif()

if(POLICY CMP0042)
  cmake_policy(SET CMP0042 NEW)
endif()

if(POLICY CMP0046)
  cmake_policy(SET CMP0046 OLD)
endif()

if(POLICY CMP0051)
  cmake_policy(SET CMP0051 NEW)
endif()

if(POLICY CMP0056)
  cmake_policy(SET CMP0056 NEW)
endif()

if(POLICY CMP0067)
  cmake_policy(SET CMP0067 NEW)
endif()

include(cmake/OpenCVUtils.cmake)

# must go before the project command
ocv_update(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE)
if(DEFINED CMAKE_BUILD_TYPE)
  set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS ${CMAKE_CONFIGURATION_TYPES} )
endif()

enable_testing()

project(OpenCV CXX C)

if(MSVC)
  set(CMAKE_USE_RELATIVE_PATHS ON CACHE INTERNAL "" FORCE)
endif()

ocv_cmake_eval(DEBUG_PRE ONCE)

ocv_clear_vars(OpenCVModules_TARGETS)

include(cmake/OpenCVDownload.cmake)

# ----------------------------------------------------------------------------
# Break in case of popular CMake configuration mistakes
# ----------------------------------------------------------------------------
if(NOT CMAKE_SIZEOF_VOID_P GREATER 0)
  message(FATAL_ERROR "CMake fails to deterimine the bitness of target platform.
  Please check your CMake and compiler installation. If you are crosscompiling then ensure that your CMake toolchain file correctly sets the compiler details.")
endif()

# ----------------------------------------------------------------------------
# Detect compiler and target platform architecture
# ----------------------------------------------------------------------------
OCV_OPTION(ENABLE_CXX11 "Enable C++11 compilation mode" "${OPENCV_CXX11}")
include(cmake/OpenCVDetectCXXCompiler.cmake)

# Add these standard paths to the search paths for FIND_LIBRARY
# to find libraries from these locations first
if(UNIX AND NOT ANDROID)
  if(X86_64 OR CMAKE_SIZEOF_VOID_P EQUAL 8)
    if(EXISTS /lib64)
      list(APPEND CMAKE_LIBRARY_PATH /lib64)
    else()
      list(APPEND CMAKE_LIBRARY_PATH /lib)
    endif()
    if(EXISTS /usr/lib64)
      list(APPEND CMAKE_LIBRARY_PATH /usr/lib64)
    else()
      list(APPEND CMAKE_LIBRARY_PATH /usr/lib)
    endif()
  elseif(X86 OR CMAKE_SIZEOF_VOID_P EQUAL 4)
    if(EXISTS /lib32)
      list(APPEND CMAKE_LIBRARY_PATH /lib32)
    else()
      list(APPEND CMAKE_LIBRARY_PATH /lib)
    endif()
    if(EXISTS /usr/lib32)
      list(APPEND CMAKE_LIBRARY_PATH /usr/lib32)
    else()
      list(APPEND CMAKE_LIBRARY_PATH /usr/lib)
    endif()
  endif()
endif()

# Add these standard paths to the search paths for FIND_PATH
# to find include files from these locations first
if(MINGW)
  if(EXISTS /mingw)
      list(APPEND CMAKE_INCLUDE_PATH /mingw)
  endif()
  if(EXISTS /mingw32)
      list(APPEND CMAKE_INCLUDE_PATH /mingw32)
  endif()
  if(EXISTS /mingw64)
      list(APPEND CMAKE_INCLUDE_PATH /mingw64)
  endif()
endif()

EDIT

CMake version -3.5

Compiler GNU 5.4.1

EDIT2

I'm compiling with GNU 7.1.0 now but I get different error

Build output check failed:
    Regex: 'command line option .* is valid for .* but not for C\+\+'
    Output line: 'cc1plus: warning: command line option ‘-Wmissing-prototypes’ is valid for C/ObjC but not for C++'
Compilation failed:
    source file: '/home/jhros/opencv-3.3.0/build/CMakeFiles/CMakeTmp/src.cxx'
    check option: ' -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations  -Wmissing-prototypes'

Body:
I installed OpenCV 3.3.1 on Linux Mint 18.2, followed this article (https://www.learnopencv.com/install-opencv3-on-ubuntu/) and I had the same problem. I changed cmake command from

cmake -D CMAKE_BUILD_TYPE=RELEASE \
  -D CMAKE_INSTALL_PREFIX=/usr/local \
  -D INSTALL_C_EXAMPLES=ON \
  -D INSTALL_PYTHON_EXAMPLES=ON \
  -D WITH_TBB=ON \
  -D WITH_V4L=ON \
  -D WITH_QT=ON \
  -D WITH_OPENGL=ON \
  -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
  -D BUILD_EXAMPLES=ON ..

to

cmake -D CMAKE_BUILD_TYPE=RELEASE \
  -DCMAKE_INSTALL_PREFIX=/usr/local \
  -D INSTALL_C_EXAMPLES=OFF \
  -D INSTALL_PYTHON_EXAMPLES=OFF \
  -D WITH_TBB=ON \
  -D WITH_V4L=ON \
  -D WITH_QT=ON \
  -D WITH_OPENGL=ON \
  -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
  -D BUILD_EXAMPLES=OFF ..

(changed from -D CMAKE_INSTALL_PREFIX=/usr/local \ to -DCMAKE_INSTALL_PREFIX=/usr/local \) and it worked for me. Hope useful.
Note: 3.3.0 is not work.
(Sorry about my English)


问:
Adding username to comment history Magento 1.9
I want to add an initial to my comment history. Like the username will automatically show in the comment so the person do not have to key in manually. It will only display their username of their own.

I have found two guides in this problem. However, it only fits Magento 1.4 and Magento 1.7. After I changed the files in their guide, it is still not working.

Is there a way to make it happen?

Things I have added to my code:

```<code>/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php

    public function addCommentAction(){
 ......

 // get the login info of current user
 $_user = Mage::getSingleton('admin/session');
 $user['email'] = $_user->getUser()->getEmail();
 $user['firstname'] = $_user->getUser()->getFirstname();
 $user['lastname'] = $_user->getUser()->getLastname();

 $order->addStatusHistoryComment($data['comment'] . " Add by {$user['firstname']}", $data['status'])
                ->setIsVisibleOnFront($visible)
                ->setIsCustomerNotified($notify);
</code>```

答:
You need to create simple module and write below code</p>

```<code>app/code/local/Modulenamespace/Modulename/etc/config.xml

<adminhtml>
        <events>
            <controller_action_predispatch_adminhtml_sales_order_addComment>
                <observers>
                    <modulenamespace_modulename_unique_node>
                        <class>Your_Module_Model_Observer</class>
                        <method>controllerActionPredispatchAdminhtmlSalesOrderAddComment</method>
                    </modulenamespace_modulename_unique_node>
                </observers>
            </controller_action_predispatch_adminhtml_sales_order_addComment>
            <controller_action_predispatch_adminhtml_sales_order_creditmemo_save>
                <observers>
                    <modulenamespace_modulename_unique_node>
                        <class>Your_Module_Model_Observer</class>
                        <method>controllerActionPredispatchAdminhtmlSalesOrderCreditmemoSave</method>
                    </modulenamespace_modulename_unique_node>
                </observers>
            </controller_action_predispatch_adminhtml_sales_order_creditmemo_save>
            <controller_action_predispatch_adminhtml_sales_order_creditmemo_addComment>
                <observers>
                    <modulenamespace_modulename_unique_node>
                        <class>SSD_Authorizenetcim_Model_Observer</class>
                        <method>controllerActionPredispatchAdminhtmlSalesOrderCreditmemoAddComment</method>
                    </modulenamespace_modulename_unique_node>
                </observers>
            </controller_action_predispatch_adminhtml_sales_order_creditmemo_addComment>
        </events>
    </adminhtml>

/app/code/local/Modulenamespace/Modulename/Model/Observer.php

function controllerActionPredispatchAdminhtmlSalesOrderAddComment($observer)
{
    $history = Mage::app()->getRequest()->getPost('history');
    if ($history && isset($history['comment'])) {
        $history['comment'] .= $this->_getAppend();
        Mage::app()->getRequest()->setPost('history', $history);
    }
}
function controllerActionPredispatchAdminhtmlSalesOrderCreditmemoSave($observer)
{
    $post = Mage::app()->getRequest()->getPost('creditmemo');
    if ($post && isset($post['comment_text'])) {
        $post['comment_text'] .= $this->_getAppend();
        Mage::app()->getRequest()->setPost('creditmemo', $post);
    }
}
function controllerActionPredispatchAdminhtmlSalesOrderCreditmemoAddComment($observer)
{
    $post = Mage::app()->getRequest()->getPost('comment');
    if ($post && isset($post['comment'])) {
        $post['comment'] .= $this->_getAppend();
        Mage::app()->getRequest()->setPost('comment', $post);
    }
}
protected function _getAppend()
{
    $user     = Mage::getSingleton('admin/session');
    $username = $user->getUser()->getUsername();
    return "<br/><br/> Posted by: " . $username;
}
</code>```

Body:
I want to add an initial to my comment history. Like the username will automatically show in the comment so the person do not have to key in manually. It will only display their username of their own.

I have found two guides in this problem. However, it only fits Magento 1.4 and Magento 1.7. After I changed the files in their guide, it is still not working.

Is there a way to make it happen?

Things I have added to my code:

/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php

    public function addCommentAction(){
 ......

 // get the login info of current user
 $_user = Mage::getSingleton('admin/session');
 $user['email'] = $_user->getUser()->getEmail();
 $user['firstname'] = $_user->getUser()->getFirstname();
 $user['lastname'] = $_user->getUser()->getLastname();

 $order->addStatusHistoryComment($data['comment'] . " Add by {$user['firstname']}", $data['status'])
                ->setIsVisibleOnFront($visible)
                ->setIsCustomerNotified($notify);

Body:
You need to create simple module and write below code

app/code/local/Modulenamespace/Modulename/etc/config.xml

<adminhtml>
        <events>
            <controller_action_predispatch_adminhtml_sales_order_addComment>
                <observers>
                    <modulenamespace_modulename_unique_node>
                        <class>Your_Module_Model_Observer</class>
                        <method>controllerActionPredispatchAdminhtmlSalesOrderAddComment</method>
                    </modulenamespace_modulename_unique_node>
                </observers>
            </controller_action_predispatch_adminhtml_sales_order_addComment>
            <controller_action_predispatch_adminhtml_sales_order_creditmemo_save>
                <observers>
                    <modulenamespace_modulename_unique_node>
                        <class>Your_Module_Model_Observer</class>
                        <method>controllerActionPredispatchAdminhtmlSalesOrderCreditmemoSave</method>
                    </modulenamespace_modulename_unique_node>
                </observers>
            </controller_action_predispatch_adminhtml_sales_order_creditmemo_save>
            <controller_action_predispatch_adminhtml_sales_order_creditmemo_addComment>
                <observers>
                    <modulenamespace_modulename_unique_node>
                        <class>SSD_Authorizenetcim_Model_Observer</class>
                        <method>controllerActionPredispatchAdminhtmlSalesOrderCreditmemoAddComment</method>
                    </modulenamespace_modulename_unique_node>
                </observers>
            </controller_action_predispatch_adminhtml_sales_order_creditmemo_addComment>
        </events>
    </adminhtml>

/app/code/local/Modulenamespace/Modulename/Model/Observer.php

function controllerActionPredispatchAdminhtmlSalesOrderAddComment($observer)
{
    $history = Mage::app()->getRequest()->getPost('history');
    if ($history && isset($history['comment'])) {
        $history['comment'] .= $this->_getAppend();
        Mage::app()->getRequest()->setPost('history', $history);
    }
}
function controllerActionPredispatchAdminhtmlSalesOrderCreditmemoSave($observer)
{
    $post = Mage::app()->getRequest()->getPost('creditmemo');
    if ($post && isset($post['comment_text'])) {
        $post['comment_text'] .= $this->_getAppend();
        Mage::app()->getRequest()->setPost('creditmemo', $post);
    }
}
function controllerActionPredispatchAdminhtmlSalesOrderCreditmemoAddComment($observer)
{
    $post = Mage::app()->getRequest()->getPost('comment');
    if ($post && isset($post['comment'])) {
        $post['comment'] .= $this->_getAppend();
        Mage::app()->getRequest()->setPost('comment', $post);
    }
}
protected function _getAppend()
{
    $user     = Mage::getSingleton('admin/session');
    $username = $user->getUser()->getUsername();
    return "<br/><br/> Posted by: " . $username;
}


问:
Automated way to update a view code using sql script?
Lets suppose i have a table A with 4 columns and I've created a view for the same table which consists of all 4 columns. Now i want to write a script/stored procedure which should update the view code whenever new column is added to Table A in a same physical order.

For Example:
Table  A has following columns

```<code>'Name','Age','Gender','Address'
</code>```

Supposed view code is:

```<code>Select Name,Age,Gender,Address from Table A
</code>```

Now i add an additional column PhoneNumber on Table A. When i run script/Stored Procedure this new column should automatically be added to the query as follows:

Desired view code generated after i run script should be like this:

```<code>Select Name,Age,Gender,Address,PhoneNumber from Table A
</code>```

答:
Hope It will works </p>

```<code>    DECLARE @tablename as varchar(20)
    DECLARE @query AS NVARCHAR(MAX)
    DECLARE @ColumnName AS NVARCHAR(MAX)
    set @tablename='tableName'
    SELECT @ColumnName= ISNULL(@ColumnName + ',','')
            + QUOTENAME(COLUMN_NAME)
    FROM ( SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = @tablename
                )  as ccc
    set @query='select '+@ColumnName+' from '+@tablename+''
    EXEC (@query)
</code>```

Body:
Lets suppose i have a table A with 4 columns and I've created a view for the same table which consists of all 4 columns. Now i want to write a script/stored procedure which should update the view code whenever new column is added to Table A in a same physical order.

For Example:
Table  A has following columns

'Name','Age','Gender','Address'

Supposed view code is:

Select Name,Age,Gender,Address from Table A

Now i add an additional column PhoneNumber on Table A. When i run script/Stored Procedure this new column should automatically be added to the query as follows:

Desired view code generated after i run script should be like this:

Select Name,Age,Gender,Address,PhoneNumber from Table A

Body:
Hope It will works

    DECLARE @tablename as varchar(20)
    DECLARE @query AS NVARCHAR(MAX)
    DECLARE @ColumnName AS NVARCHAR(MAX)
    set @tablename='tableName'
    SELECT @ColumnName= ISNULL(@ColumnName + ',','')
            + QUOTENAME(COLUMN_NAME)
    FROM ( SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = @tablename
                )  as ccc
    set @query='select '+@ColumnName+' from '+@tablename+''
    EXEC (@query)