问:
Epson printer connect fails status ERR_CONN
I have an Epson printer and I used epos2_printer (sample project) code given with SDK to integrate with my app. I have copied the same code but it never seems to work!

However, the same works when I connect the sample project to my printer.

```<code>private boolean runPrintReceiptSequence() {
    if (!initializeObject()) {
        return false;
    }

    if (!createReceiptData()) {
        finalizeObject();
        return false;
    }

    if (!printData()) {
        finalizeObject();
        return false;
    }

    return true;
}

private boolean initializeObject() {
    try {

        final SpnModelsItem spnModel = new SpnModelsItem("TM-T82 Series", Printer.TM_T82);
        final SpnModelsItem spnLang = new SpnModelsItem("ANK", Printer.MODEL_ANK);

        mPrinter = new Printer(spnModel.getModelConstant(),
                                spnLang.getModelConstant(), this);
    }
    catch (Exception e) {
        Log.e("Printer", e.toString());
        return false;
    }

    mPrinter.setReceiveEventListener(this);

    return true;
}

private boolean createReceiptData() {
    String method = "";
    Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.logo_saltnpepper);
    StringBuilder textData = new StringBuilder();
    final int barcodeWidth = 2;
    final int barcodeHeight = 100;
    Date currentDate = new Date();
    info.saltnpepper.ordersmart2.MenuItem currItem = null;

    double price = 0;
    double total = 0;
    int totalQty =0;

    if (mPrinter == null) {
        return false;
    }

    try {
        method = "addTextAlign";
        mPrinter.addTextAlign(Printer.ALIGN_CENTER);

        method = "addImage";
        mPrinter.addImage(logoData, 0, 0,
                          logoData.getWidth(),
                          logoData.getHeight(),
                          Printer.COLOR_1,
                          Printer.MODE_MONO,
                          Printer.HALFTONE_DITHER,
                          Printer.PARAM_DEFAULT,
                          Printer.COMPRESS_AUTO);

        method = "addFeedLine";
        mPrinter.addFeedLine(1);
        textData.append("SALT-N-PEPPER\n");
        //textData.append("STORE DIRECTOR â€“ John Smith\n");
        textData.append("\n");
        textData.append((new SimpleDateFormat("dd/MM/yy HH:mm:ss")).format(currentDate).toString() + "\n");
        //textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
        if(alFinalOrder != null)
        {
            for(int i=0; i < alFinalOrder.size(); i++)
            {
                currItem = alFinalOrder.get(i);
                textData.append(currItem.getName()+"  "+currItem.getQty()+"  "+currItem.getPrice()+"\n");

                //calculate total quantity
                totalQty = totalQty + currItem.getQty();

                //calculate price
                double dPrice = currItem.getQty()*Double.parseDouble(currItem.getPrice().substring(1));
                total = total + dPrice;
                total = Math.round(total*100.0)/100.0;

            }
        }
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

        textData.append("TOTAL                   "+"\n");
        textData.append("TAX                     "+"\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
</code>```

mPrinter.addFeedLine(2);

```<code>        method = "addBarcode";
        mPrinter.addBarcode("01209457",
                            Printer.BARCODE_CODE39,
                            Printer.HRI_BELOW,
                            Printer.FONT_A,
                            barcodeWidth,
                            barcodeHeight);

        method = "addCut";
        mPrinter.addCut(Printer.CUT_FEED);
    }
    catch (Exception e) {
        //ShowMsg.showException(e, method, mContext);
        return false;
    }

    textData = null;

    return true;
}

private boolean printData() {
    if (mPrinter == null) {
        return false;
    }

    if (!connectPrinter()) {
        return false;
    }

    PrinterStatusInfo status = mPrinter.getStatus();

    dispPrinterWarnings(status);

    if (!isPrintable(status)) {
        Log.e("Printer", "Is not printable");
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    try {
        mPrinter.sendData(Printer.PARAM_DEFAULT);
    }
    catch (Exception e) {
        Log.e("Printer", e.getMessage());
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    return true;
}

private boolean connectPrinter() {
    boolean isBeginTransaction = false;

    if (mPrinter == null) {
        return false;
    }

    try {
        mPrinter.connect("TCP:"+mIP, Printer.PARAM_DEFAULT);
    }
    catch (Epos2Exception e) {
        //ShowMsg.showException(e, "connect", this);
        if(e.getErrorStatus() == Epos2Exception.ERR_CONNECT)
        {
            Log.e("testing", "error connect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_OPENED)
        {
            Log.e("testing", "already open");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_USED)
        {
            Log.e("testing", "already used");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_CLIENT_OVER)
        {
            Log.e("testing", "box client over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_COUNT_OVER)
        {
            Log.e("testing", "count over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_DISCONNECT)
        {
            Log.e("testing", "disconnect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_FAILURE)
        {
            Log.e("testing", "failure");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ILLEGAL)
        {
            Log.e("testing", "illegal");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_IN_USE)
        {
            Log.e("testing", "in use");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_MEMORY)
        {
            Log.e("testing", "memory");
        }
        return false;
    }

    try {
        mPrinter.beginTransaction();
        isBeginTransaction = true;
    }
    catch (Exception e) {
        Log.e("Printer", e.toString ());
    }

    if (isBeginTransaction == false) {
        try {
            mPrinter.disconnect();
        }
        catch (Epos2Exception e) {
            // Do nothing
            return false;
        }
    }

    return true;
}
</code>```

It always gives me exception ERR_CONNECT on printer.connect inside connectprinter function.

What am I doing wrong?

This code works fine with the sample app.
P.S: I have tried to connect this app before connecting the sample app to check if the sample app holds the connection and does not allow other apps to connect but that is not the case. Epson help is unable to provide any further help.

My AndroidManifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="21"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MenuActivity" >
    </activity>
    <activity
        android:name=".SaltnPepperActivity"
        android:label="@string/title_activity_saltn_pepper" >
    </activity>
            <activity
        android:name=".FinalOrder"
         ></activity>
                <activity
        android:name=".ZinVietActivity"
         >
    </activity>
     <activity
        android:name="com.epson.epos2_printer.DiscoverActivity"
         ></activity>

</application>
</code>```

答:
Status ERR_CONN is basically shows if device cannot be reached or connection failing with device. It can be USB, LAN/NETWORK, Bluetooth Connection failure status.

If you are trying to connect printer with Bluetooth then you must write below permissions:

```<code><uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
</code>```

If you are using LAN for network printers then

```<code><uses-permission android:name="android.permission.INTERNET"/>
</code>```

For USB Printer Connection Use:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</code>```

As you are using EPOS2 Sample Project, remember to import Jar file "EPOS2.jar". Click here to download the file.

Body:
I have an Epson printer and I used epos2_printer (sample project) code given with SDK to integrate with my app. I have copied the same code but it never seems to work!

However, the same works when I connect the sample project to my printer.

private boolean runPrintReceiptSequence() {
    if (!initializeObject()) {
        return false;
    }

    if (!createReceiptData()) {
        finalizeObject();
        return false;
    }

    if (!printData()) {
        finalizeObject();
        return false;
    }

    return true;
}

private boolean initializeObject() {
    try {

        final SpnModelsItem spnModel = new SpnModelsItem("TM-T82 Series", Printer.TM_T82);
        final SpnModelsItem spnLang = new SpnModelsItem("ANK", Printer.MODEL_ANK);

        mPrinter = new Printer(spnModel.getModelConstant(),
                                spnLang.getModelConstant(), this);
    }
    catch (Exception e) {
        Log.e("Printer", e.toString());
        return false;
    }

    mPrinter.setReceiveEventListener(this);

    return true;
}

