问:
Complete remaining field of form upon entering data in one field of form PHP AJAX SQL
Javascript Code:
Here when the value is entered in ticket number field, I want to call ajax and retrieve data from fill.php file.

```<code>        <script type="text/javascript">
          $("#tktNum").change(function() {
            var ticket = $('#tktNum').val();
        alert(ticket);
            $.ajax({
              type: "POST",
              dataType: 'json',
              data:"ticket="+ticket,
              url: "fill.php",
                 success: function(json) {
                 $('#bookNum').val(json.booking);
                 $("#email").val(json.email);
                 $("#mobile").val(json.mobile);
                 $("#fName").val(json.fname);
                 $("#lName").val(json.lname);
                 $("#mName").val(json.mname);
                 $("#airline").val(json.airline);
               },
               error : function(){
                 alert('Some error occurred!');
               }
             });
          });
        </script>

    FORM: This is the form where data should appear dynamically upon entering the value in ticket number field. The field with id tktNum is where the key change option will work.

    <div class="form-group col-lg-6">
                    <input name="bookNum" value="" id="bookNum"   class="form-control" aria-required="true" aria-invalid="false" required placeholder="Booking Number/PNR*" type="text">
                  </div>

                  <div class="form-group col-lg-6">
                    <input name="tktNum" id="tktNum" value="" class="form-control" aria-required="true" aria-invalid="false" required placeholder="Ticket Number*" type="text">
                  </div>

                  <div class="form-group col-lg-6">
                    <input name="fName" id="fName" value="" class="form-control" aria-required="true" aria-invalid="false" style="text-transform: capitalize;" required placeholder="First Name*" type="text">
                  </div>

                  <div class="form-group col-lg-6">
                    <input name="mName" id="mName" value="" class="form-control" aria-required="true" aria-invalid="false" style="text-transform: capitalize;" placeholder="Middle Name (if applicable)" type="text">
                  </div>

                  <div class="form-group col-lg-6">
                    <input name="lName" id="lName" value="" class="form-control validates-as-required" aria-required="true"style="text-transform: capitalize;" required aria-invalid="false" placeholder="Last Name*" type="text">
                  </div>

                  <div class="form-group col-lg-6">
                    <input name="mobile" id="mobile" value="" class="form-control validates-as-required" aria-required="true" required aria-invalid="false" placeholder="Mobile*" type="tel">
                  </div>

                  <div class="form-group col-lg-6">
                    <input name="email" value="" class="form-control validates-as-required" aria-required="true" required aria-invalid="false" placeholder="Email*" type="email">
                  </div>

                  <div class="form-group col-lg-6">
                    <input name="airline" id="airline" value="" class="form-control validates-as-required" aria-required="true" required aria-invalid="false" placeholder="Airline*" type="text">
                  </div>
</code>```

FILL.PHP
//Connection is working fine
The connection part is working fine.

```<code>$server = array('127.0.0.1','::1');
if(!in_array($_SERVER['REMOTE_ADDR'], $server)){
$conn = new mysqli("***","***","******","***_com_au");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$selected = mysqli_select_db($conn,"***_com_au")
  or die("Could not select everestpnr");
}
else
{
  $conn = new mysqli("localhost","root","","everestpnr");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$selected = mysqli_select_db($conn,"everestpnr")
  or die("Could not select everestpnr");
}
 $results="SELECT * FROM `booking` WHERE `ticket`='".$_POST['ticket']."'";
        $result = $conn->query($results);
        $row = mysql_fetch_assoc($query);

                // send the data encoded as JSON
                $json = array('booking' => $row['booking'],
                            'fname' => $row['fName'],
                            'mname' => $row['mname'],
                            'lname' => $row['lname'],
                            'mobile' => $row['mobile'],
                            'email' => $row['email'],
                            'airplane' => $row['airplane']);
                echo json_encode($json );

        exit;
        }
</code>```

The fields are not dynamically updated upon key change in the ticket number field of the form. I need the form to dynamically pull data from database and fill in all inputs upon entering the ticket number in ticket number field of the form.

答:
If you want to change that problem through java-script you should
use this code

```<code>    <script type="text/javascript">
    $("#tktNum").change(function() {
        var ticket = $('#tktNum').val();
        //alert(ticket);
        $.ajax({
            type: "POST",
            dataType: 'json',
            data: "ticket=" + ticket,
            url: "fill.php",
            success: function(response) {
                json = JSON.parse(response);
                $('#bookNum').val(json.booking);
                $("#email").val(json.email);
                $("#mobile").val(json.mobile);
                $("#fName").val(json.fname);
                $("#lName").val(json.lname);
                $("#mName").val(json.mname);
                $("#airline").val(json.airline);
            },
            error: function() {
                alert('Some error occurred!');
            }
        });
    });
</script>
</code>```

If you want to fix the problem you can use this,
Please mention header type header('Content-type: application/json'); that says response in the json format

```<code><?php
header('Content-type: application/json');

//Connection is working fine
//The connection part is working fine.

    $server = array('127.0.0.1','::1');
    if(!in_array($_SERVER['REMOTE_ADDR'], $server)){
    $conn = new mysqli("***","***","******","***_com_au");
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $selected = mysqli_select_db($conn,"***_com_au")
      or die("Could not select everestpnr");
    }
    else
    {
      $conn = new mysqli("localhost","root","","everestpnr");
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $selected = mysqli_select_db($conn,"everestpnr")
      or die("Could not select everestpnr");
    }
     $results="SELECT * FROM `booking` WHERE `ticket`='".$_POST['ticket']."'";
            $result = $conn->query($results);
            $row = mysql_fetch_assoc($result);

                    // send the data encoded as JSON
                    $json = array('booking' => $row['booking'],
                                'fname' => $row['fName'],
                                'mname' => $row['mname'],
                                'lname' => $row['lname'],
                                'mobile' => $row['mobile'],
                                'email' => $row['email'],
                                'airplane' => $row['airplane']);
                    echo json_encode($json );

            exit;
</code>```

Body:
Javascript Code:
Here when the value is entered in ticket number field, I want to call ajax and retrieve data from fill.php file.

    FORM: This is the form where data should appear dynamically upon entering the value in ticket number field. The field with id tktNum is where the key change option will work.

                    <input name="bookNum" value="" id="bookNum"   class="form-control" aria-required="true" aria-invalid="false" required placeholder="Booking Number/PNR*" type="text">

                    <input name="tktNum" id="tktNum" value="" class="form-control" aria-required="true" aria-invalid="false" required placeholder="Ticket Number*" type="text">

                    <input name="fName" id="fName" value="" class="form-control" aria-required="true" aria-invalid="false" style="text-transform: capitalize;" required placeholder="First Name*" type="text">

                    <input name="mName" id="mName" value="" class="form-control" aria-required="true" aria-invalid="false" style="text-transform: capitalize;" placeholder="Middle Name (if applicable)" type="text">

                    <input name="lName" id="lName" value="" class="form-control validates-as-required" aria-required="true"style="text-transform: capitalize;" required aria-invalid="false" placeholder="Last Name*" type="text">

                    <input name="mobile" id="mobile" value="" class="form-control validates-as-required" aria-required="true" required aria-invalid="false" placeholder="Mobile*" type="tel">

                    <input name="email" value="" class="form-control validates-as-required" aria-required="true" required aria-invalid="false" placeholder="Email*" type="email">

                    <input name="airline" id="airline" value="" class="form-control validates-as-required" aria-required="true" required aria-invalid="false" placeholder="Airline*" type="text">

FILL.PHP
//Connection is working fine
The connection part is working fine.

$server = array('127.0.0.1','::1');
if(!in_array($_SERVER['REMOTE_ADDR'], $server)){
$conn = new mysqli("***","***","******","***_com_au");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$selected = mysqli_select_db($conn,"***_com_au")
  or die("Could not select everestpnr");
}
else
{
  $conn = new mysqli("localhost","root","","everestpnr");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$selected = mysqli_select_db($conn,"everestpnr")
  or die("Could not select everestpnr");
}
 $results="SELECT * FROM `booking` WHERE `ticket`='".$_POST['ticket']."'";
        $result = $conn->query($results);
        $row = mysql_fetch_assoc($query);

                // send the data encoded as JSON
                $json = array('booking' => $row['booking'],
                            'fname' => $row['fName'],
                            'mname' => $row['mname'],
                            'lname' => $row['lname'],
                            'mobile' => $row['mobile'],
                            'email' => $row['email'],
                            'airplane' => $row['airplane']);
                echo json_encode($json );

        exit;
        }

The fields are not dynamically updated upon key change in the ticket number field of the form. I need the form to dynamically pull data from database and fill in all inputs upon entering the ticket number in ticket number field of the form.

Body:
If you want to change that problem through java-script you should
use this code

    <script type="text/javascript">
    $("#tktNum").change(function() {
        var ticket = $('#tktNum').val();
        //alert(ticket);
        $.ajax({
            type: "POST",
            dataType: 'json',
            data: "ticket=" + ticket,
            url: "fill.php",
            success: function(response) {
                json = JSON.parse(response);
                $('#bookNum').val(json.booking);
                $("#email").val(json.email);
                $("#mobile").val(json.mobile);
                $("#fName").val(json.fname);
                $("#lName").val(json.lname);
                $("#mName").val(json.mname);
                $("#airline").val(json.airline);
            },
            error: function() {
                alert('Some error occurred!');
            }
        });
    });
</script>

If you want to fix the problem you can use this,
Please mention header type header('Content-type: application/json'); that says response in the json format

<?php
header('Content-type: application/json');

