问:
Can I dynamically import TypeScript modules in Node.js/Express?
I have a Node.js server built with Express.js and coded in TypeScript. Here's a snippet of the get call for my server:

server.ts

```<code>private get(req: Request, res: Response, next: NextFunction, objectName: string) {
    var DatabaseObject = require("./models/" + objectName + ".js")(this.orm, Sequelize.DataTypes);
    var Transform = require("./routes/" + objectName + ".js");
    var transform = new Transform();

    // ...

    console.log(req.query["columns"]);
    console.log(transform.columnWhitelist);
    console.log(transform);

    // ...

    if (transform.columnWhitelist) {
        console.log("Column Whitelist Exists.");
    }
    // ...
}
</code>```

It dynamically loads the Sequelize module for the database object being requested in the URL and then tries to load a TypeScript module with rules on what columns can be selected, which columns can be queried on, etc. Here's the beginning of my ruleset class:

account.ts

```<code>export default class Transform {
    static columnWhitelist : Object = {"id": "id", "name": "name", "parentAccountId":"parentAccountId", "masterAccountId":"masterAccountId"};

    constructor() { }
}
</code>```

However, running my application, I get:

```<code>id,name,parentAccountId
undefined
{ default:
   { [Function: Transform]
     columnWhitelist:
      { id: 'id',
        name: 'name',
        parentAccountId: 'parentAccountId',
        masterAccountId: 'masterAccountId' } } }
</code>```

Making the call transform.columnWhitelist, I get undefined, despite seeing it in the generated JavaScript file as well. I've also tried just:

```<code>    var transform = require("./routes/" + objectName + ".js");
</code>```

Or:

```<code>    var transform = require("./routes/" + objectName + ".js")();
</code>```

But neither of these work either.

答:
If you have commonjs as a module in your tsconfig.json and Transform class exported as default you should probably import it as </p>

```<code> var transform = require("./routes/" + objectName + ".js").default;
</code>```

Body:
I have a Node.js server built with Express.js and coded in TypeScript. Here's a snippet of the get call for my server:

server.ts

private get(req: Request, res: Response, next: NextFunction, objectName: string) {
    var DatabaseObject = require("./models/" + objectName + ".js")(this.orm, Sequelize.DataTypes);
    var Transform = require("./routes/" + objectName + ".js");
    var transform = new Transform();

    // ...

    console.log(req.query["columns"]);
    console.log(transform.columnWhitelist);
    console.log(transform);

    // ...

    if (transform.columnWhitelist) {
        console.log("Column Whitelist Exists.");
    }
    // ...
}

It dynamically loads the Sequelize module for the database object being requested in the URL and then tries to load a TypeScript module with rules on what columns can be selected, which columns can be queried on, etc. Here's the beginning of my ruleset class:

account.ts

export default class Transform {
    static columnWhitelist : Object = {"id": "id", "name": "name", "parentAccountId":"parentAccountId", "masterAccountId":"masterAccountId"};

    constructor() { }
}

However, running my application, I get:

id,name,parentAccountId
undefined
{ default:
   { [Function: Transform]
     columnWhitelist:
      { id: 'id',
        name: 'name',
        parentAccountId: 'parentAccountId',
        masterAccountId: 'masterAccountId' } } }

Making the call transform.columnWhitelist, I get undefined, despite seeing it in the generated JavaScript file as well. I've also tried just:

    var transform = require("./routes/" + objectName + ".js");

Or:

    var transform = require("./routes/" + objectName + ".js")();

But neither of these work either.

Body:
If you have commonjs as a module in your tsconfig.json and Transform class exported as default you should probably import it as

 var transform = require("./routes/" + objectName + ".js").default;


来源: stackexchange

问:
Build fails when I add the latest version on local notification plugin using CLI Command failed with exit code 8
Below is the full error message

C:\joel1\joel1\platforms\android\src\de\appplant\cordova\plugin\localnotificatio
n\LocalNotification.java:495: error: cannot find symbol
                    webView.evaluateJavascript(js, null);
                           ^
  symbol:   method evaluateJavascript(String,)
  location: variable webView of type CordovaWebView
C:\joel1\joel1\platforms\android\src\de\appplant\cordova\plugin\localnotificatio
n\LocalNotification.java:492: error: cannot find symbol
        webView.post(new Runnable(){
               ^
  symbol:   method post()
  location: variable webView of type CordovaWebView
2 errors
:compileDebugJava FAILED

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':compileDebugJava'.

Compilation failed; see the compiler error output for details.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output.

BUILD FAILED

Total time: 5.529 secs

C:\joel1\joel1\platforms\android\cordova\node_modules\q\q.js:126
                    throw e;
                          ^
Error code 1 for command: cmd with args: /s /c "C:\joel1\joel1\platforms\android
\gradlew cdvBuildDebug -b C:\joel1\joel1\platforms\android\build.gradle -PcdvBui
ldArch=arm -Dorg.gradle.daemon=true"
ERROR running one or more of the platforms: Error: C:\joel1\joel1\platforms\andr
oid\cordova\run.bat: Command failed with exit code 8
You may not have the required environment or OS to run this project

答:
In platforms/android/src/de/appplant/cordova/plugin/localnotification/LocalNotification.java file

```<code>private static synchronized void sendJavascript(final String js) {

    if (!deviceready) {
        eventQueue.add(js);
        return;
    }
    webView.getView().post(new Runnable(){
      public void run(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
          webView.sendJavascript(js);
        } else {
          webView.loadUrl("javascript:" + js);
        }
      }
    });
    // webView.post(new Runnable(){
    //     public void run(){
    //         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    //             webView.evaluateJavascript(js, null);
    //         } else {
    //             webView.loadUrl("javascript:" + js);
    //         }
    //     }
    // });
}
</code>```

https://github.com/katzer/cordova-plugin-local-notifications/issues/426

ContentLicense: CC BY-SA 3.0

Body:
In platforms/android/src/de/appplant/cordova/plugin/localnotification/LocalNotification.java file

private static synchronized void sendJavascript(final String js) {

    if (!deviceready) {
        eventQueue.add(js);
        return;
    }
    webView.getView().post(new Runnable(){
      public void run(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
          webView.sendJavascript(js);
        } else {
          webView.loadUrl("javascript:" + js);
        }
      }
    });
    // webView.post(new Runnable(){
    //     public void run(){
    //         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    //             webView.evaluateJavascript(js, null);
    //         } else {
    //             webView.loadUrl("javascript:" + js);
    //         }
    //     }
    // });
}

https://github.com/katzer/cordova-plugin-local-notifications/issues/426


问:
Missing data while Laravel create()
I try create new post using:

```<code>$post = $this->post->create($session, $response['PAYMENTINFO_0_TRANSACTIONID']);
</code>```

In $session are complete array of data for store.
In $response['PAYMENTINFO_0_TRANSACTIONID'] is token of payment.

When I check database, some fields are missing, but all data are in $session.

Why create() in Laravel don't want store all data?

答:
Please add the field names in

```<code>protected $fillable = ['field1','field2','field3'];
</code>```

in your Eloquent Model

Title: Missing data while Laravel create()

Body:
I try create new post using:

$post = $this->post->create($session, $response['PAYMENTINFO_0_TRANSACTIONID']);

In $session are complete array of data for store.
In $response['PAYMENTINFO_0_TRANSACTIONID'] is token of payment.

When I check database, some fields are missing, but all data are in $session.

Why create() in Laravel don't want store all data?

Body:
Please add the field names in

protected $fillable = ['field1','field2','field3'];

in your Eloquent Model


问:
UICollection is very slow in showing Image with Swift 3
I'm using UICollectionView to show the images in my app.

The problem is that it takes very slow to show images. After 50 seconds, the images in collection view appears. :(

When I find the solution in google, mostly they write the following codes.
But it is not work for me.

```<code>  cell.layer.shouldRasterize = true
  cell.layer.rasterizationScale = UIScreen.main.scale
</code>```

and

```<code>extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    debugPrint("seeAllLIStCell Count \(assetsTable.count)")
    return assetsTable.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "seeAllListCell", for: indexPath) as! SeeAllPhotoCell

    let list = assetsTable[(indexPath as NSIndexPath).row]

    var imageName: String? = (list.poster_image_url)
    var image: UIImage? = (images_cache[imageName!])
    if image != nil {
        debugPrint("Yes Image")

        cell.imageView.image = image

    } else{
        debugPrint("NO Image")
        cell.imageView.image = nil

        DispatchQueue.main.async(){
            let url = NSURL(string: list.poster_image_url)
            let data = NSData(contentsOf:url! as URL)
            var image = UIImage(data: data as! Data)
            DispatchQueue.main.async(execute: {() -> Void in
                cell.movieTitle.text = list.name
                cell.imageView?.image = image
            })
            self.images_cache[imageName!] = image
        }

    }

    return cell
}

}

// MARK: - UICollectionViewDelegate

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

            debugPrint("Selected")

    let list = assetsTable[(indexPath as NSIndexPath).row]
    debugPrint(list.poster_image_url)
    debugPrint(list.name)

    prefs.set(list.poster_image_url, forKey: "poster_image_url")
    prefs.set(list.name, forKey: "name")
    prefs.set(list.assets_id, forKey: "VIDEO_ID")
    prefs.set(false, forKey: "FLAG")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "DetailsChannel") as UIViewController
            self.present(vc, animated: true, completion: nil)

}
</code>```

}

Here is my screenshot when I run the project. I got these many lines of codes when I run.

Please anyone help me how should I do?

答:
this line:

```<code>DispatchQueue.main.async()
</code>```

upon downloading image is probably causing the error, it blocks the main thread and executes network requests on main (UI) queue, not to mention the fact that these requests are then performed serially (therefore slow). Try to change the snippet to:

```<code>DispatchQueue.global.async(qos: DispatchQoS.QoSClass.background){
        let url = NSURL(string: list.poster_image_url)
        let data = NSData(contentsOf:url! as URL)
        var image = UIImage(data: data as! Data)
        DispatchQueue.main.async(execute: {() -> Void in
</code>```

where global stands for global queue default for such network operations.

EDIT: apart from using main queue for network calls there may be an issue with actually too many images loaded for rows which are not currently visible on the screen. If there are lot of them and connection is not-so-good you will end up with app pending downloads for onscreen cells. Consider lazy loading images only for onscreen cells - and cancelling downloads for rows which are not visible. There is a quite good tutorial (however for table view, but you can easily extend it for collection) in Swift on how to accomplish this.

Body:
I'm using UICollectionView to show the images in my app.

The problem is that it takes very slow to show images. After 50 seconds, the images in collection view appears. :(

When I find the solution in google, mostly they write the following codes.
But it is not work for me.

  cell.layer.shouldRasterize = true
  cell.layer.rasterizationScale = UIScreen.main.scale

and

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    debugPrint("seeAllLIStCell Count \(assetsTable.count)")
    return assetsTable.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "seeAllListCell", for: indexPath) as! SeeAllPhotoCell

    let list = assetsTable[(indexPath as NSIndexPath).row]

    var imageName: String? = (list.poster_image_url)
    var image: UIImage? = (images_cache[imageName!])
    if image != nil {
        debugPrint("Yes Image")

        cell.imageView.image = image

    } else{
        debugPrint("NO Image")
        cell.imageView.image = nil

        DispatchQueue.main.async(){
            let url = NSURL(string: list.poster_image_url)
            let data = NSData(contentsOf:url! as URL)
            var image = UIImage(data: data as! Data)
            DispatchQueue.main.async(execute: {() -> Void in
                cell.movieTitle.text = list.name
                cell.imageView?.image = image
            })
            self.images_cache[imageName!] = image
        }

    }

    return cell
}

}