private boolean createReceiptData() {
    String method = "";
    Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.logo_saltnpepper);
    StringBuilder textData = new StringBuilder();
    final int barcodeWidth = 2;
    final int barcodeHeight = 100;
    Date currentDate = new Date();
    info.saltnpepper.ordersmart2.MenuItem currItem = null;

    double price = 0;
    double total = 0;
    int totalQty =0;

    if (mPrinter == null) {
        return false;
    }

    try {
        method = "addTextAlign";
        mPrinter.addTextAlign(Printer.ALIGN_CENTER);

        method = "addImage";
        mPrinter.addImage(logoData, 0, 0,
                          logoData.getWidth(),
                          logoData.getHeight(),
                          Printer.COLOR_1,
                          Printer.MODE_MONO,
                          Printer.HALFTONE_DITHER,
                          Printer.PARAM_DEFAULT,
                          Printer.COMPRESS_AUTO);

        method = "addFeedLine";
        mPrinter.addFeedLine(1);
        textData.append("SALT-N-PEPPER\n");
        //textData.append("STORE DIRECTOR â€“ John Smith\n");
        textData.append("\n");
        textData.append((new SimpleDateFormat("dd/MM/yy HH:mm:ss")).format(currentDate).toString() + "\n");
        //textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());
        if(alFinalOrder != null)
        {
            for(int i=0; i < alFinalOrder.size(); i++)
            {
                currItem = alFinalOrder.get(i);
                textData.append(currItem.getName()+"  "+currItem.getQty()+"  "+currItem.getPrice()+"\n");

                //calculate total quantity
                totalQty = totalQty + currItem.getQty();

                //calculate price
                double dPrice = currItem.getQty()*Double.parseDouble(currItem.getPrice().substring(1));
                total = total + dPrice;
                total = Math.round(total*100.0)/100.0;

            }
        }
        textData.append("------------------------------\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

        textData.append("TOTAL                   "+"\n");
        textData.append("TAX                     "+"\n");
        method = "addText";
        mPrinter.addText(textData.toString());
        textData.delete(0, textData.length());

mPrinter.addFeedLine(2);

        method = "addBarcode";
        mPrinter.addBarcode("01209457",
                            Printer.BARCODE_CODE39,
                            Printer.HRI_BELOW,
                            Printer.FONT_A,
                            barcodeWidth,
                            barcodeHeight);

        method = "addCut";
        mPrinter.addCut(Printer.CUT_FEED);
    }
    catch (Exception e) {
        //ShowMsg.showException(e, method, mContext);
        return false;
    }

    textData = null;

    return true;
}

private boolean printData() {
    if (mPrinter == null) {
        return false;
    }

    if (!connectPrinter()) {
        return false;
    }

    PrinterStatusInfo status = mPrinter.getStatus();

    dispPrinterWarnings(status);

    if (!isPrintable(status)) {
        Log.e("Printer", "Is not printable");
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    try {
        mPrinter.sendData(Printer.PARAM_DEFAULT);
    }
    catch (Exception e) {
        Log.e("Printer", e.getMessage());
        try {
            mPrinter.disconnect();
        }
        catch (Exception ex) {
            // Do nothing
        }
        return false;
    }

    return true;
}

private boolean connectPrinter() {
    boolean isBeginTransaction = false;

    if (mPrinter == null) {
        return false;
    }

    try {
        mPrinter.connect("TCP:"+mIP, Printer.PARAM_DEFAULT);
    }
    catch (Epos2Exception e) {
        //ShowMsg.showException(e, "connect", this);
        if(e.getErrorStatus() == Epos2Exception.ERR_CONNECT)
        {
            Log.e("testing", "error connect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_OPENED)
        {
            Log.e("testing", "already open");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_USED)
        {
            Log.e("testing", "already used");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_CLIENT_OVER)
        {
            Log.e("testing", "box client over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_BOX_COUNT_OVER)
        {
            Log.e("testing", "count over");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_DISCONNECT)
        {
            Log.e("testing", "disconnect");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_FAILURE)
        {
            Log.e("testing", "failure");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_ILLEGAL)
        {
            Log.e("testing", "illegal");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_IN_USE)
        {
            Log.e("testing", "in use");
        }
        if(e.getErrorStatus() == Epos2Exception.ERR_MEMORY)
        {
            Log.e("testing", "memory");
        }
        return false;
    }

    try {
        mPrinter.beginTransaction();
        isBeginTransaction = true;
    }
    catch (Exception e) {
        Log.e("Printer", e.toString ());
    }

    if (isBeginTransaction == false) {
        try {
            mPrinter.disconnect();
        }
        catch (Epos2Exception e) {
            // Do nothing
            return false;
        }
    }

    return true;
}

It always gives me exception ERR_CONNECT on printer.connect inside connectprinter function.

What am I doing wrong?

This code works fine with the sample app.
P.S: I have tried to connect this app before connecting the sample app to check if the sample app holds the connection and does not allow other apps to connect but that is not the case. Epson help is unable to provide any further help.

My AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="21"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MenuActivity" >
    </activity>
    <activity
        android:name=".SaltnPepperActivity"
        android:label="@string/title_activity_saltn_pepper" >
    </activity>
            <activity
        android:name=".FinalOrder"
         ></activity>
                <activity
        android:name=".ZinVietActivity"
         >
    </activity>
     <activity
        android:name="com.epson.epos2_printer.DiscoverActivity"
         ></activity>

</application>

Body:
Status ERR_CONN is basically shows if device cannot be reached or connection failing with device. It can be USB, LAN/NETWORK, Bluetooth Connection failure status.

If you are trying to connect printer with Bluetooth then you must write below permissions:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

If you are using LAN for network printers then

<uses-permission android:name="android.permission.INTERNET"/>

For USB Printer Connection Use:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

As you are using EPOS2 Sample Project, remember to import Jar file "EPOS2.jar". Click here to download the file.


来源: stackexchange

问:
scss not applying throwing error
I am using webpack 2 and node 6.9 and trying to implement the css/scss in my project. I have installed all the required loaders like style,sass etc. earlier below was my webpack configuration and it is working fine but scss is not applied on my project,

```<code>rules: [{
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader',
            options: {
                cacheDirectory: true
            }
        }]
</code>```

to apply the css i have installed all the loaders and i changed the above webpack configuration to below

```<code>rules: [{
           test: /\.scss$/,
loader: ExtractTextPlugin.extract({
  fallbackLoader: 'style-loader',
  loader: [
    'css-loader',
    'babel-loader',
    'postcss',
    {
      loader: 'sass-loader',
      query: {
        sourceMap: false,
        presets: ['es2015'],
      }
    }
  ],
})
        }]
    };
    plugins: [
new ExtractTextPlugin("style.css"),
  ]
</code>```

but it is still not working for me. i have tried some other configurations also but everytime it is giving me same error as below,

```<code>Uncaught Error: Module parse failed: \index.js Unexpected token (7:3)
 You may need an appropriate loader to handle this file type.

ReactDOM.render((
 <App />
), document.getElementById('root'));
at Object.<anonymous> (bootstrap 6298272…:708)
at __webpack_require__ (bootstrap 6298272…:659)
at bootstrap 6298272…:708
at bootstrap 6298272…:708
</code>```

Can anyone help me to get rid of the error and apply the scss. Thanks in advance!!

答:
Able to make it work. Below is the code:

```<code>rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015', 'react']
            }
        },
        {
            test: /\.scss$/,
            loaders: [ "style-loader", "css-loader", 'sass-loader' ],
        }]
</code>```

ContentLicense: CC BY-SA 3.0

Title: scss not applying throwing error

Body:
I am using webpack 2 and node 6.9 and trying to implement the css/scss in my project. I have installed all the required loaders like style,sass etc. earlier below was my webpack configuration and it is working fine but scss is not applied on my project,

rules: [{
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader',
            options: {
                cacheDirectory: true
            }
        }]

to apply the css i have installed all the loaders and i changed the above webpack configuration to below

rules: [{
           test: /\.scss$/,
loader: ExtractTextPlugin.extract({
  fallbackLoader: 'style-loader',
  loader: [
    'css-loader',
    'babel-loader',
    'postcss',
    {
      loader: 'sass-loader',
      query: {
        sourceMap: false,
        presets: ['es2015'],
      }
    }
  ],
})
        }]
    };
    plugins: [
new ExtractTextPlugin("style.css"),
  ]

but it is still not working for me. i have tried some other configurations also but everytime it is giving me same error as below,

Uncaught Error: Module parse failed: \index.js Unexpected token (7:3)
 You may need an appropriate loader to handle this file type.

ReactDOM.render((
 <App />
), document.getElementById('root'));
at Object.<anonymous> (bootstrap 6298272…:708)
at __webpack_require__ (bootstrap 6298272…:659)
at bootstrap 6298272…:708
at bootstrap 6298272…:708

Can anyone help me to get rid of the error and apply the scss. Thanks in advance!!

Body:
Able to make it work. Below is the code:

rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015', 'react']
            }
        },
        {
            test: /\.scss$/,
            loaders: [ "style-loader", "css-loader", 'sass-loader' ],
        }]

ContentLicense: CC BY-SA 4.0


问:
How to run STS on Java version 1.7
I need to  run eclipse(java 1.7) and  STS 3.8.1  ( java 1.8) but if i select the  java 7 as default i am getting error in the  STS 3.8.1.
 I am using OS : ubuntu 14.10

```<code>Error  : Version 1.7.0_80 of the JVM is not suitable for this product. Version: 1.8 or greater is required.
</code>```

Or I select java 1.8 as default eclipse is not working fine.

My requirement is  to build a Project using java 1.7  with STS.  and latest version 3.8.1 doesnot  support the  java 1.7.

and i try to search which version of STS support 1.7 but i am not getting any answer .

答: I just set the jdk in the  alternative jre value .

Title: How to run STS on Java version 1.7

Body:
I need to  run eclipse(java 1.7) and  STS 3.8.1  ( java 1.8) but if i select the  java 7 as default i am getting error in the  STS 3.8.1.
 I am using OS : ubuntu 14.10

Error  : Version 1.7.0_80 of the JVM is not suitable for this product. Version: 1.8 or greater is required.

Or I select java 1.8 as default eclipse is not working fine.

My requirement is  to build a Project using java 1.7  with STS.  and latest version 3.8.1 doesnot  support the  java 1.7.

and i try to search which version of STS support 1.7 but i am not getting any answer .


问:
click on TableViewCell to open profile view of current user
I am using firebase database and have a table view showing name, age, location, and image of user at index path.row. How would I go about showing another view when the cell is clicked to the users profile with more information and photos of the user. here is the code for my tableView.

```<code> override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return userList.count

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell

      let user = userList[indexPath.row]

    cell.name.text = userList[indexPath.row].name
    cell.location.text = userList[indexPath.row].location

    if let imageURL = user.image {

        cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
    }
          return cell
}

    }
</code>```

答:
Add this below code

```<code>override  func tableView(_ tableView: UITableView, didSelectRowAtindexPath: IndexPath){

   let detailVC = storyboard.instantiateViewControllerWithIdentifier("MyDetailVC") as MyDetailVC // get the obect of other VC
   detailVC.myImage = <your_image> // assign your image which you wanted to send to other VC.
   self.navigationController?.pushViewController(detailVC,animated: true // Push to other VC
}
</code>```

in MyDetailVC.swift

```<code>var myImage : UIImage? // Create variable of image type in required VC where you wanted to send data
</code>```

Now use your Image in MyDetailVC.swift.

Any further query you can ask.

Body:
I am using firebase database and have a table view showing name, age, location, and image of user at index path.row. How would I go about showing another view when the cell is clicked to the users profile with more information and photos of the user. here is the code for my tableView.

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return userList.count

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell

      let user = userList[indexPath.row]

    cell.name.text = userList[indexPath.row].name
    cell.location.text = userList[indexPath.row].location

    if let imageURL = user.image {

        cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
    }
          return cell
}

    }

