问:
Add-Migration fails with Dependency injection in console core 2.0 app
I try to use EF Core 2.0 in a console .net core 2.0 application. When i either use IDesignTimeDbContextFactory or override OnConfiguring method of a DbContext derived class CustomerDbContext, then Add-Migration is successfull in package manager console. But if i try to use AddDbContext like in an asp.net core application, i receive the message:

Unable to create an object of type 'CustomerDbContext'

The code snippet for console .net core application is:

```<code>class Program
{

    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        IConfigurationRoot config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json")     //needs Microsoft.Extensions.Configuration.Json
            .Build();

        string conn = config.GetConnectionString("WarehouseConnection");
        services
            .AddDbContext<CustomerDbContext>(
            options => options.UseSqlServer(config.GetConnectionString("WarehouseConnection")));

        var provider = services.BuildServiceProvider();
        using(var context = provider.GetService<CustomerDbContext>())
        {
             ...
        }

    }

}
</code>```

the config.json contains the connection string:

```<code>{
  "ConnectionStrings": {
    "WarehouseConnection": "Server=(localdb)\\mssqllocaldb;Database=WAREHOUSE;Trusted_Connection=True;MultipleActiveResultSets=true"
}
</code>```

the CustomerDbContext class is:

```<code>class CustomerDbContext : DbContext
{
    public CustomerDbContext(DbContextOptions<CustomerDbContext> options) : base(options) { }
    public DbSet<Customer> Customers { get; set; }
}
</code>```

Any ideas why this approach fails?

答:
So you need to implement IDesignTimeDbContextFactory interface. Add a class that implements this interface inside of your project.

```<code>public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public CustomerDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        var builder = new DbContextOptionsBuilder<CustomerDbContext>();
        var connectionString = configuration.GetConnectionString("WarehouseConnection");
        builder.UseSqlServer(connectionString);

        return new CustomerDbContext(builder.Options);
    }
}
</code>```

For more info read Cannot make migration. ef core 2.0

Body:
I try to use EF Core 2.0 in a console .net core 2.0 application. When i either use IDesignTimeDbContextFactory or override OnConfiguring method of a DbContext derived class CustomerDbContext, then Add-Migration is successfull in package manager console. But if i try to use AddDbContext like in an asp.net core application, i receive the message:

Unable to create an object of type 'CustomerDbContext'

The code snippet for console .net core application is:

class Program
{

    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        IConfigurationRoot config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json")     //needs Microsoft.Extensions.Configuration.Json
            .Build();

        string conn = config.GetConnectionString("WarehouseConnection");
        services
            .AddDbContext<CustomerDbContext>(
            options => options.UseSqlServer(config.GetConnectionString("WarehouseConnection")));

        var provider = services.BuildServiceProvider();
        using(var context = provider.GetService<CustomerDbContext>())
        {
             ...
        }

    }

}

the config.json contains the connection string:

{
  "ConnectionStrings": {
    "WarehouseConnection": "Server=(localdb)\\mssqllocaldb;Database=WAREHOUSE;Trusted_Connection=True;MultipleActiveResultSets=true"
}

the CustomerDbContext class is:

class CustomerDbContext : DbContext
{
    public CustomerDbContext(DbContextOptions<CustomerDbContext> options) : base(options) { }
    public DbSet<Customer> Customers { get; set; }
}

Any ideas why this approach fails?

Body:
So you need to implement IDesignTimeDbContextFactory interface. Add a class that implements this interface inside of your project.

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public CustomerDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        var builder = new DbContextOptionsBuilder<CustomerDbContext>();
        var connectionString = configuration.GetConnectionString("WarehouseConnection");
        builder.UseSqlServer(connectionString);

        return new CustomerDbContext(builder.Options);
    }
}

For more info read Cannot make migration. ef core 2.0


来源: stackexchange

问:
QByteArray to QString
I'm having issues with QByteArray and QString.

I'm reading a file and stores its information in a QByteArray. The file is in unicode, so it contains something like: t\0 e\0 s\0 t\0 \0 \0

I'm trying to compare this value to my specified value, but it fails, because in the debugger I see it's not an unicode string.

The code will explain everything:

```<code>QByteArray Data; //contains unicode string "t\0 e\0 s\0 t\0 \0 \0"
QString myValue = "test"; //value to compare.
if(Data.contains(myValue))
    //do some stuff.
else
    //do other stuff.
</code>```

In the debugger, it shows me that the variable Data has the value "t\0 e\0 s\0 t\0 \0 \0" and myValue has the value "test". How can I fix it?

答:
You can use:</p>

```<code>QString::fromStdString(byteArray.toStdString())
</code>```

ContentLicense: CC BY-SA 3.0

Title: QByteArray to QString

Body:
I'm having issues with QByteArray and QString.

I'm reading a file and stores its information in a QByteArray. The file is in unicode, so it contains something like: t\0 e\0 s\0 t\0 \0 \0

I'm trying to compare this value to my specified value, but it fails, because in the debugger I see it's not an unicode string.

The code will explain everything:

QByteArray Data; //contains unicode string "t\0 e\0 s\0 t\0 \0 \0"
QString myValue = "test"; //value to compare.
if(Data.contains(myValue))
    //do some stuff.
else
    //do other stuff.

In the debugger, it shows me that the variable Data has the value "t\0 e\0 s\0 t\0 \0 \0" and myValue has the value "test". How can I fix it?

Body:
You can use:

QString::fromStdString(byteArray.toStdString())

ContentLicense: CC BY-SA 4.0


问:
Turning off the screen in android

Hi, for a project I'm working on I have to turn off the screen of the android device. After searching on here I came to use this code:

```<code>public static final int REQUEST_ADMIN_ENABLE = 12345;
ComponentName dPAComponent;
DevicePolicyManager devicePolicyManager;

public void screenOff(){
    dPAComponent = new ComponentName(this, AdminReceiver.class);
    devicePolicyManager = (DevicePolicyManager)
            getApplicationContext().getSystemService(Context.DEVICE_POLICY_SERVICE);
    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, dPAComponent);
    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "pls gib");
    startActivityForResult(intent, REQUEST_ADMIN_ENABLE);
}

@Override
protected void onActivityResult(int request, int result, Intent data){
    super.onActivityResult(request, result, data);
    if(devicePolicyManager.isAdminActive(dPAComponent)){
        if(result == RESULT_OK) {

            switch (request) {
                case REQUEST_ADMIN_ENABLE:
                    devicePolicyManager.lockNow();
                    break;
            }
        }

    }
}
</code>```

"screenOff" is run once a button is pressed in the activity. "AdminReceiver.class" looks like this:

```<code>public class AdminReceiver extends DeviceAdminReceiver {

    @Override
    public void onEnabled(Context context, Intent intent) {
        Log.d("AdminReceiver", "Device Admin enabled");
        //Common.becomeHomeActivity(context);
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        return "Warning: Device Admin is going to be disabled.";
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        Log.d("AdminReceiver", "Device Admin disabled");
    }

    @Override
    public void onLockTaskModeEntering(Context context, Intent intent, String pkg) {
        Log.d("AdminReceiver", "Kiosk Mode enabled");
    }

    @Override
    public void onLockTaskModeExiting(Context context, Intent intent) {
        Log.d("AdminReceiver", "Kiosk Mode disabled");
    }
}
</code>```

This seems to work for others, I even tried some github projects which worked the same way. I, however, keep getting the following error message, triggered by "devicePolicyManager.lockNow();":

```<code>Caused by: java.lang.SecurityException: No active admin owned by uid 10109 for policy #3
</code>```

Obviously I'm doing something wrong here. Can anyone help me find it?

PS: My AndroidManifest.xml contains the following lines, just so you know:

```<code>    <receiver
        android:name=".AdminReceiver"
        android:label="My DeviceAdmin"
        android:permission="android.permission.BIND_DEVICE_ADMIN" >
        <meta-data
            android:name="android.app.device_admin"
            android:resource="@xml/device_admin" />

        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>
</code>```

Thanks in advance

答:
Thanks to user CommonsWare I found out that the res/xml/device_admin.xml file was empty:

```<code><device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>

    </uses-policies>
</device-admin>
</code>```

In my case it should look like this:

```<code><device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>
</code>```

Thanks a lot for the quick answer!

I should've read the Device Admin page on developer.android.com before copy-pasting code I didn't quite understand. Next time I will

Title: Turning off the screen in android

Body:
Hi, for a project I'm working on I have to turn off the screen of the android device. After searching on here I came to use this code:

public static final int REQUEST_ADMIN_ENABLE = 12345;
ComponentName dPAComponent;
DevicePolicyManager devicePolicyManager;

public void screenOff(){
    dPAComponent = new ComponentName(this, AdminReceiver.class);
    devicePolicyManager = (DevicePolicyManager)
            getApplicationContext().getSystemService(Context.DEVICE_POLICY_SERVICE);
    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, dPAComponent);
    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "pls gib");
    startActivityForResult(intent, REQUEST_ADMIN_ENABLE);
}

@Override
protected void onActivityResult(int request, int result, Intent data){
    super.onActivityResult(request, result, data);
    if(devicePolicyManager.isAdminActive(dPAComponent)){
        if(result == RESULT_OK) {

            switch (request) {
                case REQUEST_ADMIN_ENABLE:
                    devicePolicyManager.lockNow();
                    break;
            }
        }

    }
}

"screenOff" is run once a button is pressed in the activity. "AdminReceiver.class" looks like this:

public class AdminReceiver extends DeviceAdminReceiver {

    @Override
    public void onEnabled(Context context, Intent intent) {
        Log.d("AdminReceiver", "Device Admin enabled");
        //Common.becomeHomeActivity(context);
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        return "Warning: Device Admin is going to be disabled.";
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        Log.d("AdminReceiver", "Device Admin disabled");
    }

    @Override
    public void onLockTaskModeEntering(Context context, Intent intent, String pkg) {
        Log.d("AdminReceiver", "Kiosk Mode enabled");
    }

    @Override
    public void onLockTaskModeExiting(Context context, Intent intent) {
        Log.d("AdminReceiver", "Kiosk Mode disabled");
    }
}

This seems to work for others, I even tried some github projects which worked the same way. I, however, keep getting the following error message, triggered by "devicePolicyManager.lockNow();":

Caused by: java.lang.SecurityException: No active admin owned by uid 10109 for policy #3

