问:
GetOleDbSchemaTable throws exception becaues it doesn't find the object sheet$'Print_Area'
I'm trying to expose the column names from excel in a vb.net application. The code looks like this.

```<code>Dim EXCEL_CONNECTION_TEMPLATE As String =
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;'"
Using con As OleDbConnection = New OleDbConnection(String.Format(EXCEL_CONNECTION_TEMPLATE, savePath))
    con.Open()
    Dim schema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, Nothing)
    DoStuffWith(schema)
End Using
</code>```

After execution i get an exception throwed by GetOleDbSchemaTable:

The Microsoft Jet database engine could not find the object
  ''sheetname $'Print_Area'.  Make sure the object exists and that you
  spell its name and the path name correctly.
  System.Data.OleDb.OleDbException

It looks like, that GetOleDbSchemaTable has some problem with the sheetnames if they contains space and has print area defined with it on the same time.

Tried to supply parameters like:

```<code>Dim schema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, New Object() {Nothing, Nothing, "sheetname $"})
</code>```

This way it didn't throwed the exception but returned with no value.

Any tip / workaround / suggestion is welcomed. And it's obviously not an option to ask the users not to include space and print area in the excel file they uploads.

答:
Found the solution.

It seems that if any of the sheet names in the uploaded excel file contains space, the oledb wraps it between single quote. This seems to working now:

```<code>Dim schema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, New Object() {Nothing, Nothing, "'sheetname $'"})
</code>```

Body:
I'm trying to expose the column names from excel in a vb.net application. The code looks like this.

Dim EXCEL_CONNECTION_TEMPLATE As String =
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;'"
Using con As OleDbConnection = New OleDbConnection(String.Format(EXCEL_CONNECTION_TEMPLATE, savePath))
    con.Open()
    Dim schema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, Nothing)
    DoStuffWith(schema)
End Using

After execution i get an exception throwed by GetOleDbSchemaTable:

The Microsoft Jet database engine could not find the object
  ''sheetname $'Print_Area'.  Make sure the object exists and that you
  spell its name and the path name correctly.
  System.Data.OleDb.OleDbException

It looks like, that GetOleDbSchemaTable has some problem with the sheetnames if they contains space and has print area defined with it on the same time.

Tried to supply parameters like:

Dim schema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, New Object() {Nothing, Nothing, "sheetname $"})

This way it didn't throwed the exception but returned with no value.

Any tip / workaround / suggestion is welcomed. And it's obviously not an option to ask the users not to include space and print area in the excel file they uploads.

Body:
Found the solution.

It seems that if any of the sheet names in the uploaded excel file contains space, the oledb wraps it between single quote. This seems to working now:

Dim schema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, New Object() {Nothing, Nothing, "'sheetname $'"})


来源: stackexchange

问:
Can't download from AWS boto3 generated signed url

I'm trying to upload a file to an existing AWS s3 bucket, generate a public URL and use that URL (somewhere else) to download the file.
I'm closely following the example here:

```<code>import os
import boto3
import requests
import tempfile

s3 = boto3.client('s3')

with tempfile.NamedTemporaryFile(mode="w", delete=False) as outfile:
    outfile.write("dummycontent")
    file_name = outfile.name

with open(file_name, mode="r") as outfile:
    s3.upload_file(outfile.name, "twistimages", "filekey")

os.unlink(file_name)

url = s3.generate_presigned_url(
    ClientMethod='get_object',
    Params={
        'Bucket': 'twistimages',
        'Key': 'filekey'
    }
)

response = requests.get(url)
print(response)
</code>```

I would expect to see a success return code (200) from the requests library.

Instead, stdout is: <Response [400]>

Also, if I navigate to the corresponding URL with a webbrowser, I get an XML file with an error code: InvalidRequest and an error message:

The authorization mechanism you have provided is not supported. Please
  use AWS4-HMAC-SHA256.

How can I use boto3 to generate a public URL, which can easily be downloaded by any user by just navigating to the corresponding URL, without generating complex headers?

Why does the example code from the official documentation not work in my case?

答:
AWS S3 still support legacy old v2 signature in US region(prior 2014). But under new AWS region, only AWS4-HMAC-SHA256(s3v4) are allowed.

To support this features , you must specify them explicitly in .aws/config file or during boto3.s3 resource/client instantiation.  e.g.

```<code># add this entry under ~/.aws/config
[default]
s3.signature_version = s3v4

[other profile]
s3.signature_version = s3v4
</code>```

Or declare them explicitly

```<code>s3client = boto3.client('s3', config= boto3.session.Config(signature_version='s3v4'))

s3resource = boto3.resource('s3', config= boto3.session.Config(signature_version='s3v4'))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to upload a file to an existing AWS s3 bucket, generate a public URL and use that URL (somewhere else) to download the file.
I'm closely following the example here:

import os
import boto3
import requests
import tempfile

s3 = boto3.client('s3')

with tempfile.NamedTemporaryFile(mode="w", delete=False) as outfile:
    outfile.write("dummycontent")
    file_name = outfile.name

with open(file_name, mode="r") as outfile:
    s3.upload_file(outfile.name, "twistimages", "filekey")

os.unlink(file_name)

url = s3.generate_presigned_url(
    ClientMethod='get_object',
    Params={
        'Bucket': 'twistimages',
        'Key': 'filekey'
    }
)

response = requests.get(url)
print(response)

I would expect to see a success return code (200) from the requests library.

Instead, stdout is: <Response [400]>

Also, if I navigate to the corresponding URL with a webbrowser, I get an XML file with an error code: InvalidRequest and an error message:

The authorization mechanism you have provided is not supported. Please
  use AWS4-HMAC-SHA256.

How can I use boto3 to generate a public URL, which can easily be downloaded by any user by just navigating to the corresponding URL, without generating complex headers?

Why does the example code from the official documentation not work in my case?

Body:
AWS S3 still support legacy old v2 signature in US region(prior 2014). But under new AWS region, only AWS4-HMAC-SHA256(s3v4) are allowed.

To support this features , you must specify them explicitly in .aws/config file or during boto3.s3 resource/client instantiation.  e.g.

# add this entry under ~/.aws/config
[default]
s3.signature_version = s3v4

[other profile]
s3.signature_version = s3v4

Or declare them explicitly

s3client = boto3.client('s3', config= boto3.session.Config(signature_version='s3v4'))

s3resource = boto3.resource('s3', config= boto3.session.Config(signature_version='s3v4'))


问:
Render then append new component after click
Is it possible to render and append a new component after click? I have my calendar component

```<code>return (
  <span
    key={date.toString()}
    className={"day" + (isToday ? " today" : "") + (isCurrentMonth ? "" : " different-month") + (date.isSame(selected) ? " selected" : "")}
    onClick={()=>select(day)}>{number}</span>
);
</code>```

onClick I want to render my jsWindow Component

```<code>render(){
    return (
        <div className="js-window">
        {console.log(this.props)}
            <Icon icon={close} className="closeBtn" size={24} onClick={(e)=>e.target.parentNode.parentNode.remove()}/>
            {this.props.children}
        </div>
    )
}
</code>```

After click close icon I want remove JsWindow.

答:
You can use conditional rendering:</p>

```<code>{ condition && <Component /> }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to render and append a new component after click? I have my calendar component

return (
  select(day)}>{number}
);

onClick I want to render my jsWindow Component

render(){
    return (

        {console.log(this.props)}
            <Icon icon={close} className="closeBtn" size={24} onClick={(e)=>e.target.parentNode.parentNode.remove()}/>
            {this.props.children}

    )
}

After click close icon I want remove JsWindow.

Body:
You can use conditional rendering:

{ condition && <Component /> }


问:
Delaying excecution of a controller until all json files are loaded
I'm still getting my head around AngularJS, so my question may be flawed, but is it possible to delay the execution of a controller until the json files are loaded (in a different function)?

Here's the controller:

```<code>app.controller('progressCtrl', ['$scope', '$routeParams', '$http', 'content', function($scope, $routeParams, $http, content) {

    function initScope() {
        $scope.pageId = $routeParams.pageId;
        $scope.totalPages = 0;

        content.success(function(data) {
        $scope.pages = data;
        angular.forEach($scope.pages, function(value, key) {
            if ($scope.totalPages <= value.id) $scope.totalPages = value.id;
            if ($scope.pageId == value.id) {
                value.class = "active";
            } else {
                value.class = "";
            }
            if (incompleteObjectives.length>0) {
                var matchFound = false;
                for (var i=0;i<incompleteObjectives.length-1;i++) {
                    if (incompleteObjectives[i].indexOf('page-'+value.id+'-')) {
                        matchFound = true;
                    }
                }
                if (!matchFound) {
                    value.class += " completed";
                }
            } else {
                value.class += " completed";
            }
        });
    });
}

    initScope();

}]);
</code>```

And here is the factory that calls the 'getData' function, which is where the json files are loaded...

```<code>/*Factory that runs http.get on content.json, used by multiple controllers */
app.factory('content', ['$http', function($http) {
    var url = 'json/content.js';
    return $http.get(url)
        .success(function(data) {

            for (var i = 0; i < data.length; i++) {
                numberOfPages += 1;
            }
            // load page .js files
            var tempData = getData(0);
            for (var i = 1; i < numberOfPages; i++) {
                (function(i) {
                    tempData = tempData.then(function() {
                        return getData(i);
                    });
                }(i));
            }

            return data;
        })
        .error(function(data) {
            return data;
        });
}]);

// loads individual page data, stores in pageData
function getData(id) {
    return $.ajax({
        url: 'json/page' + (id + 1) + '.js',
        dataType: 'json'
    }).done(function(d) {
        if(firstRun)
            addPageObjectives(id, d)
        // push data into pageData array, for use later when pages are routed to
        console.log("pushing page data into pageData for page "+id);
        pageData.push(d);
    }).fail(function() {
        // console.log('ERROR loading page index ' + id);
    });
}
</code>```

For completion's sake, here's the angular html, which features an ng-class:

```<code><div ng-if="content.titletext!=undefined" class="sidetitle" ng-controller="progressCtrl">
                <div class="container">
                    <div>
                        {{content.titletext}}
                    </div>
                    <div class="progress-buttons">
                        <div ng-repeat="(skey,page) in pages" class="button {{skey+1}}" ng-class="page.class" ng-attr-id="{{'nav-'+(skey+1)}}">
                            <div ng-switch="page.titletext || '_undefined_'">
                                <span ng-switch-when="_undefined_">{{skey+1}}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="container">
                    <div ng-if="content.chapterTitleText!=undefined" class="side-chapter-title">
                        {{content.chapterTitleText}}
                    </div>
                    <div class="progress-pages">
                        <span>{{pageId}} of {{totalPages}}</span>
                    </div>
                </div>
            </div>
</code>```