Body:
Add this below code

override  func tableView(_ tableView: UITableView, didSelectRowAtindexPath: IndexPath){

   let detailVC = storyboard.instantiateViewControllerWithIdentifier("MyDetailVC") as MyDetailVC // get the obect of other VC
   detailVC.myImage = <your_image> // assign your image which you wanted to send to other VC.
   self.navigationController?.pushViewController(detailVC,animated: true // Push to other VC
}

in MyDetailVC.swift

var myImage : UIImage? // Create variable of image type in required VC where you wanted to send data

Now use your Image in MyDetailVC.swift.

Any further query you can ask.


问:
why I'm getting "UNMET PEER DEPENDENCY" error in angular 2
I'm trying to install angular2-flash-messages to my angular-src, not to the root. then I tried with npm install angular2-flash-messages. then it returns this,

```<code>├── UNMET PEER DEPENDENCY @angular/core@2.4.10
└── angular2-flash-messages@1.0.7
</code>```

then I tried to resolve this with installing rxjs and angluar/cli globally. But it didn't work. How do I fix this?

there is a warning :
  npm WARN angular2-flash-messages@1.0.7 requires a peer of @angular/core@^4.0.0 but none was installed.

答: It means that that version of angular2-flash-messages uses @angular/core version 4.0.0^. Your project might still work but that's the recommended version. If there are any breaking changes in the peer library your app might crash so it's recommended to install the correct peer dependencies.

Body:
I'm trying to install angular2-flash-messages to my angular-src, not to the root. then I tried with npm install angular2-flash-messages. then it returns this,

├── UNMET PEER DEPENDENCY @angular/core@2.4.10
└── angular2-flash-messages@1.0.7

then I tried to resolve this with installing rxjs and angluar/cli globally. But it didn't work. How do I fix this?

there is a warning :
  npm WARN angular2-flash-messages@1.0.7 requires a peer of @angular/core@^4.0.0 but none was installed.


问:
Reading Hibernate configurations dynamically
I need to fetch hibernate connection url, username and password configurations from another service AMS (just like amazon KMS).

I have written another method to fetch those values from AMS. BUT how to set/use these values hibernate to connect my database.

eg. hibernate.cfg.xml

```<code><property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
</code>```

Util.java

```<code>getAMSValue(propertyName){
...
}
</code>```

how can I achieve this?

答:
Why don't you specify complete configuration in a java file instead of XML?

See this documentation

A org.hibernate.cfg.Configuration also allows you to specify
  configuration properties.

... ...

This is not the only way to pass configuration properties to
  Hibernate. Some alternative options include:

Pass an instance of java.util.Properties to Configuration.setProperties().

Place a file named hibernate.properties in a root directory of the classpath.

Set System properties using java -Dproperty=value.

Include  elements in hibernate.cfg.xml (this is discussed later).

In your case, you can configure somewhat like this in your java file

```<code>Configuration configuration = new Configuration().configure();

...
...
configuration.setProperty("hibernate.connection.url", getAMSValue("url"));
configuration.setProperty("hibernate.connection.username", getAMSValue("username"));
configuration.setProperty("hibernate.connection.password", getAMSValue("password"));
</code>```

Body:
I need to fetch hibernate connection url, username and password configurations from another service AMS (just like amazon KMS).

I have written another method to fetch those values from AMS. BUT how to set/use these values hibernate to connect my database.

eg. hibernate.cfg.xml

<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>

Util.java

getAMSValue(propertyName){
...
}

how can I achieve this?

Body:
Why don't you specify complete configuration in a java file instead of XML?

See this documentation

A org.hibernate.cfg.Configuration also allows you to specify
  configuration properties.

... ...

This is not the only way to pass configuration properties to
  Hibernate. Some alternative options include:

Pass an instance of java.util.Properties to Configuration.setProperties().

Place a file named hibernate.properties in a root directory of the classpath.

Set System properties using java -Dproperty=value.

Include  elements in hibernate.cfg.xml (this is discussed later).

In your case, you can configure somewhat like this in your java file

Configuration configuration = new Configuration().configure();

...
...
configuration.setProperty("hibernate.connection.url", getAMSValue("url"));
configuration.setProperty("hibernate.connection.username", getAMSValue("username"));
configuration.setProperty("hibernate.connection.password", getAMSValue("password"));


问:
fopen() not working or showing errors
I want to create a new file along with the the creation of a record in my db. The db part works fine, but the file part isn't working. I want to create a file in another folder in the root directory and I used the same code with changes in the file name. Despite setting ini_set('display_errors',3) the code doesn't return any errors, I've also tried fopen($file_name,"w") or die("unable to open file"), still the code ran. I've given IIS_IUSRS full control over the directory. Here is my code

```<code>$data = mysqli_fetch_array(mysqli_query($conn,"Select * from content where link='$url'")); //fetch data from db
$id = $data['id'];
$file_name="/files/$id.html"; //sets file name
$file = fopen($file_name,"w"); //creates the file
fwrite($file,$_POST['desc']); //writes to the file
fclose($file); //closes the file
</code>```

答: The problem was PHP wasn't going to the root directory. I added $root = $_SERVER['DOCUMENT_ROOT'] and replaced $file_name="/files/$id.html" with $file_name="$root/files/$id.html"; and it worked like a charm.

Title: fopen() not working or showing errors

Body:
I want to create a new file along with the the creation of a record in my db. The db part works fine, but the file part isn't working. I want to create a file in another folder in the root directory and I used the same code with changes in the file name. Despite setting ini_set('display_errors',3) the code doesn't return any errors, I've also tried fopen($file_name,"w") or die("unable to open file"), still the code ran. I've given IIS_IUSRS full control over the directory. Here is my code

$data = mysqli_fetch_array(mysqli_query($conn,"Select * from content where link='$url'")); //fetch data from db
$id = $data['id'];
$file_name="/files/$id.html"; //sets file name
$file = fopen($file_name,"w"); //creates the file
fwrite($file,$_POST['desc']); //writes to the file
fclose($file); //closes the file


问:
Intellij Idea15 CE fails to launch with -XX:+UseG1GC
I am trying to test running with string interning to see if it helps ease the massive memory requirements of intellij. In order to use java 8's built in interning you need to run the G1GC.  However adding this parameter to the user idea.vmoptions file causes the jvm to fail to start. It is definitely this parameter only and other collectors seem not to be an issue. The bundled jre is 8u40 and i'm running on OS X.

12/28/16 11:06:24.559 AM idea[15003]: JNI_CreateJavaVM (/Applications/IntelliJ IDEA 15 CE.app/Contents/jre/jdk) failed: 4294967295

I also find it odd that the application is launched as a platform native binary which creates a jvm via jni, but that may be beside the point.

答:
Use this config: </p>

```<code>-XX:-UseParallelGC
-XX:-UseConcMarkSweepGC
-XX:+UseG1GC
</code>```

Body:
Use this config:

-XX:-UseParallelGC
-XX:-UseConcMarkSweepGC
-XX:+UseG1GC


问:
Could not resolve placeholder 'XXX' in string value "${XXX}"
In my spring boot example, I'd like to read environment variables from my local machine(Win 7).

```<code>@Data
@Component
public class EnvironmentVariableSystemProperties {

  @Value("${java.home}")
  private String javaHome;

  @Value("${DATASTORE.DATASET}")
  private String datastoreDataset;

  @Value("${SPRINGA}")
  private String springConfigName;

}
</code>```

It works well when reading java.home and DATASTORE.DATASET which have been added in my OS environment variables before.
I just added a new variable SPRINGA. When running spring boot example, I got the error:

```<code>Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'SPRINGA' in string value "${SPRINGA}".
</code>```

Should I restart up my machine to make the variable work?
I just restarted Eclipse, but it didn't work.

答:
Restarting Eclipse with the Restart in the Menu doesn't work.

Exiting Eclipse and Running it again works.

How weird it is!

Body:
In my spring boot example, I'd like to read environment variables from my local machine(Win 7).

@Data
@Component
public class EnvironmentVariableSystemProperties {

  @Value("${java.home}")
  private String javaHome;

  @Value("${DATASTORE.DATASET}")
  private String datastoreDataset;

  @Value("${SPRINGA}")
  private String springConfigName;

}

It works well when reading java.home and DATASTORE.DATASET which have been added in my OS environment variables before.
I just added a new variable SPRINGA. When running spring boot example, I got the error:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'SPRINGA' in string value "${SPRINGA}".

Should I restart up my machine to make the variable work?
I just restarted Eclipse, but it didn't work.


问:
Change R class package android/eclipse
Im working on a little interface in android and when I run it the "xxx application has stopped unexpectedly" appears. Im looking for posible errors but I don't find anything.

Anyway I would like to change the R class package name, when I refactor->rename it eclipse generates another one in the old package,even if I delete that package eclipse generates it again, I can't get rid of it!

答:
Look at your LogCat. It should have the stack trace of your error.

To see your LogCat from Eclipse, go to Window > Show View > Other > Android > LogCat.

To see your LogCat from the command line, go to your SDK/tools folder and run "adb logcat"

It's not possible to change the R class package.

ContentLicense: CC BY-SA 2.5

Title: Change R class package android/eclipse


问:
How sort posts by date from json
Note:  Reformatted to make code more readable, had to add text here so edit would be acceptable to the system.:

My json data is :

```<code>[
   {
      "language": "en",
      "polarity": 10,
      "rating": "",
      "source": "Facebook",
      "text": "FortyLove Sport Centers likes a photo.",
      "time": "2013-06-02",
      "wordsCount": 6,
      "details": "http://tour-pedia.org/api/getReviewDetails?    id=53513431ae9eef9405b2f18c"

   },
   {
      "language": "en",
      "polarity": 10,
      "rating": "",
      "source": "Facebook",
      "text": "FortyLove Sport Centers likes a status.",
      "time": "2013-05-26",
      "wordsCount": 6,
      "details": "http://tour-pedia.org/api/getReviewDetails?id=53513431ae9eef9405b2f18d"
   }
]
</code>```

And my source code is

```<code>let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { (data, response , error) in
if error != nil {
    print(error?.localizedDescription ?? "")
}
if let resultArray = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
        for jsonreviews in resultArray {
            let review = Review()
            review.rating = jsonreviews["rating"] as? Int ?? 0
            review.text = jsonreviews["text"] as! String
            review.time = jsonreviews["time"] as! String
            reviews.append(review)
        }
        DispatchQueue.main.async {
        self.tableview.reloadData()   // if you use tableview
        }
    }
}
task.resume()
</code>```

I don't have any idea how to sort by date, help me with code

答:
You should model your response of API call and then call the sort function on the array of your modeled data.Here is a blog on "working with json" by Apple:
https://developer.apple.com/swift/blog/?id=37

Here is a method as you have your data in reviews array,

```<code>    func sortByDate(){

    let formatter = DateFormatter()
    //define your date format
    formatter.dateFormat = "yyyy-MM-dd "
    formatter.timeZone = TimeZone(identifier: "UTC")

     reviews.sort{

        let date1  = formatter.date(from: $0.time)
        let date2 = formatter.date(from: $1.time)

        if date1 != nil && date2 != nil{
        return date1! > date2!
        }
        return false
      }

    }
</code>```

Title: How sort posts by date from json

Body:
Note:  Reformatted to make code more readable, had to add text here so edit would be acceptable to the system.:

My json data is :

[
   {
      "language": "en",
      "polarity": 10,
      "rating": "",
      "source": "Facebook",
      "text": "FortyLove Sport Centers likes a photo.",
      "time": "2013-06-02",
      "wordsCount": 6,
      "details": "http://tour-pedia.org/api/getReviewDetails?    id=53513431ae9eef9405b2f18c"

   },
   {
      "language": "en",
      "polarity": 10,
      "rating": "",
      "source": "Facebook",
      "text": "FortyLove Sport Centers likes a status.",
      "time": "2013-05-26",
      "wordsCount": 6,
      "details": "http://tour-pedia.org/api/getReviewDetails?id=53513431ae9eef9405b2f18d"
   }
]

And my source code is

let task = URLSession.shared.dataTask(with: URL(string: "http://tour-pedia.org/api/getReviews?location=Rome&category=poi")!) { (data, response , error) in
if error != nil {
    print(error?.localizedDescription ?? "")
}
if let resultArray = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
        for jsonreviews in resultArray {
            let review = Review()
            review.rating = jsonreviews["rating"] as? Int ?? 0
            review.text = jsonreviews["text"] as! String
            review.time = jsonreviews["time"] as! String
            reviews.append(review)
        }
        DispatchQueue.main.async {
        self.tableview.reloadData()   // if you use tableview
        }
    }
}
task.resume()