// MARK: - UICollectionViewDelegate

extension SeeAllCollectionView {

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

            debugPrint("Selected")

    let list = assetsTable[(indexPath as NSIndexPath).row]
    debugPrint(list.poster_image_url)
    debugPrint(list.name)

    prefs.set(list.poster_image_url, forKey: "poster_image_url")
    prefs.set(list.name, forKey: "name")
    prefs.set(list.assets_id, forKey: "VIDEO_ID")
    prefs.set(false, forKey: "FLAG")
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "DetailsChannel") as UIViewController
            self.present(vc, animated: true, completion: nil)

}

}

Here is my screenshot when I run the project. I got these many lines of codes when I run.

Please anyone help me how should I do?

Body:
this line:

DispatchQueue.main.async()

upon downloading image is probably causing the error, it blocks the main thread and executes network requests on main (UI) queue, not to mention the fact that these requests are then performed serially (therefore slow). Try to change the snippet to:

DispatchQueue.global.async(qos: DispatchQoS.QoSClass.background){
        let url = NSURL(string: list.poster_image_url)
        let data = NSData(contentsOf:url! as URL)
        var image = UIImage(data: data as! Data)
        DispatchQueue.main.async(execute: {() -> Void in

where global stands for global queue default for such network operations.

EDIT: apart from using main queue for network calls there may be an issue with actually too many images loaded for rows which are not currently visible on the screen. If there are lot of them and connection is not-so-good you will end up with app pending downloads for onscreen cells. Consider lazy loading images only for onscreen cells - and cancelling downloads for rows which are not visible. There is a quite good tutorial (however for table view, but you can easily extend it for collection) in Swift on how to accomplish this.


问:
How can I make Intent From Activity to Fragment in android?
Like this. It is working good from fragment to activity.</p>
```<code>Intent intent = new Intent(Location.this,MessageActivity.class);
startActivity(intent);
</code>```

答:
You can't make intent for Fragment from Activity...there is fragment transaction to get Intent of Fragment in Activity.

Follow: FragmentTransaction

```<code>MyFragmentB fragmentB = new MyFragmentB();
</code>```

To replace Fragment:

```<code>getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, fragmentB)
                    .addToBackStack(MyFragmentA.class.getSimpleName())
                    .commit();
</code>```

To Add Fragment:

```<code>getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, fragmentB)
                    .addToBackStack(MyFragmentA.class.getSimpleName())
                    .commit();
</code>```

To pass Bundle to Fragment(From Activity to Fragment OR Fragment to Fragment) :

```<code>Bundle bundle = new Bundle();
bundle.putString("String", "String text");
bundle.putInt("Integer", Integer value);
bundle.putDouble("Double", Double value);
bundle.putBoolean("Boolean", Boolean value);
...
fragmentB.setArguments(bundle);
</code>```

To get Bundle in Fragment:

```<code>getArguments().getString("String");//String text
getArguments().getInt("Integer");//Integer value
getArguments().getDouble("Double");//Double value
getArguments().getBoolean("Boolean");//Boolean value
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Like this. It is working good from fragment to activity.

Intent intent = new Intent(Location.this,MessageActivity.class);
startActivity(intent);

Body:
You can't make intent for Fragment from Activity...there is fragment transaction to get Intent of Fragment in Activity.

Follow: FragmentTransaction

MyFragmentB fragmentB = new MyFragmentB();

To replace Fragment:

getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, fragmentB)
                    .addToBackStack(MyFragmentA.class.getSimpleName())
                    .commit();

To Add Fragment:

getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, fragmentB)
                    .addToBackStack(MyFragmentA.class.getSimpleName())
                    .commit();

To pass Bundle to Fragment(From Activity to Fragment OR Fragment to Fragment) :

Bundle bundle = new Bundle();
bundle.putString("String", "String text");
bundle.putInt("Integer", Integer value);
bundle.putDouble("Double", Double value);
bundle.putBoolean("Boolean", Boolean value);
...
fragmentB.setArguments(bundle);

To get Bundle in Fragment:

getArguments().getString("String");//String text
getArguments().getInt("Integer");//Integer value
getArguments().getDouble("Double");//Double value
getArguments().getBoolean("Boolean");//Boolean value


问:
How to move a file between servers using PHP
I need to make a PHP function to move a file between 2 servers... For example, I have Sever1  and Server2, I have a file1.php locate on Server1, I need to execute a PHP function like: server1/execute.php to move file1.php to specific directory on Server2.

I'm using:

```<code><?php
$filename="file1.php";
unlink("ftp://USER:PASSWORD@IPADDRESS/httpdocs/DESTINATIONFOLDER/".$filename);
if(!copy($filename, "ftp://USER:PASSWORD@IPADDRESS/httpdocs/DESTINATIONFOLDER/".$filename))
{echo "error";}

?>
</code>```

that code work on my local server but when I publish on the server, the file is copied incomplete.

Some idea?

答:
Well you can transfer a file using ftp. Use the below simple and easy code to do this.</p>

```<code>/**
* Transfer (Export) Files Server to Server using PHP FTP
*/

/* Remote File Name and Path */
$remote_file = 'files.zip';

/* FTP Account (Remote Server) */
$ftp_host = 'your-ftp-host.com'; /* host */
$ftp_user_name = 'ftp-username@your-ftp-host.com'; /* username */
$ftp_user_pass = 'ftppassword'; /* password */

/* File and path to send to remote FTP server */
$local_file = 'files.zip';

/* Connect using basic FTP */
$connect_it = ftp_connect( $ftp_host );

/* Login to FTP */
$login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );

/* Send $local_file to FTP */
if ( ftp_put( $connect_it, $remote_file, $local_file, FTP_BINARY ) ) {
echo "WOOT! Successfully transfer $local_file\n";
}
else {
echo "Doh! There was a problem\n";
}

/* Close the connection */
ftp_close( $connect_it );
</code>```

Body:
I need to make a PHP function to move a file between 2 servers... For example, I have Sever1  and Server2, I have a file1.php locate on Server1, I need to execute a PHP function like: server1/execute.php to move file1.php to specific directory on Server2.

I'm using:

<?php
$filename="file1.php";
unlink("ftp://USER:PASSWORD@IPADDRESS/httpdocs/DESTINATIONFOLDER/".$filename);
if(!copy($filename, "ftp://USER:PASSWORD@IPADDRESS/httpdocs/DESTINATIONFOLDER/".$filename))
{echo "error";}

?>

that code work on my local server but when I publish on the server, the file is copied incomplete.

Some idea?

Body:
Well you can transfer a file using ftp. Use the below simple and easy code to do this.

/**
* Transfer (Export) Files Server to Server using PHP FTP
*/

/* Remote File Name and Path */
$remote_file = 'files.zip';

/* FTP Account (Remote Server) */
$ftp_host = 'your-ftp-host.com'; /* host */
$ftp_user_name = 'ftp-username@your-ftp-host.com'; /* username */
$ftp_user_pass = 'ftppassword'; /* password */

/* File and path to send to remote FTP server */
$local_file = 'files.zip';

/* Connect using basic FTP */
$connect_it = ftp_connect( $ftp_host );

/* Login to FTP */
$login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );

/* Send $local_file to FTP */
if ( ftp_put( $connect_it, $remote_file, $local_file, FTP_BINARY ) ) {
echo "WOOT! Successfully transfer $local_file\n";
}
else {
echo "Doh! There was a problem\n";
}

/* Close the connection */
ftp_close( $connect_it );


问:
How to convert a number where I replaced the dot with a comma from a string back to a decimal number
I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using  ParseFloat the 2 decimals after the comma disappear.

Example:

User enter in the input field : 79,99 which is then set into the variable totalAmount:

```<code>$('#amount-1').keyup(function() {

getRefundAmount(1); // This function calls the calcTotalAmount function

})

function calcTotalAmount() {
console.log('calcTotalAmount');

var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;

for(var i = 1; i < 4; i++ ) {
    rowAmount = parseFloat($('#amount-' + i).val());
    rowRefund = parseFloat($('#result-' + i).text());
    if(!isNaN(rowAmount)) {
        totalAmount += rowAmount;
        totalRefund += rowRefund;
    }
}

var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);

$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
    $('#footer-total').text("0.00");
}
}
</code>```

The Result displayed in the footer is : 79.00 instead of 79.99

答:
It seems like the code you've given works just fine but there are some fixes you could apply :

```<code>totalAmount = ("" + totalAmount).replace(/\,/g,'.');
totalAmount = parseFloat(totalAmount);
//use toFixed only if you don't restrict input to 2 decimals, but I'd recommend restricting input otherwise you'll encounter rounding issues
</code>```

Btw, you do $('#footer-refund').text(totalRefund.toFixed(2)), shouldn't it be $("#footer-refund").text(totalAmount) (not sure why you use toFixed here too) ?

Body:
I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using  ParseFloat the 2 decimals after the comma disappear.

Example:

User enter in the input field : 79,99 which is then set into the variable totalAmount:

$('#amount-1').keyup(function() {

getRefundAmount(1); // This function calls the calcTotalAmount function

})

function calcTotalAmount() {
console.log('calcTotalAmount');

var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;

for(var i = 1; i < 4; i++ ) {
    rowAmount = parseFloat($('#amount-' + i).val());
    rowRefund = parseFloat($('#result-' + i).text());
    if(!isNaN(rowAmount)) {
        totalAmount += rowAmount;
        totalRefund += rowRefund;
    }
}

var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);

$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
    $('#footer-total').text("0.00");
}
}

The Result displayed in the footer is : 79.00 instead of 79.99

Body:
It seems like the code you've given works just fine but there are some fixes you could apply :

totalAmount = ("" + totalAmount).replace(/\,/g,'.');
totalAmount = parseFloat(totalAmount);
//use toFixed only if you don't restrict input to 2 decimals, but I'd recommend restricting input otherwise you'll encounter rounding issues

Btw, you do $('#footer-refund').text(totalRefund.toFixed(2)), shouldn't it be $("#footer-refund").text(totalAmount) (not sure why you use toFixed here too) ?


问:
Ocaml List: Implement append and map functions
I'm currently trying to extend a friend's OCaml program. It's a huge collection of functions needed for some data analysis.. Since I'm not really an OCaml crack I'm currently stuck on a (for me) strange List implementation:

```<code>type 'a cell = Nil
    | Cons of ('a * 'a llist)