Ultimately it's the pageData array I want to access but, at the point the progress controller is running only the first json file has loaded so I can only access details from the first page. I'd like to have the code in progressController run when all the json files are loaded - and still have access to the value.class property.

Is that possible?

Thanks.

UPDATE

From an answer below, here's what I've tried. I know the following is wrong, but I'd like some tips on how it's wrong, if possible.

```<code>/*Factory that runs http.get on content.json, used by multiple controllers */
app.factory('content', ['$http', function($http) {
    var promise;
    var url = 'json/content.js';
    function init() {
        console.log("Good news! content factory init function does get called!");
        promise = $http.get(url).then(function success(data) {
            for (var i = 0; i < data.length; i++) {
                numberOfPages += 1;
            }
            console.log("data.length = "+data.length); // this outputs as 'undefined'; I'm not sure why, given loading was, presumably, successful
            // load page .js files
            var tempData = getData(0);
            for (var i = 1; i < numberOfPages; i++) {
                (function(i) {
                    tempData = tempData.then(function() {
                        return getData(i);
                    });
                }(i));
            }
            return data;
        }); // I took off the .error lines because they threw an error - I'm assuming the syntax didn't match the new 'success' syntax above
    }

    init(); // I added this - not sure if that's right, but otherwise the init function didn't run...

    function getData(id) {
        return $.ajax({
            url: 'json/page' + (id + 1) + '.js',
            dataType: 'json'
        }).done(function(d) {
            if(firstRun)
                addPageObjectives(id, d)
            // push data into pageData array, for use later when pages are routed to
            console.log("pushing page data into pageData for page "+id);
            pageData.push(d);
        }).fail(function() {
            // console.log('ERROR loading page index ' + id);
        });
        return promise;
    }

    // public API
    return {
        getData: getData
    }

}]);
</code>```

Elsewhere, in the controllers I'm using lines, such as:

```<code>content.getData().then(function(data) {
    ....
}
</code>```

...to access the page data (which, I think is not working). I'm guessing this update is wrong in a lot of places, but if folks are willing to help, that would be great. Thanks again.

答:
My suggestion would be to expose a getData function in your contents factory that returns a Promise with the data results. You can use the $q service to aggregate your pageData http calls.

```<code>app.factory('content', ['$http', '$q', function($http, $q) {
var promise;
var url = 'json/content.js';
function init() {
    promise = $http.get(url).then(function success(data) {
        var numberOfPages = 0;
        var dataRequests = [];
        for (var i = 0; i < data.length; i++) {
            numberOfPages += 1;
        }
        // load page .js files
        for (var i = 0; i < numberOfPages; i++) {
            dataRequests.push(fetchPageData(i));
        }

        return $q.all(dataRequests).then(function (pageData) {
            /* pageData is an array of results from fetchPageData calls */
            return pageData;
        });
    });
}

function fetchPageData(id) {
    return $http({
        method: 'GET',
        url: 'json/page' + (id + 1) + '.js',
        responseType: 'json'
    }).then(function(d) {
        return d;
    }, function(error) {/*handle error*/});
}

function getData () {
    return promise; /* this is the pageData result from $q.all above */
}

init();

// public API
return {
    getData: getData
}
...
</code>```

in your controller:

```<code>content.getData().then(function(data) {
    //do stuff here
})
</code>```

Body:
I'm still getting my head around AngularJS, so my question may be flawed, but is it possible to delay the execution of a controller until the json files are loaded (in a different function)?

Here's the controller:

app.controller('progressCtrl', ['$scope', '$routeParams', '$http', 'content', function($scope, $routeParams, $http, content) {

    function initScope() {
        $scope.pageId = $routeParams.pageId;
        $scope.totalPages = 0;

        content.success(function(data) {
        $scope.pages = data;
        angular.forEach($scope.pages, function(value, key) {
            if ($scope.totalPages <= value.id) $scope.totalPages = value.id;
            if ($scope.pageId == value.id) {
                value.class = "active";
            } else {
                value.class = "";
            }
            if (incompleteObjectives.length>0) {
                var matchFound = false;
                for (var i=0;i<incompleteObjectives.length-1;i++) {
                    if (incompleteObjectives[i].indexOf('page-'+value.id+'-')) {
                        matchFound = true;
                    }
                }
                if (!matchFound) {
                    value.class += " completed";
                }
            } else {
                value.class += " completed";
            }
        });
    });
}

    initScope();

}]);

And here is the factory that calls the 'getData' function, which is where the json files are loaded...

/*Factory that runs http.get on content.json, used by multiple controllers */
app.factory('content', ['$http', function($http) {
    var url = 'json/content.js';
    return $http.get(url)
        .success(function(data) {

            for (var i = 0; i < data.length; i++) {
                numberOfPages += 1;
            }
            // load page .js files
            var tempData = getData(0);
            for (var i = 1; i < numberOfPages; i++) {
                (function(i) {
                    tempData = tempData.then(function() {
                        return getData(i);
                    });
                }(i));
            }

            return data;
        })
        .error(function(data) {
            return data;
        });
}]);

// loads individual page data, stores in pageData
function getData(id) {
    return $.ajax({
        url: 'json/page' + (id + 1) + '.js',
        dataType: 'json'
    }).done(function(d) {
        if(firstRun)
            addPageObjectives(id, d)
        // push data into pageData array, for use later when pages are routed to
        console.log("pushing page data into pageData for page "+id);
        pageData.push(d);
    }).fail(function() {
        // console.log('ERROR loading page index ' + id);
    });
}

For completion's sake, here's the angular html, which features an ng-class:

                        {{content.titletext}}

                                {{skey+1}}

                        {{content.chapterTitleText}}

                        {{pageId}} of {{totalPages}}

Ultimately it's the pageData array I want to access but, at the point the progress controller is running only the first json file has loaded so I can only access details from the first page. I'd like to have the code in progressController run when all the json files are loaded - and still have access to the value.class property.

Is that possible?

Thanks.

UPDATE

From an answer below, here's what I've tried. I know the following is wrong, but I'd like some tips on how it's wrong, if possible.

/*Factory that runs http.get on content.json, used by multiple controllers */
app.factory('content', ['$http', function($http) {
    var promise;
    var url = 'json/content.js';
    function init() {
        console.log("Good news! content factory init function does get called!");
        promise = $http.get(url).then(function success(data) {
            for (var i = 0; i < data.length; i++) {
                numberOfPages += 1;
            }
            console.log("data.length = "+data.length); // this outputs as 'undefined'; I'm not sure why, given loading was, presumably, successful
            // load page .js files
            var tempData = getData(0);
            for (var i = 1; i < numberOfPages; i++) {
                (function(i) {
                    tempData = tempData.then(function() {
                        return getData(i);
                    });
                }(i));
            }
            return data;
        }); // I took off the .error lines because they threw an error - I'm assuming the syntax didn't match the new 'success' syntax above
    }

    init(); // I added this - not sure if that's right, but otherwise the init function didn't run...

    function getData(id) {
        return $.ajax({
            url: 'json/page' + (id + 1) + '.js',
            dataType: 'json'
        }).done(function(d) {
            if(firstRun)
                addPageObjectives(id, d)
            // push data into pageData array, for use later when pages are routed to
            console.log("pushing page data into pageData for page "+id);
            pageData.push(d);
        }).fail(function() {
            // console.log('ERROR loading page index ' + id);
        });
        return promise;
    }

    // public API
    return {
        getData: getData
    }

}]);

Elsewhere, in the controllers I'm using lines, such as:

content.getData().then(function(data) {
    ....
}

...to access the page data (which, I think is not working). I'm guessing this update is wrong in a lot of places, but if folks are willing to help, that would be great. Thanks again.

Body:
My suggestion would be to expose a getData function in your contents factory that returns a Promise with the data results. You can use the $q service to aggregate your pageData http calls.

app.factory('content', ['$http', '$q', function($http, $q) {
var promise;
var url = 'json/content.js';
function init() {
    promise = $http.get(url).then(function success(data) {
        var numberOfPages = 0;
        var dataRequests = [];
        for (var i = 0; i < data.length; i++) {
            numberOfPages += 1;
        }
        // load page .js files
        for (var i = 0; i < numberOfPages; i++) {
            dataRequests.push(fetchPageData(i));
        }

        return $q.all(dataRequests).then(function (pageData) {
            /* pageData is an array of results from fetchPageData calls */
            return pageData;
        });
    });
}

function fetchPageData(id) {
    return $http({
        method: 'GET',
        url: 'json/page' + (id + 1) + '.js',
        responseType: 'json'
    }).then(function(d) {
        return d;
    }, function(error) {/*handle error*/});
}

function getData () {
    return promise; /* this is the pageData result from $q.all above */
}

init();

// public API
return {
    getData: getData
}
...

in your controller:

content.getData().then(function(data) {
    //do stuff here
})


问:
RadioButton and CheckBox not showing in Custom Look and Feel
I'm creating a custom Look and Feel for a company as my final trainee ship for graduation. I've been stuck on this part for a few days now and me and my colleagues can't seem to fix it.

I'm trying to create a custom radio button an checkbox for the Look and Feel. Now when I want to display the stock ones to the screen / JFrame it won't display.

Once I activate my Look and Feel the checkboxes and radio buttons dissapear. But the label of them does display on screen. When I create the checkbox / radio outside the look and feel or give a nimbus look and feel to them, it does display. So somehow my Look and Feel is breaking things. Can anyone help?

This is my code for the radio button;

```<code>public class MyRadioBut extends BasicRadioButtonUI {

    public MyRadioBut()
    {
        super();
    }

    public static ComponentUI createUI(JComponent c) {
        return new MyRadioBut();
    }

    @Override
    public void installUI(final JComponent c) {
        super.installUI(c);
    }

    public static MyRadioBut createRadio()
    {
        MyRadioBut radio = new MyRadioBut();

        return radio;
    }
    private boolean defaults_initialized = false;
    @Override
    public void installDefaults(AbstractButton b) {
        super.installDefaults(b);

    }
}
</code>```

Code for checkbox is the same.

Look and feel code;

```<code>package iac.lookandfeel;

import java.awt.Font;

import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicLookAndFeel;

public class MyLookAndFeel extends BasicLookAndFeel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    static MyButton btn = new MyButton();
    static MyProgressBar pb = new MyProgressBar();
    static MyLabel lbl = new MyLabel();
    static MyTab tab = new MyTab();
    static MyRadioBut radio = new MyRadioBut();
    static MyComboBox combo = new MyComboBox();

    public MyLookAndFeel() {
        super();

    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return "IAC Look and Feel";
    }

    @Override
    public String getID() {
        // TODO Auto-generated method stub
        return "IAC Look and Feel";
    }

    @Override
    public String getDescription() {
        // TODO Auto-generated method stub
        return "IAC's Look And Feel";
    }

    @Override
    public boolean isNativeLookAndFeel() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isSupportedLookAndFeel() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean getSupportsWindowDecorations()
    {
        return true;
    }
    public static void setAllFonts() {
        Font defaultFont = UIManager.getDefaults().getFont("Button.font");
        int defaultSize = defaultFont.getSize();
        Font font = new Font("Serif", Font.PLAIN, 50);

        UIManager.put("Button.font", font);

        UIManager.put("RadioButton.font", font);
        UIManager.put("CheckBox.font", font);

        UIManager.put("ComboBox.font", font);
        UIManager.put("Label.font", font);
        UIManager.put("TabbedPane.font", font);
        UIManager.put("TextField.font", font);
        UIManager.put("PasswordField.font", font);
        UIManager.put("TextArea.font", font);
        UIManager.put("ProgressBar.font", font);

    }

    @Override
    protected void initClassDefaults(UIDefaults table)
    {
        setAllFonts();
        MyButton.createButton();
        MyProgressBar.createBar();
        MyLabel.createLabel();
        MyTab.createTab();
        MyRadioBut.createRadio();
        MyCheckBox.createCheckBox();
        MyComboBox.createCombo();

        super.initClassDefaults(table);
        String IACPackage = "iac.lookandfeel.";
        final String basicPackageName = "javax.swing.plaf.basic.";
        Object[] uiDefaults = {
                "ButtonUI", IACPackage + "MyButton",
                "CheckBoxUI", IACPackage + "MyCheckBox",
                "ColorChooserUI", basicPackageName + "BasicColorChooserUI",
                "FormattedTextFieldUI", basicPackageName + "BasicFormattedTextFieldUI",
                "MenuBarUI", basicPackageName + "BasicMenuBarUI",
                "MenuUI", basicPackageName + "BasicMenuUI",
                "MenuItemUI", basicPackageName + "BasicMenuItemUI",
                "CheckBoxMenuItemUI", basicPackageName + "BasicCheckBoxMenuItemUI",
                "RadioButtonMenuItemUI", basicPackageName + "BasicRadioButtonMenuItemUI",
                "RadioButtonUI", IACPackage + "MyRadioBut",
                "ToggleButtonUI", basicPackageName + "BasicToggleButtonUI",
                "PopupMenuUI", basicPackageName + "BasicPopupMenuUI",
                "ProgressBarUI", IACPackage + "MyProgressBar",
                "ScrollBarUI", basicPackageName + "BasicScrollBarUI",
                "ScrollPaneUI", basicPackageName + "BasicScrollPaneUI",
                "SplitPaneUI", basicPackageName + "BasicSplitPaneUI",
                "SliderUI", basicPackageName + "BasicSliderUI",
                "SeparatorUI", basicPackageName + "BasicSeparatorUI",
                "SpinnerUI", basicPackageName + "BasicSpinnerUI",
                "ToolBarSeparatorUI", basicPackageName + "BasicToolBarSeparatorUI",
                "PopupMenuSeparatorUI", basicPackageName + "BasicPopupMenuSeparatorUI",
                "TabbedPaneUI", IACPackage + "MyTab",
                "TextAreaUI", basicPackageName + "BasicTextAreaUI",
                "TextFieldUI", basicPackageName + "BasicTextFieldUI",
                "PasswordFieldUI", basicPackageName + "BasicPasswordFieldUI",
                "TextPaneUI", basicPackageName + "BasicTextPaneUI",
                "EditorPaneUI", basicPackageName + "BasicEditorPaneUI",
                "TreeUI", basicPackageName + "BasicTreeUI",
                "LabelUI", IACPackage + "MyLabel",
                "ListUI", basicPackageName + "BasicListUI",
                "ToolBarUI", basicPackageName + "BasicToolBarUI",
                "ToolTipUI", basicPackageName + "BasicToolTipUI",
                "ComboBoxUI", IACPackage + "MyComboBox",
                "TableUI", basicPackageName + "BasicTableUI",
                "TableHeaderUI", basicPackageName + "BasicTableHeaderUI",
                "InternalFrameUI", basicPackageName + "BasicInternalFrameUI",
                "DesktopPaneUI", basicPackageName + "BasicDesktopPaneUI",
                "DesktopIconUI", basicPackageName + "BasicDesktopIconUI",
                "FileChooserUI", basicPackageName + "BasicFileChooserUI",
                "OptionPaneUI", basicPackageName + "BasicOptionPaneUI",
                "PanelUI", basicPackageName + "BasicPanelUI",
                "ViewportUI", basicPackageName + "BasicViewportUI",
                "RootPaneUI", basicPackageName + "BasicRootPaneUI",
        };
        //   UIManager.put(MyLookAndFeel.UI_CLASS_ID,  MyButton.class.getName());
        table.putDefaults(uiDefaults);
    }
}
</code>```

IACPackage is my own package which I use in all components.

Hope one of you guys got an idea.

I have a test gui which I test the look and feel on: I create the checkbox and radio like this;

JCheckBox CBox = new JCheckBox("Checkbox");
    JRadioButton Radio = new JRadioButton("Radio");

It does display the string but not the icons.

答:
Fixed it myself.

```<code>Icon defaultIcon;
defaultIcon = UIManager.getIcon("CheckBox.icon");
UIManager.put("CheckBox.icon", defaultIcon);
</code>```

I used this to get the default icon from UI manager and after that I put it back with the put statement. Quite stupid solution but it works!

Body:
I'm creating a custom Look and Feel for a company as my final trainee ship for graduation. I've been stuck on this part for a few days now and me and my colleagues can't seem to fix it.

I'm trying to create a custom radio button an checkbox for the Look and Feel. Now when I want to display the stock ones to the screen / JFrame it won't display.

Once I activate my Look and Feel the checkboxes and radio buttons dissapear. But the label of them does display on screen. When I create the checkbox / radio outside the look and feel or give a nimbus look and feel to them, it does display. So somehow my Look and Feel is breaking things. Can anyone help?

This is my code for the radio button;

public class MyRadioBut extends BasicRadioButtonUI {

    public MyRadioBut()
    {
        super();
    }

    public static ComponentUI createUI(JComponent c) {
        return new MyRadioBut();
    }

    @Override
    public void installUI(final JComponent c) {
        super.installUI(c);
    }

    public static MyRadioBut createRadio()
    {
        MyRadioBut radio = new MyRadioBut();

        return radio;
    }
    private boolean defaults_initialized = false;
    @Override
    public void installDefaults(AbstractButton b) {
        super.installDefaults(b);

    }
}

Code for checkbox is the same.

Look and feel code;

package iac.lookandfeel;

import java.awt.Font;

import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicLookAndFeel;

public class MyLookAndFeel extends BasicLookAndFeel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    static MyButton btn = new MyButton();
    static MyProgressBar pb = new MyProgressBar();
    static MyLabel lbl = new MyLabel();
    static MyTab tab = new MyTab();
    static MyRadioBut radio = new MyRadioBut();
    static MyComboBox combo = new MyComboBox();

    public MyLookAndFeel() {
        super();

    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return "IAC Look and Feel";
    }

    @Override
    public String getID() {
        // TODO Auto-generated method stub
        return "IAC Look and Feel";
    }

    @Override
    public String getDescription() {
        // TODO Auto-generated method stub
        return "IAC's Look And Feel";
    }

    @Override
    public boolean isNativeLookAndFeel() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isSupportedLookAndFeel() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean getSupportsWindowDecorations()
    {
        return true;
    }
    public static void setAllFonts() {
        Font defaultFont = UIManager.getDefaults().getFont("Button.font");
        int defaultSize = defaultFont.getSize();
        Font font = new Font("Serif", Font.PLAIN, 50);

        UIManager.put("Button.font", font);

        UIManager.put("RadioButton.font", font);
        UIManager.put("CheckBox.font", font);

        UIManager.put("ComboBox.font", font);
        UIManager.put("Label.font", font);
        UIManager.put("TabbedPane.font", font);
        UIManager.put("TextField.font", font);
        UIManager.put("PasswordField.font", font);
        UIManager.put("TextArea.font", font);
        UIManager.put("ProgressBar.font", font);

    }

    @Override
    protected void initClassDefaults(UIDefaults table)
    {
        setAllFonts();
        MyButton.createButton();
        MyProgressBar.createBar();
        MyLabel.createLabel();
        MyTab.createTab();
        MyRadioBut.createRadio();
        MyCheckBox.createCheckBox();
        MyComboBox.createCombo();

        super.initClassDefaults(table);
        String IACPackage = "iac.lookandfeel.";
        final String basicPackageName = "javax.swing.plaf.basic.";
        Object[] uiDefaults = {
                "ButtonUI", IACPackage + "MyButton",
                "CheckBoxUI", IACPackage + "MyCheckBox",
                "ColorChooserUI", basicPackageName + "BasicColorChooserUI",
                "FormattedTextFieldUI", basicPackageName + "BasicFormattedTextFieldUI",
                "MenuBarUI", basicPackageName + "BasicMenuBarUI",
                "MenuUI", basicPackageName + "BasicMenuUI",
                "MenuItemUI", basicPackageName + "BasicMenuItemUI",
                "CheckBoxMenuItemUI", basicPackageName + "BasicCheckBoxMenuItemUI",
                "RadioButtonMenuItemUI", basicPackageName + "BasicRadioButtonMenuItemUI",
                "RadioButtonUI", IACPackage + "MyRadioBut",
                "ToggleButtonUI", basicPackageName + "BasicToggleButtonUI",
                "PopupMenuUI", basicPackageName + "BasicPopupMenuUI",
                "ProgressBarUI", IACPackage + "MyProgressBar",
                "ScrollBarUI", basicPackageName + "BasicScrollBarUI",
                "ScrollPaneUI", basicPackageName + "BasicScrollPaneUI",
                "SplitPaneUI", basicPackageName + "BasicSplitPaneUI",
                "SliderUI", basicPackageName + "BasicSliderUI",
                "SeparatorUI", basicPackageName + "BasicSeparatorUI",
                "SpinnerUI", basicPackageName + "BasicSpinnerUI",
                "ToolBarSeparatorUI", basicPackageName + "BasicToolBarSeparatorUI",
                "PopupMenuSeparatorUI", basicPackageName + "BasicPopupMenuSeparatorUI",
                "TabbedPaneUI", IACPackage + "MyTab",
                "TextAreaUI", basicPackageName + "BasicTextAreaUI",
                "TextFieldUI", basicPackageName + "BasicTextFieldUI",
                "PasswordFieldUI", basicPackageName + "BasicPasswordFieldUI",
                "TextPaneUI", basicPackageName + "BasicTextPaneUI",
                "EditorPaneUI", basicPackageName + "BasicEditorPaneUI",
                "TreeUI", basicPackageName + "BasicTreeUI",
                "LabelUI", IACPackage + "MyLabel",
                "ListUI", basicPackageName + "BasicListUI",
                "ToolBarUI", basicPackageName + "BasicToolBarUI",
                "ToolTipUI", basicPackageName + "BasicToolTipUI",
                "ComboBoxUI", IACPackage + "MyComboBox",
                "TableUI", basicPackageName + "BasicTableUI",
                "TableHeaderUI", basicPackageName + "BasicTableHeaderUI",
                "InternalFrameUI", basicPackageName + "BasicInternalFrameUI",
                "DesktopPaneUI", basicPackageName + "BasicDesktopPaneUI",
                "DesktopIconUI", basicPackageName + "BasicDesktopIconUI",
                "FileChooserUI", basicPackageName + "BasicFileChooserUI",
                "OptionPaneUI", basicPackageName + "BasicOptionPaneUI",
                "PanelUI", basicPackageName + "BasicPanelUI",
                "ViewportUI", basicPackageName + "BasicViewportUI",
                "RootPaneUI", basicPackageName + "BasicRootPaneUI",
        };
        //   UIManager.put(MyLookAndFeel.UI_CLASS_ID,  MyButton.class.getName());
        table.putDefaults(uiDefaults);
    }
}

IACPackage is my own package which I use in all components.

Hope one of you guys got an idea.

I have a test gui which I test the look and feel on: I create the checkbox and radio like this;

JCheckBox CBox = new JCheckBox("Checkbox");
    JRadioButton Radio = new JRadioButton("Radio");

It does display the string but not the icons.

Body:
Fixed it myself.

Icon defaultIcon;
defaultIcon = UIManager.getIcon("CheckBox.icon");
UIManager.put("CheckBox.icon", defaultIcon);

I used this to get the default icon from UI manager and after that I put it back with the put statement. Quite stupid solution but it works!


问:
Rewrite under exists
Say I have the following relation:

```<code>Inductive my_relation: nat -> Prop :=
constr n: my_relation n.
</code>```

and I want to prove the following:

```<code>Lemma example:
  (forall n, my_relation n -> my_relation (S n)) -> (exists n, my_relation n) -> exists n, my_relation (S n).
Proof.
  intros.
</code>```

After introducing, I have the following environment:

```<code>1 subgoal
H : forall n : nat, my_relation n -> my_relation (S n)
H0 : exists n : nat, my_relation n
______________________________________(1/1)
exists n : nat, my_relation (S n)
</code>```

My question is: is there a possibility to rewrite H under the exists quantifier ? If not, is there a strategy to solve this kind of problem (this particular one is not really relevant, but problems where you have to prove an exists using another exists, and where, informally, you can « deduce » a way to rewrite the exists in the hypothesis into the exists in the goal) ?

For instance, if I try rewrite H in H0. I have, an error (Error: Cannot find a relation to rewrite.).

答:
I found a way, I post it here for any similar questions in the future.

It is possible to inverse the exists hypothesis, in order to "instantiate" the quantified variable, for instance, here, the proof can be finished by:

```<code>  inversion H0.
  apply H in H1.
  exists x.
  apply H1.
Qed.
</code>```

After inversion H0, we have in the environment:

```<code>1 subgoal
H : forall n : nat, my_relation n -> my_relation (S n)
H0 : exists n : nat, my_relation n
x : nat
H1 : my_relation x
______________________________________(1/1)
exists n : nat, my_relation (S n)
</code>```

and we can now work with x.

Title: Rewrite under exists

Body:
Say I have the following relation:

Inductive my_relation: nat -> Prop :=
constr n: my_relation n.

and I want to prove the following:

Lemma example:
  (forall n, my_relation n -> my_relation (S n)) -> (exists n, my_relation n) -> exists n, my_relation (S n).
Proof.
  intros.

After introducing, I have the following environment:

1 subgoal
H : forall n : nat, my_relation n -> my_relation (S n)
H0 : exists n : nat, my_relation n
______________________________________(1/1)
exists n : nat, my_relation (S n)

My question is: is there a possibility to rewrite H under the exists quantifier ? If not, is there a strategy to solve this kind of problem (this particular one is not really relevant, but problems where you have to prove an exists using another exists, and where, informally, you can « deduce » a way to rewrite the exists in the hypothesis into the exists in the goal) ?

For instance, if I try rewrite H in H0. I have, an error (Error: Cannot find a relation to rewrite.).

Body:
I found a way, I post it here for any similar questions in the future.

It is possible to inverse the exists hypothesis, in order to "instantiate" the quantified variable, for instance, here, the proof can be finished by:

  inversion H0.
  apply H in H1.
  exists x.
  apply H1.
Qed.

After inversion H0, we have in the environment:

1 subgoal
H : forall n : nat, my_relation n -> my_relation (S n)
H0 : exists n : nat, my_relation n
x : nat
H1 : my_relation x
______________________________________(1/1)
exists n : nat, my_relation (S n)

and we can now work with x.


问:
Combining C++ header files
Is there an automated way to take a large amount of C++ header files and combine them in a single one?

This operation must, of course, concatenate the files in the right order so that no types, etc. are defined before they are used in upcoming classes and functions.

Basically, I'm looking for something that allows me to distribute my library in two files (libfoo.h, libfoo.a), instead of the current bunch of include files + the binary library.

答:
A little bit late, but here it is. I just recently stumbled into this same problem myself and coded this solution: https://github.com/rpvelloso/oneheader

How does it works?

Your project's folder is scanned for C/C++ headers and a list of headers found is created;

For every header in the list it analyzes its #include directives and assemble a dependency graph in the following way:

If the included header is not located inside the project's folder then it is ignored (e.g., if it is a system header);

If the included header is located inside the project's folder then an edge is create in the dependency graph, linking the included header to the current header being analyzed;

The dependency graph is topologically sorted to determine the correct order to concatenate the headers into a single file. If a cycle is found in the graph, the process is interrupted (i.e., if it is not a DAG);

Limitations:

It currently only detects single line #include directives (e.g., #include );

It does not handles headers with the same name in different paths;

It only gives you a correct order to combine all the headers, you still need to concatenate them (maybe you want remove or modify some of them prior to merging).

Compiling:

g++ -Wall -ggdb -std=c++1y -lstdc++fs oneheader.cpp -o oneheader[.exe]

Usage:

./oneheader[.exe] project_folder/ > file_sequence.txt

Title: Combining C++ header files


问:
C# string manipulation, why this doesn't work?
```<code>int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}
</code>```

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

答:
The way you have defined your string doesn't look correct to me at all. I'm guessing the code you're looking for is:

```<code>int i = 1;
for(; i <= 10; i++)
{
    string str = string.Format("test{0}", i);
    Console.WriteLine(str);
}
</code>```

But in that case there's really no reason to create a new string and call Format() for every iteration. You can create a single string and let Console.WriteLine() handle the formating.

```<code>string str = "test{0}";

for(int i = 1; i <= 10; i++)
    Console.WriteLine(str, i);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

Body:
The way you have defined your string doesn't look correct to me at all. I'm guessing the code you're looking for is:

int i = 1;
for(; i <= 10; i++)
{
    string str = string.Format("test{0}", i);
    Console.WriteLine(str);
}

But in that case there's really no reason to create a new string and call Format() for every iteration. You can create a single string and let Console.WriteLine() handle the formating.

string str = "test{0}";

for(int i = 1; i <= 10; i++)
    Console.WriteLine(str, i);


问:
Android FFMPEG do nothing
I try to scale down video on Android device using FFMPEG.
OnCreate of Activity where I call scaleVideo(), also initialization of FFMPEG and binaries load.

```<code>private void scaleVideo(String path) throws FFmpegCommandAlreadyRunningException, IOException {
    File copy = new File(DESTINATION_PATH + FilenameUtils.getBaseName(path) + "_scaled." + FilenameUtils.getExtension(path));

    if (!copy.exists())
        copy.createNewFile();

    String cmd = "-i " + path + " -vf scale=320:-1 " + copy.getPath();
    String[] command = cmd.split(" ");
    fFmpeg.execute(command, new FFmpegExecuteResponseHandler() {
        @Override
        public void onSuccess(String message) {
            Log.i("FFmpeg", message);
            mProgressDialog.cancel();

            runOnUiThread(() -> Toast.makeText(TrimmerActivity.this, getString(R.string.video_saved_at, copy.getPath()), Toast.LENGTH_SHORT).show());

            VideoModel videoModel = new VideoModel();
            videoModel.setPath(copy.getPath());
            videoModel.save();

            finish();
        }

        @Override
        public void onProgress(String message) {
            Log.i("FFmpeg", message);
        }

        @Override
        public void onFailure(String message) {
            Log.e("FFmpeg", message);
        }

        @Override
        public void onStart() {
            Log.i("FFmpeg", "on start");
        }

        @Override
        public void onFinish() {
            Log.i("FFmpeg", "on finish");
        }
    });
}
</code>```

And as output I get:

```<code>I/FFmpeg: on start
D/FFmpeg: Running publishing updates method
I/FFmpeg: ffmpeg version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
I/FFmpeg:   built with gcc 4.8 (GCC)
I/FFmpeg:   configuration: --target-os=linux --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=
I/FFmpeg:   libavutil      55. 17.103 / 55. 17.103
I/FFmpeg:   libavcodec     57. 24.102 / 57. 24.102
I/FFmpeg:   libavformat    57. 25.100 / 57. 25.100
I/FFmpeg:   libavdevice    57.  0.101 / 57.  0.101
I/FFmpeg:   libavfilter     6. 31.100 /  6. 31.100
I/FFmpeg:   libswscale      4.  0.100 /  4.  0.100
I/FFmpeg:   libswresample   2.  0.101 /  2.  0.101
I/FFmpeg:   libpostproc    54.  0.100 / 54.  0.100
I/FFmpeg: Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/storage/emulated/0/MP4_20161015_001403.mp4':
I/FFmpeg:   Metadata:
I/FFmpeg:     major_brand     : iso6
I/FFmpeg:     minor_version   : 1
I/FFmpeg:     compatible_brands: mp42iso6avc1isom
I/FFmpeg:     creation_time   : 2016-10-14 21:14:03
I/FFmpeg:   Duration: 00:00:02.10, start: 0.000000, bitrate: 19564 kb/s
I/FFmpeg:     Stream #0:0(eng): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p, 1920x1080, 19403 kb/s, SAR 1:1 DAR 16:9, 14.75 fps, 15 tbr, 90k tbn, 180k tbc (default)
I/FFmpeg:     Metadata:
I/FFmpeg:       rotate          : 90
I/FFmpeg:       creation_time   : 2016-10-14 21:13:52
I/FFmpeg:     Side data:
I/FFmpeg:       displaymatrix: rotation of -90.00 degrees
I/FFmpeg:     Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 156 kb/s (default)
I/FFmpeg:     Metadata:
I/FFmpeg:       creation_time   : 2016-10-14 21:13:52
</code>```

Video output and input are correct. Files exist and video player can recognize input.
And that's all. CPU/GPU/Memory do nothing and no callbacks called.
That my first time using FFMPEG, so I don't know what to do.

答: I know I'm a little bit late, but the issue here is that the file you're trying to write the output to already exists. In case someone else experiences this, just delete the file or add the -y argument. It will overwrite the existing file.

Title: Android FFMPEG do nothing

Body:
I try to scale down video on Android device using FFMPEG.
OnCreate of Activity where I call scaleVideo(), also initialization of FFMPEG and binaries load.

private void scaleVideo(String path) throws FFmpegCommandAlreadyRunningException, IOException {
    File copy = new File(DESTINATION_PATH + FilenameUtils.getBaseName(path) + "_scaled." + FilenameUtils.getExtension(path));

    if (!copy.exists())
        copy.createNewFile();

    String cmd = "-i " + path + " -vf scale=320:-1 " + copy.getPath();
    String[] command = cmd.split(" ");
    fFmpeg.execute(command, new FFmpegExecuteResponseHandler() {
        @Override
        public void onSuccess(String message) {
            Log.i("FFmpeg", message);
            mProgressDialog.cancel();

            runOnUiThread(() -> Toast.makeText(TrimmerActivity.this, getString(R.string.video_saved_at, copy.getPath()), Toast.LENGTH_SHORT).show());

            VideoModel videoModel = new VideoModel();
            videoModel.setPath(copy.getPath());
            videoModel.save();

            finish();
        }

        @Override
        public void onProgress(String message) {
            Log.i("FFmpeg", message);
        }

        @Override
        public void onFailure(String message) {
            Log.e("FFmpeg", message);
        }

        @Override
        public void onStart() {
            Log.i("FFmpeg", "on start");
        }

        @Override
        public void onFinish() {
            Log.i("FFmpeg", "on finish");
        }
    });
}

And as output I get:

I/FFmpeg: on start
D/FFmpeg: Running publishing updates method
I/FFmpeg: ffmpeg version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
I/FFmpeg:   built with gcc 4.8 (GCC)
I/FFmpeg:   configuration: --target-os=linux --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=
I/FFmpeg:   libavutil      55. 17.103 / 55. 17.103
I/FFmpeg:   libavcodec     57. 24.102 / 57. 24.102
I/FFmpeg:   libavformat    57. 25.100 / 57. 25.100
I/FFmpeg:   libavdevice    57.  0.101 / 57.  0.101
I/FFmpeg:   libavfilter     6. 31.100 /  6. 31.100
I/FFmpeg:   libswscale      4.  0.100 /  4.  0.100
I/FFmpeg:   libswresample   2.  0.101 /  2.  0.101
I/FFmpeg:   libpostproc    54.  0.100 / 54.  0.100
I/FFmpeg: Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/storage/emulated/0/MP4_20161015_001403.mp4':
I/FFmpeg:   Metadata:
I/FFmpeg:     major_brand     : iso6
I/FFmpeg:     minor_version   : 1
I/FFmpeg:     compatible_brands: mp42iso6avc1isom
I/FFmpeg:     creation_time   : 2016-10-14 21:14:03
I/FFmpeg:   Duration: 00:00:02.10, start: 0.000000, bitrate: 19564 kb/s
I/FFmpeg:     Stream #0:0(eng): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p, 1920x1080, 19403 kb/s, SAR 1:1 DAR 16:9, 14.75 fps, 15 tbr, 90k tbn, 180k tbc (default)
I/FFmpeg:     Metadata:
I/FFmpeg:       rotate          : 90
I/FFmpeg:       creation_time   : 2016-10-14 21:13:52
I/FFmpeg:     Side data:
I/FFmpeg:       displaymatrix: rotation of -90.00 degrees
I/FFmpeg:     Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 156 kb/s (default)
I/FFmpeg:     Metadata:
I/FFmpeg:       creation_time   : 2016-10-14 21:13:52

Video output and input are correct. Files exist and video player can recognize input.
And that's all. CPU/GPU/Memory do nothing and no callbacks called.
That my first time using FFMPEG, so I don't know what to do.


问:
How to save Blob in Ionic
I am new to ionic framework, actually I am getting byte array as response from back end service and converting it to blob. How can I save it to PDF in ionic?

```<code>var blob = new Blob([res], { type: 'application/pdf' });
</code>```

Here res is the response (byte array) from the service.

Code

```<code>var blob = new Blob([res], { type: 'application/pdf' });

        let fileName="Receipt.pdf";
        let filePath = (this.platform.is('android')) ?
        this.file.externalRootDirectory : this.file.cacheDirectory;

        this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry) => {

          console.log("File created!");
          this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
            .then(() => console.log('File is opened'))
            .catch(err => console.error('Error openening file: ' + err));
        })
          .catch((err) => {
            console.error("Error creating file: " + err);
            throw err;
          });
</code>```

Thanks in advance.

答:
In order to SAVE the PDF, you'll need to use some cordova plugins.  Ionic has some nice wrappers around these here.  Check out the File, File Transfer, and File Opener plugins.

Here's some example code you could use once you get these plugins incorporated into your project:

```<code>    var blob = new Blob([res], { type: 'application/pdf' });

    //Determine a native file path to save to
    let filePath = (this.appConfig.isNativeAndroid) ? this.file.externalRootDirectory : this.file.cacheDirectory;

    //Write the file
    this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry: FileEntry) => {

      console.log("File created!");

      //Open with File Opener plugin
      this.fileOpener.open(fileEntry.toURL(), data.type)
        .then(() => console.log('File is opened'))
        .catch(err => console.error('Error openening file: ' + err));
    })
      .catch((err) => {
        console.error("Error creating file: " + err);
        throw err;  //Rethrow - will be caught by caller
      });