I don't have any idea how to sort by date, help me with code

Body:
You should model your response of API call and then call the sort function on the array of your modeled data.Here is a blog on "working with json" by Apple:
https://developer.apple.com/swift/blog/?id=37

Here is a method as you have your data in reviews array,

    func sortByDate(){

    let formatter = DateFormatter()
    //define your date format
    formatter.dateFormat = "yyyy-MM-dd "
    formatter.timeZone = TimeZone(identifier: "UTC")

     reviews.sort{

        let date1  = formatter.date(from: $0.time)
        let date2 = formatter.date(from: $1.time)

        if date1 != nil && date2 != nil{
        return date1! > date2!
        }
        return false
      }

    }


问:
How to determine the number of elements scanned into an array- c proramming
How can I determine the number of elements in an array of scanned in data?
For example, say I have an array that looks like this:

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

Obviously I can count the number of elements in this array, but if I scan in a much larger array, I don't want to count the number of elements individually. How can I use code to find the number of elements?

答:
You could use

```<code>int numberofelements = sizeof(array)/sizeof(int) //using type of array as int
</code>```

However this cannot be done inside a function as the array is passed to it as a pointer so sizeof(array) will return size of the pointer.
Perform this calculation before calling any function

Body:
How can I determine the number of elements in an array of scanned in data?
For example, say I have an array that looks like this:

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