and 'a llist = (unit -> 'a cell);;
</code>```

I've figured out that this implements some sort of "lazy" list, but I have absolutely no idea how it really works. I need to implement an Append and a Map Function based on the above type. Has anybody got an idea how to do that?

Any help would really be appreciated!

答:
```<code>let rec append l1 l2 =
    match l1 () with
        Nil -> l2 |
        (Cons (a, l)) -> fun () -> (Cons (a, append l l2));;

let rec map f l =
    fun () ->
        match l () with
            Nil -> Nil |
            (Cons (a, r)) -> fun () -> (Cons (f a, map f r));;
</code>```

The basic idea of this implementation of lazy lists is that each computation is encapsulated in a function (the technical term is a closure) via fun () -> x.
The expression x is then only evaluated when the function is applied to () (the unit value, which contains no information).

OwnerDisplayName: Chriss

ContentLicense: CC BY-SA 2.5

Body:
I'm currently trying to extend a friend's OCaml program. It's a huge collection of functions needed for some data analysis.. Since I'm not really an OCaml crack I'm currently stuck on a (for me) strange List implementation:

type 'a cell = Nil
    | Cons of ('a * 'a llist)
and 'a llist = (unit -> 'a cell);;

I've figured out that this implements some sort of "lazy" list, but I have absolutely no idea how it really works. I need to implement an Append and a Map Function based on the above type. Has anybody got an idea how to do that?

Any help would really be appreciated!

LastEditorDisplayName: starblue

Body:
let rec append l1 l2 =
    match l1 () with
        Nil -> l2 |
        (Cons (a, l)) -> fun () -> (Cons (a, append l l2));;

let rec map f l =
    fun () ->
        match l () with
            Nil -> Nil |
            (Cons (a, r)) -> fun () -> (Cons (f a, map f r));;

The basic idea of this implementation of lazy lists is that each computation is encapsulated in a function (the technical term is a closure) via fun () -> x.
The expression x is then only evaluated when the function is applied to () (the unit value, which contains no information).

OwnerDisplayName: starblue


问:
Compile Tensorflow from source with Docker to get CPU speed up
I am looking for a way to set up or modify an existing Docker image for installing tensorflow that will install it such that the SSE4, AVX, AVX2, and FMA instructions can be utilized for CPU speed up. So far I have found how to install from source using bazel How to Compile Tensorflow... and CPU instructions not compiled.... Neither of these explain how to do this within Docker. So I think what I am looking for is what you need to add to an existing docker image that installs without these options so that you can get a compile version of tensorflow with the CPU options enabled. The existing docker images do not do this because they want the image to run on as many machines as possible. I am using Ubuntu 14.04 on linux PC. I am new to docker but have installed tensorflow and have it working without getting the CPU warnings I get when I use the docker images. I may not need this for speed, but I have seen posts that claim the speed up can be significant. I searched for existing docker images that do this and could not find anything. I need this to work with gpu so needs to be compatible with nvidia-docker. </p>

<p>I just found this docker support for bazel and it might provide an answer, however I do not understand it well enough to know for sure. I believe this is saying that you can not build tensorflow with bazel inside a Dockerfile. You have to build a Dockerfile using bazel. Is my understanding correct and is this the only way to get a docker image with tensorflow compiled from source? If so, I could still use help in how to do it and still get the other dependencies that I would get if using an existing docker image for tensorflow. </p>

答:
Dockerfiles that build with CPU support can be found here.

Hope that helps!  Spent many a late night here on Stack Overflow and Github Issues and stuff.  Now it's my turn to give back!  :)

The GPU stuff in particular is really hairy - especially when enabling the XLA/JIT/AOT stuff as well as the Graph Transform Tools.

Lots of hacks embedded in my Dockerfiles.  Feel free to review and ask me questions!

Body:
I am looking for a way to set up or modify an existing Docker image for installing tensorflow that will install it such that the SSE4, AVX, AVX2, and FMA instructions can be utilized for CPU speed up. So far I have found how to install from source using bazel How to Compile Tensorflow... and CPU instructions not compiled.... Neither of these explain how to do this within Docker. So I think what I am looking for is what you need to add to an existing docker image that installs without these options so that you can get a compile version of tensorflow with the CPU options enabled. The existing docker images do not do this because they want the image to run on as many machines as possible. I am using Ubuntu 14.04 on linux PC. I am new to docker but have installed tensorflow and have it working without getting the CPU warnings I get when I use the docker images. I may not need this for speed, but I have seen posts that claim the speed up can be significant. I searched for existing docker images that do this and could not find anything. I need this to work with gpu so needs to be compatible with nvidia-docker.

I just found this docker support for bazel and it might provide an answer, however I do not understand it well enough to know for sure. I believe this is saying that you can not build tensorflow with bazel inside a Dockerfile. You have to build a Dockerfile using bazel. Is my understanding correct and is this the only way to get a docker image with tensorflow compiled from source? If so, I could still use help in how to do it and still get the other dependencies that I would get if using an existing docker image for tensorflow.


问:
Why is my instance variable changing indirectly?
I'm a starter at ruby, and I'm really stuck with this code... I can't understand why is @plays changing when a call test_code</p>

```<code>class Board
  attr_reader :plays

  def initialize(secret_code)
    @secret_code = secret_code
    @plays = []
  end

  def insert_code(code)
    @plays.push(code)
    p @plays         #-> [["red", "red", "red", "red"]]
    test_code(code)  #-> When i call this method the changes on 'code' make to '@plays' array...
    p @plays         #-> [["check", "red", "red", "red"]]
  end

  private

  def test_code(code)
    s_code = @secret_code  # made a copy of @secret_code to keep it intact but is changing just like @plays
    s_code.each_index do |i|
      if s_code[i] == code[i]
        s_code[i] = "O"
        code[i] = "check"  #in this line the @plays array is changed, and i can't figure out why
      end
    end
  end
end

board = Board.new(["red", "blue", "blue", "blue"])
board.insert_code(["red", "red", "red", "red"])
</code>```

答:
you defined the @plays like this:

```<code>  def insert_code(code)
    @plays.push(code)          # here is not a clone but a quote
  end