</code>```

Title: How to save Blob in Ionic

Body:
I am new to ionic framework, actually I am getting byte array as response from back end service and converting it to blob. How can I save it to PDF in ionic?

var blob = new Blob([res], { type: 'application/pdf' });

Here res is the response (byte array) from the service.

Code

var blob = new Blob([res], { type: 'application/pdf' });

        let fileName="Receipt.pdf";
        let filePath = (this.platform.is('android')) ?
        this.file.externalRootDirectory : this.file.cacheDirectory;

        this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry) => {

          console.log("File created!");
          this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
            .then(() => console.log('File is opened'))
            .catch(err => console.error('Error openening file: ' + err));
        })
          .catch((err) => {
            console.error("Error creating file: " + err);
            throw err;
          });

Thanks in advance.

Body:
In order to SAVE the PDF, you'll need to use some cordova plugins.  Ionic has some nice wrappers around these here.  Check out the File, File Transfer, and File Opener plugins.

Here's some example code you could use once you get these plugins incorporated into your project:

    var blob = new Blob([res], { type: 'application/pdf' });

    //Determine a native file path to save to
    let filePath = (this.appConfig.isNativeAndroid) ? this.file.externalRootDirectory : this.file.cacheDirectory;

    //Write the file
    this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry: FileEntry) => {

      console.log("File created!");

      //Open with File Opener plugin
      this.fileOpener.open(fileEntry.toURL(), data.type)
        .then(() => console.log('File is opened'))
        .catch(err => console.error('Error openening file: ' + err));
    })
      .catch((err) => {
        console.error("Error creating file: " + err);
        throw err;  //Rethrow - will be caught by caller
      });


问:
az acs kubernetes get-credentials | Invalid EC key. | ssh known_hosts corrupted
I run into this issue, and it took me a while, some intuition, educated guess, and an strace -f command to find this bug.
I believe it is wrongly caught exception of the paramico? library, hidden by some Azure CLI exception catcher.

Anyway, there I leave it, so the futere-me, and future-you can find it.

```<code>az acs kubernetes get-credentials
Invalid EC key.