Obviously I can count the number of elements in this array, but if I scan in a much larger array, I don't want to count the number of elements individually. How can I use code to find the number of elements?

Body:
You could use

int numberofelements = sizeof(array)/sizeof(int) //using type of array as int

However this cannot be done inside a function as the array is passed to it as a pointer so sizeof(array) will return size of the pointer.
Perform this calculation before calling any function


问:
App Doesn't Declare proper UIBackgroundMode
I am attempting to run an app in Xcode and every time I build, it says:

The request was denied by service delegate (SBMainWorkspace) for reason: Disabled ("Unable to launch NameOfApp because this app doesn't declare the proper UIBackgroundMode").

I don't know what I did to cause this or how to fix this.

info.plist source code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>GTFoos</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIStatusBarTintParameters</key>
    <dict>
        <key>UINavigationBar</key>
        <dict>
            <key>Style</key>
            <string>UIBarStyleDefault</string>
            <key>Translucent</key>
            <false/>
        </dict>
    </dict>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
</dict>
</plist>
</code>```

答:
I Know It Is Very Late But May be this will help some one else</p>

```<code><key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>remote-notification</string>
</array>
</code>```

Body:
I am attempting to run an app in Xcode and every time I build, it says:

The request was denied by service delegate (SBMainWorkspace) for reason: Disabled ("Unable to launch NameOfApp because this app doesn't declare the proper UIBackgroundMode").

I don't know what I did to cause this or how to fix this.

info.plist source code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>GTFoos</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIStatusBarTintParameters</key>
    <dict>
        <key>UINavigationBar</key>
        <dict>
            <key>Style</key>
            <string>UIBarStyleDefault</string>
            <key>Translucent</key>
            <false/>
        </dict>
    </dict>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
</dict>
</plist>

Body:
I Know It Is Very Late But May be this will help some one else

<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>remote-notification</string>
</array>


问:
How do you get Angular 2 (or 4) PrimeNg Charts to refresh asynchronously?
Problem: How to get PrimeNg Charts to refresh asynchronously?

Scenario: I have a dropdown that I want to refresh the chart based on a user selection.

I thought I knew the answer to this question after gaining an understanding of Angular change detection and how I would need to reassign an object for it to see the data had been changed (as opposed to updating the data within the object in place), but after reading about many other charts and even trying them, I learned that the problem was a bit more difficult than I initially thought.

When I read about ng2-charts, which builds directives off of charts.js as well, they use solutions that were a bit cloogy to get around this problem in Angular.  Here is an excerpt from their example code:

```<code>/**
* (My guess), for Angular to recognize the change in the dataset
* it has to change the dataset variable directly,
* so one way around it, is to clone the data, change it and then
* assign it;
**/
</code>```

http://valor-software.com/ng2-charts/

Even though they stringify and reparse the data to make a clone copy and reassign the data and it seemed to work for them, I tried this approach with PrimeNg with no success.

In other examples, they do a .slice() on the chart data, or access the CHART_DIRECTIVES directly and .update() the chart. They also wait to draw the chart until the data is loaded in asynchronously, which only loads the first time and wouldn't solve my desired behavior.
Why should I practice Test Driven Development and how should I start?

I know my data is there behind the scenes, I just need to know how to refresh the chart (i.e. come up with a way for Angular to properly recognize I have changed the data).

答:
I wanted a "real" solution, so I went to the source.  I was informed that
after 4.0.0-rc.1 that the behavior of the charts was changed.  I installed 4.0.0-rc.1 and followed the following example and got it to work as intended.

```<code>   changeData() {
            this.changedData = {
                labels: ['X','Y','Z'],
                datasets: [
                    {
                        data: [200, 200, 50],
                        backgroundColor: [
                            "#50f442",
                            "#f441c4",
                            "#4195f4"
                        ],
                        hoverBackgroundColor: [
                            "#50f442",
                            "#f441c4",
                            "#4195f4"
                        ]
                     }]
            }
            this.data = Object.assign({}, this.changedData);

}
</code>```

https://github.com/primefaces/primeng/issues/2235

Body:
Problem: How to get PrimeNg Charts to refresh asynchronously?

Scenario: I have a dropdown that I want to refresh the chart based on a user selection.

I thought I knew the answer to this question after gaining an understanding of Angular change detection and how I would need to reassign an object for it to see the data had been changed (as opposed to updating the data within the object in place), but after reading about many other charts and even trying them, I learned that the problem was a bit more difficult than I initially thought.

When I read about ng2-charts, which builds directives off of charts.js as well, they use solutions that were a bit cloogy to get around this problem in Angular.  Here is an excerpt from their example code:

/**
* (My guess), for Angular to recognize the change in the dataset
* it has to change the dataset variable directly,
* so one way around it, is to clone the data, change it and then
* assign it;
**/

http://valor-software.com/ng2-charts/

Even though they stringify and reparse the data to make a clone copy and reassign the data and it seemed to work for them, I tried this approach with PrimeNg with no success.

In other examples, they do a .slice() on the chart data, or access the CHART_DIRECTIVES directly and .update() the chart. They also wait to draw the chart until the data is loaded in asynchronously, which only loads the first time and wouldn't solve my desired behavior.
Why should I practice Test Driven Development and how should I start?

I know my data is there behind the scenes, I just need to know how to refresh the chart (i.e. come up with a way for Angular to properly recognize I have changed the data).

Body:
I wanted a "real" solution, so I went to the source.  I was informed that
after 4.0.0-rc.1 that the behavior of the charts was changed.  I installed 4.0.0-rc.1 and followed the following example and got it to work as intended.

   changeData() {
            this.changedData = {
                labels: ['X','Y','Z'],
                datasets: [
                    {
                        data: [200, 200, 50],
                        backgroundColor: [
                            "#50f442",
                            "#f441c4",
                            "#4195f4"
                        ],
                        hoverBackgroundColor: [
                            "#50f442",
                            "#f441c4",
                            "#4195f4"
                        ]
                     }]
            }
            this.data = Object.assign({}, this.changedData);

}

https://github.com/primefaces/primeng/issues/2235


问:
ssh localhost still needs password for Mac OS, how to deal with?
when ssh localhost still needs password, how to do?

ssh -vvv localhost

```<code>Last login: Fri Mar 31 12:51:03 on ttys000
chendeMacBook-Pro:~ chen$ ssh -vvv localhost
OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /etc/ssh/ssh_config
debug2: resolving "localhost" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to localhost [::1] port 22.
debug1: Connection established.
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_rsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_rsa-cert type -1
debug1: identity file /Users/chen/.ssh/id_dsa type 2
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4
debug1: match: OpenSSH_7.4 pat OpenSSH* compat 0x04000000
debug2: fd 5 setting O_NONBLOCK
debug1: Authenticating to localhost:22 as 'chen'
debug3: hostkeys_foreach: reading file "/Users/chen/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /Users/chen/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from localhost
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:oLpgYaEG7m2RJpeirxitnwrvjOo55nfEvLhriphbO8Q
debug3: hostkeys_foreach: reading file "/Users/chen/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /Users/chen/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from localhost
debug1: Host 'localhost' is known and matches the ECDSA host key.
debug1: Found key in /Users/chen/.ssh/known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: Skipping ssh-dss key /Users/chen/.ssh/id_dsa - not in PubkeyAcceptedKeyTypes
debug2: key: /Users/chen/.ssh/github_rsa (0x7ffbb2d00cd0), agent
debug2: key: /Users/chen/.ssh/id_rsa (0x0)
debug2: key: /Users/chen/.ssh/id_ecdsa (0x0)
debug2: key: /Users/chen/.ssh/id_ed25519 (0x0)
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug3: start over, passed a different list publickey,password,keyboard-interactive
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/chen/.ssh/github_rsa
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Trying private key: /Users/chen/.ssh/id_rsa
debug3: no such identity: /Users/chen/.ssh/id_rsa: No such file or directory
debug1: Trying private key: /Users/chen/.ssh/id_ecdsa
debug3: no such identity: /Users/chen/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /Users/chen/.ssh/id_ed25519
debug3: no such identity: /Users/chen/.ssh/id_ed25519: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup keyboard-interactive
debug3: remaining preferred: password
debug3: authmethod_is_enabled keyboard-interactive
debug1: Next authentication method: keyboard-interactive
debug2: userauth_kbdint
debug3: send packet: type 50
debug2: we sent a keyboard-interactive packet, wait for reply
debug3: receive packet: type 60
debug2: input_userauth_info_req
debug2: input_userauth_info_req: num_prompts 1
Password:
</code>```

答:
```<code>debug1: Skipping ssh-dss key /Users/chen/.ssh/id_dsa - not in PubkeyAcceptedKeyTypes
</code>```

This line says that the client has only DSA host key. This is considered weak these days with fixed length of 1024 bits. You should update the server and set up different keys (RSA).

As a workaround, you can use PubkeyAcceptedKeyTypes +ssh-dss in ~/.ssh/config, which will allow you to connect using this ke, exactly as described in the official documentation for legacy algorithms in OpenSSH.

Body:
when ssh localhost still needs password, how to do?

ssh -vvv localhost

Last login: Fri Mar 31 12:51:03 on ttys000
chendeMacBook-Pro:~ chen$ ssh -vvv localhost
OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /etc/ssh/ssh_config
debug2: resolving "localhost" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to localhost [::1] port 22.
debug1: Connection established.
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_rsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_rsa-cert type -1
debug1: identity file /Users/chen/.ssh/id_dsa type 2
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/chen/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4
debug1: match: OpenSSH_7.4 pat OpenSSH* compat 0x04000000
debug2: fd 5 setting O_NONBLOCK
debug1: Authenticating to localhost:22 as 'chen'
debug3: hostkeys_foreach: reading file "/Users/chen/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /Users/chen/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from localhost
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:oLpgYaEG7m2RJpeirxitnwrvjOo55nfEvLhriphbO8Q
debug3: hostkeys_foreach: reading file "/Users/chen/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /Users/chen/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from localhost
debug1: Host 'localhost' is known and matches the ECDSA host key.
debug1: Found key in /Users/chen/.ssh/known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: Skipping ssh-dss key /Users/chen/.ssh/id_dsa - not in PubkeyAcceptedKeyTypes
debug2: key: /Users/chen/.ssh/github_rsa (0x7ffbb2d00cd0), agent
debug2: key: /Users/chen/.ssh/id_rsa (0x0)
debug2: key: /Users/chen/.ssh/id_ecdsa (0x0)
debug2: key: /Users/chen/.ssh/id_ed25519 (0x0)
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug3: start over, passed a different list publickey,password,keyboard-interactive
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/chen/.ssh/github_rsa
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Trying private key: /Users/chen/.ssh/id_rsa
debug3: no such identity: /Users/chen/.ssh/id_rsa: No such file or directory
debug1: Trying private key: /Users/chen/.ssh/id_ecdsa
debug3: no such identity: /Users/chen/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /Users/chen/.ssh/id_ed25519
debug3: no such identity: /Users/chen/.ssh/id_ed25519: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup keyboard-interactive
debug3: remaining preferred: password
debug3: authmethod_is_enabled keyboard-interactive
debug1: Next authentication method: keyboard-interactive
debug2: userauth_kbdint
debug3: send packet: type 50
debug2: we sent a keyboard-interactive packet, wait for reply
debug3: receive packet: type 60
debug2: input_userauth_info_req
debug2: input_userauth_info_req: num_prompts 1
Password:

Body:
debug1: Skipping ssh-dss key /Users/chen/.ssh/id_dsa - not in PubkeyAcceptedKeyTypes

This line says that the client has only DSA host key. This is considered weak these days with fixed length of 1024 bits. You should update the server and set up different keys (RSA).

As a workaround, you can use PubkeyAcceptedKeyTypes +ssh-dss in ~/.ssh/config, which will allow you to connect using this ke, exactly as described in the official documentation for legacy algorithms in OpenSSH.


问:
Using MVCContrib's WindsorControllerFactory with new Windsor Castle 2.0
I'm trying to use WindsorControllerFactory (the latest 1.0.0.916 version) together with the new Windsor Castle 2.0 (again, the latest version). But I'm getting the

Could not load file or assembly
  'Castle.Windsor, Version=1.0.3.0...

error when starting the Web application. Anyway, during writing of this question I managed to persuade the Web app to bind to new Castle's dlls by adding this block to the Web.config file:

```<code>  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Castle.Windsor" culture="neutral" publicKeyToken="407dd0808d44fbdc"/>
        <bindingRedirect oldVersion="1.0.3.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.Core" culture="neutral" publicKeyToken="407dd0808d44fbdc"/>
        <bindingRedirect oldVersion="1.0.3.0" newVersion="1.1.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.MicroKernel" culture="neutral" publicKeyToken="407dd0808d44fbdc"/>
        <bindingRedirect oldVersion="1.0.3.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</code>```