</code>```

after running the methond "test_code", the variable "code" is changed to ["check", "red", "red", "red"]
so you see the @plays is also changed to [["check", "red", "red", "red"]]

Body:
I'm a starter at ruby, and I'm really stuck with this code... I can't understand why is @plays changing when a call test_code

class Board
  attr_reader :plays

  def initialize(secret_code)
    @secret_code = secret_code
    @plays = []
  end

  def insert_code(code)
    @plays.push(code)
    p @plays         #-> [["red", "red", "red", "red"]]
    test_code(code)  #-> When i call this method the changes on 'code' make to '@plays' array...
    p @plays         #-> [["check", "red", "red", "red"]]
  end

  private

  def test_code(code)
    s_code = @secret_code  # made a copy of @secret_code to keep it intact but is changing just like @plays
    s_code.each_index do |i|
      if s_code[i] == code[i]
        s_code[i] = "O"
        code[i] = "check"  #in this line the @plays array is changed, and i can't figure out why
      end
    end
  end
end

board = Board.new(["red", "blue", "blue", "blue"])
board.insert_code(["red", "red", "red", "red"])

Body:
you defined the @plays like this:

  def insert_code(code)
    @plays.push(code)          # here is not a clone but a quote
  end

after running the methond "test_code", the variable "code" is changed to ["check", "red", "red", "red"]
so you see the @plays is also changed to [["check", "red", "red", "red"]]


问:
PrestaShop, use tinymce directly from Smarty template
I'm doing a PrestaShop module. This module will be anchored to the hook called "hookDisplayAdminProductsExtra".

I need to use the TEXTAREA field tinymce using the library, you can do so by creating the textarea directly from Smarty and not as a controller? Maybe using jQuery function or adding a class to the field?

My code in tpl file is:

```<code>{foreach $row_list as $row}
    <textarea id="description_1" name="description_1" class="autoload_rte" aria-hidden="true">
        {$row['desc']}
    </textarea>
{/foreach}
</code>```

My module function is:

```<code>$this->context->smarty->assign(
    array(
        'row_list'  => $this->getField($id)
    )
);
return $this->display(__FILE__, 'admin-view.tpl');
</code>```

答:
The autoload_rte is "used" when tab Informations is loaded by Prestashop using:

```<code>$(document).ready(function(){

    // Execute when tab Informations has finished loading
    tabs_manager.onLoad('Informations', function(){
        tinySetup({
            editor_selector :"autoload_rte",
            setup : function(ed) {
                ed.on('init', function(ed)
                {
                    if (typeof ProductMultishop.load_tinymce[ed.target.id] != 'undefined')
                    {
                        if (typeof ProductMultishop.load_tinymce[ed.target.id])
                            tinyMCE.get(ed.target.id).hide();
                        else
                            tinyMCE.get(ed.target.id).show();
                    }
                });

                ed.on('keydown', function(ed, e) {
                    tinyMCE.triggerSave();
                    textarea = $('#'+tinymce.activeEditor.id);
                    var max = textarea.parent('div').find('span.counter').data('max');
                    if (max != 'none')
                    {
                        count = tinyMCE.activeEditor.getBody().textContent.length;
                        rest = max - count;
                        if (rest < 0)
                            textarea.parent('div').find('span.counter').html('<span style="color:red;">Maximum '+ max +' characters : '+rest+'</span>');
                        else
                            textarea.parent('div').find('span.counter').html(' ');
                    }
                });
            }
        });
    });

});
</code>```

In addition to this, the other tabs are also loaded later than the Informations tab. To solve this, you need to initialized the tinymce for the field you want. Choose another selector (not sure it's needed but at least there is 100% no chance to mess with the current ones), for example the class mytextarea, then use:

```<code><script>$(document).ready(function(){tinymce.init({mode : "textareas", editor_selector : "mytextarea", plugins: "textcolor paste code"});})</script>
</code>```

This can be in your tpl.
In my tests, if there is no plugins setup there would be an error in console log. But you can adjust the tinymce settings as you wish.

Body:
I'm doing a PrestaShop module. This module will be anchored to the hook called "hookDisplayAdminProductsExtra".

I need to use the TEXTAREA field tinymce using the library, you can do so by creating the textarea directly from Smarty and not as a controller? Maybe using jQuery function or adding a class to the field?

My code in tpl file is:

{foreach $row_list as $row}
    <textarea id="description_1" name="description_1" class="autoload_rte" aria-hidden="true">
        {$row['desc']}
    </textarea>
{/foreach}

My module function is:

$this->context->smarty->assign(
    array(
        'row_list'  => $this->getField($id)
    )
);
return $this->display(__FILE__, 'admin-view.tpl');

Body:
The autoload_rte is "used" when tab Informations is loaded by Prestashop using:

$(document).ready(function(){

    // Execute when tab Informations has finished loading
    tabs_manager.onLoad('Informations', function(){
        tinySetup({
            editor_selector :"autoload_rte",
            setup : function(ed) {
                ed.on('init', function(ed)
                {
                    if (typeof ProductMultishop.load_tinymce[ed.target.id] != 'undefined')
                    {
                        if (typeof ProductMultishop.load_tinymce[ed.target.id])
                            tinyMCE.get(ed.target.id).hide();
                        else
                            tinyMCE.get(ed.target.id).show();
                    }
                });

                ed.on('keydown', function(ed, e) {
                    tinyMCE.triggerSave();
                    textarea = $('#'+tinymce.activeEditor.id);
                    var max = textarea.parent('div').find('span.counter').data('max');
                    if (max != 'none')
                    {
                        count = tinyMCE.activeEditor.getBody().textContent.length;
                        rest = max - count;
                        if (rest < 0)
                            textarea.parent('div').find('span.counter').html('<span style="color:red;">Maximum '+ max +' characters : '+rest+'</span>');
                        else
                            textarea.parent('div').find('span.counter').html(' ');
                    }
                });
            }
        });
    });

});

In addition to this, the other tabs are also loaded later than the Informations tab. To solve this, you need to initialized the tinymce for the field you want. Choose another selector (not sure it's needed but at least there is 100% no chance to mess with the current ones), for example the class mytextarea, then use:

<script>$(document).ready(function(){tinymce.init({mode : "textareas", editor_selector : "mytextarea", plugins: "textcolor paste code"});})</script>

This can be in your tpl.
In my tests, if there is no plugins setup there would be an error in console log. But you can adjust the tinymce settings as you wish.


问:
UITableView when cell scroll to top, the cell will fixed on the top
In TableView Middle that one "Popular | Latest | Top Sales | Price"
when scroll in tableview, the middle cell will fixed on the top.

So, How to use UITableView Do like this?

Below Sample photo

Photo Sample First

Photo Sample Second

答:
That was not cell. It was TableView header.

For making custom tableview header use viewForHeaderInSection:(NSInteger)section.

Below also provided demo code for making custom tableview header.

```<code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    //Create Button with title "Popular".
    let b1 = UIButton()
    b1.setTitle("Popular", for: .normal)
    b1.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(95), height: CGFloat(35))
    b1.setTitleColor(UIColor.black, for: .normal)

    //Create Button with title "Latest".
    let b2 = UIButton()
    b2.setTitle("Latest", for: .normal)
    b2.frame = CGRect(x: CGFloat(105), y: CGFloat(0), width: CGFloat(95), height: CGFloat(35))
    b2.setTitleColor(UIColor.black, for: .normal)

    //Create Button with title "Top Sales".
    let b3 = UIButton()
    b3.setTitle("Top sales", for: .normal)
    b3.frame = CGRect(x: CGFloat(210), y: CGFloat(0), width: CGFloat(95), height: CGFloat(35))
    b3.setTitleColor(UIColor.black, for: .normal)

    //Create Button with Title "Price"
    let b4 = UIButton()
    b4.setTitle("Price", for: .normal)
    b4.frame = CGRect(x: CGFloat(300), y: CGFloat(0), width: CGFloat(95), height: CGFloat(35))
    b4.setTitleColor(UIColor.black, for: .normal)

    //Create UIView and Setup UIView
    let view = UIView()
    view.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(365), height: CGFloat(60))
    view.backgroundColor = UIColor.white

    //Add Button In UIView
    view.addSubview(b1)
    view.addSubview(b2)
    view.addSubview(b3)
    view.addSubview(b4)

    //Return UiView
    return view
}
</code>```

Body:
That was not cell. It was TableView header.

For making custom tableview header use viewForHeaderInSection:(NSInteger)section.

Below also provided demo code for making custom tableview header.

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    //Create Button with title "Popular".
    let b1 = UIButton()
    b1.setTitle("Popular", for: .normal)
    b1.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(95), height: CGFloat(35))
    b1.setTitleColor(UIColor.black, for: .normal)

    //Create Button with title "Latest".
    let b2 = UIButton()
    b2.setTitle("Latest", for: .normal)
    b2.frame = CGRect(x: CGFloat(105), y: CGFloat(0), width: CGFloat(95), height: CGFloat(35))
    b2.setTitleColor(UIColor.black, for: .normal)

    //Create Button with title "Top Sales".
    let b3 = UIButton()
    b3.setTitle("Top sales", for: .normal)
    b3.frame = CGRect(x: CGFloat(210), y: CGFloat(0), width: CGFloat(95), height: CGFloat(35))
    b3.setTitleColor(UIColor.black, for: .normal)

    //Create Button with Title "Price"
    let b4 = UIButton()
    b4.setTitle("Price", for: .normal)
    b4.frame = CGRect(x: CGFloat(300), y: CGFloat(0), width: CGFloat(95), height: CGFloat(35))
    b4.setTitleColor(UIColor.black, for: .normal)

    //Create UIView and Setup UIView
    let view = UIView()
    view.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(365), height: CGFloat(60))
    view.backgroundColor = UIColor.white

    //Add Button In UIView
    view.addSubview(b1)
    view.addSubview(b2)
    view.addSubview(b3)
    view.addSubview(b4)

    //Return UiView
    return view
}


问:
Replace Mysql database from one Computer to Other in Rails as we do in sqlite3
I switched to mysql dtabase in Rails.I got a databse.sql file generated in db folder.But when i login to mysql and check data in tables then there is no records present in tables.

i used this command for dump

mysql –u root –p database_name < database_name.sql```

there was no error while executing this command but when i checked the tables then there were no records in the tables.So please help me to insert all my records in database using database.sql file.There is one fiel generated database.sq.IO ned to copy this file to another pc and make all my records to insert.So how may i do this.