$ strace -f az acs kubernetes get-credentials

(interesting part of MissingHostKeyPolicy wrt hostkeys (my guess - known_hosts file)

[pid  9035] open("/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/client.py", O_RDONLY) = 4
[pid  9035] fstat(4, {st_mode=S_IFREG|0664, st_size=30983, ...}) = 0
[pid  9035] fstat(4, {st_mode=S_IFREG|0664, st_size=30983, ...}) = 0
[pid  9035] read(4, "# Copyright (C) 2006-2007  Robey"..., 8192) = 8192
[pid  9035] read(4, " sock=None,\n        gss_auth=Fal"..., 4096) = 4096
[pid  9035] read(4, "t be\n            verified\n      "..., 4096) = 4096
[pid  9035] read(4, "        )\n            else:\n    "..., 4096) = 4096
[pid  9035] read(4, "    chan = self._transport.open_"..., 4096) = 4096
[pid  9035] read(4, "                allowed_types = "..., 4096) = 4096
[pid  9035] read(4, " MissingHostKeyPolicy (object):\n"..., 4096) = 2311
[pid  9035] read(4, "", 4096)           = 0
[pid  9035] close(4)                    = 0
[pid  9035] stat("/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/hostkeys.py", {st_mode=S_IFREG|0664, st_size=13135, ...}) = 0

(part just before crush)
[pid  9035] read(4, "    bn_ptr = self._lib.BN_bin2bn"..., 4096) = 4096
[pid  9035] read(4, "lf._lib.BIO_new_mem_buf(\n       "..., 4096) = 4096
[pid  9035] read(4, "              hashes.SHA1,\n     "..., 4096) = 4096
[pid  9035] read(4, "DSA_free)\n\n        p = self._int"..., 4096) = 4096
[pid  9035] read(4, "ror(\n                \"MD5 is not"..., 4096) = 4096
[pid  9035] read(4, " CRL version. We only support v2"..., 4096) = 4096
[pid  9035] read(4, ": {0}'.format(extension.oid)\n   "..., 4096) = 4096
[pid  9035] read(4, "   return self._evp_pkey_to_priv"..., 4096) = 4096
[pid  9035] read(4, "eturn _CertificateRevocationList"..., 4096) = 4096
[pid  9035] read(4, " _Reasons.UNSUPPORTED_CIPHER\n   "..., 4096) = 4096
[pid  9035] read(4, "i.NULL)\n        ec_cdata = self."..., 4096) = 4096
[pid  9035] read(4, "res != 1:\n            self._cons"..., 4096) = 4096
[pid  9035] read(4, "ding must be an item from the En"..., 4096) = 4096
[pid  9035] read(4, "            write_bio = self._li"..., 4096) = 4096
[pid  9035] read(4, "        parameter_numbers = numb"..., 4096) = 4096
[pid  9035] read(4, "        self._lib.NID_X25519, se"..., 4096) = 1791
[pid  9035] read(4, "", 4096)           = 0
</code>```

I was right - 2 lines of my known_hosts glued together. Strange that only az cli did fail

```<code>|1|YDdg1mMCRjdmiJt7MkMpelWDk2o=|i1EMCbgw/5my5flPsw2BiFa8mUM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTAAABBBCpdyijGVsvUtMdlLoB5ekaQHQ2ZzQ0Z8UY5xdOAx9qqb3cYCYJgv8mc32yUzSu8D4iKfW2E5JXB8fG5otZsi3E=
|1|bssRIVCpG+vfNtdM4RAwH6zUCW8=|7AFIFRTmvoqO12bTZ0CyTgTqKdw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIB|1|AOjIgeSGPSh32t33uEGOX3iycrc=|7LupvcIR6QL8USA193kRORnA1rQ= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIBbAp0NBe9dYmuyTytpGxOWvmWoA1gjbNd/ekXW+m8gd6Yf8pDE/Cg=
|1|67+OBFoZyiXGx6mDl+lu/3SpBOc=|K6GLNh6ztZ9eb8cNGV64Rn3/yIM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBD7n79Vhwqw8zmRFFQvjnE2UB24vl8JWAN0ZPPFDOtr9jBd90AKsbZEXmqZhP1GennphesTU1cdHayQrQGbjV8=
</code>```

答:
A side topic:
After splitting the line, the error message has changed to more readable output. In the end I did remove the corrupted line to make it work.</p>

```<code>edited known_hosts file
|1|YDdg1mMCRjdmiJt7MkMpelWDk2o=|i1EMCbgw/5my5flPsw2BiFa8mUM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTAAABBBCpdyijGVsvUtMdlLoB5ekaQHQ2ZzQ0Z8UY5xdOAx9qqb3cYCYJgv8mc32yUzSu8D4iKfW2E5JXB8fG5otZsi3E=
|1|bssRIVCpG+vfNtdM4RAwH6zUCW8=|7AFIFRTmvoqO12bTZ0CyTgTqKdw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIB
|1|AOjIgeSGPSh32t33uEGOX3iycrc=|7LupvcIR6QL8USA193kRORnA1rQ= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIBbAp0NBe9dYmuyTytpGxOWvmWoA1gjbNd/ekXW+m8gd6Yf8pDE/Cg=
|1|67+OBFoZyiXGx6mDl+lu/3SpBOc=|K6GLNh6ztZ9eb8cNGV64Rn3/yIM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBD7n79Vhwqw8zmRFFQvjnE2UB24vl8JWAN0ZPPFDOtr9jBd90AKsbZEXmqZhP1GennphesTU1cdHayQrQGbjV8=

az acs kubernetes get-credentials --resource-group=myResourcGroup --name=myK8sCluster
('|1|bssRIVCpG+vfNtdM4RAwH6zUCW8=|7AFIFRTmvoqO12bTZ0CyTgTqKdw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIB', Error('Incorrect padding',))
Traceback (most recent call last):
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/main.py", line 36, in main
    cmd_result = APPLICATION.execute(args)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/core/application.py", line 216, in execute
    result = expanded_arg.func(params)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 377, in __call__
    return self.handler(*args, **kwargs)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 620, in _execute_command
    reraise(*sys.exc_info())
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 602, in _execute_command
    result = op(client, **kwargs) if client else op(**kwargs)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/command_modules/acs/custom.py", line 776, in k8s_get_credentials
    _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/command_modules/acs/custom.py", line 797, in _k8s_get_credentials_internal
    '.kube/config', path_candidate, key_filename=ssh_key_file)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/command_modules/acs/acs_client.py", line 70, in secure_copy
    ssh.load_system_host_keys()
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/client.py", line 102, in load_system_host_keys
    self._system_host_keys.load(filename)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/hostkeys.py", line 97, in load
    e = HostKeyEntry.from_line(line, lineno)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/hostkeys.py", line 366, in from_line
    raise InvalidHostKey(line, e)