So I guess I answered my own question, but I wanted to share this with anybody having the same problem. Or is there a better way (apart from compiling the MVCContrib sources myself)?

答:
We use the same approach. There is one issue with the last available MvcContrib (v.2.0.96.0). It uses Castel.Windsor v.2.1.0.0 that is not compatible with the latest version of Castel.Windsor (2.5.1.0): AddComponentLifeStyle is obsolete. So you will have to change related MvcContrib code.

BTW, you can sign MvcContrib dlls without rebuilding them, for example with this tool: http://signer.codeplex.com/

Body:
I'm trying to use WindsorControllerFactory (the latest 1.0.0.916 version) together with the new Windsor Castle 2.0 (again, the latest version). But I'm getting the

Could not load file or assembly
  'Castle.Windsor, Version=1.0.3.0...

error when starting the Web application. Anyway, during writing of this question I managed to persuade the Web app to bind to new Castle's dlls by adding this block to the Web.config file:

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Castle.Windsor" culture="neutral" publicKeyToken="407dd0808d44fbdc"/>
        <bindingRedirect oldVersion="1.0.3.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.Core" culture="neutral" publicKeyToken="407dd0808d44fbdc"/>
        <bindingRedirect oldVersion="1.0.3.0" newVersion="1.1.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.MicroKernel" culture="neutral" publicKeyToken="407dd0808d44fbdc"/>
        <bindingRedirect oldVersion="1.0.3.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

So I guess I answered my own question, but I wanted to share this with anybody having the same problem. Or is there a better way (apart from compiling the MVCContrib sources myself)?


问:
Typescript 2.2 and Angular 2.0.0-beta.21 dont go well together?
I followed the handbook guide for ASP.Net 4 but when I run the project I get the following console error

```<code>Error: declare.call is not a function
  Instantiating http://localhost:29961/Home/angular2/platform/browser
  Loading http://localhost:29961/Scripts/App/main.js
  Loading /Scripts/App/main
    at registerDeclarative (system.src.js:812)
    at system.src.js:714
    at ZoneDelegate.invoke (angular2-polyfills.js:349)
    at Zone.run (angular2-polyfills.js:242)
    at angular2-polyfills.js:597
    at ZoneDelegate.invokeTask (angular2-polyfills.js:382)
    at Zone.runTask (angular2-polyfills.js:282)
    at drainMicroTaskQueue (angular2-polyfills.js:500)
</code>```

My package.json looks like this

```<code>{
  "name": "myproject",
  "version": "1.0.0",
  "devDependencies": {
    "angular2": "^2.0.0-beta.21",
    "rxjs": "^5.2.0",
    "systemjs": "^0.20.11",
    "typings": "^2.1.0",
    "zone.js": "^0.8.5"
  }
}
</code>```

May be the guide was written for an older version of Angular2 and Typescript. So I might need to downgrade?

答:
TypeScript > 2.0 is supported just in Angular 4.0 You can check the changelog:
https://github.com/angular/angular/blob/master/CHANGELOG.md

Angular 2.0.0-beta is rather old now, you could consider upgrading it to a newer version. There have been some functional changes, so the current Angular documentation may not work with a beta version.

Body:
I followed the handbook guide for ASP.Net 4 but when I run the project I get the following console error

Error: declare.call is not a function
  Instantiating http://localhost:29961/Home/angular2/platform/browser
  Loading http://localhost:29961/Scripts/App/main.js
  Loading /Scripts/App/main
    at registerDeclarative (system.src.js:812)
    at system.src.js:714
    at ZoneDelegate.invoke (angular2-polyfills.js:349)
    at Zone.run (angular2-polyfills.js:242)
    at angular2-polyfills.js:597
    at ZoneDelegate.invokeTask (angular2-polyfills.js:382)
    at Zone.runTask (angular2-polyfills.js:282)
    at drainMicroTaskQueue (angular2-polyfills.js:500)