Obviously I'm doing something wrong here. Can anyone help me find it?

PS: My AndroidManifest.xml contains the following lines, just so you know:

    <receiver
        android:name=".AdminReceiver"
        android:label="My DeviceAdmin"
        android:permission="android.permission.BIND_DEVICE_ADMIN" >
        <meta-data
            android:name="android.app.device_admin"
            android:resource="@xml/device_admin" />

        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

Thanks in advance

Body:
Thanks to user CommonsWare I found out that the res/xml/device_admin.xml file was empty:

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>

    </uses-policies>
</device-admin>

In my case it should look like this:

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

Thanks a lot for the quick answer!

I should've read the Device Admin page on developer.android.com before copy-pasting code I didn't quite understand. Next time I will


问:
why array_push don't work inside foreach loop
i have this code for file update and i need to put the files path in response array. but my array is empty:</p>

```<code>    $response = array();
    if (file_exists($directorSerie)) {
        if(is_array($_FILES)) {
            foreach ($_FILES['fileToUpload']['name'] as $name => $value){
                if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'][$name])) {
                    $sourcePath = $_FILES['fileToUpload']['tmp_name'][$name];
                    $targetPath = $directorSerieString.$_FILES['fileToUpload']['name'][$name];
                    array_push($response, $targetPath);

                    if(move_uploaded_file($sourcePath,$targetPath)) {
                        $success = "success";

                    }
                }
            }

        }
    }
exit(json_encode($response));
</code>```

答:
array_push() works on foreach.
I sugest you to put dubug to found where is the mistakes.
You could put var_dump($var) after level of your code, like this:

```<code>if (file_exists($directorSerie)) {
  var_dump($directorSerie);
</code>```

Next...

```<code>if(is_array($_FILES)) {
  var_dump($_FILES)
</code>```

Next

```<code>foreach ($_FILES['fileToUpload']['name'] as $name => $value){
   var_dump( $name ,$value);
</code>```

up until you discover...

Body:
i have this code for file update and i need to put the files path in response array. but my array is empty:

    $response = array();
    if (file_exists($directorSerie)) {
        if(is_array($_FILES)) {
            foreach ($_FILES['fileToUpload']['name'] as $name => $value){
                if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'][$name])) {
                    $sourcePath = $_FILES['fileToUpload']['tmp_name'][$name];
                    $targetPath = $directorSerieString.$_FILES['fileToUpload']['name'][$name];
                    array_push($response, $targetPath);

                    if(move_uploaded_file($sourcePath,$targetPath)) {
                        $success = "success";

                    }
                }
            }

        }
    }
exit(json_encode($response));

Body:
array_push() works on foreach.
I sugest you to put dubug to found where is the mistakes.
You could put var_dump($var) after level of your code, like this:

if (file_exists($directorSerie)) {
  var_dump($directorSerie);

Next...

if(is_array($_FILES)) {
  var_dump($_FILES)

Next

foreach ($_FILES['fileToUpload']['name'] as $name => $value){
   var_dump( $name ,$value);

up until you discover...


问:
Adding nested attribute associations on checkbox click using javascript/jquery?
I'm new to rails but getting a pretty good handle on it, but my javascript/jquery knowledge is virtually nil. I have watched Ryan Bates' Railscast on building complex forms, but I'm looking for a slightly more up-to-date, less obtrusive solution to my problem.

Essentially I have a sample batch creation form, and I would like it to accept nested attributes for a has_many :through association to a series of tests (assays) that can be performed on the batch. It makes the most sense to list these assays as a series of checkboxes. It does not make sense to initialize the form with assays.count many associations because on submission there would almost certainly be several nil associations created along with the desired associations (If I am wrong on this, feel free to set me straight, I'm a blank slate). Consequently, it makes the most sense to me that I should be creating/destroying new association instance upon click/unclick of the checkboxes, but I'm new enough to not be sure exactly how to approach this with rails and jquery/javascript.

I'm not looking for big honking chunk of code where you do my work for me, I'd be more than happy with a few links to some current guides on similar subjects as my searches have been fruitless. Thanks!

答:
You could initialize the form with assays.count objects because you can easily get rid of blank ones thanks to reject_if:

```<code>  accepts_nested_attributes_for :projects, :reject_if => lambda { |c| c[:title].blank? }
</code>```

If you want to find alternatives, check there: http://railscasts.com/episodes/197-nested-model-form-part-2

Ok it's obstrusive js but in the comments someone provides an unobstrusive solution

ContentLicense: CC BY-SA 2.5

Body:
You could initialize the form with assays.count objects because you can easily get rid of blank ones thanks to reject_if:

  accepts_nested_attributes_for :projects, :reject_if => lambda { |c| c[:title].blank? }

If you want to find alternatives, check there: http://railscasts.com/episodes/197-nested-model-form-part-2

Ok it's obstrusive js but in the comments someone provides an unobstrusive solution


问:
Merge two array of objects with same keys, some object won't have the same value?

I want to merge two arrays of objects. The keys are the same but the values might not always be the same.

Any solution is appreciated preferably in javascript, but a python solution is fine as well.

Here is the sample data:

```<code>var g= [
    { id: 36, name: 'AAA', goal: 'yes' , 'random':27},
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 39, name: 'JJJ', goal: 'yes' },
    { id: 27, name: 'CCC', goal: 'yes' , lag: "23.3343"}];

var c= [
    { id: 36, name: 'AAA', goal: 'yes', color:"purple" },
    { id: 40, name: 'BBB', circle: 'yes', color:"purple" },
    { id: 100, name: 'JJJ', circle: 'yes'} ];
</code>```

      My expected output should be :

```<code> var finalData = [{
 { id: 36, name: 'AAA', goal: 'yes' ,'random':27, color:"purple"},
 { id: 40, name: 'BBB', circle: 'yes', color:"purple"},
 { id: 39, name: 'JJJ', goal: 'yes' },
 { id: 27, name: 'CCC', goal: 'yes' ,lag: "23.3343"},
 { id: 100, name: 'JJJ', circle: 'yes' }

  }]
</code>```

Here is my current code, it works to some degree but it doesn't add keys it might have missed.

```<code>var finalData = [];
for(var i in g){
   var shared = false;
   for (var j in c)
       if (c[j].name == g[i].name) {
           shared = true;
           break;
       }
   if(!shared) finalData.push(g[i])
}
finalData = finalData.concat(c);

finalData
</code>```

答:
Here's a Python solution. This modifies g, which you may or may not want.

```<code>c_by_id = {d['id']: d for d in c}
for item in g:
    item.update(c_by_id.get(item['id']), {})
</code>```

Body:
I want to merge two arrays of objects. The keys are the same but the values might not always be the same.

Any solution is appreciated preferably in javascript, but a python solution is fine as well.

Here is the sample data:

var g= [
    { id: 36, name: 'AAA', goal: 'yes' , 'random':27},
    { id: 40, name: 'BBB', goal: 'yes' },
    { id: 39, name: 'JJJ', goal: 'yes' },
    { id: 27, name: 'CCC', goal: 'yes' , lag: "23.3343"}];

var c= [
    { id: 36, name: 'AAA', goal: 'yes', color:"purple" },
    { id: 40, name: 'BBB', circle: 'yes', color:"purple" },
    { id: 100, name: 'JJJ', circle: 'yes'} ];

      My expected output should be :

 var finalData = [{
 { id: 36, name: 'AAA', goal: 'yes' ,'random':27, color:"purple"},
 { id: 40, name: 'BBB', circle: 'yes', color:"purple"},
 { id: 39, name: 'JJJ', goal: 'yes' },
 { id: 27, name: 'CCC', goal: 'yes' ,lag: "23.3343"},
 { id: 100, name: 'JJJ', circle: 'yes' }

  }]

Here is my current code, it works to some degree but it doesn't add keys it might have missed.

var finalData = [];
for(var i in g){
   var shared = false;
   for (var j in c)
       if (c[j].name == g[i].name) {
           shared = true;
           break;
       }
   if(!shared) finalData.push(g[i])
}
finalData = finalData.concat(c);

finalData

Body:
Here's a Python solution. This modifies g, which you may or may not want.

c_by_id = {d['id']: d for d in c}
for item in g:
    item.update(c_by_id.get(item['id']), {})


问:
How do I include other files in PHP?
I just started creating a website at my home.

Absolutely, I must have these two pages to finish my website rapidly:- footer.php, header.php.

So I created those pages & put  some contents. Also created an index page as index.php inside the htdocs folder.

Then I did include the header & footer pages inside the index.php page by using these following codes.

```<code><?php include 'header.php'; ?>
<?php include 'footer.php'; ?>
</code>```

Undoubtedly, they worked fine without any trouble.

Then I created a directory as account inside the htdocs.

Now I've a login.php page inside the account directory (/account/login.php).

Repeatedly I used those same codes to include the header & footer in the login page. But they didn't work! I saw nothing is happening. If I create the login.php page inside of the  htdocs folder (not in htdocs/account/), so it works.

So, how can I include them while the login page is in account directory?

答:
I think it's a file path problem，you can use this code:

```<code><?php include '../header.php'  ?>
<?php include '../footer.php'  ?>
</code>```

Load the file of the first level directory。

Title: How do I include other files in PHP?

Body:
I just started creating a website at my home.

Absolutely, I must have these two pages to finish my website rapidly:- footer.php, header.php.

So I created those pages & put  some contents. Also created an index page as index.php inside the htdocs folder.

Then I did include the header & footer pages inside the index.php page by using these following codes.

<?php include 'header.php'; ?>
<?php include 'footer.php'; ?>

Undoubtedly, they worked fine without any trouble.

Then I created a directory as account inside the htdocs.

Now I've a login.php page inside the account directory (/account/login.php).

Repeatedly I used those same codes to include the header & footer in the login page. But they didn't work! I saw nothing is happening. If I create the login.php page inside of the  htdocs folder (not in htdocs/account/), so it works.

So, how can I include them while the login page is in account directory?

Body:
I think it's a file path problem，you can use this code:

<?php include '../header.php'  ?>
<?php include '../footer.php'  ?>

Load the file of the first level directory。


问:
Calculating throughput
I am creating a tool like J meter for load testing . I have created say 20 threads and I executed all of them in say 4 iteration .

My code is such a way that first all threads from iteration 1 will get completed then second set of threads will start.

Each thread is doing something like login etc etc . I need to calculate the throughput ? Can someone please guide me what is the correct way . Currently i am following the below procedure.

I captured the start time when in first iteration i was about to create threads
System.currentTimeMillis();

and end time i have taken as Last thread from last iteration was calculated? Is this correct ?

答: Aggregate Report will provide you solution. Just add this under Listener's in Thread group. Here you can see the clear throughput value changes.</p>

Title: Calculating throughput


问:
align the div's with same class within the same row in css Grid Layout
I want to align some div's with same class name in a row using css grid layout. when i tried all div are aligned in top of another one. How to achieve this using css grid layout.</p>

```<code>   .front{
        grid-area: front;
    }
    .accountcontainer{
        display: grid;
        margin: 0 10px;
        background: #ffffff;
        grid-template-columns: 1fr 1fr 1fr 1fr;
        grid-template-areas:
            "front   front   front  front";
        margin-bottom: 20px;
    }
</code>```

答:
Don't use grid-area

Just specify the grid-row for that class.

Note the number of divs with that class MUST be the same as (or less than) the number of columns.

.container {
  display: grid;
  margin: 10px auto;
  background: #ffffff;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-auto-flow: rows;
  margin-bottom: 20px;
  border: 1px solid grey;
}

.item {
  height: 60px;
  background: pink;
  display: flex;
  justify-content: center;
  align-items: center;
  color: whitesmoke;
  border: 1px solid red;
}

.item.front {
  background: rebeccapurple;
}

.front {
  grid-row: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item front">1</div>
  <div class="item front">2</div>
  <div class="item"></div>
  <div class="item front">3</div>
  <div class="item front">4</div>
  <div class="item"></div>
  <div class="item"></div>
</div></code>```

Body:
I want to align some div's with same class name in a row using css grid layout. when i tried all div are aligned in top of another one. How to achieve this using css grid layout.

   .front{
        grid-area: front;
    }
    .accountcontainer{
        display: grid;
        margin: 0 10px;
        background: #ffffff;
        grid-template-columns: 1fr 1fr 1fr 1fr;
        grid-template-areas:
            "front   front   front  front";
        margin-bottom: 20px;
    }

Body:
Don't use grid-area

Just specify the grid-row for that class.

Note the number of divs with that class MUST be the same as (or less than) the number of columns.

.container {
  display: grid;
  margin: 10px auto;
  background: #ffffff;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-auto-flow: rows;
  margin-bottom: 20px;
  border: 1px solid grey;
}

.item {
  height: 60px;
  background: pink;
  display: flex;
  justify-content: center;
  align-items: center;
  color: whitesmoke;
  border: 1px solid red;
}

.item.front {
  background: rebeccapurple;
}

.front {
  grid-row: 1;
}

<div class="container">
  <div class="item front">1</div>
  <div class="item front">2</div>
  <div class="item"></div>
  <div class="item front">3</div>
  <div class="item front">4</div>
  <div class="item"></div>
  <div class="item"></div>
</div>


问:
Javascript get number of files and their filenames from file input element with multiple attribute?
I have a file input with the multiple="multiple" attribute to allow users to select multiple files at once. I would like to display selected file names and their count prior to upload however I'm not sure how to get this information from file input element using javascript?

```<code><input type="file" id="fileElementId" name="files[]" size="20" multiple="multiple" />
</code>```

I've tried this:

```<code>document.getElementById('fileElementId').value
</code>```

But this only returns one file name when I select multiple files.
Using JavaScript is how do I retrieve the number of selected files and their names from a file input element with a multiple attribute?

答:
The second answer was wrong.

Answer should be document.getElementById('fileElementId').files.length; instead of document.getElementById('fileElementId').files;.

Body:
I have a file input with the multiple="multiple" attribute to allow users to select multiple files at once. I would like to display selected file names and their count prior to upload however I'm not sure how to get this information from file input element using javascript?

<input type="file" id="fileElementId" name="files[]" size="20" multiple="multiple" />

I've tried this:

document.getElementById('fileElementId').value

But this only returns one file name when I select multiple files.
Using JavaScript is how do I retrieve the number of selected files and their names from a file input element with a multiple attribute?


问:
Feature importance with keras
i have the following question. I created a neural network with Keras. That is a Part of my dataFrame.
My DataFrame looks like:

```<code>    Id          MainCl   Class     Other Options...
    1016178069  0        30        1
    1016178012  0        25        0
</code>```

My result vector gives me the probability in which class the result can be classified.
Example:

```<code>Prob_isClass_A    Prob_isClass_b
0.756686          0.243314
0.999843          0.000157006
0.999818          0.000182159
</code>```

Now to the main question:
Is there a way to get the highest probability of a feature that is responsible for the result?
Like:

```<code>Prob_isClass_A    Prob_isClass_b      Most_Probability_Reason    Probability
0.756686          0.243314            Main_CL_Feature            0.75
0.999843          0.000157006         Class_Feature              0.8
0.999818          0.000182159         Other_Option_Feature       0.7
</code>```

答:
If i understand your question, you want something like first of feature importance of every sample separately ...

Feature importance isn't supported by keras. You have to look in tree models for something like that. Furthermore you need something more that and as far as i can tell, has not yet implemented and probably wont be.

Title: Feature importance with keras

Body:
i have the following question. I created a neural network with Keras. That is a Part of my dataFrame.
My DataFrame looks like:

    Id          MainCl   Class     Other Options...
    1016178069  0        30        1
    1016178012  0        25        0

My result vector gives me the probability in which class the result can be classified.
Example:

Prob_isClass_A    Prob_isClass_b
0.756686          0.243314
0.999843          0.000157006
0.999818          0.000182159

Now to the main question:
Is there a way to get the highest probability of a feature that is responsible for the result?
Like:

Prob_isClass_A    Prob_isClass_b      Most_Probability_Reason    Probability
0.756686          0.243314            Main_CL_Feature            0.75
0.999843          0.000157006         Class_Feature              0.8
0.999818          0.000182159         Other_Option_Feature       0.7


问:
How to configure Apache Kafka to sending data at specified time?
Lets consider the following abstaract schema of working Apache Kafka:

```<code>Poducers ->(Send messages) -> Apache Kafka -> (Resend to customers) -> Customers
</code>```

It is possible to configure Kafka to send messages to customers at the specified time?

The second question is it real to roll back message to Kafka from customer?

答: Consumers pull messages from Kafka; Kafka does not push ("send") them. So it's up to your consumers to pull the data when they want it.</p>

Body:
Lets consider the following abstaract schema of working Apache Kafka:

Poducers ->(Send messages) -> Apache Kafka -> (Resend to customers) -> Customers

It is possible to configure Kafka to send messages to customers at the specified time?

The second question is it real to roll back message to Kafka from customer?


问:
Using the spread operator as parameter
What is the point of using the spread operator as parameter inreturn withDefaultStatus(...)?

I've been staring and poking at this code for a while now and i can't figure something out.

At first i thought it's used as a condition, but now i'm totally confused.

PS1: I don't think it has anything to do with lodash, but i added it anyway.

PS2: The state is being passed from a React Component.

```<code>const {defaults} = require('lodash/fp')

const withDefaultStatus = defaults({
    isFinished: false,
    isPending: true,
    code: 0
});

const state = {
    isFinished: true,
    isMutation: false,
    isPending: false,
    lastUpdated: 1512730452993,
    queryCount: 5,
    status: 1,
    url: "https://",
}

function selectQueryStatus(state) {
    const {
        isFinished,
        isPending,
        status: code,
        lastUpdated,
        queryCount
    } = state || {};

    return withDefaultStatus({
        isFinished, isPending , ...code && { code, lastUpdated, queryCount }
    });
}

console.log(selectQueryStatus(state))
//output { isFinished: true, isPending: false, code: 1, lastUpdated: 512730452993, queryCount: 5 }
</code>```

答:
In the following syntax

```<code>withDefaultStatus({
        isFinished, isPending , ...code && { code, lastUpdated, queryCount }
    });
</code>```

The reason why Spread syntax is used is because, code, lastUpdate and queryCount values need to be passed to the object only when code is available. So essentially …code && { code, lastUpdated, queryCount } will return code, lastUpdated, queryCount when code is evaluated to true. And hence you entire object will become

```<code> {
    isFinished,
    isPending ,
    code,
    lastUpdated,
    queryCount
 }
</code>```

Title: Using the spread operator as parameter

Body:
What is the point of using the spread operator as parameter inreturn withDefaultStatus(...)?

I've been staring and poking at this code for a while now and i can't figure something out.

At first i thought it's used as a condition, but now i'm totally confused.

PS1: I don't think it has anything to do with lodash, but i added it anyway.

PS2: The state is being passed from a React Component.

const {defaults} = require('lodash/fp')

const withDefaultStatus = defaults({
    isFinished: false,
    isPending: true,
    code: 0
});

const state = {
    isFinished: true,
    isMutation: false,
    isPending: false,
    lastUpdated: 1512730452993,
    queryCount: 5,
    status: 1,
    url: "https://",
}

function selectQueryStatus(state) {
    const {
        isFinished,
        isPending,
        status: code,
        lastUpdated,
        queryCount
    } = state || {};

    return withDefaultStatus({
        isFinished, isPending , ...code && { code, lastUpdated, queryCount }
    });
}

console.log(selectQueryStatus(state))
//output { isFinished: true, isPending: false, code: 1, lastUpdated: 512730452993, queryCount: 5 }

Body:
In the following syntax

withDefaultStatus({
        isFinished, isPending , ...code && { code, lastUpdated, queryCount }
    });

The reason why Spread syntax is used is because, code, lastUpdate and queryCount values need to be passed to the object only when code is available. So essentially …code && { code, lastUpdated, queryCount } will return code, lastUpdated, queryCount when code is evaluated to true. And hence you entire object will become

 {
    isFinished,
    isPending ,
    code,
    lastUpdated,
    queryCount
 }


问:
How to hide the JWPlayer play button?
How can I hide the play button that's in the center of the video screen in JW Player?

I'm using version 5.4 of the player and I am embedding it using their own 'JW Embedder' technique.

I've tried the following with no luck:

```<code>jwplayer("myPlayer").setup({
   file: 'myMediaFile.mp4',
   image: 'myPosterFile.jpg',
   controlbar: 'bottom',
   icons: false
});
</code>```

I've read somewhere that this may have been removed with version 5.0 and must now be done with a skin. But, I also read that it returned in version 5.1 ... ?

答: It seems to be that the 'icons: false' option does work, but not with the HTML 5 version of the player. Hopefully they'll get this taken care of with any versions later than JW 5.4.

Title: How to hide the JWPlayer play button?

Body:
How can I hide the play button that's in the center of the video screen in JW Player?

I'm using version 5.4 of the player and I am embedding it using their own 'JW Embedder' technique.

I've tried the following with no luck:

jwplayer("myPlayer").setup({
   file: 'myMediaFile.mp4',
   image: 'myPosterFile.jpg',
   controlbar: 'bottom',
   icons: false
});

I've read somewhere that this may have been removed with version 5.0 and must now be done with a skin. But, I also read that it returned in version 5.1 ... ?


问:
Can database remove rows itself?
Can database remove rows itself with condition?

Usually I have removed data from database by user action, but now I want database to do it by itself. It should be able to delete rows with timestamp without user. Every time when row has older timestamp than NOW() it deletes itself.

Can anyone recommend any databases or (tools) for my project?

Tools that I am going to use in this project is strictly PHP, Javascript, HTML and CSS.

I am familiar with MySQL, but I haven't found any information from the web that would answ
er to my question. At least not to my cause.

Currently I have this set up

User adds "task" to MySQL "tasks" table with startdateand enddate (both are in mm/dd/yyyy format) alse active which is 1.

I need to create event that checks each day (at midnight) each row in "tasks" table is this day older than enddate and if it is update active into 0 otherwise leave it as it is.

答:
You can try using this condition:</p>

```<code>WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY)
So that the whole SQL script looks like this:

CREATE EVENT delete_event
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
ON COMPLETION PRESERVE

DO BEGIN
      DELETE messages WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY);
END;
</code>```

Title: Can database remove rows itself?

Body:
You can try using this condition:

WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY)
So that the whole SQL script looks like this:

CREATE EVENT delete_event
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
ON COMPLETION PRESERVE

DO BEGIN
      DELETE messages WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY);
END;


问:
Database Design - Storing n weeks data in database and update each week
I want to show last four Sundays temperature for particular city, I need to update the database weekly (on Sundays)

Database Design 1

```<code>city_id     temp_pre_sunday1   temp_pre_sunday2   temp_pre_sunday3  temp_pre_sunday4
1                  24.3              35.2           24.4             28.0
2                  4.0                2.0           6.0              7.0

 .
2000
</code>```

I can update the database each Sunday. Is this good database design?

Database Design 2

```<code> city_id      temp   date
   1          24.3    2017-12-03
   1          35.2    2017-11-26
   1          24.4    2017-11-19
   1          28.0    2017-11-12
   2          4.0     2017-12-03
   2          2.0     2017-11-26
   2          6.0     2017-11-19
   2          7.0     2017-11-12
   .
   .
</code>```

I need only four Sundays not more than that.

I think first method is better, because  that way for 2000 cities I will have 2000 rows and 5 columns, in the second method I will have 8000 rows and 3 columns,

But in first method I need to update all the four columns,but in the second method I can maybe delete and insert one row.

Which is the better database design?

答:
Database design 2 is the best way. You have more control and great flexibility to manipulate the data, to make reports, and extend applications etc...

Says, what if you want to fetch the 5 weeks data, or more, instead of 4 weeks? For database design 2 you only need to modify the query:

```<code>SELECT city_id, temp FROM table WHERE date >= _last_n_week_sunday_date_
</code>```

Another things is, I may think you are creating a weather application, and trying to fetch the monthly average of temperature of each city, simpler query can get the report

```<code>SELECT city_id, YEAR(date), MONTH(date), AVG(temp) FROM table GROUP BY city_id, YEAR(date), MONTH(date)
</code>```

You may also want to store more attributes later of each city, says humidity. You only need to create 1 more column for database design 2. Instead, you may need to do more hard work to work with database design 1.

Body:
I want to show last four Sundays temperature for particular city, I need to update the database weekly (on Sundays)

Database Design 1

city_id     temp_pre_sunday1   temp_pre_sunday2   temp_pre_sunday3  temp_pre_sunday4
1                  24.3              35.2           24.4             28.0
2                  4.0                2.0           6.0              7.0

 .
2000

I can update the database each Sunday. Is this good database design?

Database Design 2

 city_id      temp   date
   1          24.3    2017-12-03
   1          35.2    2017-11-26
   1          24.4    2017-11-19
   1          28.0    2017-11-12
   2          4.0     2017-12-03
   2          2.0     2017-11-26
   2          6.0     2017-11-19
   2          7.0     2017-11-12
   .
   .

I need only four Sundays not more than that.

I think first method is better, because  that way for 2000 cities I will have 2000 rows and 5 columns, in the second method I will have 8000 rows and 3 columns,

But in first method I need to update all the four columns,but in the second method I can maybe delete and insert one row.

Which is the better database design?

Body:
Database design 2 is the best way. You have more control and great flexibility to manipulate the data, to make reports, and extend applications etc...

Says, what if you want to fetch the 5 weeks data, or more, instead of 4 weeks? For database design 2 you only need to modify the query:

SELECT city_id, temp FROM table WHERE date >= _last_n_week_sunday_date_

Another things is, I may think you are creating a weather application, and trying to fetch the monthly average of temperature of each city, simpler query can get the report

SELECT city_id, YEAR(date), MONTH(date), AVG(temp) FROM table GROUP BY city_id, YEAR(date), MONTH(date)

You may also want to store more attributes later of each city, says humidity. You only need to create 1 more column for database design 2. Instead, you may need to do more hard work to work with database design 1.


问:
Like button with Ajax
I am trying to create a like button with ajax.

This is my architecture:

models.py

```<code>class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    texto = models.CharField(max_length=200)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    fecha_publicacion = models.DateTimeField(auto_now_add=True)
    tag = models.ManyToManyField(Tags, blank=True)
    slug = models.SlugField(null=True)
    likes = models.ManyToManyField(Perfil, blank=True, related_name="likes")

    def __str__(self):
        return (self.titulo)

    @property
    def total_likes(self):
        return self.likes.count()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.titulo)
        super(Comentario, self).save(*args, **kwargs)
</code>```

views.py

```<code>def like(request):
    if request.method == 'POST':
        perfil = request.user
        slug = request.POST.get('slug', None)
        comentario = get_object_or_404(Comentario, slug=slug)

        if comentario.objects.filter(id=user.id).exists():
            comentario.likes.remove(user)

        else:
            comentario.likes.add(user)

    contexto = {'likes_count': comentario.total_likes }
    return HttpResponse(json.dumps(contexto), content_type='application/json')
</code>```

urls.py

```<code>url(r'^like$', login_required(like), name='like'),
</code>```

html

```<code><input type="button" id="like" name="{{ company_slug }}" value="Like" />
<script>
$('#like').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'home:like' %}",
               data: {'slug': $(this).attr('titulo'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert(' likes count is now ' + response.likes_count);
            },
                error: function(rs, e) {
                       alert(rs.responseText);
            }
      });
})
</script>
</code>```

When I push the button like it does not do anything. The console tells me:

POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found)

and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

What is the problem?

答:
Put JQuery script before ajax code:</p>

```<code><script src="jquery.js"></script>
$('#like').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'home:listar' %}",
               data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert(' likes count is now ' + response.likes_count);
            },
                error: function(rs, e) {
                       alert(rs.responseText);
            }
      });
})
</script>
</code>```

Title: Like button with Ajax

Body:
I am trying to create a like button with ajax.

This is my architecture:

models.py

class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    texto = models.CharField(max_length=200)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    fecha_publicacion = models.DateTimeField(auto_now_add=True)
    tag = models.ManyToManyField(Tags, blank=True)
    slug = models.SlugField(null=True)
    likes = models.ManyToManyField(Perfil, blank=True, related_name="likes")

    def __str__(self):
        return (self.titulo)

    @property
    def total_likes(self):
        return self.likes.count()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.titulo)
        super(Comentario, self).save(*args, **kwargs)

views.py

def like(request):
    if request.method == 'POST':
        perfil = request.user
        slug = request.POST.get('slug', None)
        comentario = get_object_or_404(Comentario, slug=slug)

        if comentario.objects.filter(id=user.id).exists():
            comentario.likes.remove(user)

        else:
            comentario.likes.add(user)

    contexto = {'likes_count': comentario.total_likes }
    return HttpResponse(json.dumps(contexto), content_type='application/json')

urls.py

url(r'^like$', login_required(like), name='like'),

html

<input type="button" id="like" name="{{ company_slug }}" value="Like" />

When I push the button like it does not do anything. The console tells me:

POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found)

and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

What is the problem?

Body:
Put JQuery script before ajax code:

<script src="jquery.js"></script>
$('#like').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'home:listar' %}",
               data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert(' likes count is now ' + response.likes_count);
            },
                error: function(rs, e) {
                       alert(rs.responseText);
            }
      });
})
</script>


问:
How to detect TCP connection lost?
I have crossplatform code I've written at the socket level on Linux and iPhone. It opens nonblocking sockets and connects to a server. Everything works great except sometimes when one of the client/server disconnects it halts exec via SIGPIPE on the other during a recv or send call.

That makes sense. On Linux I can use a flag to indicate to the OS lib not to raise SIGPIPE - then I can sense the error myself and handle it cleanly. That works fine

However on iPhone OS (and presumably osx which I later care about) there's no flag to indicate not to throw SIGPIPE. I can do signal(SIGPIPE, IGN); which seems to USUALLY stop it, but still sometimes I get it??? (This could be due to where I set that signal handling up - I may only do it on app start and I instead may have to do it every time the app becomes active??)

This all makes me feel like I'm catching the disconnect the wrong way - should I be using select() or friends to sense if a disconnect has occurred?? Specifically how can I do that?

答: You really should've googled for that one (for example, this page). In short, try using SO_NOPIPE socket option in addition to what you've already tried.</p>

Title: How to detect TCP connection lost?


问:
How to find "Docker Host URI" to be used in Jenkins "Docker Plugin"?
Is there any command which we can run and find out the "Docker Host URI"? I found some of related questions but didn't get it exactly. </p>

答:
Yes this is the docker host uri

tcp://127.0.0.1:2375

But before that you need to add this
DOCKER_OPTS="-H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock"

In /etc/default/docker at the end of file, then restart the docker.onec restarted docker.sock will run in 2375 and add this tcp://127.0.0.1:2375 in Jenkins


问:
Updating existing record for duplicate entry and inserting records for a new entry in INFLUX DB (Similar to ON DUPLICATE KEY UPDATE in MySQL)
I have a MySQL table where I update the existing records when there is a duplicate value and insert a new record when there is a new entry on some of the columns using 'ON DUPLICATE KEY UPDATE'.

```<code>INSERT INTO TestDB
                (col_1, col_2, col_3, col_4)
            VALUES
                (val_1, val_2, val_3, val_4)
            ON DUPLICATE KEY UPDATE
                col_2 = VALUES(col_2),
                col_3 = VALUES(col_3)