//Connection is working fine
//The connection part is working fine.

    $server = array('127.0.0.1','::1');
    if(!in_array($_SERVER['REMOTE_ADDR'], $server)){
    $conn = new mysqli("***","***","******","***_com_au");
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $selected = mysqli_select_db($conn,"***_com_au")
      or die("Could not select everestpnr");
    }
    else
    {
      $conn = new mysqli("localhost","root","","everestpnr");
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $selected = mysqli_select_db($conn,"everestpnr")
      or die("Could not select everestpnr");
    }
     $results="SELECT * FROM `booking` WHERE `ticket`='".$_POST['ticket']."'";
            $result = $conn->query($results);
            $row = mysql_fetch_assoc($result);

                    // send the data encoded as JSON
                    $json = array('booking' => $row['booking'],
                                'fname' => $row['fName'],
                                'mname' => $row['mname'],
                                'lname' => $row['lname'],
                                'mobile' => $row['mobile'],
                                'email' => $row['email'],
                                'airplane' => $row['airplane']);
                    echo json_encode($json );

            exit;


来源: stackexchange

问:
Laravel sluggable
I am using this package for slugs in my Laravel 5.5 app. I was upgrading from Laravel 4.2 and I followed upgrade instructions, so now I have this in my model:

```<code>public function sluggable()
{
    return [
        'slug' => [
            'source' => ['id', 'title'],
            'separator'  => '-',
        ]
    ];
}
</code>```

but my models don't read id at all in the slug when creating.

Before when I'd save a model, I would have 123456-model, and now I am getting just model without prepended ID.

Does anyone know what the issue may be?

答:
I have resolved the issue by setting the slug to null and then saving the model (only after the model was already in the DB). </p>

```<code>$model = new Model(...);
...
$model->save(); // <-- initial DB insert so that model has ID

// resluggify
$model->slug = null;
$model->save();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel sluggable

Body:
I am using this package for slugs in my Laravel 5.5 app. I was upgrading from Laravel 4.2 and I followed upgrade instructions, so now I have this in my model:

public function sluggable()
{
    return [
        'slug' => [
            'source' => ['id', 'title'],
            'separator'  => '-',
        ]
    ];
}

but my models don't read id at all in the slug when creating.

Before when I'd save a model, I would have 123456-model, and now I am getting just model without prepended ID.

Does anyone know what the issue may be?

Body:
I have resolved the issue by setting the slug to null and then saving the model (only after the model was already in the DB).

$model = new Model(...);
...
$model->save(); // <-- initial DB insert so that model has ID

// resluggify
$model->slug = null;
$model->save();


问:
How to add Marshmallow permission in my code to share a location?
This code run on 4.4.2  when i run this on Marshmallow crash not shared location.

```<code>shar_btn = (Button) findViewById(R.id.shrbtn);

    shar_btn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        link = formatLocation(getLocation(), getResources().getStringArray(R.array.link_templates)[0]);
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_SEND);
                        intent.putExtra(Intent.EXTRA_TEXT, link);
                        intent.setType("text/plain");
                        startActivity(Intent.createChooser(intent, getString(R.string.share_location_via)));
                    }

                });
      }
</code>```

答:
I think it will help you Ask for permission at runtime</p>

```<code>if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
        if (ActivityCompat.checkSelfPermission(AboutProduct.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);

            return;
        }
// write your code here
link = formatLocation(getLocation(), getResources().getStringArray(R.array.link_templates)[0]);
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_TEXT, link);
                    intent.setType("text/plain");
                    startActivity(Intent.createChooser(intent, getString(R.string.share_location_via)));

    }
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

}
</code>```

Body:
This code run on 4.4.2  when i run this on Marshmallow crash not shared location.

shar_btn = (Button) findViewById(R.id.shrbtn);

    shar_btn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        link = formatLocation(getLocation(), getResources().getStringArray(R.array.link_templates)[0]);
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_SEND);
                        intent.putExtra(Intent.EXTRA_TEXT, link);
                        intent.setType("text/plain");
                        startActivity(Intent.createChooser(intent, getString(R.string.share_location_via)));
                    }

                });
      }

Body:
I think it will help you Ask for permission at runtime

if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
        if (ActivityCompat.checkSelfPermission(AboutProduct.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);

            return;
        }
// write your code here
link = formatLocation(getLocation(), getResources().getStringArray(R.array.link_templates)[0]);
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_TEXT, link);
                    intent.setType("text/plain");
                    startActivity(Intent.createChooser(intent, getString(R.string.share_location_via)));

    }
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

}


问:
Detect the content has been inserted into UIcollectionview
```<code>let collectionView = UICollectionView(frame: containerView.frame ,collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
self.collectionView?.contentSize.width
</code>```

I found that it cannot find the content size immediately after init the collection view.

How can i detect the content has been inserted into uicollectionview?

Or alternatively, how can i insert the content immediately?

答:
You can use performBatchUpdates (Apple docs) to get notified when the data is loaded and showed

```<code>func performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil)
</code>```

Animates multiple insert, delete, reload, and move operations as a group

So your actual code will look something like this:

```<code>let collectionView = UICollectionView(frame: containerView.frame ,collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.reloadData()
collectionView.performBatchUpdates(nil, completion: { (successFinish) in
     self.collectionView?.contentSize.width
})
</code>```

Body:
let collectionView = UICollectionView(frame: containerView.frame ,collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
self.collectionView?.contentSize.width

I found that it cannot find the content size immediately after init the collection view.

How can i detect the content has been inserted into uicollectionview?

Or alternatively, how can i insert the content immediately?

Body:
You can use performBatchUpdates (Apple docs) to get notified when the data is loaded and showed

func performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil)

Animates multiple insert, delete, reload, and move operations as a group

So your actual code will look something like this:

let collectionView = UICollectionView(frame: containerView.frame ,collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.reloadData()
collectionView.performBatchUpdates(nil, completion: { (successFinish) in
     self.collectionView?.contentSize.width
})


问:
Matplotlib, avoid update mouse cursor when draw
When a plot is updated with the set_data and draw method, the mouse cursor change few milliseconds from an arrow to a circle. Is it possible to avoid this? Because I update my plot 10 times per second so it is very ugly to see my mouse cursor change so quickly.

I am using Python 3.6, PyQt5, and matplotlib 2.1. Thank you in advance ;)

答:
I found a solution : use QApplication.restoreOverrideCursor() when I leave the axe and QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor)) when I enter in it. Something like this so:

```<code>self.figure.canvas.mpl_connect("axes_enter_event", self.figureEntree)
self.figure.canvas.mpl_connect("axes_leave_event", self.figureSortie)
def figureSortie(self, event):
   QApplication.restoreOverrideCursor()
def figureEntree(self, event):
   QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))
</code>```

And it is possible to adapt the figureEntree function if you have a toolbar (change the cursor along the tool active => variables which change when you select a tool).

Body:
I found a solution : use QApplication.restoreOverrideCursor() when I leave the axe and QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor)) when I enter in it. Something like this so:

self.figure.canvas.mpl_connect("axes_enter_event", self.figureEntree)
self.figure.canvas.mpl_connect("axes_leave_event", self.figureSortie)
def figureSortie(self, event):
   QApplication.restoreOverrideCursor()
def figureEntree(self, event):
   QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))

And it is possible to adapt the figureEntree function if you have a toolbar (change the cursor along the tool active => variables which change when you select a tool).


问:
How to clear the cache of HttpWebRequest
I am developing against a proprietary library and I'm experiencing some issues with the cache of the HttpWebRequest. The library is using code equivalent to the one below to make the requests:

```<code>var request = WebRequest.Create("http://example.com/") as HttpWebRequest;

request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);
</code>```

The external resource doesn't disallow caching although each response differs. Thus I am ending up getting the same response each time.

Is there any way to clear the contents of the HttpWebRequest cache? The right solution would be to fix the external source or perhaps change the cache policy, but neither is possible - hence the question.

Clearing the cache could have various impacts, so preferably the solution would be to invalidate the cache on a per resource basis.

答:
Add the following line to clear the cache as and when the Webclient fetches the data:</p>

```<code>Webclient.Headers.Add(HttpRequestHeader.CacheControl, "no-cache")
</code>```

OwnerDisplayName: troethom

Body:
I am developing against a proprietary library and I'm experiencing some issues with the cache of the HttpWebRequest. The library is using code equivalent to the one below to make the requests:

var request = WebRequest.Create("http://example.com/") as HttpWebRequest;

request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);

The external resource doesn't disallow caching although each response differs. Thus I am ending up getting the same response each time.

Is there any way to clear the contents of the HttpWebRequest cache? The right solution would be to fix the external source or perhaps change the cache policy, but neither is possible - hence the question.

Clearing the cache could have various impacts, so preferably the solution would be to invalidate the cache on a per resource basis.

LastEditorDisplayName: troethom

Body:
Add the following line to clear the cache as and when the Webclient fetches the data:

Webclient.Headers.Add(HttpRequestHeader.CacheControl, "no-cache")


问:
Sails v0.10.x doesn't respect connection config in production.js when in production mode
What is the correct way to set a db connection in Sails v.0.10.x for production use? I expected Sails to use the connection I referred to in production.js when I start my app in production mode (environment), but it doesn't. It seems to always always use the default connection - 'localDiskDb'.

However, when I start sails in development mode (environment), it does use the connection specified in config/development.js, as I would have expected.

UPDATED

Note: I was mistaken when I wrote the location of production.js. It was in /config/env/production.js just like sgress454 said it should be. Actually, this file was created by the generator and put in the right place and I didn't change that.

config/env/production.js looks like this:

```<code>// config/env/production.js

module.exports = {
    connection: 'mongo_production'
};
</code>```

config/models.js looks like this:

```<code>// config/models.js

module.exports.models = {
    // connection: 'localDiskDb'
};
</code>```

config/connections.js looks like this:

```<code>// config/connections.js