答:
You can import .sql file using the standard input like this:

```<code>mysql -u <user> -p<password> <dbname> < file.sql
</code>```

Note: There shouldn't space between -p and password

Body:
I switched to mysql dtabase in Rails.I got a databse.sql file generated in db folder.But when i login to mysql and check data in tables then there is no records present in tables.

i used this command for dump

mysql –u root –p database_name < database_name.sql

there was no error while executing this command but when i checked the tables then there were no records in the tables.So please help me to insert all my records in database using database.sql file.There is one fiel generated database.sq.IO ned to copy this file to another pc and make all my records to insert.So how may i do this.

Body:
You can import .sql file using the standard input like this:

mysql -u <user> -p<password> <dbname> < file.sql

Note: There shouldn't space between -p and password


问:
Protobuf with many unknown types
What is the best approach when I do not know at runtime which types are de/serialized with protobuf?

Currently I am playing with the idea to extend the RuntimeTypeModel in the type initializers of the types which are candidates for serialization which seems to work pretty well for serialiation. But when deserializing in a different process I would need to load the same type model from somewhere which was used to serialize the types. Is it possible to serialize the RuntimeTypeModel to disk to reuse it later when the serialized data is read again from disk? Ideally I would put the model into the serialized stream as well to have a full self describing object model. Or would I need to record the steps and put this data in front of my serialized stream?

One could create a header which contains the offset to the real data and the runtime type model and the length which would be pretty nice. Or is there a better approach how to deal with a plug in architecture where at serialization time I have all types registered but during deseralization I might stil need to load some types from their respective assemblies because the code was not yet touched?

```<code>using ProtoBuf;
using ProtoBuf.Meta;
using System.Collections.Generic;
using System.IO;

namespace protobuf
{
    [ProtoContract]
    public interface IAbstraction
    {
        [ProtoMember(1)]
        string Name { get; set; }
    }

    [ProtoContract]
    public class Base : IAbstraction
    {
        static Base()
        {
            ProtobufTypeModels.MainModel.Add(typeof(IAbstraction), true).AddSubType(101, typeof(Base));
        }

        [ProtoMember(1)]
        public string Name { get; set; }

        [ProtoMember(2, AsReference =true)]
        public List<IAbstraction> Instances = new List<IAbstraction>();
    }

    [ProtoContract]
    public class Next : Base
    {
        static Next()
        {
            ProtobufTypeModels.MainModel.Add(typeof(IAbstraction), true).AddSubType(100, typeof(Next));
        }

        [ProtoMember(1)]
        public string NextName { get; set; }
    }

    public static class ProtobufTypeModels
    {
        public static readonly RuntimeTypeModel MainModel = TypeModel.Create();
    }

    class Program
    {
        static void Main(string[] args)
        {
            Base b = new Base { Name = "Alois" };
            b.Instances.Add(new Next { Name = "Base", NextName = "Christian" });
            b.Instances.Add(new Base { Name = "SecondBase", Instances = b.Instances });
            var mem = new MemoryStream();
            ProtobufTypeModels.MainModel.Serialize(mem, b);
            mem.Position = 0;
            var deser = (Base) ProtobufTypeModels.MainModel.Deserialize(mem, null, typeof(Base));
        }
    }
}
</code>```

答:
Random thought: you could use .Compile(serializerName,dllPath) after you've finished the initialization and write the baked serializer to disk; then you can reference it, use new SerializerName() to create the instance, and use the .Serialize etc methods from there. The dll will never change. This also means it never has to process any metadata ever again; no reflection, no IL emit, etc.

Other than that: we could possibly do something more gentle in terms of storing the configuration, but: protobuf-net doesn't currently add anything directly to support it, and it would probably be more relevant for you to have your own bespoke configuration data that you simply consume at startup.

Title: Protobuf with many unknown types

Body:
What is the best approach when I do not know at runtime which types are de/serialized with protobuf?

Currently I am playing with the idea to extend the RuntimeTypeModel in the type initializers of the types which are candidates for serialization which seems to work pretty well for serialiation. But when deserializing in a different process I would need to load the same type model from somewhere which was used to serialize the types. Is it possible to serialize the RuntimeTypeModel to disk to reuse it later when the serialized data is read again from disk? Ideally I would put the model into the serialized stream as well to have a full self describing object model. Or would I need to record the steps and put this data in front of my serialized stream?

One could create a header which contains the offset to the real data and the runtime type model and the length which would be pretty nice. Or is there a better approach how to deal with a plug in architecture where at serialization time I have all types registered but during deseralization I might stil need to load some types from their respective assemblies because the code was not yet touched?

using ProtoBuf;
using ProtoBuf.Meta;
using System.Collections.Generic;
using System.IO;

namespace protobuf
{
    [ProtoContract]
    public interface IAbstraction
    {
        [ProtoMember(1)]
        string Name { get; set; }
    }

    [ProtoContract]
    public class Base : IAbstraction
    {
        static Base()
        {
            ProtobufTypeModels.MainModel.Add(typeof(IAbstraction), true).AddSubType(101, typeof(Base));
        }

        [ProtoMember(1)]
        public string Name { get; set; }

        [ProtoMember(2, AsReference =true)]
        public List<IAbstraction> Instances = new List<IAbstraction>();
    }

    [ProtoContract]
    public class Next : Base
    {
        static Next()
        {
            ProtobufTypeModels.MainModel.Add(typeof(IAbstraction), true).AddSubType(100, typeof(Next));
        }

        [ProtoMember(1)]
        public string NextName { get; set; }
    }

    public static class ProtobufTypeModels
    {
        public static readonly RuntimeTypeModel MainModel = TypeModel.Create();
    }

    class Program
    {
        static void Main(string[] args)
        {
            Base b = new Base { Name = "Alois" };
            b.Instances.Add(new Next { Name = "Base", NextName = "Christian" });
            b.Instances.Add(new Base { Name = "SecondBase", Instances = b.Instances });
            var mem = new MemoryStream();
            ProtobufTypeModels.MainModel.Serialize(mem, b);
            mem.Position = 0;
            var deser = (Base) ProtobufTypeModels.MainModel.Deserialize(mem, null, typeof(Base));
        }
    }
}


问:
mysql error 1064 when inserting

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(country,ping,order) VALUES (China,1,1)' at line 1

this is my code

```<code>INSERT INTO
  (country, ping, order)
VALUES
  ('China', '1', '1');
</code>```

答:
are ping and order text fields or numeric?  if numeric remove the ticks from the 1's

```<code>INSERT INTO Tablename (country,ping,order) VALUES ('China',1,1)
</code>```

could also be reserved word try:

```<code>INSERT INTO Tablename (country,`ping`,`order`) VALUES ('China',1,1)
</code>```

Title: mysql error 1064 when inserting

Body:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(country,ping,order) VALUES (China,1,1)' at line 1

this is my code

INSERT INTO
  (country, ping, order)
VALUES
  ('China', '1', '1');

Body:
are ping and order text fields or numeric?  if numeric remove the ticks from the 1's

INSERT INTO Tablename (country,ping,order) VALUES ('China',1,1)

could also be reserved word try:

INSERT INTO Tablename (country,`ping`,`order`) VALUES ('China',1,1)


问:
how to use @JoinColumn in OneToOne mapping in hibernate?
I have seen many questions asked on @JoinColumn and this concept was clear to me until I came across the following situation.

Let's consider mapping is OneToOne Unidirectional mapping. i have used following annatation in the parent class:
Case 1:-
@JoinColumn(name="test_Id",referencedColumnName="refToPrimaryKey") and  Entity class is not implementing Serializable interface. in this case program is executing without any exception.
Case 2:-
@JoinColumn(name="test_Id",referencedColumnName="refToNonPrimaryKey") and  Entity class is not implementing Serializable interface.

Here program is throwing exception like:

```<code>threw exception [java.lang.ClassCastException:
com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable] with root cause
java.lang.ClassCastException: com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable at org.hibernate.type.CollectionType.getKeyOfOwner(CollectionType.java:414)
</code>```

Can you Guys help me out to know the concept why it is happening?

答:
Are you using second level caching, As per caused show
cannot be cast to java.io.Serializable at org.hibernate.type.CollectionType.getKeyOfOwner(CollectionType.java:414)

As per hibernate doc, disassemble Return a disassembled representation of the object.  This is the value Hibernate will use in second level caching, so care should be taken to break values down to their simplest forms; for entities especially, this
means breaking them down into their constituent parts.

If you will check the org.hibernate.type.CollectionType package

```<code>    //This solution would allow us to eliminate the owner arg to disassemble(), but
    //what if the collection was null, and then later had elements added? seems unsafe
    //session.getPersistenceContext().getCollectionEntry( (PersistentCollection) value ).getKey();

    final Serializable key = getKeyOfOwner(owner, session);
    if (key==null) {
        return null;
    }
    else {
        return getPersister(session)
                .getKeyType()
                .disassemble( key, session, owner );
    }
</code>```

So you need to implement Serializable interface in your entity

Body:
I have seen many questions asked on @JoinColumn and this concept was clear to me until I came across the following situation.

Let's consider mapping is OneToOne Unidirectional mapping. i have used following annatation in the parent class:
Case 1:-
@JoinColumn(name="test_Id",referencedColumnName="refToPrimaryKey") and  Entity class is not implementing Serializable interface. in this case program is executing without any exception.
Case 2:-
@JoinColumn(name="test_Id",referencedColumnName="refToNonPrimaryKey") and  Entity class is not implementing Serializable interface.

Here program is throwing exception like:

threw exception [java.lang.ClassCastException:
com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable] with root cause
java.lang.ClassCastException: com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable at org.hibernate.type.CollectionType.getKeyOfOwner(CollectionType.java:414)

Can you Guys help me out to know the concept why it is happening?

Body:
Are you using second level caching, As per caused show
cannot be cast to java.io.Serializable at org.hibernate.type.CollectionType.getKeyOfOwner(CollectionType.java:414)

As per hibernate doc, disassemble Return a disassembled representation of the object.  This is the value Hibernate will use in second level caching, so care should be taken to break values down to their simplest forms; for entities especially, this
means breaking them down into their constituent parts.

If you will check the org.hibernate.type.CollectionType package

    //This solution would allow us to eliminate the owner arg to disassemble(), but
    //what if the collection was null, and then later had elements added? seems unsafe
    //session.getPersistenceContext().getCollectionEntry( (PersistentCollection) value ).getKey();

    final Serializable key = getKeyOfOwner(owner, session);
    if (key==null) {
        return null;
    }
    else {
        return getPersister(session)
                .getKeyType()
                .disassemble( key, session, owner );
    }

So you need to implement Serializable interface in your entity


问:
Changes in package.json for Angular 2 to 4 migration
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

```<code>"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}
</code>```

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

```<code>{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}
</code>```

答:
You need not make changes in the package.json file manually you can run this command if you are using windows

```<code>npm cache clean

npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/platform-browser@next @angular/platform-browser-dynamic@next @angular/platform-server@next @angular/router@next @angular/animations@next --save
</code>```

This will help

After you comment

you should update your typescript and also can try changing this in tsconfig.json

```<code>{
    "compilerOptions": {
        "target": "es5",
        "lib": ["es2016", "dom"] //or es6 instead of es2016(es7)
    }
}
</code>```

Body:
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}

Body:
You need not make changes in the package.json file manually you can run this command if you are using windows

npm cache clean

npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/platform-browser@next @angular/platform-browser-dynamic@next @angular/platform-server@next @angular/router@next @angular/animations@next --save

This will help

After you comment

you should update your typescript and also can try changing this in tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["es2016", "dom"] //or es6 instead of es2016(es7)
    }
}


问:
Get connection string from App.config
```<code>var connection = ConnectionFactory.GetConnection(
    ConfigurationManager.ConnectionStrings["Test"]
    .ConnectionString, DataBaseProvider);
</code>```

And this is my App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>
```

But when my project runs this is my error:

Object reference not set to an instance of an object.

答:
I had the same Issue. my solution was built up from two projects. A Class library and a website referencing to the class library project. the problem was that i was trying to access the App.config in my Class library project but the system was searching in Web.config of the website. I put the connection string inside Web.config and ... problem solved!

The main reason was that despite ConfigurationManager was used in another assembly it was searching inside the runnig project .

Title: Get connection string from App.config

Body:
var connection = ConnectionFactory.GetConnection(
    ConfigurationManager.ConnectionStrings["Test"]
    .ConnectionString, DataBaseProvider);

And this is my App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

But when my project runs this is my error:

Object reference not set to an instance of an object.


问:
Run docker build in ubuntu:16.04 docker
I want to build a docker image in docker container.

So, I tried to create a docker-installed ubuntu docker image following https://docs.docker.com/engine/installation/linux/ubuntu/, but failed.

```<code>FROM ubuntu:16.04

RUN apt-get update && \
    apt-get install -y \
        apt-transport-https \
        ca-certificates \
        software-properties-common

RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -

RUN apt-key fingerprint 0EBFCD88

RUN add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

RUN apt-get update && \
    apt-get install -y docker-ce
</code>```

When I run docker images or other commands on the docker image created by above Dockerfile, the error happens.

```<code>Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
</code>```

Is there any way to solve this problem? Thanks.

答:
Besides the affect of AWS environment, the problem you have is caused by that you did not start docker daemon inside your container, as the error message shown.

Here's the steps to show how to make it work manually:

Start and enter a container using the image built from your Dockerfile:

docker run --privileged -it dind /bin/bash

And here is the problem you have:

```<code>root@82d6eab69331:/# docker images
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
</code>```

Start docker daemon inside this container:

root@82d6eab69331:~# /usr/bin/dockerd -H unix:///var/run/docker.sock > dockerd.log 2>&1 &

Check log file to make sure it started correctly, and then try docker images:

root@82d6eab69331:~# docker images
 REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

So you may need to add entrypoint to start docker daemon in your Dockerfile. I test on environment of CentOS 7.2 and docker 1.12. Hope this could be helpful to you :-)

Title: Run docker build in ubuntu:16.04 docker

Body:
I want to build a docker image in docker container.

So, I tried to create a docker-installed ubuntu docker image following https://docs.docker.com/engine/installation/linux/ubuntu/, but failed.

FROM ubuntu:16.04

RUN apt-get update && \
    apt-get install -y \
        apt-transport-https \
        ca-certificates \
        software-properties-common

RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -

RUN apt-key fingerprint 0EBFCD88

RUN add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

RUN apt-get update && \
    apt-get install -y docker-ce

When I run docker images or other commands on the docker image created by above Dockerfile, the error happens.

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Is there any way to solve this problem? Thanks.

Body:
Besides the affect of AWS environment, the problem you have is caused by that you did not start docker daemon inside your container, as the error message shown.

Here's the steps to show how to make it work manually:

Start and enter a container using the image built from your Dockerfile:

docker run --privileged -it dind /bin/bash

And here is the problem you have:

root@82d6eab69331:/# docker images
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Start docker daemon inside this container:

root@82d6eab69331:~# /usr/bin/dockerd -H unix:///var/run/docker.sock > dockerd.log 2>&1 &

Check log file to make sure it started correctly, and then try docker images:

root@82d6eab69331:~# docker images
 REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

So you may need to add entrypoint to start docker daemon in your Dockerfile. I test on environment of CentOS 7.2 and docker 1.12. Hope this could be helpful to you :-)


问:
Unknown plugin specified in .babelrc, attempted to resolve relative to path
So I've started a new react-native project and copied over the .babelrc file from my previous project.  I've installed the necessary plugins but I'm getting the error

Unknown plugin transform-decorators-legacy specified in .babelrc, attempted to resolve relative to "/mypath/project"

I've checked the node_modules in the path and see that the plugin was installed using yarn add.  I'm also getting similar errors with my eslint plugins.  Am I missing something in my project setup to have babel and eslint see the node_modules?

Is it perhaps caused by installing react-native-code-push?  I think it had some errors when I installed codepush where it duplicated the react pod in the pod install - and so I removed it from the podfile.  Is it trying to use a cached code-push js even though I don't have code push implemented in my react js files?

答:
trasnform-decorators-legacy

You have a typo here.


问:
All Ruby tests raising: undefined method `authenticate' for nil:NilClass
Most of my tests are raising the following and I don't understand why. All methods call raise the 'authenticate' error. I've checked the code if there was a method called "authenticate" but there is no such method.

```<code>  1) Admin::CommentsController handling GET to index is successful
     Failure/Error: get :index
     undefined method `authenticate!' for nil:NilClass
     # ./spec/controllers/admin/comments_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

  124) PostsController handling GET for a single post should render show template
     Failure/Error: get :show, :year => '2008', :month => '01', :day => '01', :slug => 'a-post'
     undefined method `authenticate' for nil:NilClass
     # ./app/controllers/application_controller.rb:18:in `set_current_user_for_model'
     # ./spec/controllers/posts_controller_spec.rb:131:in `do_get'
     # ./spec/controllers/posts_controller_spec.rb:140:in `block (3 levels) in <top (required)>'
</code>```

The project can be found over there => https://github.com/agilepandas/enki in case you'd like to run the tests your self.

答:
This question has been answered on Twitter by @MatthewClosson

@jeffehh You need to create a
  spec/support/devise.rb file as
  specified here https://github.com/plataformatec/devise#test-helpers to
  include the devise test helpers #ruby

Thanks once again.

Body:
Most of my tests are raising the following and I don't understand why. All methods call raise the 'authenticate' error. I've checked the code if there was a method called "authenticate" but there is no such method.

  1) Admin::CommentsController handling GET to index is successful
     Failure/Error: get :index
     undefined method `authenticate!' for nil:NilClass
     # ./spec/controllers/admin/comments_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

  124) PostsController handling GET for a single post should render show template
     Failure/Error: get :show, :year => '2008', :month => '01', :day => '01', :slug => 'a-post'
     undefined method `authenticate' for nil:NilClass
     # ./app/controllers/application_controller.rb:18:in `set_current_user_for_model'
     # ./spec/controllers/posts_controller_spec.rb:131:in `do_get'
     # ./spec/controllers/posts_controller_spec.rb:140:in `block (3 levels) in <top (required)>'

The project can be found over there => https://github.com/agilepandas/enki in case you'd like to run the tests your self.


问:
Issue when trying to iterate through textfile lines
I am trying something pretty simple but i have issue I do not understand.
Basically I have a file that is filled with text with this form

```<code>Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
</code>```

What I want to do is write all blocks of 3 lines that have an accuracy above 0.90 in another file.
To navigate through the lines I used the solution proposed here.
My code is the following :

```<code>with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     for line in range(1,int(len(oldfile.readlines()))):
         print(line)
         if line%3==0:
             f=oldfile.readlines()[line-2]
             f=f.split(' ')[3]
             if int(f)>0.90:
                 newfile.write(oldfile.readlines()[line-2])
                 newfile.write(oldfile.readlines()[line-1])
                 newfile.write(oldfile.readlines()[line])
</code>```

Starting here I have 2 issues I do not understand ...
the first one is