</code>```

Now, I need the exact case with influxdb also. But I can't find anything that will do the same with influx.

Influx measurement will be something like this

```<code>INSERT TestDB,col_1=val_1,col_2=val_2,col_3=val_3 col_4="val_4"
</code>```

In the current scenario with Influx DB, when I insert a duplicate record, it inserts a new record with obviously a new timestamp, but what I require is, to update the first record if it tries to insert a duplicate value (with new timestamp) and insert a new record only if val_2 and val_3 changes.

So, is there an 'ON DUPLICATE KEY UPDATE' equivalent in Influx DB to achieve the same result?

NB: I'm using using the influx command line in my local machine and the admin page (with 8083 port) to insert and query the measurements.

答:
InfluxDB updates the same record if all the tags(including time) in the record to be inserted into influx are duplicate no matter whether fields are different or not.

i.e., influx maintains the unique tags combination key

Body:
I have a MySQL table where I update the existing records when there is a duplicate value and insert a new record when there is a new entry on some of the columns using 'ON DUPLICATE KEY UPDATE'.

INSERT INTO TestDB
                (col_1, col_2, col_3, col_4)
            VALUES
                (val_1, val_2, val_3, val_4)
            ON DUPLICATE KEY UPDATE
                col_2 = VALUES(col_2),
                col_3 = VALUES(col_3)

Now, I need the exact case with influxdb also. But I can't find anything that will do the same with influx.

Influx measurement will be something like this

INSERT TestDB,col_1=val_1,col_2=val_2,col_3=val_3 col_4="val_4"

In the current scenario with Influx DB, when I insert a duplicate record, it inserts a new record with obviously a new timestamp, but what I require is, to update the first record if it tries to insert a duplicate value (with new timestamp) and insert a new record only if val_2 and val_3 changes.

So, is there an 'ON DUPLICATE KEY UPDATE' equivalent in Influx DB to achieve the same result?

NB: I'm using using the influx command line in my local machine and the admin page (with 8083 port) to insert and query the measurements.


问:
php xml schema formatting
I have a php page what post's a xml to Heartinternet API and after a long time I have got it to work but now I cant find away to only pull only one part out of the replyed XML

```<code>$some_xml = '<?xml version="1.0"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:package="http://www.heartinternet.co.uk/whapi/package-2.2">
  <command>
    <info>
      <package:info>
        <package:id>171371a16973b1bf</package:id>
      </package:info>
    </info>
    <extension>
      <ext-package:preAuthenticate xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2"/>
    </extension>
    <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
  </command>