module.exports.connections = {
    mongo_development: {
        adapter: 'sails-mongo',
        host: 'localhost',
        port: 27017,
        user: '',
        password: '',
        database: 'my_local_db'
    },

    mongo_production: {
        adapter: 'sails-mongo',
        url: 'mongodb://me:mypw@foobar.mongohq.com:10052/my_production_db'
    }
};
</code>```

答:
In sails version 0.12 there will be two env files under config/env folder.
So we can write mode specific (production/development) configuration in those two files.

In order to run our sails app in specific mode, we must follow the below steps:

Step 1)
In config/local.js file

```<code>module.exports = {
   // port: process.env.PORT || 1337,   // comment this line if you want to set the different ports for different modes
   environment: process.env.NODE_ENV || 'development'
};
</code>```

Step 2) In env/developement.js file

Write the development specific configurations.

```<code>module.exports = {
  port: 8080, // will change from default port 1337 to 8080
  models: {
      connection: 'developement_db',
      migrate: 'alter'
  }
};
</code>```

Step 3) In env/production.js file

Write the production specific configurations.

```<code>module.exports = {
  port: 9090, // will change from default port 1337 to 9090
  models: {
      connection: 'production_db',
      migrate: 'safe'
  }
};
</code>```

Step 4) To run sails app in specific mode,

To run in production mode

$ NODE_ENV=production npm start

Sails will be running on port 9090

To run in developement mode

$ NODE_ENV=developement npm start

Sails will be running on port 8080

Body:
What is the correct way to set a db connection in Sails v.0.10.x for production use? I expected Sails to use the connection I referred to in production.js when I start my app in production mode (environment), but it doesn't. It seems to always always use the default connection - 'localDiskDb'.

However, when I start sails in development mode (environment), it does use the connection specified in config/development.js, as I would have expected.

UPDATED

Note: I was mistaken when I wrote the location of production.js. It was in /config/env/production.js just like sgress454 said it should be. Actually, this file was created by the generator and put in the right place and I didn't change that.

config/env/production.js looks like this:

// config/env/production.js

module.exports = {
    connection: 'mongo_production'
};

config/models.js looks like this:

// config/models.js

module.exports.models = {
    // connection: 'localDiskDb'
};

config/connections.js looks like this:

// config/connections.js

module.exports.connections = {
    mongo_development: {
        adapter: 'sails-mongo',
        host: 'localhost',
        port: 27017,
        user: '',
        password: '',
        database: 'my_local_db'
    },

    mongo_production: {
        adapter: 'sails-mongo',
        url: 'mongodb://me:mypw@foobar.mongohq.com:10052/my_production_db'
    }
};

Body:
In sails version 0.12 there will be two env files under config/env folder.
So we can write mode specific (production/development) configuration in those two files.

In order to run our sails app in specific mode, we must follow the below steps:

Step 1)
In config/local.js file

module.exports = {
   // port: process.env.PORT || 1337,   // comment this line if you want to set the different ports for different modes
   environment: process.env.NODE_ENV || 'development'
};

Step 2) In env/developement.js file

Write the development specific configurations.

module.exports = {
  port: 8080, // will change from default port 1337 to 8080
  models: {
      connection: 'developement_db',
      migrate: 'alter'
  }
};

Step 3) In env/production.js file

Write the production specific configurations.

module.exports = {
  port: 9090, // will change from default port 1337 to 9090
  models: {
      connection: 'production_db',
      migrate: 'safe'
  }
};

Step 4) To run sails app in specific mode,

To run in production mode

$ NODE_ENV=production npm start

Sails will be running on port 9090

To run in developement mode

$ NODE_ENV=developement npm start

Sails will be running on port 8080


问:
Opensource Nuget packages to open and read Excel files in ASP.NET MVC
Any Opensource Nuget packages available to open and read Excel files in ASP.NET MVC?</p>

答: EPPlus A library to manage Excel spreadsheets, using OOXML.</p>


问:
Python: trying to check for a valid phone number
I am trying to write a program that accepts a phone number in the format XXX-XXX-XXXX and translates any letters in the entry to their corresponding numbers.

Now I have this, and it will allow you to reenter the correct number if its not correct to start, but then it translates the original number entered. how do i fix this?

```<code>def main():
    phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
    validNumber(phone_number)
    translateNumber(phone_number)

def validNumber(phone_number):
for i,c in enumerate(phone_number):
    if i in [3,7]:
        if c != '-':
            phone_number=input('Please enter a valid phone number: ')
        return phone_number
    elif not c.isalnum():
        phone_number=input('Please enter a valid phone number: ')
        return phone_number
return phone_number

def translateNumber(phone_number):
    s=""
    for char in phone_number:
        if char is '1':
            x1='1'
            s= s + x1
        elif char is '-':
            x2='-'
            s= s + x2
        elif char in 'ABCabc':
            x3='2'
            s= s + x3
        elif char in 'DEFdef':
            x4='3'
            s= s + x4
        elif char in 'GHIghi':
            x5='4'
            s= s + x5
        elif char in 'JKLjkl':
            x6='5'
            s= s + x6
        elif char in 'MNOmno':
            x7='6'
            s= s + x7
        elif char in 'PQRSpqrs':
            x8='7'
            s= s + x8
        elif char in 'TUVtuv':
            x9='8'
            s= s + x9
        elif char in 'WXYZwxyz':
            x10='9'
            s= s + x10
    print(s)
</code>```

答:
you can go for:-</p>

```<code>def contact_validate(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

>>> print contact_validate("+12345")
True
>>> print contact_validate("75.0")
False
>>> print contact_validate("hello")
False
</code>```

Body:
I am trying to write a program that accepts a phone number in the format XXX-XXX-XXXX and translates any letters in the entry to their corresponding numbers.

Now I have this, and it will allow you to reenter the correct number if its not correct to start, but then it translates the original number entered. how do i fix this?

def main():
    phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
    validNumber(phone_number)
    translateNumber(phone_number)

def validNumber(phone_number):
for i,c in enumerate(phone_number):
    if i in [3,7]:
        if c != '-':
            phone_number=input('Please enter a valid phone number: ')
        return phone_number
    elif not c.isalnum():
        phone_number=input('Please enter a valid phone number: ')
        return phone_number
return phone_number

def translateNumber(phone_number):
    s=""
    for char in phone_number:
        if char is '1':
            x1='1'
            s= s + x1
        elif char is '-':
            x2='-'
            s= s + x2
        elif char in 'ABCabc':
            x3='2'
            s= s + x3
        elif char in 'DEFdef':
            x4='3'
            s= s + x4
        elif char in 'GHIghi':
            x5='4'
            s= s + x5
        elif char in 'JKLjkl':
            x6='5'
            s= s + x6
        elif char in 'MNOmno':
            x7='6'
            s= s + x7
        elif char in 'PQRSpqrs':
            x8='7'
            s= s + x8
        elif char in 'TUVtuv':
            x9='8'
            s= s + x9
        elif char in 'WXYZwxyz':
            x10='9'
            s= s + x10
    print(s)

Body:
you can go for:-

def contact_validate(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

>>> print contact_validate("+12345")
True
>>> print contact_validate("75.0")
False
>>> print contact_validate("hello")
False


问:
UserName or guid UserID?
When saving data in different sql tables, is it best to use the GUID userID or simply use the username? is there a performance difference when using guid?</p>

答:
Use the guid.  It is the system internal identifier for your users.  This then allows the ability to change usernames if people wish.

This then fits nicely with the concept of an internal ID that means something to your system, versus the external ID that means something to your users.

OwnerDisplayName: zsharp

ContentLicense: CC BY-SA 2.5

Title: UserName or guid UserID?

OwnerDisplayName: Neil Barnwell


问:
Object Mapper result window shows no objects although 13 items were found
I installed the Db4o VS plugin and connected to a local source.
When I right-click my class in the db4o browser window and choose "Show all objects" the rsult window pops up with the text "No. of Objects Retrieved: 13" but none are shown.

Creating and running a custom query gives the same result.
Any ideas?

答:
Which Version are you using? The object manager which is shipped with 7.12? Or the one with the 8.0 betas?

Maybe adding the assemblies with your class-model helps: Goto "Tools" -> "Object Manager Enterprise" -> "Options"->"Assembly Search Path..." and add your assemblies. However the OME will lock the assemblies, so maybe better use a copy.

Another question: Are you using any type-handler? I thing currently the OME cannot deal with database which were created using custom typehandlers.


问:
How to readlines without having the \n at the end? (python)
As I was finishing off a game I made, I made a save button that saves to a file. When the game opens, it will then read the file and save those lines as variables. I do so, but then I see that it needs to be an integer, so I use int(). But then it does not work, because the variable is "0\n" instead of "0". I have checked many other questions, but they do not ask or answer the same question.

So I am wondering, is there a way to readlines() without the \n at the end? Or is there a way that I can backspace the variable automatically? Here is my code:

```<code>import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---
def eggvalue_change():
    global eggvalue, eggvalueupgrade, money, eggz
    if money > int(round(eggvalueupgrade)):
        eggz -= eggvalueupgrade / eggvalue
        eggvalue+=0.2
        eggvalueupgrade += int(round(eggvalueupgrade + (eggvalueupgrade / 7)))
def moar_eggz():
    global eggzps, chookz
    chookz += 1
def saving():
    savedfile.write(money)
    savedfile.write(eggvalueupgrade)
    savedfile.write(eggzps)
    savedfile.write(chookz)
    savedfile.write(eggvalue)
    savedfile.write(eggz)
def main_loop():
    global eggz, eggzps, money
    eggzps = chookz / 100.0
    money = eggz * eggvalue

    try:
        openbutton2.config( text="Egg Value: " + str(eggvalue) + " --> " + str(eggvalue+0.2) + " ($" + str(eggvalueupgrade) + ")", command=eggvalue_change)
        label2.config(text="Money: $" + str(int(round(money))), font=("Terminal", 50), borderwidth=5, relief="ridge", bg="black", foreground="white",pady=10, padx=498)
        if eggzps >= 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(int(round(eggzps)))+" | Egg Value: $" + str(eggvalue) + " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        elif eggzps < 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(eggzps)+" | Egg Value: $" + str(eggvalue)+ " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        if money < int(round(eggvalueupgrade)):
            openbutton2.config(fg="gray")
        elif money > int(round(eggvalueupgrade)):
            openbutton2.config(fg="white")
    except Exception as e:
        print(e) # display exception to see problem
    root.after(20, main_loop)
def update_eggz():
    global eggz
    try:
        eggz += eggzps
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 1000ms
    root.after(1000, update_eggz)

# --- main ---

root = tk.Tk()
root.title("Chicken Clicker")

savedfile = open("savedata\\mainsave.txt", "a+")
savedlines = savedfile.readlines()
print savedlines

if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue

eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])