InvalidHostKey: ('|1|bssRIVCpG+vfNtdM4RAwH6zUCW8=|7AFIFRTmvoqO12bTZ0CyTgTqKdw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIB', Error('Incorrect padding',))
</code>```

Body:
I run into this issue, and it took me a while, some intuition, educated guess, and an strace -f command to find this bug.
I believe it is wrongly caught exception of the paramico? library, hidden by some Azure CLI exception catcher.

Anyway, there I leave it, so the futere-me, and future-you can find it.

az acs kubernetes get-credentials
Invalid EC key.

$ strace -f az acs kubernetes get-credentials

(interesting part of MissingHostKeyPolicy wrt hostkeys (my guess - known_hosts file)

[pid  9035] open("/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/client.py", O_RDONLY) = 4
[pid  9035] fstat(4, {st_mode=S_IFREG|0664, st_size=30983, ...}) = 0
[pid  9035] fstat(4, {st_mode=S_IFREG|0664, st_size=30983, ...}) = 0
[pid  9035] read(4, "# Copyright (C) 2006-2007  Robey"..., 8192) = 8192
[pid  9035] read(4, " sock=None,\n        gss_auth=Fal"..., 4096) = 4096
[pid  9035] read(4, "t be\n            verified\n      "..., 4096) = 4096
[pid  9035] read(4, "        )\n            else:\n    "..., 4096) = 4096
[pid  9035] read(4, "    chan = self._transport.open_"..., 4096) = 4096
[pid  9035] read(4, "                allowed_types = "..., 4096) = 4096
[pid  9035] read(4, " MissingHostKeyPolicy (object):\n"..., 4096) = 2311
[pid  9035] read(4, "", 4096)           = 0
[pid  9035] close(4)                    = 0
[pid  9035] stat("/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/hostkeys.py", {st_mode=S_IFREG|0664, st_size=13135, ...}) = 0

(part just before crush)
[pid  9035] read(4, "    bn_ptr = self._lib.BN_bin2bn"..., 4096) = 4096
[pid  9035] read(4, "lf._lib.BIO_new_mem_buf(\n       "..., 4096) = 4096
[pid  9035] read(4, "              hashes.SHA1,\n     "..., 4096) = 4096
[pid  9035] read(4, "DSA_free)\n\n        p = self._int"..., 4096) = 4096
[pid  9035] read(4, "ror(\n                \"MD5 is not"..., 4096) = 4096
[pid  9035] read(4, " CRL version. We only support v2"..., 4096) = 4096
[pid  9035] read(4, ": {0}'.format(extension.oid)\n   "..., 4096) = 4096
[pid  9035] read(4, "   return self._evp_pkey_to_priv"..., 4096) = 4096
[pid  9035] read(4, "eturn _CertificateRevocationList"..., 4096) = 4096
[pid  9035] read(4, " _Reasons.UNSUPPORTED_CIPHER\n   "..., 4096) = 4096
[pid  9035] read(4, "i.NULL)\n        ec_cdata = self."..., 4096) = 4096
[pid  9035] read(4, "res != 1:\n            self._cons"..., 4096) = 4096
[pid  9035] read(4, "ding must be an item from the En"..., 4096) = 4096
[pid  9035] read(4, "            write_bio = self._li"..., 4096) = 4096
[pid  9035] read(4, "        parameter_numbers = numb"..., 4096) = 4096
[pid  9035] read(4, "        self._lib.NID_X25519, se"..., 4096) = 1791
[pid  9035] read(4, "", 4096)           = 0

I was right - 2 lines of my known_hosts glued together. Strange that only az cli did fail

|1|YDdg1mMCRjdmiJt7MkMpelWDk2o=|i1EMCbgw/5my5flPsw2BiFa8mUM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTAAABBBCpdyijGVsvUtMdlLoB5ekaQHQ2ZzQ0Z8UY5xdOAx9qqb3cYCYJgv8mc32yUzSu8D4iKfW2E5JXB8fG5otZsi3E=
|1|bssRIVCpG+vfNtdM4RAwH6zUCW8=|7AFIFRTmvoqO12bTZ0CyTgTqKdw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIB|1|AOjIgeSGPSh32t33uEGOX3iycrc=|7LupvcIR6QL8USA193kRORnA1rQ= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIBbAp0NBe9dYmuyTytpGxOWvmWoA1gjbNd/ekXW+m8gd6Yf8pDE/Cg=
|1|67+OBFoZyiXGx6mDl+lu/3SpBOc=|K6GLNh6ztZ9eb8cNGV64Rn3/yIM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBD7n79Vhwqw8zmRFFQvjnE2UB24vl8JWAN0ZPPFDOtr9jBd90AKsbZEXmqZhP1GennphesTU1cdHayQrQGbjV8=

Body:
A side topic:
After splitting the line, the error message has changed to more readable output. In the end I did remove the corrupted line to make it work.

edited known_hosts file
|1|YDdg1mMCRjdmiJt7MkMpelWDk2o=|i1EMCbgw/5my5flPsw2BiFa8mUM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTAAABBBCpdyijGVsvUtMdlLoB5ekaQHQ2ZzQ0Z8UY5xdOAx9qqb3cYCYJgv8mc32yUzSu8D4iKfW2E5JXB8fG5otZsi3E=
|1|bssRIVCpG+vfNtdM4RAwH6zUCW8=|7AFIFRTmvoqO12bTZ0CyTgTqKdw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIB
|1|AOjIgeSGPSh32t33uEGOX3iycrc=|7LupvcIR6QL8USA193kRORnA1rQ= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIBbAp0NBe9dYmuyTytpGxOWvmWoA1gjbNd/ekXW+m8gd6Yf8pDE/Cg=
|1|67+OBFoZyiXGx6mDl+lu/3SpBOc=|K6GLNh6ztZ9eb8cNGV64Rn3/yIM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBD7n79Vhwqw8zmRFFQvjnE2UB24vl8JWAN0ZPPFDOtr9jBd90AKsbZEXmqZhP1GennphesTU1cdHayQrQGbjV8=

az acs kubernetes get-credentials --resource-group=myResourcGroup --name=myK8sCluster
('|1|bssRIVCpG+vfNtdM4RAwH6zUCW8=|7AFIFRTmvoqO12bTZ0CyTgTqKdw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIB', Error('Incorrect padding',))
Traceback (most recent call last):
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/main.py", line 36, in main
    cmd_result = APPLICATION.execute(args)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/core/application.py", line 216, in execute
    result = expanded_arg.func(params)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 377, in __call__
    return self.handler(*args, **kwargs)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 620, in _execute_command
    reraise(*sys.exc_info())
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 602, in _execute_command
    result = op(client, **kwargs) if client else op(**kwargs)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/command_modules/acs/custom.py", line 776, in k8s_get_credentials
    _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/command_modules/acs/custom.py", line 797, in _k8s_get_credentials_internal
    '.kube/config', path_candidate, key_filename=ssh_key_file)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/azure/cli/command_modules/acs/acs_client.py", line 70, in secure_copy
    ssh.load_system_host_keys()
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/client.py", line 102, in load_system_host_keys
    self._system_host_keys.load(filename)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/hostkeys.py", line 97, in load
    e = HostKeyEntry.from_line(line, lineno)
  File "/home/kuba/lib/azure-cli/local/lib/python2.7/site-packages/paramiko/hostkeys.py", line 366, in from_line
    raise InvalidHostKey(line, e)
InvalidHostKey: ('|1|bssRIVCpG+vfNtdM4RAwH6zUCW8=|7AFIFRTmvoqO12bTZ0CyTgTqKdw= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBaXNnBKKBlQ1WDqy90c1zNjklBL7zXqDIB', Error('Incorrect padding',))


问:
Index python dict by object or two floats
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.

I need to record that, for example:

```<code>Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7
Point(X = 1.23, Y = 2.43) -> 9
Point(X = 8.342, Y = 6.754) -> 5
</code>```

I then need to be able to look up the resulting value by the X and Y values. I've tried using the Point objects as the dictionary's key, but this doesn't work as when I recreate the point object from the X and Y values it doesn't look it up properly anymore (presumably because the object ID has changed).

How should I go about linking these point values to the integers. Is there another way that I can use a dictionary?

答: Use a namedtuple: http://docs.python.org/dev/library/collections.html#collections.namedtuple</p>

Body:
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.

I need to record that, for example:

Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7
Point(X = 1.23, Y = 2.43) -> 9
Point(X = 8.342, Y = 6.754) -> 5

I then need to be able to look up the resulting value by the X and Y values. I've tried using the Point objects as the dictionary's key, but this doesn't work as when I recreate the point object from the X and Y values it doesn't look it up properly anymore (presumably because the object ID has changed).

How should I go about linking these point values to the integers. Is there another way that I can use a dictionary?


问:
Custom output of user input in java using scanner
is there any way to get custom output, of user input using scanner?

For Example:

```<code>import java.util.Scanner;