</epp>';
</code>```

This is the code what is posted to the API. Full code can been seen here.

This is what I get back and can't figure out how to pull one line from the reply.

```<code><?xml version='1.0'?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2">
  <response>
    <result code='1000'>
      <msg>Command completed successfully</msg>
    </result>
    <resData>
      <ext-package:redirectURL>http://bobcp.example.org/sso.cgi?session=LUB9UNbw6jTW</ext-package:redirectURL>
    </resData>
    <trID>
      <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
      <svTRID>test-19272326601ef4c3bf6b64730d09c6cf</svTRID>
    </trID>
  </response>
</epp>
</code>```

The one line I need to show is ext-package:redirectURL.

If anyone could help me or point me in the right direction to find how to sort this I would be grateful!

答:
You can get the redirect url by registering the namespace urn:ietf:params:xml:ns:epp-1.0 and then you could use an xpath expression for example. In this case, I have chosen u as the prefix.

/u:epp/u:response/u:resData/ext-package:redirectURL

Using SimpleXML with your returned xml:

The response xml from the comments is slightly different. This is the updated code:

```<code>$returned_xml->registerXPathNamespace('u', 'urn:ietf:params:xml:ns:epp-1.0');
$returned_xml->registerXPathNamespace('ext-package', 'http://www.heartinternet.co.uk/whapi/ext-package-2.2');
$redirectUrl = $returned_xml->xpath('/u:epp/u:response/u:resData/ext-package:redirectURL');
echo $redirectUrl[0];
</code>```

Or with DOMDocument:

```<code>$doc = new DOMDocument();
$doc->loadXML(file_get_contents("https://custom-hosting.co.uk/source/test.php"));
$xpath = new DOMXpath($doc);
$xpath->registerNamespace('u', 'urn:ietf:params:xml:ns:epp-1.0');
$xpath->registerNamespace('ext-package', 'http://www.heartinternet.co.uk/whapi/ext-package-2.2');
$redirectUrl = $xpath->query('/u:epp/u:response/u:resData/ext-package:redirectURL')->item(0)->nodeValue;

echo $redirectUrl;
</code>```

That will give you for example:

http://bobcp.example.org/sso.cgi?session=LUB9UNbw6jTW

Title: php xml schema formatting

Body:
I have a php page what post's a xml to Heartinternet API and after a long time I have got it to work but now I cant find away to only pull only one part out of the replyed XML

$some_xml = '<?xml version="1.0"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:package="http://www.heartinternet.co.uk/whapi/package-2.2">
  <command>
    <info>
      <package:info>
        <package:id>171371a16973b1bf</package:id>
      </package:info>
    </info>
    <extension>
      <ext-package:preAuthenticate xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2"/>
    </extension>
    <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
  </command>
</epp>';

This is the code what is posted to the API. Full code can been seen here.

This is what I get back and can't figure out how to pull one line from the reply.

<?xml version='1.0'?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:ext-package="http://www.heartinternet.co.uk/whapi/ext-package-2.2">
  <response>
    <result code='1000'>
      <msg>Command completed successfully</msg>
    </result>
    <resData>
      <ext-package:redirectURL>http://bobcp.example.org/sso.cgi?session=LUB9UNbw6jTW</ext-package:redirectURL>
    </resData>
    <trID>
      <clTRID>fac89208bea460fa3fef11b22a519cce</clTRID>
      <svTRID>test-19272326601ef4c3bf6b64730d09c6cf</svTRID>
    </trID>
  </response>
</epp>

The one line I need to show is ext-package:redirectURL.

If anyone could help me or point me in the right direction to find how to sort this I would be grateful!

Body:
You can get the redirect url by registering the namespace urn:ietf:params:xml:ns:epp-1.0 and then you could use an xpath expression for example. In this case, I have chosen u as the prefix.

/u:epp/u:response/u:resData/ext-package:redirectURL

Using SimpleXML with your returned xml:

The response xml from the comments is slightly different. This is the updated code:

$returned_xml->registerXPathNamespace('u', 'urn:ietf:params:xml:ns:epp-1.0');
$returned_xml->registerXPathNamespace('ext-package', 'http://www.heartinternet.co.uk/whapi/ext-package-2.2');
$redirectUrl = $returned_xml->xpath('/u:epp/u:response/u:resData/ext-package:redirectURL');
echo $redirectUrl[0];

Or with DOMDocument:

$doc = new DOMDocument();
$doc->loadXML(file_get_contents("https://custom-hosting.co.uk/source/test.php"));
$xpath = new DOMXpath($doc);
$xpath->registerNamespace('u', 'urn:ietf:params:xml:ns:epp-1.0');
$xpath->registerNamespace('ext-package', 'http://www.heartinternet.co.uk/whapi/ext-package-2.2');
$redirectUrl = $xpath->query('/u:epp/u:response/u:resData/ext-package:redirectURL')->item(0)->nodeValue;

echo $redirectUrl;

That will give you for example:

http://bobcp.example.org/sso.cgi?session=LUB9UNbw6jTW


问:
Converting linear scale to log scale in java
I looked and found one post which helped me here:
Convert Linear scale to Logarithmic

However I either did some mistake I can't find or I got wrong idea of the formula. I want to convert any number from linear 1-256 range to their respective values if it was logarithmic scale. Can someone help me to correct my code? When i try values low values from zero it works kind of fine but trying to convert anything over 160 gets me result which is > 256.
Here is my code:

```<code>package linear2log;

public class Linear2Log {

    public static void main(String[] args) {

        System.out.println("Ats3: " + lin2log(160));
    }