savedfile.close()

# empty labels - `update_labels` will add text

label2 = tk.Label(root)
label1 = tk.Label(root)

label2.pack()
label1.pack()

chickencnv = Image.open("img\\1.png")
chicken = ImageTk.PhotoImage(chickencnv)
openbutton3 =tk.Button(root, bg="black", fg="white", font=("Terminal", 13), command=saving)
openbutton2= tk.Button(root, bg="black", fg="gray", font=("Terminal", 15))
openbutton1= tk.Button(root, image=chicken, width=500, height=500, command=moar_eggz, bg="black")

openbutton1.pack()
openbutton2.pack()
openbutton3.pack()

# run it first time at once
update_eggz()
main_loop()

root.mainloop()
</code>```

If there is no answer, I am fine with you commenting or answering that.

答:
```<code>In [17]: fff = open('/somefile', 'r')

In [18]: ss = fff.readlines()

In [19]: ss
Out[19]: ['qqq\n', 'www\n', 'aaa\n']

In [20]: ss = [ww.strip('\n') for ww in ss]

In [21]: ss
Out[21]: ['qqq', 'www', 'aaa']
</code>```

Body:
As I was finishing off a game I made, I made a save button that saves to a file. When the game opens, it will then read the file and save those lines as variables. I do so, but then I see that it needs to be an integer, so I use int(). But then it does not work, because the variable is "0\n" instead of "0". I have checked many other questions, but they do not ask or answer the same question.

So I am wondering, is there a way to readlines() without the \n at the end? Or is there a way that I can backspace the variable automatically? Here is my code:

import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---
def eggvalue_change():
    global eggvalue, eggvalueupgrade, money, eggz
    if money > int(round(eggvalueupgrade)):
        eggz -= eggvalueupgrade / eggvalue
        eggvalue+=0.2
        eggvalueupgrade += int(round(eggvalueupgrade + (eggvalueupgrade / 7)))
def moar_eggz():
    global eggzps, chookz
    chookz += 1
def saving():
    savedfile.write(money)
    savedfile.write(eggvalueupgrade)
    savedfile.write(eggzps)
    savedfile.write(chookz)
    savedfile.write(eggvalue)
    savedfile.write(eggz)
def main_loop():
    global eggz, eggzps, money
    eggzps = chookz / 100.0
    money = eggz * eggvalue

    try:
        openbutton2.config( text="Egg Value: " + str(eggvalue) + " --> " + str(eggvalue+0.2) + " ($" + str(eggvalueupgrade) + ")", command=eggvalue_change)
        label2.config(text="Money: $" + str(int(round(money))), font=("Terminal", 50), borderwidth=5, relief="ridge", bg="black", foreground="white",pady=10, padx=498)
        if eggzps >= 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(int(round(eggzps)))+" | Egg Value: $" + str(eggvalue) + " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        elif eggzps < 10:
            label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(eggzps)+" | Egg Value: $" + str(eggvalue)+ " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498)
        if money < int(round(eggvalueupgrade)):
            openbutton2.config(fg="gray")
        elif money > int(round(eggvalueupgrade)):
            openbutton2.config(fg="white")
    except Exception as e:
        print(e) # display exception to see problem
    root.after(20, main_loop)
def update_eggz():
    global eggz
    try:
        eggz += eggzps
    except Exception as e:
        print(e) # display exception to see problem

    # repeat it after 1000ms
    root.after(1000, update_eggz)

# --- main ---

root = tk.Tk()
root.title("Chicken Clicker")

savedfile = open("savedata\\mainsave.txt", "a+")
savedlines = savedfile.readlines()
print savedlines

if savedlines == []:
    eggz = 0
    eggvalue = 0.2
    chookz = 0
    eggzps = 0.0
    eggvalueupgrade = 100
    money = eggz * eggvalue

eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])

savedfile.close()

# empty labels - `update_labels` will add text

label2 = tk.Label(root)
label1 = tk.Label(root)

label2.pack()
label1.pack()

chickencnv = Image.open("img\\1.png")
chicken = ImageTk.PhotoImage(chickencnv)
openbutton3 =tk.Button(root, bg="black", fg="white", font=("Terminal", 13), command=saving)
openbutton2= tk.Button(root, bg="black", fg="gray", font=("Terminal", 15))
openbutton1= tk.Button(root, image=chicken, width=500, height=500, command=moar_eggz, bg="black")

openbutton1.pack()
openbutton2.pack()
openbutton3.pack()

# run it first time at once
update_eggz()
main_loop()

root.mainloop()

If there is no answer, I am fine with you commenting or answering that.


问:
npm install running failed

Even though I use Administrator install gulp, it still failed.

What's wrong with it?

答:
If you are in China, there's some network problem to install node-sass.

you can try to use this command to install node: SASS_BINARY_SITE=https://npm.taobao.org/mirrors/node-sass/ npm install node-sass --save-dev

Title: npm install running failed


问:
What is the difference between __str__ and __repr__?
What is the difference between __str__ and __repr__ in Python?

答:
Understand __str__ and __repr__ intuitively and permanently distinguish them at all.

__str__ return the string disguised body of a given object for readable of eyes

__repr__ return the real flesh body of a given object (return itself) for unambiguity to identify.

See it in an example

```<code>In [30]: str(datetime.datetime.now())
Out[30]: '2017-12-07 15:41:14.002752'
Disguised in string form
</code>```

As to __repr__

```<code>In [32]: datetime.datetime.now()
Out[32]: datetime.datetime(2017, 12, 7, 15, 43, 27, 297769)
Presence in real body which allows to be manipulated directly.
</code>```

We can do arithmetic operation on __repr__ results conveniently.

```<code>In [33]: datetime.datetime.now()
Out[33]: datetime.datetime(2017, 12, 7, 15, 47, 9, 741521)
In [34]: datetime.datetime(2017, 12, 7, 15, 47, 9, 741521) - datetime.datetime(2
    ...: 017, 12, 7, 15, 43, 27, 297769)
Out[34]: datetime.timedelta(0, 222, 443752)
</code>```

if apply the operation on __str__

```<code>In [35]: '2017-12-07 15:43:14.002752' - '2017-12-07 15:41:14.002752'
TypeError: unsupported operand type(s) for -: 'str' and 'str'
</code>```

Returns nothing but error.

Another example.

```<code>In [36]: str('string_body')
Out[36]: 'string_body' # in string form

In [37]: repr('real_body')
Out[37]: "'real_body'" #its real body hide inside
</code>```

Hope this help you build concrete grounds to explore more answers.

ContentLicense: CC BY-SA 4.0

Body:
Understand __str__ and __repr__ intuitively and permanently distinguish them at all.

__str__ return the string disguised body of a given object for readable of eyes

__repr__ return the real flesh body of a given object (return itself) for unambiguity to identify.

See it in an example

In [30]: str(datetime.datetime.now())
Out[30]: '2017-12-07 15:41:14.002752'
Disguised in string form

As to __repr__

In [32]: datetime.datetime.now()
Out[32]: datetime.datetime(2017, 12, 7, 15, 43, 27, 297769)
Presence in real body which allows to be manipulated directly.

We can do arithmetic operation on __repr__ results conveniently.

In [33]: datetime.datetime.now()
Out[33]: datetime.datetime(2017, 12, 7, 15, 47, 9, 741521)
In [34]: datetime.datetime(2017, 12, 7, 15, 47, 9, 741521) - datetime.datetime(2
    ...: 017, 12, 7, 15, 43, 27, 297769)
Out[34]: datetime.timedelta(0, 222, 443752)

if apply the operation on __str__

In [35]: '2017-12-07 15:43:14.002752' - '2017-12-07 15:41:14.002752'
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Returns nothing but error.

Another example.

In [36]: str('string_body')
Out[36]: 'string_body' # in string form

In [37]: repr('real_body')
Out[37]: "'real_body'" #its real body hide inside

Hope this help you build concrete grounds to explore more answers.


问:
How to get json property content
I use a property to save my json payload

```<code><property expression="json-eval($.)" name="req_json" scope="default" type="STRING"/>
</code>```

The json content as below:

```<code>{ "schema": { "computerName": "PC243854", "ipAddress": "11.2.45.120"}, "data": { "code": "ZFIR006", "filters":[{ "dataType": "integer", "fieldName": "TEST", "operator": "=", "values": ["1","9"] } ], "schema":1} }
</code>```

I want to use the "req_json" property to get json content value of filters,how can I do?

```<code>[{ "dataType": "integer", "fieldName": "TEST", "operator": "=", "values": ["1","9"] } ]
</code>```

答:
is it mandatory for you to get it from req_json property? You could get it easier from the payload and store it in another property like that

```<code><property expression="json-eval($.data.filters)" name="req_filters" scope="default"/>
</code>```

You can get more sample of json manipulation here : https://docs.wso2.com/display/EI611/JSON+Support

Title: How to get json property content

Body:
I use a property to save my json payload

<property expression="json-eval($.)" name="req_json" scope="default" type="STRING"/>

The json content as below:

{ "schema": { "computerName": "PC243854", "ipAddress": "11.2.45.120"}, "data": { "code": "ZFIR006", "filters":[{ "dataType": "integer", "fieldName": "TEST", "operator": "=", "values": ["1","9"] } ], "schema":1} }

I want to use the "req_json" property to get json content value of filters,how can I do?

[{ "dataType": "integer", "fieldName": "TEST", "operator": "=", "values": ["1","9"] } ]

Body:
is it mandatory for you to get it from req_json property? You could get it easier from the payload and store it in another property like that

<property expression="json-eval($.data.filters)" name="req_filters" scope="default"/>

You can get more sample of json manipulation here : https://docs.wso2.com/display/EI611/JSON+Support


问:
failed to connect to mail server in PHP
I have written a small piece of PHP code for sending mail:

```<code>   <?php
    //define the receiver of the email
    $to = 'rohaanthakare@gmail.com';
    //define the subject of the email
    $subject = 'Hishob email';
    //define the message to be sent. Each line should be separated with \n
    $message = "Hello World!\n\nThis is my first mail.";
    //define the headers we want passed. Note that they are separated with \r\n
    $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
    //send the email
    $mail_sent = mail( $to, $subject, $message, $headers );
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
    echo $mail_sent ? "Mail sent" : "Mail failed";
    ?>