public class test {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.println("Choose one of the fruits:\n"+
            "1)Mango\n"+
            "2)Apple\n"+
            "3)Melon\n"+
            "4)Papaya\n");
        String fruit = input.next();
        if (fruit.equals("1") || fruit.equals("Mango")) {

        }
    }
}
</code>```

So when i execute it, this is output

```<code>Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1
</code>```

and it exits...

what i want is

```<code>Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1)Mango Selected
</code>```

On pressing 1 it should print Mango Selected... Well i could have added println for that but i also want to not show 1 or Mango (whatever user entered) instead i want to show my custom message..

How to do it?

答:
You can add them to a map and then get them by the key

```<code> import java.util.Scanner;

 public class test {
    public static void main(String args[]){

    Map<Integer, String> selection = Maps.newHashMap();

    selection.put(1, "Mango");
    selection.put(2, "Apple");
    selection.put(3, "Melon");
    selection.put(4, "Papaya");

    Scanner input = new Scanner(System.in);

    System.out.println("Choose one of the fruits:\n"+
     "1)Mango\n"+
     "2)Apple\n"+
     "3)Melon\n"+
     "4)Papaya\n");

    int fruit = input.nextInt();

     System.out.println("you selected " + selection.get(fruit));
    }
}
</code>```

If you don't want to enter the selection through the console then you can use a Dialog box

```<code>   Map<Integer, String> selection = Maps.newHashMap();

    selection.put(1, "Mango");
    selection.put(2, "Apple");
    selection.put(3, "Melon");
    selection.put(4, "Papaya");

    System.out.println("Choose one of the fruits:\n"+
    "1)Mango\n"+
    "2)Apple\n"+
    "3)Melon\n"+
    "4)Papaya\n");

    int mySelection = Integer.valueOf(JOptionPane.showInputDialog("Enter
    your selection here"));

    System.out.println("you selected " + selection.get(mySelection));
</code>```

Body:
is there any way to get custom output, of user input using scanner?

For Example:

import java.util.Scanner;

public class test {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.println("Choose one of the fruits:\n"+
            "1)Mango\n"+
            "2)Apple\n"+
            "3)Melon\n"+
            "4)Papaya\n");
        String fruit = input.next();
        if (fruit.equals("1") || fruit.equals("Mango")) {

        }
    }
}

So when i execute it, this is output

Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1

and it exits...

what i want is

Choose one of the fruits:
1)Mango
2)Apple
3)Melon
4)Papaya

1)Mango Selected

On pressing 1 it should print Mango Selected... Well i could have added println for that but i also want to not show 1 or Mango (whatever user entered) instead i want to show my custom message..

How to do it?

Body:
You can add them to a map and then get them by the key

 import java.util.Scanner;

 public class test {
    public static void main(String args[]){

    Map<Integer, String> selection = Maps.newHashMap();

    selection.put(1, "Mango");
    selection.put(2, "Apple");
    selection.put(3, "Melon");
    selection.put(4, "Papaya");

    Scanner input = new Scanner(System.in);

    System.out.println("Choose one of the fruits:\n"+
     "1)Mango\n"+
     "2)Apple\n"+
     "3)Melon\n"+
     "4)Papaya\n");

    int fruit = input.nextInt();

     System.out.println("you selected " + selection.get(fruit));
    }
}

If you don't want to enter the selection through the console then you can use a Dialog box

   Map<Integer, String> selection = Maps.newHashMap();

    selection.put(1, "Mango");
    selection.put(2, "Apple");
    selection.put(3, "Melon");
    selection.put(4, "Papaya");

    System.out.println("Choose one of the fruits:\n"+
    "1)Mango\n"+
    "2)Apple\n"+
    "3)Melon\n"+
    "4)Papaya\n");

    int mySelection = Integer.valueOf(JOptionPane.showInputDialog("Enter
    your selection here"));

    System.out.println("you selected " + selection.get(mySelection));


问:
Cannot insert value for identity when Identitt_insert is set to OFF
I'm aware that I'm not the first to ask this question here. But after going through a LOT of answers about this, I still cannot fix my issue.

So here it is.

I have multiple derived models in my Code First model, sharing the same Idenity property.

Here is an  example of my models

```<code>public class Foo
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int FooId { get; set; }

    public string SomeProperty{get;set;}
}

public class DerivedFoo : Foo
{
    public string SomeOtherProperty {get;set;}
}

public class EvenMordeDerivedFoo : DerivedFoo
{
    public string AndAnotherProperty {get;set;}
}
</code>```

So from my understanding my FooContext override should look like this :

```<code>public class FooContext : DbContext
{
   public DbSet<Foo> Foos{get;set;}
   public DbSet<DerivedFoo> DerivedFoos{get;set;}
   public DbSet<EvenMordeDerivedFoo > EvenMordeDerivedFoos{get;set;}

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<DerivedFoo>().ToTable("DerivedFoo");
        modelBuilder.Entity<EvenMordeDerivedFoo >().ToTable("EvenMordeDerivedFoo ");
    }
}
</code>```

With this, I can create and run context.SaveChanges() with Foo without any problem. But when i try to create a DerivedFoo via:

```<code>var derivedFoo= _context.DerivedFoos.Create();
_context.DerivedFoos.Add(derivedFoo);
_context.SaveChanges();
</code>```

I end up with the infamous error :

"Cannot insert explicit value for identity column in table
  'DerivedFoo' when IDENTITY_INSERT is set to OFF."

From my understanding, Entity Framework is trying to explain that I shouldn't being modifying the porperty FooId by myself if I set Identity_Insert to true.

I agree with EF on this, because I want this FooId property to set itself every time I create a new Foo, DerivedFoo or EvenMordeDerivedFoo, this explaining why I added the line

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
</code>```

So if anyone could explain what i did wrong could explain, that would be very nice.

Edit : I still can't find an answer, and after verification, my model mostly match this tutorial model. So I'm pretty sure the answer is quite simple, but I fail to find what I missed

答:
I should add some ID properties in DerivedFoo and EvenMoreDerivedFoo

No.  The Entities are fine.  The tables for the derived types need to not have IDENTITY property.

EG, this will create tables where only Foo's ID column has the IDENTITY property:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;

namespace Ef6Test
{

    public class Foo
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int FooId { get; set; }