    public static long lin2log(int z) {
        int x = 1;
        int y = 256;
        double b = Math.log(y/x)/(y-x);
        double a = 10 / Math.exp(b*10);
        double tempAnswer = a * Math.exp(b*z);
        long finalAnswer = Math.max(Math.round(tempAnswer) - 1, 0);

        return finalAnswer;
    }
}
</code>```

答:
You get the formula wrong.

For sure this line

```<code>double a = 10 / Math.exp(b*10);
</code>```

You are using value 10 from example, but you should be using your value which is 256.

```<code>double a = y / Math.exp(b * y);
</code>```

I don't get why are you using this line:

```<code> long finalAnswer = Math.max(Math.round(tempAnswer) - 1, 0);
</code>```

This way you are always getting value that is one less than actual value.

Body:
I looked and found one post which helped me here:
Convert Linear scale to Logarithmic

However I either did some mistake I can't find or I got wrong idea of the formula. I want to convert any number from linear 1-256 range to their respective values if it was logarithmic scale. Can someone help me to correct my code? When i try values low values from zero it works kind of fine but trying to convert anything over 160 gets me result which is > 256.
Here is my code:

package linear2log;

public class Linear2Log {

    public static void main(String[] args) {

        System.out.println("Ats3: " + lin2log(160));
    }

    public static long lin2log(int z) {
        int x = 1;
        int y = 256;
        double b = Math.log(y/x)/(y-x);
        double a = 10 / Math.exp(b*10);
        double tempAnswer = a * Math.exp(b*z);
        long finalAnswer = Math.max(Math.round(tempAnswer) - 1, 0);

        return finalAnswer;
    }
}

Body:
You get the formula wrong.

For sure this line

double a = 10 / Math.exp(b*10);

You are using value 10 from example, but you should be using your value which is 256.

double a = y / Math.exp(b * y);

I don't get why are you using this line:

 long finalAnswer = Math.max(Math.round(tempAnswer) - 1, 0);

This way you are always getting value that is one less than actual value.


问:
What's the point using "git add <file>" if you can just use "git add ." everytime?
If I add say 2 new files. Is there any advantage to using the former over the latter? Or is it just useless syntax?</p>

答: git add <file> allows you to add only a specific file. Imagine you did some changes on the config file of your project to enable a feature flag, or to change a DB setting. you probably don't want that change to be committed.


问:
Is there a way to execute JavaScript in Perl?
I've worked some years now in Perl building Web scrapers, and given the problem that spam represents, and how scraping Web pages would turn out to be much more easier to those folks if, for example, Perl's LWP::UserAgent could handle its cup of JavaScript, I'm amazed no one has built a JS engine for it yet.

What am I missing here?

Thanks in advance. Regards.

PS: I'm not a spammer. Just curious.

答:
You can try to install SpiderMonkey and -in your perl program-  execute javascript in backticks, and capture the result, just like from any other unix command line tool. Spidermonkey has a command line option for that, similar to perl's -e command line option. The spidermonkey binary is called "js", thus:

/path/to/spidermonkey/bin/js -e "print(10);"

> 10

I think you can also install v8-shell as an alternative engine, but then you must install 'scons' first, which is available on unix-only.

./v8-shell -e 'print("10*10 = " + 10*10)'


问:
Trying to create hyperlinks in the <text-angular> with ng-change but when user paste URL, it moves cursor to the start
```<code><text-angular name="myEditor" class="deal-notes" ta-
toolbar-class="btn-toolbar pull-right" ng-model-options="{ debounce: 500}"
ng-change="updateDeal('deal.notes');" ng-blur="makeLinks()" ta-toolbar-
group-class="btn-group" ta-toolbar="[['bold','italics', 'insertLink']]" ng-
model="deal.notes">
</code>```

Trying to create hyperlinks in the  with ng-change but when user paste URL, it moves cursor to the start.

```<code><script>
    function makeLinks(){
        var linkedText = Autolinker.link($scope.deal.notes, {stripPrefix: false});
        $scope.deal.notes = linkedText;
        updateDeal('deal.notes');
    }
<script>
</code>```

答:
What you need to do, is to store the position of caret before you make any modifications to the html/text. After the changes have been made, you set the caret back to the original position (or you calculate the new position according to changes)

So modify the makeLinks() function like this

```<code>function makeLinks()
    {
      var caretPosition = editorElement.prop("selectionStart");
      var linkedText = Autolinker.link($scope.deal.notes, {stripPrefix: false});
      $scope.deal.notes = linkedText;
      updateDeal('deal.notes');

      // set the cursor back to correct position
      editorElement.setSelectionRange(caretPosition, caretPosition);
    }
</code>```

Body:
<text-angular name="myEditor" class="deal-notes" ta-
toolbar-class="btn-toolbar pull-right" ng-model-options="{ debounce: 500}"
ng-change="updateDeal('deal.notes');" ng-blur="makeLinks()" ta-toolbar-
group-class="btn-group" ta-toolbar="[['bold','italics', 'insertLink']]" ng-
model="deal.notes">

Trying to create hyperlinks in the  with ng-change but when user paste URL, it moves cursor to the start.

Body:
What you need to do, is to store the position of caret before you make any modifications to the html/text. After the changes have been made, you set the caret back to the original position (or you calculate the new position according to changes)

So modify the makeLinks() function like this

function makeLinks()
    {
      var caretPosition = editorElement.prop("selectionStart");
      var linkedText = Autolinker.link($scope.deal.notes, {stripPrefix: false});
      $scope.deal.notes = linkedText;
      updateDeal('deal.notes');

      // set the cursor back to correct position
      editorElement.setSelectionRange(caretPosition, caretPosition);
    }


问:
How to handle a line break in SQL and Python to appropriately return all lines?
A string with a line break, e.g. first line here[linebreak]NEXT ONE is entered in a GUI-tool and read into an SQL server database where it appears to be a one line string, i.e. first line here NEXT ONE. However, if this field is read by Python, it is returned as NEXT ONEne here. It seems that the line break is registered somehow, but the handling is wrong as both lines are written on the same line. How to handle the line break in this chain GUI-SQL-Python to appropriately return both lines?

答:
In case that you use MySQL you can use the escape_string method of mysqldb: https://dev.mysql.com/doc/connector-python/en/connector-python-api-cext-escape-string.html

This will escape the new line character (e.g. \n) before storing it into your database.

Consider using a debugger (e.g.pdb  or pudb) to examin the string you store into and the one you receive from the database.


问:
How to redirect 404 page to home page in magento
I am trying to redirect 404 page to home page in magento 1.9.

From admin config->web I can set in 'cms no page' to 'Home Page' option and it is redirecting properly.

Like, 'www.example.com/abcv' which is 404 page, this redirecting to home page but in browser url is not changing.

I have tried .htaccess to ,

ErrorDocument 404 /index.php

but its not working,

ANy suggestion would be great.

答: Please see 404-Error-To-Home Page-Redirection.png


问:
updated table and related table in Laravel
In Laravel I have relation:

```<code> class Address extends Model
{
    protected $fillable = [
      'street', 'city', 'post_code', 'country', 'state',
    ];

    public function companies() {
      return $this->hasMany('App\Company');
    }
}
</code>```

```<code>class Company extends Model
{
    protected $fillable = [
      'name',  'nip', 'email', 'phone', 'address_id'
    ];

    public function address() {
      return $this->belongsTo('App\Address');
    }
}
</code>```

and in CompaniesController.php I want to do update tables. My code looks like this:

```<code>public function update(Request $request, $id)
    {
  Company::where('id', $id)->update([
          'name' => $request->name,
          'email' => $request->email,
          'phone' => $request->phone,
          'nip' => $request->nip,
        ]);
}
</code>```

How to also update the address associated with this company?

答:
If the ID is your primary key, you should use find instead of where, as the former will guarantee that you only retrieve one row.

You can then query the relationship of your Company model, using the following code:

```<code>$company = Company::find($id);
$company->update([
      'name' => $request->name,
      'email' => $request->email,
      'phone' => $request->phone,
      'nip' => $request->nip,
]);
$company->address()->update([
    'street' => 'street value',
    'city' => 'city value',
    'post_code' => 'post_code value',
    'country' => 'country value',
    'state' => 'state value',
]);
</code>```

Please refer to the laravel docs

Body:
In Laravel I have relation:

 class Address extends Model
{
    protected $fillable = [
      'street', 'city', 'post_code', 'country', 'state',
    ];

    public function companies() {
      return $this->hasMany('App\Company');
    }
}

class Company extends Model
{
    protected $fillable = [
      'name',  'nip', 'email', 'phone', 'address_id'
    ];

    public function address() {
      return $this->belongsTo('App\Address');
    }
}

and in CompaniesController.php I want to do update tables. My code looks like this:

public function update(Request $request, $id)
    {
  Company::where('id', $id)->update([
          'name' => $request->name,
          'email' => $request->email,
          'phone' => $request->phone,
          'nip' => $request->nip,
        ]);
}

How to also update the address associated with this company?

Body:
If the ID is your primary key, you should use find instead of where, as the former will guarantee that you only retrieve one row.

You can then query the relationship of your Company model, using the following code:

$company = Company::find($id);
$company->update([
      'name' => $request->name,
      'email' => $request->email,
      'phone' => $request->phone,
      'nip' => $request->nip,
]);
$company->address()->update([
    'street' => 'street value',
    'city' => 'city value',
    'post_code' => 'post_code value',
    'country' => 'country value',
    'state' => 'state value',
]);

Please refer to the laravel docs


问:
Angular2 How to navigate to certain section of the page identified with an id attribute
How to navigate to certain section of the page identified with an id attribute?

Example:

I need to navigate to "structure" paragraph on my page

```<code><div id="info">
  <h3>Info</h3>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<div id="structure">
  <h3>Structure</h3>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</code>```

And I have a following navigation structure:

```<code><li>
  <ul materialize="collapsible" class="collapsible" data-collapsible="accordion">
    <li><a routerLink="policies" class="collapsible-header">Policies</a>
      <div class="collapsible-body">
         <ul>
           <li><a >Info</a></li>
           <li><a >Structure</a></li>
           <li><a >Something Else</a></li>
         </ul>
      </div>
    </li>
   </ul>
 </li>
</code>```

It is my understanding that in Angular1.0 I simply could've navigate to the page section using something like: ui-sref="policies({'#':'structure'})"  or href="#structure"  or ui-sref="policies" href="#structure"...

How can I do it in Angular2? I looked at the Fragment example in the docs: Query Parameters and Fragments section and I am finding they example to be very confusing and a bit overkill for such a potentially simple task

答:
Angular 2: I would prefer to go with scrollIntoView() method scrollIntoView. It would provide smooth scrolling transition effect in the browser.

HTML Code

Info

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Structure

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Policies

Info

Structure

Something Else

```
<p>and in the Component.</p>