</code>```

after executing it I got following warning:

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\NewHishob\PhpFiles\send_mail.php on line 11

  Mail failed

I am using a WAMP server and there are two files, INI-DIST and other is INI-RECOMENDED. Which one is important?

I had also gone through php.ini-dist file and for SMTP it contains the following:

```<code>[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
</code>```

Please suggest what I should do? Thanks to all in advance.

答:
Forget about this, if you are on localhost and Windows machine, just won't work.

Use PHPMailer instead!

I have managed to sent email thru GMail service (just for testing). It is realy simple... Try it
PHPMailer

Title: failed to connect to mail server in PHP

Body:
I have written a small piece of PHP code for sending mail:

   <?php
    //define the receiver of the email
    $to = 'rohaanthakare@gmail.com';
    //define the subject of the email
    $subject = 'Hishob email';
    //define the message to be sent. Each line should be separated with \n
    $message = "Hello World!\n\nThis is my first mail.";
    //define the headers we want passed. Note that they are separated with \r\n
    $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
    //send the email
    $mail_sent = mail( $to, $subject, $message, $headers );
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
    echo $mail_sent ? "Mail sent" : "Mail failed";
    ?>

after executing it I got following warning:

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\NewHishob\PhpFiles\send_mail.php on line 11

  Mail failed

I am using a WAMP server and there are two files, INI-DIST and other is INI-RECOMENDED. Which one is important?

I had also gone through php.ini-dist file and for SMTP it contains the following:

[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =

Please suggest what I should do? Thanks to all in advance.


问:
How to create XPT file from CSV using R
How can we read a CSV file and input the data into write.xport() function in R?

Here am mainly confused with converting the csv data that I read to input the write.xport() functionality. I just started learning R.

Thanks!

答:
Here is an example of reading a CSV file, using the Baltimore City Employee Salary data.

```<code>#
# City of Baltimore 2016 employee salary data
#

theFile <- "https://data.baltimorecity.gov/api/views/65ac-s4v5/rows.csv?accessType=DOWNLOAD"

download.file(theFile,
              "./data/baltimoreEmployeeSalaries2016.csv",
              method="wininet", # for Windows, use "curl" for OS X / Linux
              mode="w")

salaries <- read.csv("./data/baltimoreEmployeeSalaries2016.csv",header=TRUE,stringsAsFactors=FALSE)
head(salaries)
</code>```

...and the output.

```<code>> head(salaries)
                   Name                      JobTitle AgencyID                        Agency               HireDate
1      Aaron,Patricia G Facilities/Office Services II   A03031      OED-Employment Dev (031) 10/24/1979 12:00:00 AM
2         Aaron,Petra L    ASSISTANT STATE'S ATTORNEY   A29045 States Attorneys Office (045) 09/25/2006 12:00:00 AM
3        Abbey,Emmanuel         CONTRACT SERV SPEC II   A40001     M-R Info Technology (001) 05/01/2013 12:00:00 AM
4  Abbott-Cole,Michelle        Operations Officer III   A90005           TRANS-Traffic (005) 11/28/2014 12:00:00 AM
5    Abdal-Rahim,Naim A   EMT Firefighter Suppression   A64120         Fire Department (120) 03/30/2011 12:00:00 AM
6 Abdelmeguid,Shahrazad         CONTRACT SERV SPEC II   A29010 States Attorneys Office (010) 11/30/2015 12:00:00 AM
  AnnualSalary  GrossPay
1    $56705.00 $54135.44
2    $75500.00 $72445.87
3    $60060.00 $59602.58
4    $70000.00 $59517.21
5    $64365.00 $74770.82
6    $40019.00 $16283.26
>
</code>```

At this point you can use write.xport(salaries,...) to generate a SAS export file.

Title: How to create XPT file from CSV using R

Body:
Here is an example of reading a CSV file, using the Baltimore City Employee Salary data.

#
# City of Baltimore 2016 employee salary data
#

theFile <- "https://data.baltimorecity.gov/api/views/65ac-s4v5/rows.csv?accessType=DOWNLOAD"

download.file(theFile,
              "./data/baltimoreEmployeeSalaries2016.csv",
              method="wininet", # for Windows, use "curl" for OS X / Linux
              mode="w")

salaries <- read.csv("./data/baltimoreEmployeeSalaries2016.csv",header=TRUE,stringsAsFactors=FALSE)
head(salaries)

...and the output.

> head(salaries)
                   Name                      JobTitle AgencyID                        Agency               HireDate
1      Aaron,Patricia G Facilities/Office Services II   A03031      OED-Employment Dev (031) 10/24/1979 12:00:00 AM
2         Aaron,Petra L    ASSISTANT STATE'S ATTORNEY   A29045 States Attorneys Office (045) 09/25/2006 12:00:00 AM
3        Abbey,Emmanuel         CONTRACT SERV SPEC II   A40001     M-R Info Technology (001) 05/01/2013 12:00:00 AM
4  Abbott-Cole,Michelle        Operations Officer III   A90005           TRANS-Traffic (005) 11/28/2014 12:00:00 AM
5    Abdal-Rahim,Naim A   EMT Firefighter Suppression   A64120         Fire Department (120) 03/30/2011 12:00:00 AM
6 Abdelmeguid,Shahrazad         CONTRACT SERV SPEC II   A29010 States Attorneys Office (010) 11/30/2015 12:00:00 AM
  AnnualSalary  GrossPay
1    $56705.00 $54135.44
2    $75500.00 $72445.87
3    $60060.00 $59602.58
4    $70000.00 $59517.21
5    $64365.00 $74770.82
6    $40019.00 $16283.26
>

At this point you can use write.xport(salaries,...) to generate a SAS export file.


问:
How to fetch the latest records and status from a group?
This is what my data looks like

You will notice there are 3 groups of rows; only the createdAt, Status columns are different. I want to fetch the "latest" record from each group, i.e the highlighted rows, with PK = {3,6,9}.

Can this be done with one SQL statement? (dialect is Microsoft SQL Server)

答:
use the row_number feature

```<code>;with cte
as
(
    select
        SeqNo = ROW_NUMBER() OVER(PARTITION BY RefDocNo ORDER BY CreateAt DESC),
        *
        FROM YourTable
)
SELECT
    *
    FROM cte
        WHERE SeqNo = 1
</code>```

This feature is called Common Table Expression - CTE. It work's just like a subquery except, you can call a cte recursively inside the same. but it is not necessary to name it as cte, instead you can give it any name you like

Body:
use the row_number feature

;with cte
as
(
    select
        SeqNo = ROW_NUMBER() OVER(PARTITION BY RefDocNo ORDER BY CreateAt DESC),
        *
        FROM YourTable
)
SELECT
    *
    FROM cte
        WHERE SeqNo = 1

This feature is called Common Table Expression - CTE. It work's just like a subquery except, you can call a cte recursively inside the same. but it is not necessary to name it as cte, instead you can give it any name you like


问:
How to align dynamically created cardView vertically in recyclerView?
I have created cardviews dynamically,but while displaying that into the recyclerview,cardviews getting displayed horizontally even though the parent linear layout orientation is vertical.

I wants to display the cardviews vertically (i.e)one card after another card,can anyone help me to address this issue?

Adapter Class

```<code>public RecyclerAdapter(HashMap<String, List<EventDataModel>> stringListHashMap, Context ctx) {

            cardViews = new ArrayList<>();
            this.stringListHashMap = stringListHashMap;
            CardView.LayoutParams cardViewParams=new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
            cardViewParams.gravity= Gravity.CENTER_VERTICAL;
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );

            for(Map.Entry<String, List<EventDataModel>> listEntry : this.stringListHashMap.entrySet()) {
                CardView cardView = new CardView(ctx);
                cardView.setLayoutParams(cardViewParams);
                cardView.setPadding(10,5,10,5);
                cardView.setContentPadding(10,10,10,10);
                cardView.setUseCompatPadding(true);
                cardView.setCardElevation(10);
                cardView.setMaxCardElevation(15);
                cardView.setRadius(9);

                LinearLayout layout = new LinearLayout(ctx);
                layout.setLayoutParams(layoutParams);
                layout.setOrientation(LinearLayout.VERTICAL);
                layout.setPadding(5,5,5,5);
                layout.setBackgroundColor(Color.GREEN);

                for(EventDataModel eventDataModel : listEntry.getValue()) {
                    LinearLayout linearLayout = new LinearLayout(ctx);
                    linearLayout.setLayoutParams(layoutParams);
                    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                    linearLayout.setPadding(5,5,5,5);
                    linearLayout.setBackgroundColor(Color.RED);

                    TextView textViewKey = new TextView(ctx);
                    TextView textViewValue = new TextView(ctx);
                    textViewKey.setLayoutParams(layoutParams);
                    textViewKey.setPadding(5,5,5,5);
                    textViewValue.setLayoutParams(layoutParams);
                    textViewValue.setPadding(5,5,5,5);
                    textViewKey.setText(eventDataModel.getKey());
                    textViewValue.setText(eventDataModel.getValue());

                    linearLayout.addView(textViewKey);
                    linearLayout.addView(textViewValue);

                    layout.addView(linearLayout);

                }

                cardView.addView(layout);
                cardViews.add(cardView);
            }
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_layout, parent, false);

            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {

            Log.d("position>>",position+"");
            holder.rootLayout.addView(cardViews.get(position));
        }