My package.json looks like this

{
  "name": "myproject",
  "version": "1.0.0",
  "devDependencies": {
    "angular2": "^2.0.0-beta.21",
    "rxjs": "^5.2.0",
    "systemjs": "^0.20.11",
    "typings": "^2.1.0",
    "zone.js": "^0.8.5"
  }
}

May be the guide was written for an older version of Angular2 and Typescript. So I might need to downgrade?


问:
How does timer_tick execute the code block?
Does timer execute the code block each tick even if the code block not completely done ? and if the answer is yes how to make timer tick completes the code block and then start over again.</p>

答:
Yes, it does execute the code each tick even if it's still not done. What you can do is when you execute the code block, stop the timer first, then run it again after the execution of the code block is done.

```<code>void Tick_Event(...){
timer.Stop();
// Do something
timer.Start();
}
</code>```

Hope it helps!

Body:
Yes, it does execute the code each tick even if it's still not done. What you can do is when you execute the code block, stop the timer first, then run it again after the execution of the code block is done.

void Tick_Event(...){
timer.Stop();
// Do something
timer.Start();
}

Hope it helps!


问:
Can I bind to multiple consumer groups with Spring Cloud Stream?
I am writing an application that will process event messages (posted to the topic file-upload-completed). I have multiple endpoints that should consume these messages (metadata-reader and quota-checker), and for pragmatic reasons I would like to deploy these endpoints together in an aggregated package.

With Spring Cloud Stream, I could use spring.cloud.stream.bindings.file-upload-completed.group=metadata-reader to set the consumer group for the first endpoint; I would also like to process messages under the quota-check group, but the property-based configuration only permits one consumer group binding per message queue.

Is there a way to configure Spring Cloud Stream so that I can bind to a single message queue under multiple consumer groups in the same application?

答:
but the property-based configuration only permits one consumer group binding per message queue.

by per message queue, do you mean, per-binding?

Also, when you specify the property spring.cloud.stream.bindings.file-upload-completed.group=metadata-reader, the file-upload-completed here means the bound target name (ex: the channel name) and you can define as many number of channels and their bindings with the specific consumer group that bound to a specific destination (topic: file-upload-completed)

```<code>spring.cloud.stream.bindings.mychannel1.destination=file-upload-completed
spring.cloud.stream.bindings.mychannel1.group=metadata-reader

spring.cloud.stream.bindings.mychannel2.destination=file-upload-completed
spring.cloud.stream.bindings.mychannel2.group=metadata-reader
</code>```

With the above configuration, you can perform operations such as join etc., something like this:

```<code>@StreamListener
 public void receive(@Input(Processor.INPUT) SubscribableChannel input1,
 @Input("mychannel2") SubscribableChannel input2) {
// perform operations (join etc.,)
}
</code>```

Body:
but the property-based configuration only permits one consumer group binding per message queue.

by per message queue, do you mean, per-binding?

Also, when you specify the property spring.cloud.stream.bindings.file-upload-completed.group=metadata-reader, the file-upload-completed here means the bound target name (ex: the channel name) and you can define as many number of channels and their bindings with the specific consumer group that bound to a specific destination (topic: file-upload-completed)

spring.cloud.stream.bindings.mychannel1.destination=file-upload-completed
spring.cloud.stream.bindings.mychannel1.group=metadata-reader

spring.cloud.stream.bindings.mychannel2.destination=file-upload-completed
spring.cloud.stream.bindings.mychannel2.group=metadata-reader

With the above configuration, you can perform operations such as join etc., something like this:

@StreamListener
 public void receive(@Input(Processor.INPUT) SubscribableChannel input1,
 @Input("mychannel2") SubscribableChannel input2) {
// perform operations (join etc.,)
}


问:
Use HTTP method 'OPTIONS' for custom usage?
I am working on a RESTful api. Now I categorize requests into get, modify and action.

get uses GET

modify uses POST, PUT, PATCH, DELETE

action uses OPTIONS

An example for action is OPTIONS /dogs/:id/feed, this will result in dog status changing flowing the logic defined in server scripts.

So, will there be any problems if I use OPTIONS for this usage?

答:
There might be problems, because you're abusing OPTIONS. Read Section 4.2.1 of RFC 7231 (https://greenbytes.de/tech/webdav/rfc7231.html#rfc.section.4.2.1):

Request methods are considered "safe" if their defined semantics are
  essentially read-only; i.e., the client does not request, and does not
  expect, any state change on the origin server as a result of applying
  a safe method to a target resource. Likewise, reasonable use of a safe
  method is not expected to cause any harm, loss of property, or unusual
  burden on the origin server.

...

Of the request methods defined by this specification, the GET, HEAD,
  OPTIONS, and TRACE methods are defined to be safe.


问:
xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH - Since updating Xcode
Updated Xcode this morning and now ionic project wont deploy to a device.

```<code>ionic run ios --device
</code>```

Returns:

```<code>** BUILD SUCCEEDED **

xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH

Error: Error code 72 for command: xcrun with args: -sdk,iphoneos,PackageApplication,-v
</code>```

No idea what to do to fix, Googling returns lots of options but none correct.

答:
I used shenzhen this automatic procedure encountered a similar problem, and finally in accordance with the github Pull Request to solve my problem, hope for your reference!
https://github.com/nomad/shenzhen/pull/347

Body:
Updated Xcode this morning and now ionic project wont deploy to a device.

ionic run ios --device

Returns:

** BUILD SUCCEEDED **

xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH

Error: Error code 72 for command: xcrun with args: -sdk,iphoneos,PackageApplication,-v

No idea what to do to fix, Googling returns lots of options but none correct.


问:
pandas - How to check consecutive order of dates and copy groups of them?
At first I have two problems, the first will follow now:

I a dataframe df with many times the same userid and along with it a date and some unimportant other columns:

```<code>    userid   date
0    243     2014-04-01
1    234     2014-12-01
2    234     2015-11-01
3    589     2016-07-01
4    589     2016-03-01
</code>```

I am currently trying to groupby them by userid and sort the dates descending and cut out the twelve oldest. My code looks like this:

```<code>df = df.groupby(['userid'], group_keys=False).agg(lambda x: x.sort_values(['date'], ascending=False, inplace=False).head(12))
</code>```

And I get this error:

```<code>ValueError: cannot copy sequence with size 6 to array axis with dimension 12
</code>```

At the moment my aim is to avoid to split the dataframe in individual ones.

My second problem is more complex:

I try to find out if the sorted dates (respectively per group of userids) are monthly consecutive. This means if there is an date for one group of  userid, for example userid: 234 and date: 2014-04-01, the next entry below must be userid: 234 and date:2014-03-01. There is no focus on the day, only the year and month are important.
And only this consecutive 12 dates should be copied in another dataframe.

A second dataframe df2 contains the same userid, but they are unique and another column is 'code'. Here is an example:

```<code>         userid  code
0          433805  1
24          5448   0
48          3434   1
72          34434  1
96          3202   1
120         23766  1
153         39457  0
168         4113   1
172         3435   5
374         34093  1
</code>```

I summarize: I try to check if there are 12 consecutive months per userid and copy every correct sequence in another dataframe. For this I have also compare the 'code' from df2.

This is a version of my code:

```<code>df['YearMonthDiff'] = df['date'].map(lambda x: 1000*x.year + x.month).diff()
    df['id_before'] = df['userid'].shift()
    final_df = pd.DataFrame()
    for group in df.groupby(['userid'], group_keys=False):
        fi = group[1]
        if (fi['userid'] <> fi['id_before']) &  group['YearMonthDiff'].all(-1.0) & df.loc[fi.userid]['code'] != 5:
            final_df.append(group['userid','date', 'consum'])
</code>```

At first calculated from the date an integer and made diff(). On other posts I saw they shift the column to compare the values from the current row and the row before. Then I made groupby(userid) to iterate over the single groups. Now it's extra ugly I tried to find the beginning of such an userid-group, try to check if there are only consecutive months and the correct 'code'. And at least I append it on the final dataframe.

On of the biggest problems is to compare the row with the following row. I can iterate over them with iterrow(), but I cannot compare them without shift(). There exits a calendar function, but on these I will take a look on the weekend. Sorry for the mess I am new to pandas.