<pre class="lang-ts prettyprint-override"><code>  @Component({
    selector: 'my-app',
    template: `template.html        `
  })
  export class AppComponent {
    @ViewChild('structure') public structure : ElementRef;

    @ViewChild('info') public info : ElementRef;

    public moveToStructure():void {
            this.structure.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
    }

    public infoStruc():void {
        setImmediate(() => {
            this.info.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
        });
    }
}
</code>```

Body:
How to navigate to certain section of the page identified with an id attribute?

Example:

I need to navigate to "structure" paragraph on my page

Info

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Structure

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

And I have a following navigation structure:

Policies

Info

Structure

Something Else

It is my understanding that in Angular1.0 I simply could've navigate to the page section using something like: ui-sref="policies({'#':'structure'})"  or href="#structure"  or ui-sref="policies" href="#structure"...

How can I do it in Angular2? I looked at the Fragment example in the docs: Query Parameters and Fragments section and I am finding they example to be very confusing and a bit overkill for such a potentially simple task

Body:
Angular 2: I would prefer to go with scrollIntoView() method scrollIntoView. It would provide smooth scrolling transition effect in the browser.

HTML Code

    <div #info id="info">
        <h3>Info</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
    <div #structure  id="structure">
        <h3>Structure</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>

  <li>
    <ul materialize="collapsible" class="collapsible" data-collapsible="accordion">
      <li><a routerLink="policies" class="collapsible-header">Policies</a>
        <div class="collapsible-body">
           <ul>
             <li (click)="infoStruc()"><a >Info</a></li>
             <li (click)="moveToStructure()"><a  >Structure</a></li>
             <li><a >Something Else</a></li>
         </ul>
       </div>
     </li>
   </ul>
 </li>

and in the Component.

  @Component({
    selector: 'my-app',
    template: `template.html        `
  })
  export class AppComponent {
    @ViewChild('structure') public structure : ElementRef;

    @ViewChild('info') public info : ElementRef;

    public moveToStructure():void {
            this.structure.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
    }

    public infoStruc():void {
        setImmediate(() => {
            this.info.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
        });
    }
}


问:
NixOS - Module imports with arguments
Let's say I have my NixOS configuration.nix set up as follows:

```<code>{config, pkgs, ...}:
{
  services.openssh.enable = true;
}
</code>```

I now want to have a second file called networking.nix which sets my hostname based on an argument.

```<code>{config, pkgs, hostname, ...}:
{
  networking.hostName = hostname
}
</code>```

Is this possible? How can I include the file. I already tried doing it by using imports = [ ./networking.nix { hostname = "helloworld"; } ]; but that didn't work.

Thanks.

答:
You should be able to use the _module.argsoption [1] to do that. So your configuration.nix would be like:

```<code>{config, pkgs, ...}:
{
  _module.args.hostname = "ahostname";
  services.openssh.enable = true;
}
</code>```

However where the values are very simple it will probably be much easier to just set them directly, e.g. just define networking.hostname in configuration.nix. This section of the manual re. merging and priorities may be helpful also [2].

Further discussion:

The value of _module.args is indeed applied to all imported configurations (though the value will only be used in modules that directly refer to it, such as the pkgs value, the ... represents all the values that aren't referenced).

For passing arguments to modules it seems a good approach to me, but from your comments perhaps a different approach might be more suitable.

Another solution could be to flip the relationship in the imports: rather than a single common config that passes multiple different arguments instead multiple different configs import the common configuration. E.g.

```<code>$cat ./common.nix
{ services.openssh.enable = true; }
$cat ./ahostname.nix
{ imports = [ ./common.nix ]; networking.hostname = "ahostname"; }
</code>```

The NixOS config in this Reddit comment looks like it uses this approach. There are quite a few other NixOS configurations that people have shared publicly online so you might find some useful ideas there. The points in the answer from Robert Hensing are very useful to bear in mind as well.

However it's hard to say what might be a better solution in your case without knowing a bit more about the context in which you want to use it. You could create a new SO question with some more information on that which might make it easier to see a more appropriate solution.

Title: NixOS - Module imports with arguments

Body:
Let's say I have my NixOS configuration.nix set up as follows:

{config, pkgs, ...}:
{
  services.openssh.enable = true;
}

I now want to have a second file called networking.nix which sets my hostname based on an argument.

{config, pkgs, hostname, ...}:
{
  networking.hostName = hostname
}

Is this possible? How can I include the file. I already tried doing it by using imports = [ ./networking.nix { hostname = "helloworld"; } ]; but that didn't work.

Thanks.

Body:
You should be able to use the _module.argsoption [1] to do that. So your configuration.nix would be like:

{config, pkgs, ...}:
{
  _module.args.hostname = "ahostname";
  services.openssh.enable = true;
}

However where the values are very simple it will probably be much easier to just set them directly, e.g. just define networking.hostname in configuration.nix. This section of the manual re. merging and priorities may be helpful also [2].

Further discussion:

The value of _module.args is indeed applied to all imported configurations (though the value will only be used in modules that directly refer to it, such as the pkgs value, the ... represents all the values that aren't referenced).

For passing arguments to modules it seems a good approach to me, but from your comments perhaps a different approach might be more suitable.

Another solution could be to flip the relationship in the imports: rather than a single common config that passes multiple different arguments instead multiple different configs import the common configuration. E.g.

$cat ./common.nix
{ services.openssh.enable = true; }
$cat ./ahostname.nix
{ imports = [ ./common.nix ]; networking.hostname = "ahostname"; }

The NixOS config in this Reddit comment looks like it uses this approach. There are quite a few other NixOS configurations that people have shared publicly online so you might find some useful ideas there. The points in the answer from Robert Hensing are very useful to bear in mind as well.

However it's hard to say what might be a better solution in your case without knowing a bit more about the context in which you want to use it. You could create a new SO question with some more information on that which might make it easier to see a more appropriate solution.


问:
How to detemine learning rate during training neural network?
If I want to use manual learning rate, for example, initial learning rate is 0.01, after 10000 steps, decay learning rate to 0.001, and after 20000 steps, decay learning rate to 0.0001.

How can I know these steps I need to decay learning rate? Is there any experience can guide me?

We usually can find these steps in paper, but how does author get these steps?

答:
A good initial learning rate is one that is as high as possible without causing the error to diverge. This is found by trial and error. Guess some typical initial learning rate like 0.01, run a few epochs and see what happens. If the error is diverging then divide by 10, otherwise multiply by 10. Settle on the highest value before you run into divergent error.

A good time to lower the learning rate is when you notice the error does not seem to be improving anymore. For example you run 100 epochs at lr=0.01 and the error is plateauing. Try reducing your learning rate to 0.001.

You can also consider using learning rate decay where you set a schedule to decay the learning rate automatically.


问:
Background image not loading
I am new to html/css and I do not understand why my background image is not showing up. This is part of a simple test CSS sheet and HTML code for a simple site. I am trying to add a background-image and I have done this once and it worked and I do not know why it does not work now.</p>

```<code>.timeline{
    width: 100%;
    height: 400px;
    display: inline-flex;
    background-image:url("img/back.jpg");
}
</code>```

答:
```<code>.timeline{
  width: 100%;
  height: 400px;
  display: inline-flex;
  background-image:url("./img/back.jpg");

}
</code>```

Title: Background image not loading

Body:
I am new to html/css and I do not understand why my background image is not showing up. This is part of a simple test CSS sheet and HTML code for a simple site. I am trying to add a background-image and I have done this once and it worked and I do not know why it does not work now.

.timeline{
    width: 100%;
    height: 400px;
    display: inline-flex;
    background-image:url("img/back.jpg");
}


问:
Ajax function working on local but not online
Here is my problem, I have a AJAX function which is working on my local server but don't return anything when I put it on my online server.

Here is my code :

Here the page where I call the function showEspece() :

echo "
";
     echo "
\n";
            echo "
\n";
                echo " Nom 	\n";
                echo " Nombre 	\n";
            echo "
\n";
      while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
          echo "
\n";
           foreach ($row as $item) {
               echo "    " . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "	\n";
           } ?>
                        <td class='tdAnimal' onclick="showEspece(<?php echo "'";echo $row['ESPECE'];echo "'";?>, <?php echo "'";echo $categorie;echo "'";?>,this);" >	 <?php
          echo "
\n";
      }
     echo "
\n\n";
    echo '
';```
</div>
</div>
</p>

<p>Here is the Ajax function :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function showEspece(espece, categorie, object)
  {
    $.ajax({
      type : 'POST',
      url: 'getespece.php',
      data: {espece: espece, categorie: categorie },
      dataType: 'json',
      success: function(data)
      {
        alert('ok');
        var tableau = data;
        $('#output').html(tableau);
      },
      error: function(xhr, status, error) {
        console.log(xhr);
      }
    });
  }</code>```

Here is the page call by the Ajax function :

<?php
     include("/includes/connexionBD.php");
         include("includes/entetepage.php");

    $requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

 oci_execute($requete);

     $table = "
\n";
            $table .= "
\n";
                $table .= " Nom 	\n";
                $table .= " Sexe 	\n";
                $table .= " Date naissance 	\n";
            $table .= "
\n";
      while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
          $table .= "
\n";
           foreach ($row as $item) {
               $table .= "    " . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "	\n";
           }
          $table .= "
\n";
      }
     $table .= "
\n\n";

     echo json_encode($table);
?>```
</div>
</div>
</p>

<p>And that is what error I get on the consol :</p>

```VM1130:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.error (ajax.js:16)
at i (jQuery.js:2)
at Object.fireWith [as rejectWith] (jQuery.js:2)
at A (jQuery.js:4)
at XMLHttpRequest.<anonymous> (jQuery.js:4)
```

Does someone know where the problem can come from and can help me ?

Sorry fo my bad english :/

答:
The issue here is that your JSON response is malformed, you could try getting the output JSON and put it through a linter to find where the problem actually is:

https://jsonlint.com/

I would recommend not building the HTML (your table) in PHP but building it using Javascript and injecting the data from the Ajax request into the table.

Body:
Here is my problem, I have a AJAX function which is working on my local server but don't return anything when I put it on my online server.

Here is my code :

Here the page where I call the function showEspece() :

echo "
";
     echo "
\n";
            echo "
\n";
                echo " Nom 	\n";
                echo " Nombre 	\n";
            echo "
\n";
      while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
          echo "
\n";
           foreach ($row as $item) {
               echo "    " . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "	\n";
           } ?>
                        <td class='tdAnimal' onclick="showEspece(<?php echo "'";echo $row['ESPECE'];echo "'";?>, <?php echo "'";echo $categorie;echo "'";?>,this);" >	 <?php
          echo "
\n";
      }
     echo "
\n\n";
    echo '
';

Here is the Ajax function :

function showEspece(espece, categorie, object)
  {
    $.ajax({
      type : 'POST',
      url: 'getespece.php',
      data: {espece: espece, categorie: categorie },
      dataType: 'json',
      success: function(data)
      {
        alert('ok');
        var tableau = data;
        $('#output').html(tableau);
      },
      error: function(xhr, status, error) {
        console.log(xhr);
      }
    });
  }

Here is the page call by the Ajax function :

<?php
     include("/includes/connexionBD.php");
         include("includes/entetepage.php");

    $requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

 oci_execute($requete);

     $table = "
\n";
            $table .= "
\n";
                $table .= " Nom 	\n";
                $table .= " Sexe 	\n";
                $table .= " Date naissance 	\n";
            $table .= "