</code>```

event_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relat"
android:orientation="vertical"
    android:background="@color/colorAccent">
</LinearLayout>
</code>```

current cardviews display

I have created one more linear layout dynamically to add that cardview into that layout,but its also pop up some error,because of already having the rootLayout.

答:
From where you are calling adapter class on recycler. Just put this code there and try::

```<code> LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
 recyclerView.setLayoutManager(layoutManager);
</code>```

We need to assign "LayoutManager" to recycler view to define it in which way it used to work, like "grid,staggered, list, so on" and we can also define the "scrolling". So just we defined the vertical behaviour.

Body:
I have created cardviews dynamically,but while displaying that into the recyclerview,cardviews getting displayed horizontally even though the parent linear layout orientation is vertical.

I wants to display the cardviews vertically (i.e)one card after another card,can anyone help me to address this issue?

Adapter Class

public RecyclerAdapter(HashMap<String, List<EventDataModel>> stringListHashMap, Context ctx) {

            cardViews = new ArrayList<>();
            this.stringListHashMap = stringListHashMap;
            CardView.LayoutParams cardViewParams=new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
            cardViewParams.gravity= Gravity.CENTER_VERTICAL;
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );

            for(Map.Entry<String, List<EventDataModel>> listEntry : this.stringListHashMap.entrySet()) {
                CardView cardView = new CardView(ctx);
                cardView.setLayoutParams(cardViewParams);
                cardView.setPadding(10,5,10,5);
                cardView.setContentPadding(10,10,10,10);
                cardView.setUseCompatPadding(true);
                cardView.setCardElevation(10);
                cardView.setMaxCardElevation(15);
                cardView.setRadius(9);

                LinearLayout layout = new LinearLayout(ctx);
                layout.setLayoutParams(layoutParams);
                layout.setOrientation(LinearLayout.VERTICAL);
                layout.setPadding(5,5,5,5);
                layout.setBackgroundColor(Color.GREEN);

                for(EventDataModel eventDataModel : listEntry.getValue()) {
                    LinearLayout linearLayout = new LinearLayout(ctx);
                    linearLayout.setLayoutParams(layoutParams);
                    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                    linearLayout.setPadding(5,5,5,5);
                    linearLayout.setBackgroundColor(Color.RED);

                    TextView textViewKey = new TextView(ctx);
                    TextView textViewValue = new TextView(ctx);
                    textViewKey.setLayoutParams(layoutParams);
                    textViewKey.setPadding(5,5,5,5);
                    textViewValue.setLayoutParams(layoutParams);
                    textViewValue.setPadding(5,5,5,5);
                    textViewKey.setText(eventDataModel.getKey());
                    textViewValue.setText(eventDataModel.getValue());

                    linearLayout.addView(textViewKey);
                    linearLayout.addView(textViewValue);

                    layout.addView(linearLayout);

                }

                cardView.addView(layout);
                cardViews.add(cardView);
            }
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_layout, parent, false);

            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {

            Log.d("position>>",position+"");
            holder.rootLayout.addView(cardViews.get(position));
        }

event_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relat"
android:orientation="vertical"
    android:background="@color/colorAccent">
</LinearLayout>

current cardviews display

I have created one more linear layout dynamically to add that cardview into that layout,but its also pop up some error,because of already having the rootLayout.

Body:
From where you are calling adapter class on recycler. Just put this code there and try::

 LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
 recyclerView.setLayoutManager(layoutManager);

We need to assign "LayoutManager" to recycler view to define it in which way it used to work, like "grid,staggered, list, so on" and we can also define the "scrolling". So just we defined the vertical behaviour.


问:
Find listBox name or typeOf object in WPF C# drag & drop
I'm writing an app where i can drag from one list to another one, but i can also drag from the same list to itself. Is there anyway to know which list is the source list (I mean which list i dragged from) or what data i dragged?
I have 2 lists: lbTwo and lbOne, and two datas (one for each list of ObservableCollection): firstDataType and secondDataType.
The only way i found to get the data is (But i prefer to get the list name and not the data it contains):

```<code> private void ListBox_Drop(object sender, DragEventArgs e)
 {
            ListBox parent = (ListBox)sender;

            string data_type = (e.Data.GetFormats())[0];
 }
</code>```

but it's not really elegant and i also get the whole name (Myapp.firstDataType).

Thanks!!

答:
Here is how my code looks like:

Xaml:

```<code><ListBox Name="LeftBox" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
             PreviewMouseLeftButtonDown="Common_PreviewMouseLeftButtonDown"
             AllowDrop="True"
             Drop="Common_Drop"/>
    <ListBox Name="RightBox" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
             PreviewMouseLeftButtonDown="Common_PreviewMouseLeftButtonDown"
             AllowDrop="True"
             Drop="Common_Drop"/>
</code>```

I call this method to load test data into my Listboxes:

```<code>private void LoadData()
    {
        var lstbox1Data = new string[] { "One", "Two", "Three", "Four", "Five" };
        var lstbox2Data = new string[] { "Alpha", "Beta", "Theta", "Gamma", "Phi" };

        foreach (var item in lstbox1Data)
        {
            LeftBox.Items.Add(item);
        }

        foreach (var item in lstbox2Data)
        {
            RightBox.Items.Add(item);
        }
    }
</code>```

This is the actual implementation of DragDrop across Listboxes & re-arrange within Listbox.

```<code>    private void Common_Drop(object sender, DragEventArgs e)
    {
        var destLisBox = sender as ListBox;
        var dragDropData = e.Data.GetData(typeof(DragDropData)) as DragDropData;

        if (dragDropData != null)
        {
            var dataWhereToInsert = GetDataFromListBox(destLisBox, e.GetPosition(destLisBox));

            if (dataWhereToInsert != null)
            {
                var insertAtIndex = destLisBox.Items.IndexOf(dataWhereToInsert);
                if (insertAtIndex >= 0)
                {
                    dragDropData.DragStartSource.Items.Remove(dragDropData.ActualData);
                    destLisBox.Items.Insert(insertAtIndex, dragDropData.ActualData);
                }
            }
            else
            {
                dragDropData.DragStartSource.Items.Remove(dragDropData.ActualData);
                destLisBox.Items.Add(dragDropData.ActualData);
            }
        }
    }

    private static object GetDataFromListBox(ListBox source, Point point)
    {
        UIElement element = source.InputHitTest(point) as UIElement;
        if (element != null)
        {
            object data = DependencyProperty.UnsetValue;
            while (data == DependencyProperty.UnsetValue)
            {
                data = source.ItemContainerGenerator.ItemFromContainer(element);
                if (data == DependencyProperty.UnsetValue)
                {
                    element = VisualTreeHelper.GetParent(element) as UIElement;
                }
                if (element == source)
                {
                    return null;
                }
            }
            if (data != DependencyProperty.UnsetValue)
            {
                return data;
            }
        }
        return null;
    }

    private void Common_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var srcListBox = sender as ListBox;
        if (srcListBox != null)
        {
            var data = GetDataFromListBox(srcListBox, e.GetPosition(srcListBox));

            if (data != null)
            {
                var dragDropData = new DragDropData
                {
                    ActualData = data,
                    DragStartSource = srcListBox
                };

                DragDrop.DoDragDrop(srcListBox, dragDropData, DragDropEffects.Move);
            }
        }
    }
</code>```

Note that I wrapped the data & sender into below class:

```<code>public class DragDropData
{
    public object ActualData { get; set; }
    public ListBox DragStartSource { get; set; }
}
</code>```