f=oldfile.readlines()[line-2] IndexError: list index out of range

That i don't understand as I print the length that is 13599, and my modulo is working so 3-2=1, no negative number of lines

The second issue that I never got before is that when I uncomment the print(len(oldfile.readlines()))line, I have no errors as it prints the value, but then stop without doing nothing. It is like the print is killing the program as it does not enter the for loop....

Thx

答:
You have no reason here to load the whole file in memory. If you later want to process huge files, it could cause useless resource problems. You only need to keep 3 lines:</p>

```<code>with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     oldlines = [None] * 3   # reserve a storage for 3 lines
     for linenum, line in enumerate(oldfile, 1):
         oldlines[linenum%3] = line    # actually store the line
         if linenum%3==0:
             f = oldlines[1]
             f=f.split(' ')[2]
             if float(f)>0.90:
                 newfile.write(oldlines[1])
                 newfile.write(oldlines[2])
                 newfile.write(oldlines[0])
</code>```

Body:
I am trying something pretty simple but i have issue I do not understand.
Basically I have a file that is filled with text with this form

Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================

What I want to do is write all blocks of 3 lines that have an accuracy above 0.90 in another file.
To navigate through the lines I used the solution proposed here.
My code is the following :

with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     for line in range(1,int(len(oldfile.readlines()))):
         print(line)
         if line%3==0:
             f=oldfile.readlines()[line-2]
             f=f.split(' ')[3]
             if int(f)>0.90:
                 newfile.write(oldfile.readlines()[line-2])
                 newfile.write(oldfile.readlines()[line-1])
                 newfile.write(oldfile.readlines()[line])

Starting here I have 2 issues I do not understand ...
the first one is

f=oldfile.readlines()[line-2] IndexError: list index out of range

That i don't understand as I print the length that is 13599, and my modulo is working so 3-2=1, no negative number of lines

The second issue that I never got before is that when I uncomment the print(len(oldfile.readlines()))line, I have no errors as it prints the value, but then stop without doing nothing. It is like the print is killing the program as it does not enter the for loop....

Thx

Body:
You have no reason here to load the whole file in memory. If you later want to process huge files, it could cause useless resource problems. You only need to keep 3 lines:

with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     oldlines = [None] * 3   # reserve a storage for 3 lines
     for linenum, line in enumerate(oldfile, 1):
         oldlines[linenum%3] = line    # actually store the line
         if linenum%3==0:
             f = oldlines[1]
             f=f.split(' ')[2]
             if float(f)>0.90:
                 newfile.write(oldlines[1])
                 newfile.write(oldlines[2])
                 newfile.write(oldlines[0])


问:
Localization fails in Visual Studio
I'm using VS2015 and I'm working on an ASP.NET MVC5 project. In my resources file I have this :

```<code>Name : Kisi_Gösterecek_Kişi
Value : Gösterecek Kişi
</code>```

In my View, I have this :

```<code><th width="45%">@Html.DisplayNameFor(model => model.ContactKisi)</th>
</code>```

As an error, I get this :

Cannot retrieve property 'Name' because localization failed.
  Type 'MyProject.Resources' is not public or does not contain a public static
  string property with the name 'Kisi_Gösterecek_Kiþi'.

I know that this is some kind of localization error. But I don't know how to solve it. Can you tell me how to fix this? Thanks.

答:
You should change Turkish characters in the key of the resource to English characters. Also consider checking out the key naming conventions to prevent further conflicts.

Kisi_Gosterecek_Kisi

Title: Localization fails in Visual Studio

Body:
I'm using VS2015 and I'm working on an ASP.NET MVC5 project. In my resources file I have this :

Name : Kisi_Gösterecek_Kişi
Value : Gösterecek Kişi

In my View, I have this :

@Html.DisplayNameFor(model => model.ContactKisi)

As an error, I get this :

Cannot retrieve property 'Name' because localization failed.
  Type 'MyProject.Resources' is not public or does not contain a public static
  string property with the name 'Kisi_Gösterecek_Kiþi'.

I know that this is some kind of localization error. But I don't know how to solve it. Can you tell me how to fix this? Thanks.


问:
How come I can't access AWS instance using Private DNS Address
I set up an AWS instance in my VPC with a private IP address -- no public IP address.  This is going to be my MongoDB instance and will only be accessed by other servers within the VPC.  I established a successful VPN connection and can SSH using Putty to the instance using the private IP address -  "10.0.0.95".  So far, so good.  I noticed that the private IP address also has a Private DNS - "ip-10-0-0-95.internal".  I tried using the Private DNS to access the instance through the VPN but got this Putty error "Unable to open connection to ip-10-0-0-95.ec2.internal.  Host does not exist".  Clearly, I can use the 10.0.0.95 IP address but was surprised that the private DNS name did not work.  How come? </p>

答:
You should enable the DNS resolution for your VPC, or you won't be able to resolve internal DNS names.

To use private hosted zones, you must set the following Amazon VPC settings to true:

enableDnsHostnames

enableDnsSupport

Steps to enable DNS resolution:

Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.

In the navigation pane, choose Your VPC.

Select the VPC from the list, choose Actions and either Edit DNS Resolution or Edit DNS Hostnames (you should enable them)

In the dialog box that opens, choose Yes, and Save.

For more info: http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-dns.html#vpc-dns-updating


问:
Java: How to get the last word of the dynamic string
I have below string which I need to capture last word.

Below is my code but its not getting the last word.

The string at below location is dynamic and is not static string.

```<code>String secques1 = driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText();

String lastWord = secques1.substring(secques1.lastIndexOf(" ")+1);`
</code>```

答:
I have a suggestion string may contains space in it's trailing:

First: try to trim string trailing (string.trim())

second: print the whole text

and check the leading and trailing spaces then print the last word
I think this will help you.

Body:
I have below string which I need to capture last word.

Below is my code but its not getting the last word.

The string at below location is dynamic and is not static string.

String secques1 = driver.findElement(By.xpath("//*[@class='small-12 medium-4 medium-offset-4 columns']/div/div/div/div[1]/div/div[1]/label")).getText();

String lastWord = secques1.substring(secques1.lastIndexOf(" ")+1);`


问:
How to re-open something after used `JQuery.remove()`?
I used a free template for my app and with this template there is a button to "hide" list like this:

the little x button

And the executed code is the following one:

```<code>$(document).on('click', '.close-link', function () {
   var $BOX_PANEL = $(this).closest('.x_panel');
   $BOX_PANEL.remove();
});
</code>```

Now I'm trying to add a button to re-open this list but here comes the struggle I can't find a way to do that. I checked the documentation of JQuery remove() and there is not JQuery open()...

Do you guy have an idea ?

[EDIT] maybe the HTML would be great so :

```<code><div class="col-md-6 col-sm-12 col-xs-12">
    <div class="x_panel">
        <div class="x_title">
            <h2>Machines</h2>
               <ul class="nav navbar-right panel_toolbox">
                  <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a></li>
                  <li class="dropdwon">
                     <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                     <ul class="dropdown-menu" role="menu"></ul>
                  </li>
                  {{#if isNotHome}}<li><a class="backLocalHostDocker"><i class="fa fa-home"></i></a></li>{{/if}}
                  <li><a class="close-link" id="closeList"><i class="fa fa-close"></i></a></li>
              </ul>
           <div class="clearfix"></div>
         </div>
         <div class="x_content">
             <br />
             <ul class="container"></ul>
         </div>
    </div>
</div>
</code>```

I just cleaned the code to just display the structure

答:
In that case do not remove() which eliminates the element from DOM.

Just use

```<code>$BOX_PANEL.hide();
</code>```

Then whenever you feel like showing it back, use

```<code>$BOX_PANEL.show();
</code>```

Body:
I used a free template for my app and with this template there is a button to "hide" list like this:

the little x button

And the executed code is the following one:

$(document).on('click', '.close-link', function () {
   var $BOX_PANEL = $(this).closest('.x_panel');
   $BOX_PANEL.remove();
});

Now I'm trying to add a button to re-open this list but here comes the struggle I can't find a way to do that. I checked the documentation of JQuery remove() and there is not JQuery open()...

Do you guy have an idea ?

[EDIT] maybe the HTML would be great so :

Machines

                  {{#if isNotHome}}

{{/if}}

I just cleaned the code to just display the structure

Body:
In that case do not remove() which eliminates the element from DOM.

Just use

$BOX_PANEL.hide();

Then whenever you feel like showing it back, use

$BOX_PANEL.show();


问:
VS 2013 - SonarQube Integration error during build
I am getting the following error when I queue my build in VS 2013.

File not found: C:\sonarqube\bin\MSBuild.SonarQube.Runner.exe

The file does exist in the folder. I have mentioned this path in the pre-build script path of the build definition. Screenshots are attached below.

SoarQube version - 5.6.6

Looking for a solution and I would appreciate all you help!

答:
I guess at least one of your build agents does not have this folder, or the build user does not have proper access to it.

So my suggestion is to double check that all of your build agents have this folder:

```<code>C:\sonarqube\bin\MSBuild.SonarQube.Runner.exe
</code>```

and also that the build user has read/execute access on it.

Body:
I guess at least one of your build agents does not have this folder, or the build user does not have proper access to it.

So my suggestion is to double check that all of your build agents have this folder:

C:\sonarqube\bin\MSBuild.SonarQube.Runner.exe

and also that the build user has read/execute access on it.


问:
Calculating how many days between dates, diffrent months
So I'm playing around JavaScript's Date object, and I ran into something I think is a little strange.

I'm trying to figure out how many days there is between 2 given dates, and for that I use the formula below:

```<code>var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-28 & 2017-05-30 it returns 2 days - as it should

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-30 & 2017-06-01 it returns 1 days - supposed to be 2 days

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

If you take 2017-05-30 & 2017-06-01 it returns 3 days - supposed to be 2 days

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 11, 29);
var secondDate = new Date(2017, 12, 01);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
</code>```

答:
I had used 1½ hour trying to figuring out what the problem was - and 10 sec after posting i figure it out.

Problem is, the date object takes:

Jan, as 0

Feb, as 1

...

...

Nov, as 10

Dec, as 11

Body:
So I'm playing around JavaScript's Date object, and I ran into something I think is a little strange.

I'm trying to figure out how many days there is between 2 given dates, and for that I use the formula below:

var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-28 & 2017-05-30 it returns 2 days - as it should

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-30 & 2017-06-01 it returns 1 days - supposed to be 2 days

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 05, 28);
var secondDate = new Date(2017, 05, 30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

If you take 2017-05-30 & 2017-06-01 it returns 3 days - supposed to be 2 days

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017, 11, 29);
var secondDate = new Date(2017, 12, 01);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));