\n";
      while ($row = oci_fetch_array($requete, OCI_ASSOC+OCI_RETURN_NULLS)) {
          $table .= "
\n";
           foreach ($row as $item) {
               $table .= "    " . ($item !== null ? htmlentities($item, ENT_QUOTES) : "") . "	\n";
           }
          $table .= "
\n";
      }
     $table .= "
\n\n";

     echo json_encode($table);
?>

And that is what error I get on the consol :

VM1130:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.error (ajax.js:16)
at i (jQuery.js:2)
at Object.fireWith [as rejectWith] (jQuery.js:2)
at A (jQuery.js:4)
at XMLHttpRequest.<anonymous> (jQuery.js:4)

Does someone know where the problem can come from and can help me ?

Sorry fo my bad english :/


问:
Xamarin Forms error while writing anim R$anim.class
Hello i am update to visual studio community 2017 15.5 on debug i have this error</p>

```<code>obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error
</code>```

答: Deleting the obj folder inside project and restarting fix the issue. But it keeps on coming every time i add a folder on Resources or something</p>

Body:
Hello i am update to visual studio community 2017 15.5 on debug i have this error

obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error


问:
How to validate 8 to 10 digit long phone number?
In my android application, phone number field used. 8 to 10 digit input value given by the user. How to validate  8 to 10 digit phone number using PHONE_REGEX?

I have already tried this method,

```<code>private static final String PHONE_REGEX = "\\d{8-10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
</code>```

答:
Use this

```<code>private static final String PHONE_REGEX = "\\d{8,10}";

public static boolean isPhoneNumber(EditText editText, boolean required) {
return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
</code>```

instead of

```<code>private static final String PHONE_REGEX = "\\d{8-10}";

public static boolean isPhoneNumber(EditText editText, boolean required) {
return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
</code>```

only one small mistake.Before ask a question,refer previous stack answers.

Body:
In my android application, phone number field used. 8 to 10 digit input value given by the user. How to validate  8 to 10 digit phone number using PHONE_REGEX?

I have already tried this method,

private static final String PHONE_REGEX = "\\d{8-10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}

Body:
Use this

private static final String PHONE_REGEX = "\\d{8,10}";

public static boolean isPhoneNumber(EditText editText, boolean required) {
return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}

instead of

private static final String PHONE_REGEX = "\\d{8-10}";

public static boolean isPhoneNumber(EditText editText, boolean required) {
return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}

only one small mistake.Before ask a question,refer previous stack answers.


问:
Node.js binary to PDF
I have got a express server, which creates a pdf file.

I am trying to send this file to the client:

const fs = require('fs');

function download(req, res) {
  var filePath = '/../../myPdf.pdf';

  fs.readFile(__dirname + filePath, function(err, data) {
    if (err) throw new Error(err);
    console.log('yeyy, no errors :)');

    if (!data) throw new Error('Expected data, but got', data);
    console.log('got data', data);

    res.contentType('application/pdf');
    res.send(data);
  });
}```
</div>
</div>
</p>

<p>On the client I want to download it:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  _handleDownloadAll = async () => {
    console.log('handle download all');
    const response = await request.get(
      `http://localhost:3000/download?accessToken=${localStorage.getItem(
        'accessToken'
      )}`
    );

    console.log(response);
  };</code>```

I recieve an body.text like

%PDF-1.4↵1 0 obj↵<<↵/Title (��)↵/Creator (��)↵/Producer (��Qt 5.5.1)↵```
</div>
</div>
</p>

<p>but I can't achieve a download. </p>

<p>How can I create a PDF from the data OR directly download it from the server?</p>

<p><strong>I've got it working:</strong>
The answer was pretty simple. I just let the browser handle the download with an html anchor tag:
server:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function download(req, res) {
  const { creditor } = req.query;
  const filePath =  `/../../${creditor}.pdf`;

  res.download(__dirname + filePath);
}</code>```

client:

Download```

答:
You can prompt the browser to download the file by setting the correct content-disposition header:</p>

```<code>res.setHeader('Content-disposition', 'attachment; filename=myfile.pdf');
</code>```

Title: Node.js binary to PDF

Body:
I have got a express server, which creates a pdf file.

I am trying to send this file to the client:

const fs = require('fs');

function download(req, res) {
  var filePath = '/../../myPdf.pdf';

  fs.readFile(__dirname + filePath, function(err, data) {
    if (err) throw new Error(err);
    console.log('yeyy, no errors :)');

    if (!data) throw new Error('Expected data, but got', data);
    console.log('got data', data);

    res.contentType('application/pdf');
    res.send(data);
  });
}

On the client I want to download it:

  _handleDownloadAll = async () => {
    console.log('handle download all');
    const response = await request.get(
      `http://localhost:3000/download?accessToken=${localStorage.getItem(
        'accessToken'
      )}`
    );

    console.log(response);
  };

I recieve an body.text like

%PDF-1.4↵1 0 obj↵<<↵/Title (��)↵/Creator (��)↵/Producer (��Qt 5.5.1)↵

but I can't achieve a download.

How can I create a PDF from the data OR directly download it from the server?

I've got it working:
The answer was pretty simple. I just let the browser handle the download with an html anchor tag:
server:

function download(req, res) {
  const { creditor } = req.query;
  const filePath =  `/../../${creditor}.pdf`;

  res.download(__dirname + filePath);
}

client:

<a href{`${BASE_URL}?accessToken=${accessToken}&creditor=${creditorId}`} download>Download

Body:
You can prompt the browser to download the file by setting the correct content-disposition header:

res.setHeader('Content-disposition', 'attachment; filename=myfile.pdf');


问:
How to neural network differentiate between images in flatten rows
I am learning from the below website

http://cs231n.github.io/classification/

I want to understand how neural network differentiate the images.

```<code>Xtr, Ytr, Xte, Yte = load_CIFAR10('data/cifar10/') # a magic function we provide
# flatten out all images to be one-dimensional
Xtr_rows = Xtr.reshape(Xtr.shape[0], 32 * 32 * 3) # Xtr_rows becomes 50000 x 3072
Xte_rows = Xte.reshape(Xte.shape[0], 32 * 32 * 3) # Xte_rows becomes 10000 x 3072
</code>```

For example here we have 50000 training examples, but when we flatten it
it becomes 50000 x 3072, it is just numbers how neural network understands
which is the first image, which is second image etc.

答:
In your dataset you have 50000 images with 32x32 pixels and 3 channels.

Flattening means that you transform each image into a one-dimensional vector.

Each image contains 32x32x3 = 3072 values. So after this step you have an array of 50000 vectors with 3072 elements each.

The first image is the first element in Xtr_rows. That's how the computer knows.

And yes neural networks as any other computer program are just crunching numbers.

Body:
I am learning from the below website

http://cs231n.github.io/classification/

I want to understand how neural network differentiate the images.

Xtr, Ytr, Xte, Yte = load_CIFAR10('data/cifar10/') # a magic function we provide
# flatten out all images to be one-dimensional
Xtr_rows = Xtr.reshape(Xtr.shape[0], 32 * 32 * 3) # Xtr_rows becomes 50000 x 3072
Xte_rows = Xte.reshape(Xte.shape[0], 32 * 32 * 3) # Xte_rows becomes 10000 x 3072

For example here we have 50000 training examples, but when we flatten it
it becomes 50000 x 3072, it is just numbers how neural network understands
which is the first image, which is second image etc.


问:
How to sum n % of values in Postgres
How to sum let's say 50 % of all values ordered by value in my Postgres table?

In table I have values 1, 2, 3, 4, 5, 6 and I'd like to get the sum of half values ordered by value DESC. So the result would be 4 + 5 + 6 = 15

Also, I might want to get only 1/3 of values so I would get 6 + 5 = 11

Is it possible with SQL in Postgres? Something like

```<code>SELECT sum(value)
FROM (
       SELECT value
       FROM table
       ORDER BY value DESC
       LIMIT 50%
     ) subquery
</code>```

答:
I would use row_number() and count():

```<code>SELECT sum(value)
FROM (SELECT value, ROW_NUMBER() OVER (ORDER BY value) as seqnum,
             COUNT(*) OVER () as cnt
      FROM table
     ) subquery
WHERE seqnum <= cnt * 0.5;
</code>```

Title: How to sum n % of values in Postgres

Body:
How to sum let's say 50 % of all values ordered by value in my Postgres table?

In table I have values 1, 2, 3, 4, 5, 6 and I'd like to get the sum of half values ordered by value DESC. So the result would be 4 + 5 + 6 = 15

Also, I might want to get only 1/3 of values so I would get 6 + 5 = 11

Is it possible with SQL in Postgres? Something like

SELECT sum(value)
FROM (
       SELECT value
       FROM table
       ORDER BY value DESC
       LIMIT 50%
     ) subquery

Body:
I would use row_number() and count():

SELECT sum(value)
FROM (SELECT value, ROW_NUMBER() OVER (ORDER BY value) as seqnum,
             COUNT(*) OVER () as cnt
      FROM table
     ) subquery
WHERE seqnum <= cnt * 0.5;


问:
Reason for icons (icon fonts) always in ::before pseudo-selector
Is there a reason, so many icon-Libraries (Glyhpicon, Font Awesome, Antd icons,…) put their icon in the ::before–pseudo selector? (rather than in the tag directly?)

```<code>i::before {
    content: '\E60A';
    ...
}
</code>```

答:
Is there a reason, so many icon-Libraries (Glyhpicon, Font Awesome, Antd icons,…) put their icon in the ::before–pseudo selector?

That method has several advantages ...

makes it trivial to switch a specific icon for a different character throughout the whole site via CSS

such icons are mostly used rather as “decoration” than actual content (so this touches on the issue of accessibility as well)

you can't insert content in an actual element itself, that is reserved for pseudo elements (thanks @Mr Lister for this one)

Body:
Is there a reason, so many icon-Libraries (Glyhpicon, Font Awesome, Antd icons,…) put their icon in the ::before–pseudo selector? (rather than in the tag directly?)

i::before {
    content: '\E60A';
    ...
}


问:
How can I reformat XAML nicely in VS 2008?
Visual Studio 2008's XAML editor (SP1) cannot reformat the XML into a consistent style.

Which tools can I use to get a nicely formatted XAML file? Studio integration preferred.

答: Have you tried CTRL + K , D?!

OwnerDisplayName: David Schmitt

LastEditorDisplayName: David Schmitt

Body: Have you tried CTRL + K , D?!

OwnerDisplayName: Jonathan Holland