That amazing : GetDataFromListBox method comes from:
[http://www.c-sharpcorner.com/uploadfile/dpatra/drag-and-drop-item-in-listbox-in-wpf/]

Body:
I'm writing an app where i can drag from one list to another one, but i can also drag from the same list to itself. Is there anyway to know which list is the source list (I mean which list i dragged from) or what data i dragged?
I have 2 lists: lbTwo and lbOne, and two datas (one for each list of ObservableCollection): firstDataType and secondDataType.
The only way i found to get the data is (But i prefer to get the list name and not the data it contains):

 private void ListBox_Drop(object sender, DragEventArgs e)
 {
            ListBox parent = (ListBox)sender;

            string data_type = (e.Data.GetFormats())[0];
 }

but it's not really elegant and i also get the whole name (Myapp.firstDataType).

Thanks!!

Body:
Here is how my code looks like:

Xaml:

<ListBox Name="LeftBox" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
             PreviewMouseLeftButtonDown="Common_PreviewMouseLeftButtonDown"
             AllowDrop="True"
             Drop="Common_Drop"/>
    <ListBox Name="RightBox" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
             PreviewMouseLeftButtonDown="Common_PreviewMouseLeftButtonDown"
             AllowDrop="True"
             Drop="Common_Drop"/>

I call this method to load test data into my Listboxes:

private void LoadData()
    {
        var lstbox1Data = new string[] { "One", "Two", "Three", "Four", "Five" };
        var lstbox2Data = new string[] { "Alpha", "Beta", "Theta", "Gamma", "Phi" };

        foreach (var item in lstbox1Data)
        {
            LeftBox.Items.Add(item);
        }

        foreach (var item in lstbox2Data)
        {
            RightBox.Items.Add(item);
        }
    }

This is the actual implementation of DragDrop across Listboxes & re-arrange within Listbox.

    private void Common_Drop(object sender, DragEventArgs e)
    {
        var destLisBox = sender as ListBox;
        var dragDropData = e.Data.GetData(typeof(DragDropData)) as DragDropData;

        if (dragDropData != null)
        {
            var dataWhereToInsert = GetDataFromListBox(destLisBox, e.GetPosition(destLisBox));

            if (dataWhereToInsert != null)
            {
                var insertAtIndex = destLisBox.Items.IndexOf(dataWhereToInsert);
                if (insertAtIndex >= 0)
                {
                    dragDropData.DragStartSource.Items.Remove(dragDropData.ActualData);
                    destLisBox.Items.Insert(insertAtIndex, dragDropData.ActualData);
                }
            }
            else
            {
                dragDropData.DragStartSource.Items.Remove(dragDropData.ActualData);
                destLisBox.Items.Add(dragDropData.ActualData);
            }
        }
    }

    private static object GetDataFromListBox(ListBox source, Point point)
    {
        UIElement element = source.InputHitTest(point) as UIElement;
        if (element != null)
        {
            object data = DependencyProperty.UnsetValue;
            while (data == DependencyProperty.UnsetValue)
            {
                data = source.ItemContainerGenerator.ItemFromContainer(element);
                if (data == DependencyProperty.UnsetValue)
                {
                    element = VisualTreeHelper.GetParent(element) as UIElement;
                }
                if (element == source)
                {
                    return null;
                }
            }
            if (data != DependencyProperty.UnsetValue)
            {
                return data;
            }
        }
        return null;
    }

    private void Common_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var srcListBox = sender as ListBox;
        if (srcListBox != null)
        {
            var data = GetDataFromListBox(srcListBox, e.GetPosition(srcListBox));

            if (data != null)
            {
                var dragDropData = new DragDropData
                {
                    ActualData = data,
                    DragStartSource = srcListBox
                };

                DragDrop.DoDragDrop(srcListBox, dragDropData, DragDropEffects.Move);
            }
        }
    }

Note that I wrapped the data & sender into below class:

public class DragDropData
{
    public object ActualData { get; set; }
    public ListBox DragStartSource { get; set; }
}

That amazing : GetDataFromListBox method comes from:
[http://www.c-sharpcorner.com/uploadfile/dpatra/drag-and-drop-item-in-listbox-in-wpf/]


问:
Error Handling in TcpClient Socket
I am new to Sockets this is my Code to send and receive data from a server.

This Code Works fine as long as the Client is able to receive data from the server.

In Case the Server does not sends the answer back in the given time then the application needs to send "No Answer Received".

How can i know if the recvBuffer is empty or NULL.

Currently the if Condition for the recvBuffer does not work and the application tries to send empty buffer which results in  "System.IndexOutOfRangeException error".

```<code> class GetSocket
 {
    public string SocketSendReceive(string server, int port, string cmd)
    {
        byte[] recvBuffer = new byte[1024];
        TcpClient tcpClient = new TcpClient();
        tcpClient.Client.ReceiveTimeout = 200;

         try
            {
                tcpClient.Connect(server, 6100);

            }
            catch (SocketException e)
            {

                MessageBox.Show(e.Message);

            }

            if (tcpClient != null && tcpClient.Connected)
            {
                try
                {
                    tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
                    tcpClient.Client.Receive(recvBuffer);

                }

                catch (SocketException e)
                {
                    MessageBox.Show(e.ErrorCode.ToString());
                }

                tcpClient.GetStream().Close();
                tcpClient.Client.Close();
                tcpClient.Client.Dispose();
                tcpClient = null;
                string tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);

                if (recvBuffer != null && recvBuffer.Length > 0)
                {
                    string[] words = tmp.Split(null);
                    return words[1];
                }
                else
                {
                    return ("No Answer Received");
                }
            }
        return null;
    }

}
</code>```

答:
The Following code works fine after making changes as suggested. </p>

```<code>class GetSocket
{
    public string SocketSendReceive(string server, int port, string cmd)
    {
        byte[] recvBuffer = new byte[1024];
        TcpClient tcpClient = new TcpClient();
        tcpClient.Client.ReceiveTimeout = 200;
        string tmp;

            try
            {
                tcpClient.Connect(server, 6100);

            }
            catch (SocketException e)
            {

                MessageBox.Show(e.Message);

            }

            if (tcpClient != null && tcpClient.Connected)
            {
                try
                {
                    tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
                    tcpClient.Client.Receive(recvBuffer);
                    tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);
                    string[] words = tmp.Split(null);
                    return words[1];

                }

                catch (SocketException e)
                {
                    return ("No Answer Received");
                }

            }
        return null;
    }

}
</code>```

Title: Error Handling in TcpClient Socket

Body:
I am new to Sockets this is my Code to send and receive data from a server.

This Code Works fine as long as the Client is able to receive data from the server.

In Case the Server does not sends the answer back in the given time then the application needs to send "No Answer Received".

How can i know if the recvBuffer is empty or NULL.

Currently the if Condition for the recvBuffer does not work and the application tries to send empty buffer which results in  "System.IndexOutOfRangeException error".

 class GetSocket
 {
    public string SocketSendReceive(string server, int port, string cmd)
    {
        byte[] recvBuffer = new byte[1024];
        TcpClient tcpClient = new TcpClient();
        tcpClient.Client.ReceiveTimeout = 200;

         try
            {
                tcpClient.Connect(server, 6100);

            }
            catch (SocketException e)
            {

                MessageBox.Show(e.Message);

            }

            if (tcpClient != null && tcpClient.Connected)
            {
                try
                {
                    tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
                    tcpClient.Client.Receive(recvBuffer);

                }

                catch (SocketException e)
                {
                    MessageBox.Show(e.ErrorCode.ToString());
                }

                tcpClient.GetStream().Close();
                tcpClient.Client.Close();
                tcpClient.Client.Dispose();
                tcpClient = null;
                string tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);

                if (recvBuffer != null && recvBuffer.Length > 0)
                {
                    string[] words = tmp.Split(null);
                    return words[1];
                }
                else
                {
                    return ("No Answer Received");
                }
            }
        return null;
    }

}

Body:
The Following code works fine after making changes as suggested.

class GetSocket
{
    public string SocketSendReceive(string server, int port, string cmd)
    {
        byte[] recvBuffer = new byte[1024];
        TcpClient tcpClient = new TcpClient();
        tcpClient.Client.ReceiveTimeout = 200;
        string tmp;

            try
            {
                tcpClient.Connect(server, 6100);

            }
            catch (SocketException e)
            {

                MessageBox.Show(e.Message);

            }

            if (tcpClient != null && tcpClient.Connected)
            {
                try
                {
                    tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
                    tcpClient.Client.Receive(recvBuffer);
                    tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);
                    string[] words = tmp.Split(null);
                    return words[1];

                }

                catch (SocketException e)
                {
                    return ("No Answer Received");
                }

            }
        return null;
    }

}


问:
maven download plugin to add downloaded resource to jar
I am using download-maven-plugin to download some of resources to be used in my project. The download is successful and I can use the downloaded file.

However, what I want is to include the downloaded file in the JAR.

Note : The resource file will be included in the JAR when it was pre-downloaded before running the build, but if it is not present (e.g. deleted or I want to update it perhaps) the resource file is not included in the JAR.

Basically what I want is to include the recently downloaded file (from mvn clean install) in the output JAR.

```<code>        <plugin>
            <groupId>com.googlecode.maven-download-plugin</groupId>
            <artifactId>download-maven-plugin</artifactId>
            <version>1.4.0</version>
            <executions>
                <execution>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>wget</goal>
                    </goals>
                    <configuration>
                        <url>https://downloadurl</url>
                        <outputFileName>error.json</outputFileName>
                        <outputDirectory>${project.resources.dir}/commons</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

Same thing happens when I use maven-ant-run plugin.

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <id>download-files</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <tasks>
                            <get src="https://downloadurl"
                                 dest="${project.resources.dir}/commons/data.json"
                                 verbose="true"
                                 usetimestamp="true"/>
                        </tasks>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

答: Just download it to ${basedir}/target/classes before packaging phase. You don't need it to be in sources in order to include it to JAR.

Body:
I am using download-maven-plugin to download some of resources to be used in my project. The download is successful and I can use the downloaded file.

However, what I want is to include the downloaded file in the JAR.

Note : The resource file will be included in the JAR when it was pre-downloaded before running the build, but if it is not present (e.g. deleted or I want to update it perhaps) the resource file is not included in the JAR.

Basically what I want is to include the recently downloaded file (from mvn clean install) in the output JAR.

        <plugin>
            <groupId>com.googlecode.maven-download-plugin</groupId>
            <artifactId>download-maven-plugin</artifactId>
            <version>1.4.0</version>
            <executions>
                <execution>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>wget</goal>
                    </goals>
                    <configuration>
                        <url>https://downloadurl</url>
                        <outputFileName>error.json</outputFileName>
                        <outputDirectory>${project.resources.dir}/commons</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Same thing happens when I use maven-ant-run plugin.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <id>download-files</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <tasks>
                            <get src="https://downloadurl"
                                 dest="${project.resources.dir}/commons/data.json"
                                 verbose="true"
                                 usetimestamp="true"/>
                        </tasks>
                    </configuration>
                </execution>
            </executions>
        </plugin>


问:
What is the difference between map() and switchMap() methods?
What is the difference between those 2 methods of the LiveData class? The official doc and tutorial are pretty vague on that. In the map() method the first parameter called source but in the switchMap() it called trigger. What's the rationale behind that?

答:
As per the documentation

Transformations.map()

Applies a function on the value stored in the LiveData object, and propagates the result downstream.

Transformations.switchMap()

Similar to map, applies a function to the value stored in the LiveData object and unwraps and dispatches the result downstream. The function passed to switchMap() must return a LiveData object.

In other words, I may not be 100% correct but if you are familiar with RxJava; Transformations#map is kind of similar to Observable#map & Transformations#switchMap is similar to Observable#switchMap.

Let's take an example, there is a LiveData which emits a string and we want to display that string in capital letters.

One approach would be as follows; in an activity or fragment

```<code>Transformations.map(stringsLiveData, String::toUpperCase)
    .observe(this, textView::setText);