Has anyone an idea how to solve my problem?

答:
for your first problem, try this</p>

```<code>df.groupby(by='userid').apply(lambda x: x.sort_values(by='date',ascending=False).iloc[[e for e in range(12) if e <len(x)]])
</code>```

Body:
At first I have two problems, the first will follow now:

I a dataframe df with many times the same userid and along with it a date and some unimportant other columns:

    userid   date
0    243     2014-04-01
1    234     2014-12-01
2    234     2015-11-01
3    589     2016-07-01
4    589     2016-03-01

I am currently trying to groupby them by userid and sort the dates descending and cut out the twelve oldest. My code looks like this:

df = df.groupby(['userid'], group_keys=False).agg(lambda x: x.sort_values(['date'], ascending=False, inplace=False).head(12))

And I get this error:

ValueError: cannot copy sequence with size 6 to array axis with dimension 12

At the moment my aim is to avoid to split the dataframe in individual ones.

My second problem is more complex:

I try to find out if the sorted dates (respectively per group of userids) are monthly consecutive. This means if there is an date for one group of  userid, for example userid: 234 and date: 2014-04-01, the next entry below must be userid: 234 and date:2014-03-01. There is no focus on the day, only the year and month are important.
And only this consecutive 12 dates should be copied in another dataframe.

A second dataframe df2 contains the same userid, but they are unique and another column is 'code'. Here is an example:

         userid  code
0          433805  1
24          5448   0
48          3434   1
72          34434  1
96          3202   1
120         23766  1
153         39457  0
168         4113   1
172         3435   5
374         34093  1

I summarize: I try to check if there are 12 consecutive months per userid and copy every correct sequence in another dataframe. For this I have also compare the 'code' from df2.

This is a version of my code:

df['YearMonthDiff'] = df['date'].map(lambda x: 1000*x.year + x.month).diff()
    df['id_before'] = df['userid'].shift()
    final_df = pd.DataFrame()
    for group in df.groupby(['userid'], group_keys=False):
        fi = group[1]
        if (fi['userid'] <> fi['id_before']) &  group['YearMonthDiff'].all(-1.0) & df.loc[fi.userid]['code'] != 5:
            final_df.append(group['userid','date', 'consum'])

At first calculated from the date an integer and made diff(). On other posts I saw they shift the column to compare the values from the current row and the row before. Then I made groupby(userid) to iterate over the single groups. Now it's extra ugly I tried to find the beginning of such an userid-group, try to check if there are only consecutive months and the correct 'code'. And at least I append it on the final dataframe.

On of the biggest problems is to compare the row with the following row. I can iterate over them with iterrow(), but I cannot compare them without shift(). There exits a calendar function, but on these I will take a look on the weekend. Sorry for the mess I am new to pandas.

Has anyone an idea how to solve my problem?

Body:
for your first problem, try this

df.groupby(by='userid').apply(lambda x: x.sort_values(by='date',ascending=False).iloc[[e for e in range(12) if e <len(x)]])


问:
T-SQL : return latest value of each ID
I have a table looks like

```<code>ID, name, Likes, Login_time
</code>```

select * from mytbl

I want to filter this table:

```<code>distinct ID, name like, login_time(last login time)
</code>```

I tried this query, but it didn't work.

```<code>select *
from
    (select
         name, likes, login_time
         rank() over (partition by id order by login_time desc) as rank
     from
         mytbl) t
where
    t.rank = 1
</code>```

答:
Try this</p>

```<code> ;WITH temps AS
    (
   SELECT Id, name, likes, login_time, row_number() over(PARTITION BY Id ORDER BY login_time desc) AS RowIndex
  )
SELECT Id, name, likes, login_time FROM temps
WHERE RowIndex = 1
</code>```

Title: T-SQL : return latest value of each ID

Body:
I have a table looks like

ID, name, Likes, Login_time

select * from mytbl

I want to filter this table:

distinct ID, name like, login_time(last login time)

I tried this query, but it didn't work.

select *
from
    (select
         name, likes, login_time
         rank() over (partition by id order by login_time desc) as rank
     from
         mytbl) t
where
    t.rank = 1

Body:
Try this

 ;WITH temps AS
    (
   SELECT Id, name, likes, login_time, row_number() over(PARTITION BY Id ORDER BY login_time desc) AS RowIndex
  )
SELECT Id, name, likes, login_time FROM temps
WHERE RowIndex = 1


问:
Can deployment be done for mass on azure AD
If we do on-premise AD sync with azure active directory using Azure connect DirSync and do not select password synchronization then

Will the deployment be done for the mass or can it be done in batches
of users?

After users are migrated to Azure, do they have to manually change

the credential to log in to their Office 365 accounts (they log in to

Office 365 with their email credentials now and after the Azure AD,

they will login with their AD credentials?

Is it possible to migrate all users to Azure but keep them inactive

and admin activate them in batches when required?

答:
You can select to synchronize specific users based on OU or Attribute based.
https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnectsync-configure-filtering#organizational-unitbased-filtering

https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnectsync-configure-filtering#attribute-based-filtering

You will not need to change the credentials, in case if you opt not to sync password hashes between your on-prem AD to AAD you can either enable federation through AD FS or pass through authentication where once credentials are entered the request comes on-prem and gets authenticated with same credentials already stored/used.

https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-azure-adfs

https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-pass-through-authentication


问:
how to avoid mutating this.state or redux object
For example, if I want to do any operation on this.state or some other object, such as Object.keys(this.state).map() to get access to all the values in the object.

Is it bad practice to do this?

```<code>Object.keys(this.state).map(k => this.state[k]);
</code>```

Thanks

答:
In React, you should only mutate this.state using this.setState() so that React knows when to re-render components.

The line of code you've written is fine, because you're not actually modifying the state object. You've already created a new array using Object.keys.

If however, you want to copy this.state without modifying it, try the following.

```<code>const state = {...this.state};

// Or

const state = Object.assign({}, this.state);
</code>```

Body:
For example, if I want to do any operation on this.state or some other object, such as Object.keys(this.state).map() to get access to all the values in the object.

Is it bad practice to do this?

Object.keys(this.state).map(k => this.state[k]);

Thanks

Body:
In React, you should only mutate this.state using this.setState() so that React knows when to re-render components.

The line of code you've written is fine, because you're not actually modifying the state object. You've already created a new array using Object.keys.

If however, you want to copy this.state without modifying it, try the following.

const state = {...this.state};

// Or

const state = Object.assign({}, this.state);


问:
Angular JS make value lower and check condition
I have value that might be upppercase or lowercase. I want to convert that to lower and compare and if that condition satisfies that it should show.

ie

```<code><div ng-if="test = 'Xyz'">show message</div>
</code>```

In this case  test is my model variable and its Xyz is the text. it can be XYZ or xyZ.

so I want every condition should satisfy.

Xyz value is fixed . it either XYZ,xYZ or XYZ all there conditions should be satisfy.

How it is possible?

答:
I got the solution. i did by

```<code><div ng-if="test.toLowerCase() == xyz">show message</div>
</code>```

And it works for me.

Body:
I have value that might be upppercase or lowercase. I want to convert that to lower and compare and if that condition satisfies that it should show.

ie

show message

In this case  test is my model variable and its Xyz is the text. it can be XYZ or xyZ.

so I want every condition should satisfy.

Xyz value is fixed . it either XYZ,xYZ or XYZ all there conditions should be satisfy.

How it is possible?

Body:
I got the solution. i did by

<div ng-if="test.toLowerCase() == xyz">show message</div>

And it works for me.


问:
Problem with max SQL function
I have this code in PHP

```<code>$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "<br>".$maxnum."hh";
</code>```

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

```<code><?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "<br>".$maxnum."hh";
    }
?>
</code>```

答:
Here is another and simpler way:

```<code>$query="SELECT MAX(num) FROM info";
list ($max) = mysql_fetch_row(mysql_query($query));
print ($max);
</code>```

num field in your database has to be a numeric datatype (i.e. int, float etc) in order for this to work properly.

Title: Problem with max SQL function

Body:
I have this code in PHP

$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "
".$maxnum."hh";

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

<?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "
".$maxnum."hh";
    }
?>

Body:
Here is another and simpler way:

$query="SELECT MAX(num) FROM info";
list ($max) = mysql_fetch_row(mysql_query($query));
print ($max);

num field in your database has to be a numeric datatype (i.e. int, float etc) in order for this to work properly.