        public string SomeProperty { get; set; }
    }

    public class DerivedFoo : Foo
    {
        public string SomeOtherProperty { get; set; }
    }

    public class EvenMordeDerivedFoo : DerivedFoo
    {
        public string AndAnotherProperty { get; set; }
    }
    class Db : DbContext
    {
        public DbSet<Foo> Foos { get; set; }
        public DbSet<DerivedFoo> DerivedFoos { get; set; }
        public DbSet<EvenMordeDerivedFoo> EvenMordeDerivedFoos { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<DerivedFoo>().ToTable("DerivedFoo");
            modelBuilder.Entity<EvenMordeDerivedFoo>().ToTable("EvenMordeDerivedFoo ");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());

            using (var db = new Db())
            {

                db.Database.Log = m => Console.WriteLine(m);
                db.Database.Initialize(true);

                var derivedFoo = db.DerivedFoos.Create();
                db.DerivedFoos.Add(derivedFoo);
                db.SaveChanges();

            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
        }
    }
}
</code>```

Body:
I'm aware that I'm not the first to ask this question here. But after going through a LOT of answers about this, I still cannot fix my issue.

So here it is.

I have multiple derived models in my Code First model, sharing the same Idenity property.

Here is an  example of my models

public class Foo
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int FooId { get; set; }

    public string SomeProperty{get;set;}
}

public class DerivedFoo : Foo
{
    public string SomeOtherProperty {get;set;}
}

public class EvenMordeDerivedFoo : DerivedFoo
{
    public string AndAnotherProperty {get;set;}
}

So from my understanding my FooContext override should look like this :

public class FooContext : DbContext
{
   public DbSet<Foo> Foos{get;set;}
   public DbSet<DerivedFoo> DerivedFoos{get;set;}
   public DbSet<EvenMordeDerivedFoo > EvenMordeDerivedFoos{get;set;}

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<DerivedFoo>().ToTable("DerivedFoo");
        modelBuilder.Entity<EvenMordeDerivedFoo >().ToTable("EvenMordeDerivedFoo ");
    }
}

With this, I can create and run context.SaveChanges() with Foo without any problem. But when i try to create a DerivedFoo via:

var derivedFoo= _context.DerivedFoos.Create();
_context.DerivedFoos.Add(derivedFoo);
_context.SaveChanges();

I end up with the infamous error :

"Cannot insert explicit value for identity column in table
  'DerivedFoo' when IDENTITY_INSERT is set to OFF."

From my understanding, Entity Framework is trying to explain that I shouldn't being modifying the porperty FooId by myself if I set Identity_Insert to true.

I agree with EF on this, because I want this FooId property to set itself every time I create a new Foo, DerivedFoo or EvenMordeDerivedFoo, this explaining why I added the line

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

So if anyone could explain what i did wrong could explain, that would be very nice.

Edit : I still can't find an answer, and after verification, my model mostly match this tutorial model. So I'm pretty sure the answer is quite simple, but I fail to find what I missed

Body:
I should add some ID properties in DerivedFoo and EvenMoreDerivedFoo

No.  The Entities are fine.  The tables for the derived types need to not have IDENTITY property.

EG, this will create tables where only Foo's ID column has the IDENTITY property:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;

namespace Ef6Test
{

    public class Foo
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int FooId { get; set; }

        public string SomeProperty { get; set; }
    }

    public class DerivedFoo : Foo
    {
        public string SomeOtherProperty { get; set; }
    }

    public class EvenMordeDerivedFoo : DerivedFoo
    {
        public string AndAnotherProperty { get; set; }
    }
    class Db : DbContext
    {
        public DbSet<Foo> Foos { get; set; }
        public DbSet<DerivedFoo> DerivedFoos { get; set; }
        public DbSet<EvenMordeDerivedFoo> EvenMordeDerivedFoos { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<DerivedFoo>().ToTable("DerivedFoo");
            modelBuilder.Entity<EvenMordeDerivedFoo>().ToTable("EvenMordeDerivedFoo ");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());

            using (var db = new Db())
            {

                db.Database.Log = m => Console.WriteLine(m);
                db.Database.Initialize(true);

                var derivedFoo = db.DerivedFoos.Create();
                db.DerivedFoos.Add(derivedFoo);
                db.SaveChanges();

            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
        }
    }
}


问:
SQL Server to mySQL converter
Hai Techies,

I have some stored procedure which was written in SQL server.Now i want to migrate this to mysql.Is there any freeware tools which can do this for me.

答: There is a toolkit for data migration, available at this link, but you might have to handle stored procedures manually. Another suggestion, that if you can find a conversion tool to move the SP's to DB2 you may have an easier time, as MySQL procedures are close to DB2 in style.</p>

Title: SQL Server to mySQL converter

LastEditorDisplayName: Cade Roux

OwnerDisplayName: Turnkey


问:
dynamic LINQ query
Hi I am using dynamic linq, using PredicateBuilder of LinqKit.

If you look at the code, line after TODO comment, i want to accomplish something like
Lets say there are 2 objects in objectList viz. object1, object2
(object1.property1 AND object1.property2) OR (object2.property1 AND object2.property2)

I know the line after TODO is incorrect, but I am looking for correct version of that line.

```

  var finalPredicate = PredicateBuilder.True();

  foreach (var item in objectList)
  {
    var predicate = PredicateBuilder.True();
    predicate = predicate.And (p => p.Description.Contains (item.property1));
    predicate = predicate.And (p => p.Description.Contains (item.property2));
    //TODO:
    finalPredicate = finalPredicate.Or(predicate);
  }
}
```

答:
Shouldn't finalPredicate start out as False? This will always evaluate to true.

EDIT:

Having looked at the exception code you posted, I think you could think of it VERY roughly as:

(pseudocode)

```<code>finalPredicate =
    true ||
    (true &&
        p.ef.Contains(item.FilterDomain) &&
        p.fname.Contains(item.ff) &&
        p.subject.Contains(item.fs)
    )
</code>```

Note that that's NOT what it really means; you're building an expression tree, which is different from classic, imperative C# (so this edit is probably begging for downvotes). But it might make it easier for you to think of it that way.

So you have at least two issues here:

What I and others were pointing out was the first true || .... A true value || anything will always produce True. So if you initialize finalPredicate to True, the whole thing is going to be True no matter what. In fact, your other expressions might not even get evaluated, which is why you only see this exception when you initialize finalPredicate to False. That's the only time your code is getting hit.

You probably have a bug somewhere in the for loop, and my guess is it has to do with those calls to Contains. However, without more knowledge of your situation or the data involved, it's hard to tell more than that.

Hope this helps.

Title: dynamic LINQ query

Body:
Hi I am using dynamic linq, using PredicateBuilder of LinqKit.

If you look at the code, line after TODO comment, i want to accomplish something like
Lets say there are 2 objects in objectList viz. object1, object2
(object1.property1 AND object1.property2) OR (object2.property1 AND object2.property2)

I know the line after TODO is incorrect, but I am looking for correct version of that line.

  var finalPredicate = PredicateBuilder.True();

  foreach (var item in objectList)
  {
    var predicate = PredicateBuilder.True();
    predicate = predicate.And (p => p.Description.Contains (item.property1));
    predicate = predicate.And (p => p.Description.Contains (item.property2));
    //TODO:
    finalPredicate = finalPredicate.Or(predicate);
  }
}

Body:
Shouldn't finalPredicate start out as False? This will always evaluate to true.

EDIT:

Having looked at the exception code you posted, I think you could think of it VERY roughly as:

(pseudocode)

finalPredicate =
    true ||
    (true &&
        p.ef.Contains(item.FilterDomain) &&
        p.fname.Contains(item.ff) &&
        p.subject.Contains(item.fs)
    )

Note that that's NOT what it really means; you're building an expression tree, which is different from classic, imperative C# (so this edit is probably begging for downvotes). But it might make it easier for you to think of it that way.

So you have at least two issues here:

What I and others were pointing out was the first true || .... A true value || anything will always produce True. So if you initialize finalPredicate to True, the whole thing is going to be True no matter what. In fact, your other expressions might not even get evaluated, which is why you only see this exception when you initialize finalPredicate to False. That's the only time your code is getting hit.

You probably have a bug somewhere in the for loop, and my guess is it has to do with those calls to Contains. However, without more knowledge of your situation or the data involved, it's hard to tell more than that.

Hope this helps.


问:
webpack file-loader image to different directories
I have 2 different picture folder.

- src / assets / img / img1.png

- src / content / media / img2.png

the dist directory output this:

- dist / img1.png

- dist / img2.png

but should be like this:

- dist / assets / img / img1.png

- dist / content / media / img2.png

what do I have to change because it works?

```<code>{
test: /\.(jpg|png|svg)$/,
            use: [
                {
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'content/media/',
                    },
                }
            ]
        },
</code>```

答:
When  you specify an outputPath as a string it is default for all entry files. Instead you can write and function which returns a different path/filename for different entries.

One more thing to consider is you need a different output based on the path of each entry, so set your name attribute to [path][name].[ext] . This way when you get the filename in your outputPath function, you know which directory to output to.

Below is an example:

```<code>use: [
      {
         loader: "file-loader",
         options: {
            name: '[path][name].[ext]',
            outputPath: (file) => {
              let path = file.split("src/")[1]; //this will yield assets/img/img1.png
              return path
            }
        }
      }
     ]
</code>```

Body:
I have 2 different picture folder.

- src / assets / img / img1.png

- src / content / media / img2.png

the dist directory output this:

- dist / img1.png

- dist / img2.png

but should be like this:

- dist / assets / img / img1.png

- dist / content / media / img2.png

what do I have to change because it works?

{
test: /\.(jpg|png|svg)$/,
            use: [
                {
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'content/media/',
                    },
                }
            ]
        },

Body:
When  you specify an outputPath as a string it is default for all entry files. Instead you can write and function which returns a different path/filename for different entries.

One more thing to consider is you need a different output based on the path of each entry, so set your name attribute to [path][name].[ext] . This way when you get the filename in your outputPath function, you know which directory to output to.

Below is an example:

use: [
      {
         loader: "file-loader",
         options: {
            name: '[path][name].[ext]',
            outputPath: (file) => {
              let path = file.split("src/")[1]; //this will yield assets/img/img1.png
              return path
            }
        }
      }
     ]


问:
Uploading multiple files to heroku serially locks up all dynos
Its my understanding that when I upload a file to my heroku instance its a synchronous request and I will get a 200 back when the request is done, which means my upload has been processed and stored by paperclip.

I am using plupload which does a serial upload (one file at a time).  On Heroku I have 3 dynos and my app becomes unresponsive and I get timeouts trying to use the app.  My upload should really only tie up at most a single dyno while all the files are being uploaded since its done serially and file 2 doesnt start until a response is returned from file 1.

As a test I bumped my dynos to 15 and ran the upload. Again I see the posts come into the logs and then I start seeing output of paperclip commands (cant remember if it was identify or convert) and I start getting timeouts.

I'm really lost as to why this is happening.  I do know I 'can' upload directly to s3 but my current approach should be just fine.  Its an admin interface that is only used by a single person and again at most it should tie up a single dyno since all the uploaded files are sent serially.

Any ideas?

答: You can use something like Dropzonejs in order to divide your files in queue and send them separately. That way the request wont timeout.</p>