问:
dotnet build fails to manage embedded resources
```<code>>dotnet --info

 Runtime Environment:
  OS Name:     Windows
  OS Version:  10.0.14393
  OS Platform: Windows
  RID:         win10-x64
  Base Path:   C:\Program Files\dotnet\sdk\1.0.0 (tested with 1.0.1 as well)
</code>```

Steps to reproduce:

Create a new class library project (under VS2017, last update)

Add a Foo.resx file (with designer)

Add a Foo.fr.resx file

Go to the project directory

Execute dotnet build

Result :

C:\Program
  Files\dotnet\sdk\1.0.0\Microsoft.Common.CurrentVersion.targets(4072,5):
  error MSB3030: Could not copy the file
  "obj\Debug\fr\ProjectName.resources.dll" because it was not found.
  [C:\Projects\SolutionName\ProjectName\ProjectName.csproj]

I have wasted too much time on that (hacks / researches / git issues digging).
Is that a bug ?

Note that there's no problem using one single file Foo.resx. (But I need multiple cultures)

答:
I had similar problem and I was able to resolve it. I found helpful info on this link: https://github.com/dotnet/cli/issues/6032

As Visual Studio build works ok, it appears that Visual Studio uses different build process then dotnet build.
Firstly, execute msbuild for your solution like:
msbuild ConsoleApp.sln and then run dotnet build.

Body:
>dotnet --info

 Runtime Environment:
  OS Name:     Windows
  OS Version:  10.0.14393
  OS Platform: Windows
  RID:         win10-x64
  Base Path:   C:\Program Files\dotnet\sdk\1.0.0 (tested with 1.0.1 as well)

Steps to reproduce:

Create a new class library project (under VS2017, last update)

Add a Foo.resx file (with designer)

Add a Foo.fr.resx file

Go to the project directory

Execute dotnet build

Result :

C:\Program
  Files\dotnet\sdk\1.0.0\Microsoft.Common.CurrentVersion.targets(4072,5):
  error MSB3030: Could not copy the file
  "obj\Debug\fr\ProjectName.resources.dll" because it was not found.
  [C:\Projects\SolutionName\ProjectName\ProjectName.csproj]

I have wasted too much time on that (hacks / researches / git issues digging).
Is that a bug ?

Note that there's no problem using one single file Foo.resx. (But I need multiple cultures)


问:
How to Group by with Count()
```<code>[OrderNo]   [OrderStatus]
PO-01       Received
PO-01       Pending
PO-01       Received
PO-02       Pending
PO-02       Pending
PO-03       Received
PO-03       Received
</code>```

In a Table a have two Column OrderNo and OrderStatus
I want a Result like.

```<code>[OrderNo]   [OrderStatus]
PO-01       Partially Received
PO-02       Pending
PO-03       Received in Full
</code>```

If All Rows of Particular [OrderNo] is Received then Make its Status 'Received in Full' and if Not make its status 'Partially received' and if Every Row is in Pending Status make its Status 'Pending'

答:
Another way using JOIN:</p>

```<code>    DECLARE @t TABLE
    (ID INT IDENTITY(1,1),OrderNo VARCHAR(20),OrderStatus VARCHAR(20))

    INSERT INTO @t VALUES
    ('PO-01','Received'),
    ('PO-01','Pending'),
    ('PO-01','Received'),
    ('PO-02','Pending'),
    ('PO-02','Pending'),
    ('PO-03','Received'),
    ('PO-03','Received')

    SELECT DISTINCT A.OrderNo,
    CASE WHEN  A.OrderStatus = 'Partially Received' THEN A.OrderStatus
    ELSE B.OrderStatus END AS [OrderStatus]
    FROM
    (
        SELECT
        OrderNo,
        CASE
            WHEN COUNT(DISTINCT OrderStatus) > 1 THEN 'Partially Received'
            ELSE 'Status' END AS [OrderStatus]

        FROM @t
        GROUP BY OrderNo
    ) A
    INNER JOIN @t B ON A.OrderNo = B.OrderNo
</code>```

Title: How to Group by with Count()

Body:
[OrderNo]   [OrderStatus]
PO-01       Received
PO-01       Pending
PO-01       Received
PO-02       Pending
PO-02       Pending
PO-03       Received
PO-03       Received

In a Table a have two Column OrderNo and OrderStatus
I want a Result like.

[OrderNo]   [OrderStatus]
PO-01       Partially Received
PO-02       Pending
PO-03       Received in Full

If All Rows of Particular [OrderNo] is Received then Make its Status 'Received in Full' and if Not make its status 'Partially received' and if Every Row is in Pending Status make its Status 'Pending'

Body:
Another way using JOIN:

    DECLARE @t TABLE
    (ID INT IDENTITY(1,1),OrderNo VARCHAR(20),OrderStatus VARCHAR(20))

    INSERT INTO @t VALUES
    ('PO-01','Received'),
    ('PO-01','Pending'),
    ('PO-01','Received'),
    ('PO-02','Pending'),
    ('PO-02','Pending'),
    ('PO-03','Received'),
    ('PO-03','Received')

    SELECT DISTINCT A.OrderNo,
    CASE WHEN  A.OrderStatus = 'Partially Received' THEN A.OrderStatus
    ELSE B.OrderStatus END AS [OrderStatus]
    FROM
    (
        SELECT
        OrderNo,
        CASE
            WHEN COUNT(DISTINCT OrderStatus) > 1 THEN 'Partially Received'
            ELSE 'Status' END AS [OrderStatus]

        FROM @t
        GROUP BY OrderNo
    ) A
    INNER JOIN @t B ON A.OrderNo = B.OrderNo


问:
TypeScript Global variables not changed in Observable subscribe method
I am trying to use rxJS to handle responses from an http request in angular2

this is the code:

```<code>isUserConfirmed(): boolean {
    let result: boolean = false;
    this.authService.isUserConfirmed().subscribe(
      retrievedData => {
        //if no errors from the server
        if (retrievedData.success) {
          //if the confirmed flag is true
          if (retrievedData.payload){
            result = true;
            console.log("i"+result);
          } else {
            result = false;

          }
        } else {
          this.showError(retrievedData.message);
        }
      },
      error => {
        this.showError(error);
      });
      console.log("o"+result);
      return result;
  },

showError(error) {
  //...
}
</code>```

EDIT

When I run this, I get this output:

ofalse

itrue

This means that the result value is set to true inside suscribe method, but  that does not change returned result value.

How can I manage to return the value set from inside the subscribe block?

答:
Its because your console statement outside the subscribe block will execute first. So your first console.log() will display false. Following your console.log() inside the subscribe block will be executed second. So it will result to true if success.

If Observable returns true, result should be :

```<code>false
true
</code>```

You can return value in this way

```<code>isUserConfirmed(): boolean {
    let result: boolean = false;
    return this.authService.isUserConfirmed().subscribe(
      retrievedData => {
        //if no errors from the server
        if (retrievedData.success) {
          //if the confirmed flag is true
          if (retrievedData.payload){
            result = true;
            console.log("i"+result);
          }
        } else {
          this.showError(retrievedData.message);
        }
        return result
      },
      error => {
        this.showError(error);
      });
  }
</code>```

Body:
I am trying to use rxJS to handle responses from an http request in angular2

this is the code:

isUserConfirmed(): boolean {
    let result: boolean = false;
    this.authService.isUserConfirmed().subscribe(
      retrievedData => {
        //if no errors from the server
        if (retrievedData.success) {
          //if the confirmed flag is true
          if (retrievedData.payload){
            result = true;
            console.log("i"+result);
          } else {
            result = false;

          }
        } else {
          this.showError(retrievedData.message);
        }
      },
      error => {
        this.showError(error);
      });
      console.log("o"+result);
      return result;
  },

showError(error) {
  //...
}

EDIT

When I run this, I get this output:

ofalse

itrue

This means that the result value is set to true inside suscribe method, but  that does not change returned result value.

How can I manage to return the value set from inside the subscribe block?

Body:
Its because your console statement outside the subscribe block will execute first. So your first console.log() will display false. Following your console.log() inside the subscribe block will be executed second. So it will result to true if success.

If Observable returns true, result should be :

false
true

You can return value in this way

isUserConfirmed(): boolean {
    let result: boolean = false;
    return this.authService.isUserConfirmed().subscribe(
      retrievedData => {
        //if no errors from the server
        if (retrievedData.success) {
          //if the confirmed flag is true
          if (retrievedData.payload){
            result = true;
            console.log("i"+result);
          }
        } else {
          this.showError(retrievedData.message);
        }
        return result
      },
      error => {
        this.showError(error);
      });
  }