</code>```

the function passed to the map returns a string only, but it's the Transformation#map which ultimately returns a LiveData.

The second approach; in an activity or fragment

```<code>Transformations.switchMap(stringsLiveData, this::getUpperCaseStringLiveData)
            .observe(this, textView::setText);

private LiveData<String> getUpperCaseStringLiveData(String str) {
    MutableLiveData<String> liveData = new MutableLiveData<>();
    liveData.setValue(str.toUpperCase());
    return liveData;
}
</code>```

If you see Transformations#switchMap has actually switched the LiveData. So, again as per the documentation The function passed to switchMap() must return a LiveData object.

So, in case of map it is the source LiveData you are transforming and in case of switchMap the passed LiveData will act as a trigger on which it will switch to another LiveData after unwrapping and dispatching the result downstream.

Body:
As per the documentation

Transformations.map()

Applies a function on the value stored in the LiveData object, and propagates the result downstream.

Transformations.switchMap()

Similar to map, applies a function to the value stored in the LiveData object and unwraps and dispatches the result downstream. The function passed to switchMap() must return a LiveData object.

In other words, I may not be 100% correct but if you are familiar with RxJava; Transformations#map is kind of similar to Observable#map & Transformations#switchMap is similar to Observable#switchMap.

Let's take an example, there is a LiveData which emits a string and we want to display that string in capital letters.

One approach would be as follows; in an activity or fragment

Transformations.map(stringsLiveData, String::toUpperCase)
    .observe(this, textView::setText);

the function passed to the map returns a string only, but it's the Transformation#map which ultimately returns a LiveData.

The second approach; in an activity or fragment

Transformations.switchMap(stringsLiveData, this::getUpperCaseStringLiveData)
            .observe(this, textView::setText);

private LiveData<String> getUpperCaseStringLiveData(String str) {
    MutableLiveData<String> liveData = new MutableLiveData<>();
    liveData.setValue(str.toUpperCase());
    return liveData;
}

If you see Transformations#switchMap has actually switched the LiveData. So, again as per the documentation The function passed to switchMap() must return a LiveData object.

So, in case of map it is the source LiveData you are transforming and in case of switchMap the passed LiveData will act as a trigger on which it will switch to another LiveData after unwrapping and dispatching the result downstream.


问:
Errors when trying to call a method
I have been looking around online, and I am still unsure of how to call a method in my child class. I am trying to call the pay() method in Executive, and when I type in the following code into my if statement, I keep getting an error.

```<code>staff[3].awardBonus(bonus);
</code>```

I keep getting an error with this method. I'm not sure how to call that method... Thanks for any help!`import java.util.Scanner;

```<code>    import java.util.Scanner;
public class Tester
{
    public static void main (String args[])
    {
        Scanner scan = new Scanner(System.in);
        StaffMember[] staff = new StaffMember[4];
        String internName = "Susan 2";
        String empName = "Tyler O.";
        String hrName = "Becky R.";
        String execName = "Daniel H.";
        String address = "Brighton";
        String phone = "420 - 0000";
        String SSN = "12345789";
        double rate = 1000;

        staff [0] = new Intern(internName, address, phone);
        staff [1] = new Employee(empName, address, phone, SSN, rate);
        staff [2] = new HourlyEmployee(hrName, address, phone, SSN, rate);
        staff [3] = new Executive(execName, address, phone, SSN, rate);

        for (StaffMember staffPrint : staff)
        {
            System.out.println (staffPrint.toString() + "\n");
        }

        System.out.println("If you would like to give an executive a bonus, press 1. \nIf you would like to increase the hours of an hourly employee, press 2.");
        int input = scan.nextInt();
        if(input == 1)
        {
            double bonus = 0;
            System.out.println("Enter the bonus for your employee: ");
            bonus = scan.nextDouble();

        }
 }
</code>```

Here is the Executive class, Employee class and the StaffMember class

```<code>public class Executive extends Employee
{
    public Executive(String name, String address, String phone, String SSN, double rate)
    {
        super(name, address, phone, SSN, rate);
    }

    public double pay()
    {
        double money = super.pay();
        return money;
    }

    public String toString()
    {
        String employee = super.toString();
        return employee;
    }

    public void awardBonus(double execBonus)
    {
        rate += execBonus;
    }
}
</code>```

Employee

```<code>    public class Employee extends StaffMember
{
    String SSN;
    double rate;

    public Employee(String name, String address, String phone, String SSN, double rate)
    {
        super(name, address, phone);
        this.SSN = SSN;
        this.rate = rate;
    }

    public double pay()
    {
        return rate;
    }

    public String toString()
    {
        String employee = "";
        employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone + "\nSocial Security Number: " + SSN + "\nPay: " + pay());
        return employee;
    }
}
</code>```

StaffMember

```<code>public abstract class StaffMember
{
    String name;
    String address;
    String phone;

    public StaffMember(String name, String address, String phone)
    {
        this.name = name;
        this.address = address;
        this.phone = phone;
    }

    public String toString()
    {
        String employee = "";
        employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone);
        return employee;
    }

    public abstract double pay();
}
</code>```

答:
By providing an awardBonus for all StaffMembers, you can call it on a StaffMember. For instance:

```<code>public abstract class StaffMember
{
    public void awardBonus(double bonus) {
        if (bonus > 0) {
            throw new IllegalStateException("Only executives receive a bonus");
        }
    }
...

public class Executive extends StaffMember
{
    @Override
    public void awardBonus(double bonus) {
</code>```

P.S. be careful to inform the company on this.

Title: Errors when trying to call a method

Body:
I have been looking around online, and I am still unsure of how to call a method in my child class. I am trying to call the pay() method in Executive, and when I type in the following code into my if statement, I keep getting an error.

staff[3].awardBonus(bonus);

I keep getting an error with this method. I'm not sure how to call that method... Thanks for any help!`import java.util.Scanner;

    import java.util.Scanner;
public class Tester
{
    public static void main (String args[])
    {
        Scanner scan = new Scanner(System.in);
        StaffMember[] staff = new StaffMember[4];
        String internName = "Susan 2";
        String empName = "Tyler O.";
        String hrName = "Becky R.";
        String execName = "Daniel H.";
        String address = "Brighton";
        String phone = "420 - 0000";
        String SSN = "12345789";
        double rate = 1000;

        staff [0] = new Intern(internName, address, phone);
        staff [1] = new Employee(empName, address, phone, SSN, rate);
        staff [2] = new HourlyEmployee(hrName, address, phone, SSN, rate);
        staff [3] = new Executive(execName, address, phone, SSN, rate);

        for (StaffMember staffPrint : staff)
        {
            System.out.println (staffPrint.toString() + "\n");
        }

        System.out.println("If you would like to give an executive a bonus, press 1. \nIf you would like to increase the hours of an hourly employee, press 2.");
        int input = scan.nextInt();
        if(input == 1)
        {
            double bonus = 0;
            System.out.println("Enter the bonus for your employee: ");
            bonus = scan.nextDouble();

        }
 }

Here is the Executive class, Employee class and the StaffMember class

public class Executive extends Employee
{
    public Executive(String name, String address, String phone, String SSN, double rate)
    {
        super(name, address, phone, SSN, rate);
    }

    public double pay()
    {
        double money = super.pay();
        return money;
    }

    public String toString()
    {
        String employee = super.toString();
        return employee;
    }

    public void awardBonus(double execBonus)
    {
        rate += execBonus;
    }
}

Employee

    public class Employee extends StaffMember
{
    String SSN;
    double rate;

    public Employee(String name, String address, String phone, String SSN, double rate)
    {
        super(name, address, phone);
        this.SSN = SSN;
        this.rate = rate;
    }

    public double pay()
    {
        return rate;
    }

    public String toString()
    {
        String employee = "";
        employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone + "\nSocial Security Number: " + SSN + "\nPay: " + pay());
        return employee;
    }
}

StaffMember

public abstract class StaffMember
{
    String name;
    String address;
    String phone;

    public StaffMember(String name, String address, String phone)
    {
        this.name = name;
        this.address = address;
        this.phone = phone;
    }

    public String toString()
    {
        String employee = "";
        employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone);
        return employee;
    }

    public abstract double pay();
}

Body:
By providing an awardBonus for all StaffMembers, you can call it on a StaffMember. For instance:

public abstract class StaffMember
{
    public void awardBonus(double bonus) {
        if (bonus > 0) {
            throw new IllegalStateException("Only executives receive a bonus");
        }
    }
...

public class Executive extends StaffMember
{
    @Override
    public void awardBonus(double bonus) {

P.S. be careful to inform the company on this.