问:
How to make Table in PHP
I want to make table with this result (look Echo),  When I put it in the table it happens is all the results are not in one table but one result of one table.

```<code>foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "$ia_key($ia_value)";
                echo "<br>";
                $z++;
            }
        }
    }
</code>```

I tried with this code. But the result is not in one table.

```<code>foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "<div class='row'>";
                    echo "<div class='col-sm-12'>";
                        echo "<h4 class='m-t-0 header-title'></h4>";
                        echo "<div class='table-responsive m-b-20'>";
                            echo "<p class='text-muted font-13 m-b-30'>";
                            echo "<table id='datatable-buttons' class='table table-striped table-bordered'>";
                                 echo "<thead>";
                                    echo "<tr>";
                                        echo "<th>No.</th>";
                                        echo "<th>Nama Item</th>";
                                        echo "<th>Jumlah</th>";
                                    echo"</tr>";
                                    echo "</thead>";
                                    echo "<tbody>";
                                    $no = 0;
                                    $no++;
                                        echo "<tr>";
                                            echo "<td> $no </td>";
                                            echo "<td> $ia_key </td>";
                                            echo "<td> $ia_value </td>";
                                            $z++;
                                        echo "</tr>";
                                    echo "</tbody>";
                                echo "</tr>";
                            echo "</table>";
                        echo "</div>";
                    echo "</div>";
                echo"</div>";
            }
        }
    }
</code>```

Result of above code <== Click to view image.

答:
You should put your table structure outside of the foreach() loop:

```<code>$no = 0;
echo "<div class='row'>";
echo "<div class='col-sm-12'>";
echo "<h4 class='m-t-0 header-title'></h4>";
echo "<div class='table-responsive m-b-20'>";
echo "<p class='text-muted font-13 m-b-30'>";
echo "<table id='datatable-buttons' class='table table-striped table-bordered'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>Nama Item</th>";
echo "<th>Jumlah</th>";
echo"</tr>";
echo "</thead>";
echo "<tbody>";

foreach ($item_array as $ia_key => $ia_value)
{
    //$theitems = explode('|',$ia_key);
    for($x = 0; $x < count($ia_key); $x++)
    {
        if (($ia_value>=$support))
        {

            $no++;
            echo "<tr>";
            echo "<td> $no </td>";
            echo "<td> $ia_key </td>";
            echo "<td> $ia_value </td>";
            $z++;
            echo "</tr>";
        }
    }
}

echo "</tbody>";
echo "</tr>";
echo "</table>";
echo "</div>";
echo "</div>";
echo"</div>";
</code>```

Title: How to make Table in PHP

Body:
I want to make table with this result (look Echo),  When I put it in the table it happens is all the results are not in one table but one result of one table.

foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "$ia_key($ia_value)";
                echo "
";
                $z++;
            }
        }
    }

I tried with this code. But the result is not in one table.

foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "
";
                    echo "
";
                        echo "

";
                        echo "
";
                            echo "
";
                            echo "
";
                                 echo "
";
                                    echo "
";
                                        echo "No.	";
                                        echo "Nama Item	";
                                        echo "Jumlah	";
                                    echo"
";
                                    echo "
";
                                    echo "
";
                                    $no = 0;
                                    $no++;
                                        echo "
";
                                            echo " $no 	";
                                            echo " $ia_key 	";
                                            echo " $ia_value 	";
                                            $z++;
                                        echo "
";
                                    echo "
";
                                echo "
";
                            echo "
";
                        echo "
";
                    echo "
";
                echo"
";
            }
        }
    }

Result of above code <== Click to view image.

Body:
You should put your table structure outside of the foreach() loop:

$no = 0;
echo "<div class='row'>";
echo "<div class='col-sm-12'>";
echo "<h4 class='m-t-0 header-title'></h4>";
echo "<div class='table-responsive m-b-20'>";
echo "<p class='text-muted font-13 m-b-30'>";
echo "<table id='datatable-buttons' class='table table-striped table-bordered'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>Nama Item</th>";
echo "<th>Jumlah</th>";
echo"</tr>";
echo "</thead>";
echo "<tbody>";

foreach ($item_array as $ia_key => $ia_value)
{
    //$theitems = explode('|',$ia_key);
    for($x = 0; $x < count($ia_key); $x++)
    {
        if (($ia_value>=$support))
        {

            $no++;
            echo "<tr>";
            echo "<td> $no </td>";
            echo "<td> $ia_key </td>";
            echo "<td> $ia_value </td>";
            $z++;
            echo "</tr>";
        }
    }
}

echo "</tbody>";
echo "</tr>";
echo "</table>";
echo "</div>";
echo "</div>";
echo"</div>";


来源: stackexchange

问:
Angular2 Material errors in webpack when importing MaterialModule
I am following the steps from the getting started page
https://github.com/angular/material2/blob/master/GETTING_STARTED.md

So far I have installed material with the following

```<code>npm install --save @angular/material
</code>```

Now I am attempting to import the MaterialModule into my app component

```<code>import { MaterialModule } from '@angular/material';
</code>```

Which causes webpack to throw a ton of errors like

```<code>ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:14:27
';' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:14:29
Duplicate identifier 'string'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:4
Duplicate identifier 'readonly'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:13
'=' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:13
Cannot find name '_tabindex'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:22
';' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:24
Duplicate identifier 'string'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:4
Duplicate identifier 'readonly'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:13
'=' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:13
Cannot find name 'menuOpen'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:21
';' expected.
</code>```

what am I doing wrong?

答: I ended up updating all the versions of my node modules by coping the package.json from the angular/webpack starter kit and the errors went away. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am following the steps from the getting started page
https://github.com/angular/material2/blob/master/GETTING_STARTED.md

So far I have installed material with the following

npm install --save @angular/material

Now I am attempting to import the MaterialModule into my app component

import { MaterialModule } from '@angular/material';

Which causes webpack to throw a ton of errors like

ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:14:27
';' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:14:29
Duplicate identifier 'string'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:4
Duplicate identifier 'readonly'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:13
'=' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:13
Cannot find name '_tabindex'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:22
';' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-item.d.ts:15:24
Duplicate identifier 'string'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:4
Duplicate identifier 'readonly'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:13
'=' expected.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:13
Cannot find name 'menuOpen'.
ERROR in [default] C:/mypathSource/Repos/dir/Web.Angular/node_modules/@angular/material/menu/menu-trigger.d.ts:26:21
';' expected.

what am I doing wrong?


问:
Why I can't see icon images on UWP?
I'm using Xamarin.Forms, following this tutorial:

```<code>public MasterPage()
{
    var masterPageItems = new List<MasterPageItem>();
    masterPageItems.Add(new MasterPageItem
    {
        Title = "Contacts",
        IconSource = "contacts.png",
        TargetType = typeof(Pages.Contacts)
    });
    masterPageItems.Add(new MasterPageItem
    {
        Title = "ToDo",
        IconSource = "todo.png",
        TargetType = typeof(Pages.ToDo)
    });
    masterPageItems.Add(new MasterPageItem
    {
        Title = "Reminders",
        IconSource = "reminders.png",
        TargetType = typeof(Pages.Reminder)
    });
    masterPageItems.Add(new MasterPageItem
    {
        Title = "Login",
        IconSource = "reminders.png",
        TargetType = typeof(Pages.Login)
    });
    masterPageItems.Add(new MasterPageItem
    {
        Title = "Sign Up",
        IconSource = "reminders.png",
        TargetType = typeof(Pages.SignUp)
    });

    listView = new ListView
    {
        ItemsSource = masterPageItems,
        ItemTemplate = new DataTemplate(() => {
            var imageCell = new ImageCell();
            imageCell.SetBinding(TextCell.TextProperty, "Title");
            imageCell.SetBinding(ImageCell.ImageSourceProperty, "IconSource");
            return imageCell;
        }),
        VerticalOptions = LayoutOptions.FillAndExpand,
        SeparatorVisibility = SeparatorVisibility.None
    };

    Padding = new Thickness(0, 40, 0, 0);
    Icon = "hamburger.png";
    Title = "Personal Organiser";
    Content = new StackLayout
    {
        VerticalOptions = LayoutOptions.FillAndExpand,
        Children = {
        listView
    }
    };
}
</code>```

I've place all the icons.png (todo, reminders, and so on) within the MyProject.UWP root.

But when I run it from Visual Studio (debug mode, x64) I just can't see the icons within Master-Detail Page's navigation layout.

EDIT: I can't see BuildAction field on the image's Properties:

EDIT 2: Now I See. You need to "Add Existing Item", not place copy/paste image on the folder.

答: The BuildAction should be set to Content</p>

Title: Why I can't see icon images on UWP?

Body:
I'm using Xamarin.Forms, following this tutorial:

public MasterPage()
{
    var masterPageItems = new List<MasterPageItem>();
    masterPageItems.Add(new MasterPageItem
    {
        Title = "Contacts",
        IconSource = "contacts.png",
        TargetType = typeof(Pages.Contacts)
    });
    masterPageItems.Add(new MasterPageItem
    {
        Title = "ToDo",
        IconSource = "todo.png",
        TargetType = typeof(Pages.ToDo)
    });
    masterPageItems.Add(new MasterPageItem
    {
        Title = "Reminders",
        IconSource = "reminders.png",
        TargetType = typeof(Pages.Reminder)
    });
    masterPageItems.Add(new MasterPageItem
    {
        Title = "Login",
        IconSource = "reminders.png",
        TargetType = typeof(Pages.Login)
    });
    masterPageItems.Add(new MasterPageItem
    {
        Title = "Sign Up",
        IconSource = "reminders.png",
        TargetType = typeof(Pages.SignUp)
    });

    listView = new ListView
    {
        ItemsSource = masterPageItems,
        ItemTemplate = new DataTemplate(() => {
            var imageCell = new ImageCell();
            imageCell.SetBinding(TextCell.TextProperty, "Title");
            imageCell.SetBinding(ImageCell.ImageSourceProperty, "IconSource");
            return imageCell;
        }),
        VerticalOptions = LayoutOptions.FillAndExpand,
        SeparatorVisibility = SeparatorVisibility.None
    };

    Padding = new Thickness(0, 40, 0, 0);
    Icon = "hamburger.png";
    Title = "Personal Organiser";
    Content = new StackLayout
    {
        VerticalOptions = LayoutOptions.FillAndExpand,
        Children = {
        listView
    }
    };
}

I've place all the icons.png (todo, reminders, and so on) within the MyProject.UWP root.

But when I run it from Visual Studio (debug mode, x64) I just can't see the icons within Master-Detail Page's navigation layout.

EDIT: I can't see BuildAction field on the image's Properties:

EDIT 2: Now I See. You need to "Add Existing Item", not place copy/paste image on the folder.


问:
Mailchimp API 3.0 - Add / remove a user to a list > group > group name
I am trying to use the Mailchimp API 3.0 to insert a user into a list > group > group name with php.

I found a nice example using curl, here it is, but, as you can see, here he shows only to add a user into a list, and not in group > group name.

The problem is that I can't find documentation about adding or deleting a user from groups.

I've tried to add the group into the json data array with label 'interests' and also to add it in the $merge_fields array ( I think this is for v2.0 ), but without success.

答:
The way I understand it you need to make a call to a lists/{list-id}/member/{member-hash} endpoint with a body like this this:

```<code>   {
      "email_address": "someone@doamin.com",
      "status": "subscribed",
      "interests": {
          <interest_id>: true,
          <interest_id>: false
      }
   }
</code>```

Mailchimp has some example JSON here: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#

Body:
The way I understand it you need to make a call to a lists/{list-id}/member/{member-hash} endpoint with a body like this this:

   {
      "email_address": "someone@doamin.com",
      "status": "subscribed",
      "interests": {
          <interest_id>: true,
          <interest_id>: false
      }
   }

Mailchimp has some example JSON here: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#


问:
How does data shape change during Conv2D and Dense in Keras?
Just as the title says. This code only works Using:

```<code>x = Flatten()(x)
</code>```

Between the convolutional layer and the dense layer.

```<code>import numpy as np
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Input
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD

# Generate dummy data
x_train = np.random.random((100, 100, 100, 3))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)

#Build Model
input_layer = Input(shape=(100, 100, 3))
x = Conv2D(32, (3, 3), activation='relu')(input_layer)
x = Dense(256, activation='relu')(x)
x = Dense(10, activation='softmax')(x)
model = Model(inputs=[input_layer],outputs=[x])

#compile network
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)

#train network
model.fit(x_train, y_train, batch_size=32, epochs=10)
</code>```

Otherwise, I receive this error:

```<code>Traceback (most recent call last):

File "/home/michael/practice_example.py", line 44, in <module>
    model.fit(x_train, y_train, batch_size=32, epochs=10)

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1435, in fit
    batch_size=batch_size)

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1315, in _standardize_user_data
    exception_prefix='target')

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 127, in _standardize_input_data
    str(array.shape))

ValueError: Error when checking target: expected dense_2 to have 4 dimensions, but got array with shape (100, 10)
</code>```

Why would the output have 4 dimensions without the flatten() layer?

答:
According to keras doc,

Conv2D Output shape

4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding.

Since you are using channels_last, the shape of layer output would be:

```<code># shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Flatten()(x)
# shape=(100, row*col*32)

x = Dense(256, activation='relu')(x)
# shape=(100, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, 10)
</code>```

Error explanation (edited, thanks to @Marcin)

Linking a 4D tensor (shape=(100, row, col, 32)) to a 2D one (shape=(100, 256)) using Dense layer will still form a 4D tensor (shape=(100, row, col, 256)) which is not what you want.

```<code># shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Dense(256, activation='relu')(x)
# shape=(100, row, col, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, row, col, 10)
</code>```

And the error will occur when the mismatch between output 4D tensor and target 2D tensor happens.

That's why you need a Flatten layer to flat it from 4D to 2D.

Reference

Conv2D
Dense

Body:
Just as the title says. This code only works Using:

x = Flatten()(x)

Between the convolutional layer and the dense layer.

import numpy as np
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Input
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD

# Generate dummy data
x_train = np.random.random((100, 100, 100, 3))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)

#Build Model
input_layer = Input(shape=(100, 100, 3))
x = Conv2D(32, (3, 3), activation='relu')(input_layer)
x = Dense(256, activation='relu')(x)
x = Dense(10, activation='softmax')(x)
model = Model(inputs=[input_layer],outputs=[x])

#compile network
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)

#train network
model.fit(x_train, y_train, batch_size=32, epochs=10)

Otherwise, I receive this error:

Traceback (most recent call last):

File "/home/michael/practice_example.py", line 44, in <module>
    model.fit(x_train, y_train, batch_size=32, epochs=10)

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1435, in fit
    batch_size=batch_size)

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1315, in _standardize_user_data
    exception_prefix='target')

File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 127, in _standardize_input_data
    str(array.shape))

ValueError: Error when checking target: expected dense_2 to have 4 dimensions, but got array with shape (100, 10)

Why would the output have 4 dimensions without the flatten() layer?

Body:
According to keras doc,

Conv2D Output shape

4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding.

Since you are using channels_last, the shape of layer output would be:

# shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Flatten()(x)
# shape=(100, row*col*32)

x = Dense(256, activation='relu')(x)
# shape=(100, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, 10)

Error explanation (edited, thanks to @Marcin)

Linking a 4D tensor (shape=(100, row, col, 32)) to a 2D one (shape=(100, 256)) using Dense layer will still form a 4D tensor (shape=(100, row, col, 256)) which is not what you want.

# shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Dense(256, activation='relu')(x)
# shape=(100, row, col, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, row, col, 10)

And the error will occur when the mismatch between output 4D tensor and target 2D tensor happens.

That's why you need a Flatten layer to flat it from 4D to 2D.

Reference

Conv2D
Dense


问:
Selecting another HTML element from an ng-click attribute
I am attempting to pass a file into a function, where the file is originated from an input type of file.  My code looks something like this.

```<code><input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile()">Upload</button>
</code>```

In short, I would like to take the file that has been added to the input and pass it into the parameter of the function of the ng-click attribute that is fired when the button is clicked.  I think this may be simple, but I cannot wrap my head around it at the moment.

I'm trying to do something like this.

```<code><input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile(#scvFileUploadId.file)">Upload</button>
</code>```

答:
You can use a simple directive with NgModelController to add ngModel support for the input type='file' like:

angular.module('myApp', [])
.controller('TestUploadController', ['$scope', function ($scope) {
    var ctrl = this;

    ctrl.imageFile = null;

    ctrl.clearFile = clearFile;
    ctrl.uploadFile = uploadFile;

    function clearFile() {
      ctrl.imageFile = null;
    }

    function uploadFile(file) {
      if (file) {
        console.log('Upload: ', file);
      }
    }
}])
.directive('fileUpload', [function () {
  return {
    require: "ngModel",
    restrict: 'A',
    link: function ($scope, el, attrs, ngModel) {
      function onChange (event) {
        //update bindings with $applyAsync
        $scope.$applyAsync(function(){
          ngModel.$setViewValue(event.target.files[0]);
        });
      }
      //change event handler
      el.on('change', onChange);

      //set up a $watch for the ngModel.$viewValue
      $scope.$watch(function () {
        return ngModel.$viewValue;
      }, function (value) {
        //clear input value if model was cleared
        if (!value) {
          el.val("");
        }
      });
      //remove change event handler on $destroy
      $scope.$on('$destroy', function(){
        el.off('change', onChange);
      });
    }
  };
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="TestUploadController as $ctrl">
    <input type="file" file-upload ng-model="$ctrl.imageFile" />
    <input type="button" ng-click="$ctrl.uploadFile($ctrl.imageFile)" value="Upload" />
    <input type="button" ng-click="$ctrl.clearFile()" value="Reset" />
    <div ng-if="$ctrl.imageFile">
      {{$ctrl.imageFile.name}}<br />
      {{$ctrl.imageFile.size}} byte(s)<br/>
      {{$ctrl.imageFile.type}}
    </div>
  </div>
</div></code>```

Body:
I am attempting to pass a file into a function, where the file is originated from an input type of file.  My code looks something like this.

<input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile()">Upload</button>

In short, I would like to take the file that has been added to the input and pass it into the parameter of the function of the ng-click attribute that is fired when the button is clicked.  I think this may be simple, but I cannot wrap my head around it at the moment.

I'm trying to do something like this.

<input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile(#scvFileUploadId.file)">Upload</button>

Body:
You can use a simple directive with NgModelController to add ngModel support for the input type='file' like:

angular.module('myApp', [])
.controller('TestUploadController', ['$scope', function ($scope) {
    var ctrl = this;

    ctrl.imageFile = null;

    ctrl.clearFile = clearFile;
    ctrl.uploadFile = uploadFile;

    function clearFile() {
      ctrl.imageFile = null;
    }

    function uploadFile(file) {
      if (file) {
        console.log('Upload: ', file);
      }
    }
}])
.directive('fileUpload', [function () {
  return {
    require: "ngModel",
    restrict: 'A',
    link: function ($scope, el, attrs, ngModel) {
      function onChange (event) {
        //update bindings with $applyAsync
        $scope.$applyAsync(function(){
          ngModel.$setViewValue(event.target.files[0]);
        });
      }
      //change event handler
      el.on('change', onChange);

      //set up a $watch for the ngModel.$viewValue
      $scope.$watch(function () {
        return ngModel.$viewValue;
      }, function (value) {
        //clear input value if model was cleared
        if (!value) {
          el.val("");
        }
      });
      //remove change event handler on $destroy
      $scope.$on('$destroy', function(){
        el.off('change', onChange);
      });
    }
  };
}]);

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="TestUploadController as $ctrl">
    <input type="file" file-upload ng-model="$ctrl.imageFile" />
    <input type="button" ng-click="$ctrl.uploadFile($ctrl.imageFile)" value="Upload" />
    <input type="button" ng-click="$ctrl.clearFile()" value="Reset" />
    <div ng-if="$ctrl.imageFile">
      {{$ctrl.imageFile.name}}<br />
      {{$ctrl.imageFile.size}} byte(s)<br/>
      {{$ctrl.imageFile.type}}
    </div>
  </div>
</div>


问:
Linq: help me to make this work
I have this column:

```<code>    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424
</code>```

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

```<code>if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);
</code>```

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach

答:
I just Showed the data of yours in Image

The issue is that you don't have any value against CategoryId=47 in column SubCategoryId thats why when you search both of them together it gives nothing.
Try it by adding any value in SubCategoryId against CategoryId=47...

Title: Linq: help me to make this work

Body:
I have this column:

    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach


问:
How does the keydown event work?
I want that if my input text value is not empty then show my .removetext div but it doesn't work properly. If you type a something after second character my .removetext is being hidden but if my input is not empty don't hide my .removetext class.

Where is my mistake? I guess I don't understand the keydown event

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    var val = $.trim(this.value);
    if (!val == "") {
      $(".removetext").show(val.length > 0, function() {
        var clear = $(this);
        clear.on('click', function() {
          alert('hey');
        })
      });
    } else {
      $(".removetext").hide();
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}</code>```

  <input type="text" class="search-hotels">

×

```

答:
You can achieve what you want by using keyup instead of keydown and changing your if statement to the following:

```<code>if ($(this).val());
</code>```

Using keydown means that it will not use the .val that was input but will check the .val before the input is updated because the .val will be updated after the keyup  event.

An even better approach would be to use the input event as follows:

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}</code>```

  <input type="text" class="search-hotels">

×

```

Title: How does the keydown event work?

Body:
I want that if my input text value is not empty then show my .removetext div but it doesn't work properly. If you type a something after second character my .removetext is being hidden but if my input is not empty don't hide my .removetext class.

Where is my mistake? I guess I don't understand the keydown event

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    var val = $.trim(this.value);
    if (!val == "") {
      $(".removetext").show(val.length > 0, function() {
        var clear = $(this);
        clear.on('click', function() {
          alert('hey');
        })
      });
    } else {
      $(".removetext").hide();
    }
  });

});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

  <input type="text" class="search-hotels">

×

Body:
You can achieve what you want by using keyup instead of keydown and changing your if statement to the following:

if ($(this).val());

Using keydown means that it will not use the .val that was input but will check the .val before the input is updated because the .val will be updated after the keyup  event.

An even better approach would be to use the input event as follows:

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>


问:
Spring jdbcTemplate vs PreparedStatement. Performance difference
I am using Oracle 11g. I have 3 tables(A,B,C) in my database A <one-many> B <many-one> C
I have a piece of code, that performs three inserts: firstly in A and C, after that in B. This piece of code is executed a lot of times(200000) and makes 200000 insert operations in each table.

I have two ways to make an insertion:

jdbc PreparedStatement:

```<code>DataSource ds = jdbcTemplate.getDataSource();

try (Connection connection = ds.getConnection();
     PreparedStatement statement = connection.prepareStatement(sql1);
     PreparedStatement statement2 = connection.prepareStatement(sql2);
     PreparedStatement statement3 = connection.prepareStatement(sql3);) {

     connection.setAutoCommit(false);
     final int batchSize = 20;
     int count = 0;

     for (int i=1; i<= total; i++ ) {

         // Define sql parameters

         statement.setString(1, p1);

         statement2.setString(1, p2);
         statement2.setString(2, p3);

         statement3.setInt(1, p4);
         statement3.setString(2, p5);

         statement.addBatch();
         statement2.addBatch();
         statement3.addBatch();

         if (++count % batchSize == 0) {
                    statement.executeBatch();
                    statement.clearBatch();
                    statement2.executeBatch();
                    statement2.clearBatch();
                    statement3.executeBatch();
                    statement3.clearBatch();
                    connection.commit();
                    System.out.println(i);
         }
      }

      statement.executeBatch();
      statement.clearBatch();
      statement2.executeBatch();
      statement2.clearBatch();
      statement3.executeBatch();
      statement3.clearBatch();
      connection.commit();
   }
   catch (SQLException e) {
       e.printStackTrace();
   }
}
</code>```

Spring jdbcTemplate:

```<code> List<String> bulkLoadRegistrationSql = new ArrayList<String>(20);

 for (int i=1; i<= total; i++ ) {

     // 1. Define sql parameters p1,p2,p,3p4,p5

     // 2. Prepare sql using parameters from 1
     String sql1String = ...
     String sql2String = ...
     String sql3String = ...

     bulkLoadRegistrationSql.add(sql1String);
     bulkLoadRegistrationSql.add(sql2String);
     bulkLoadRegistrationSql.add(sql3String);

     if (i % 20 == 0) {
          jdbcTemplate.batchUpdate(bulkLoadRegistrationSql
              .toArray(new  String[bulkLoadRegistrationSql.size()]));
          //Clear inserted batch
          bulkLoadRegistrationSql = new ArrayList<String>(20);
     }

}
</code>```

I measured execution time for total = 200000 and results are very confusing for me.
Spring jdbcTemplate is executed in 1480 seconds,
jdbc PreparedStatement in 200 seconds

I looked into jdbcTemplate source and found, that it uses Statement underneath, which should be less efficient than PreparedStatement. However the difference in results is too big and I am not sure if this happens just because of the difference between Statement and PreparedStatement. What are your ideas on that? Should the results theoretically be equaled if jdbcTemplate is replaced on namedParameterJdbcTemplate?

答:
Spring JDBCTemplate also has methods that use prepared Statement. Please Refer this link Your test results make sense - you cannot compare execution using prepared statement and Ordinary SQL.

There are overloaded batchUpdate methods in Spring JDBCTemplate that uses Prepared statements for example the below function.

int[][] batchUpdate(String sql, final Collection batchArgs, final
  int batchSize,            final ParameterizedPreparedStatementSetter pss)

Body:
I am using Oracle 11g. I have 3 tables(A,B,C) in my database A <one-many> B <many-one> C
I have a piece of code, that performs three inserts: firstly in A and C, after that in B. This piece of code is executed a lot of times(200000) and makes 200000 insert operations in each table.

I have two ways to make an insertion:

jdbc PreparedStatement:

DataSource ds = jdbcTemplate.getDataSource();

try (Connection connection = ds.getConnection();
     PreparedStatement statement = connection.prepareStatement(sql1);
     PreparedStatement statement2 = connection.prepareStatement(sql2);
     PreparedStatement statement3 = connection.prepareStatement(sql3);) {

     connection.setAutoCommit(false);
     final int batchSize = 20;
     int count = 0;

     for (int i=1; i<= total; i++ ) {

         // Define sql parameters

         statement.setString(1, p1);

         statement2.setString(1, p2);
         statement2.setString(2, p3);

         statement3.setInt(1, p4);
         statement3.setString(2, p5);

         statement.addBatch();
         statement2.addBatch();
         statement3.addBatch();

         if (++count % batchSize == 0) {
                    statement.executeBatch();
                    statement.clearBatch();
                    statement2.executeBatch();
                    statement2.clearBatch();
                    statement3.executeBatch();
                    statement3.clearBatch();
                    connection.commit();
                    System.out.println(i);
         }
      }

      statement.executeBatch();
      statement.clearBatch();
      statement2.executeBatch();
      statement2.clearBatch();
      statement3.executeBatch();
      statement3.clearBatch();
      connection.commit();
   }
   catch (SQLException e) {
       e.printStackTrace();
   }
}

Spring jdbcTemplate:

 List<String> bulkLoadRegistrationSql = new ArrayList<String>(20);

 for (int i=1; i<= total; i++ ) {

     // 1. Define sql parameters p1,p2,p,3p4,p5

     // 2. Prepare sql using parameters from 1
     String sql1String = ...
     String sql2String = ...
     String sql3String = ...

     bulkLoadRegistrationSql.add(sql1String);
     bulkLoadRegistrationSql.add(sql2String);
     bulkLoadRegistrationSql.add(sql3String);

     if (i % 20 == 0) {
          jdbcTemplate.batchUpdate(bulkLoadRegistrationSql
              .toArray(new  String[bulkLoadRegistrationSql.size()]));
          //Clear inserted batch
          bulkLoadRegistrationSql = new ArrayList<String>(20);
     }

}

I measured execution time for total = 200000 and results are very confusing for me.
Spring jdbcTemplate is executed in 1480 seconds,
jdbc PreparedStatement in 200 seconds

I looked into jdbcTemplate source and found, that it uses Statement underneath, which should be less efficient than PreparedStatement. However the difference in results is too big and I am not sure if this happens just because of the difference between Statement and PreparedStatement. What are your ideas on that? Should the results theoretically be equaled if jdbcTemplate is replaced on namedParameterJdbcTemplate?


问:
How to add a font awesome icon into input text ::after with j query?
I have a sign up form like this image:

After I use jQuery code to check valid email, and that code:

```<code>function isEmail(email) {
            var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }
</code>```

I want to insert a font awesome icon in after my email input form (check icon if true and cross icon if false), like this image:

So how can I do that with jQuery and I want to set color for this icon?

答:
function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

$('.email').on('submit', function(e) {
  e.preventDefault();
  var emailAddress = $(this).find('input[type=text]').val();
  if (isEmail(emailAddress)) {
   $(this).find('input[type=text]').addClass('fa-check')
  } else {
   $(this).find('input[type=text]').addClass('fa-times')
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="email">
  <input type="text" class="fa">
  <button>Submit</button>
</form></code>```

Body:
I have a sign up form like this image:

After I use jQuery code to check valid email, and that code:

function isEmail(email) {
            var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            return regex.test(email);
        }

I want to insert a font awesome icon in after my email input form (check icon if true and cross icon if false), like this image:

So how can I do that with jQuery and I want to set color for this icon?

Body:
function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

$('.email').on('submit', function(e) {
  e.preventDefault();
  var emailAddress = $(this).find('input[type=text]').val();
  if (isEmail(emailAddress)) {
   $(this).find('input[type=text]').addClass('fa-check')
  } else {
   $(this).find('input[type=text]').addClass('fa-times')
  };
});

<form class="email">
  <input type="text" class="fa">
  <button>Submit</button>
</form>


答: You should use keyup. Key down registers the key pressed but it hasn't populated the input yet. You can either go through the keydown event properties and use the property "key" (if i remember correctly) to get the value entered during the keydown, but if you want to grab the text in the input, you'll need "keyup"</p>

Title: How does the keydown event work?


答:
EDIT:

After the question is more clarified the following code should work

```<code>        if (ids.IdCategory != null && ids.IdSubCategory != null)
        {
            query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => (m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory) && m.IdPerson != 101);
        }
</code>```

Firstly your data will return null for your search criteria. Following are some example of linq that might help this scenario.

You can do different kind of linq.

```<code>    List<CollectionObject> ColObj = CollectionObject.GetListCollectionObj();

    List<CollectionObject> LinqResult = ColObj.Where(x => x.CategoryID == 47 && x.SubcategoryID == null).ToList();
</code>```

The following code works fine with the linq statements above.

```<code>    class CollectionObject
    {
        public int PersonID { get; set; }
        public int? CategoryID { get; set; }
        public int? SubcategoryID { get; set; }

    public static List<CollectionObject> GetListCollectionObj()
    {
        List<CollectionObject> LColObj = new List<CollectionObject>();

        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 47, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 48, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 0, SubcategoryID = 424 });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 0, SubcategoryID = 425 });
        LColObj.Add(new CollectionObject() { PersonID = 101, CategoryID = 48, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 101, CategoryID = null, SubcategoryID = 424 });
        LColObj.Add(new CollectionObject() { PersonID = 666, CategoryID = 47, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 666, CategoryID = null, SubcategoryID = 424 });

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

Title: Linq: help me to make this work

Body:
EDIT:

After the question is more clarified the following code should work

        if (ids.IdCategory != null && ids.IdSubCategory != null)
        {
            query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => (m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory) && m.IdPerson != 101);
        }

Firstly your data will return null for your search criteria. Following are some example of linq that might help this scenario.

You can do different kind of linq.

    List<CollectionObject> ColObj = CollectionObject.GetListCollectionObj();

    List<CollectionObject> LinqResult = ColObj.Where(x => x.CategoryID == 47 && x.SubcategoryID == null).ToList();

The following code works fine with the linq statements above.

    class CollectionObject
    {
        public int PersonID { get; set; }
        public int? CategoryID { get; set; }
        public int? SubcategoryID { get; set; }

    public static List<CollectionObject> GetListCollectionObj()
    {
        List<CollectionObject> LColObj = new List<CollectionObject>();

        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 47, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 48, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 0, SubcategoryID = 424 });
        LColObj.Add(new CollectionObject() { PersonID = 61, CategoryID = 0, SubcategoryID = 425 });
        LColObj.Add(new CollectionObject() { PersonID = 101, CategoryID = 48, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 101, CategoryID = null, SubcategoryID = 424 });
        LColObj.Add(new CollectionObject() { PersonID = 666, CategoryID = 47, SubcategoryID = null });
        LColObj.Add(new CollectionObject() { PersonID = 666, CategoryID = null, SubcategoryID = 424 });

        return LColObj;
    }
}


问:
Fiscal position implementation in odoo
I have seen one option in odoo accounting "Fiscal Position" under

Accounting => Configuration => Accounting => Fiscal Position

I have checked it's features but I am not really getting at which point of time it's really useful or we can implement it where.

Features are very useful that all about tax and account mapping.

I would like to know it's importance, because I think so it's useful feature in odoo.

答:
In Germany it's a really important feature. For example if you're a german company and sell goods mostly nationallly but sometimes internationally you don't have to take VAT from the customer (internationally), because Germany has double tax agreements with other countries.

But you will configure your Odoo products for the most used case -> national selling. Odoo gets lots of configured data like default tax and default accounts from the chosen product. But selling a product internationally means you have to take other taxes and accounts (in Germany for example!).

You could either handle that manually by changing taxes and accounts in invoices or you can use fiscal positions! Letter one will handle it on a much faster way.

Here a german example:

Product "Software Odoo": default tax 19% VAT, default Account 8400 (german SKR03, don't ask ;-))

Fiscal Position "Not EU":

tax mapping: 19% VAT -> no tax

account mapping: 8400 -> 8120

Creating an invoice for a non EU partner and this fiscal position, will set/map the taxes and accounts on every new invoice line automatically.

Actually that's no programming question and answer, but i've taken too much effort to write this, so i hope it will help you a bit ;-)

Title: Fiscal position implementation in odoo


答:
Keydown event is fired before a character is typed, hence you should use keyup event which is fired after the character is typed.

Also, !$(this).val() is different than $(this).val()==""

Use if($(this).val()=="")

Title: How does the keydown event work?


问:
How do you manage databases in development, test, and production?
I've had a hard time trying to find good examples of how to manage database schemas and data between development, test, and production servers.

Here's our setup. Each developer has a virtual machine running our app and the MySQL database. It is their personal sandbox to do whatever they want. Currently, developers will make a change to the SQL schema and do a dump of the database to a text file that they commit into SVN.

We're wanting to deploy a continuous integration development server that will always be running the latest committed code. If we do that now, it will reload the database from SVN for each build.

We have a test (virtual) server that runs "release candidates." Deploying to the test server is currently a very manual process, and usually involves me loading the latest SQL from SVN and tweaking it. Also, the data on the test server is inconsistent. You end up with whatever test data the last developer to commit had on his sandbox server.

Where everything breaks down is the deployment to production. Since we can't overwrite the live data with test data, this involves manually re-creating all the schema changes. If there were a large number of schema changes or conversion scripts to manipulate the data, this can get really hairy.

If the problem was just the schema, It'd be an easier problem, but there is "base" data in the database that is updated during development as well, such as meta-data in security and permissions tables.

This is the biggest barrier I see in moving toward continuous integration and one-step-builds. How do you solve it?

A follow-up question: how do you track database versions so you know which scripts to run to upgrade a given database instance? Is a version table like Lance mentions below the standard procedure?

Thanks for the reference to Tarantino. I'm not in a .NET environment, but I found their DataBaseChangeMangement wiki page to be very helpful. Especially this Powerpoint Presentation (.ppt)

I'm going to write a Python script that checks the names of *.sql scripts in a given directory against a table in the database and runs the ones that aren't there in order based on a integer that forms the first part of the filename. If it is a pretty simple solution, as I suspect it will be, then I'll post it here.

I've got a working script for this. It handles initializing the DB if it doesn't exist and running upgrade scripts as necessary. There are also switches for wiping an existing database and importing test data from a file. It's about 200 lines, so I won't post it (though I might put it on pastebin if there's interest).

答:
I'm afraid I'm in agreement with other posters. Developers need to script their changes.

In many cases a simple ALTER TABLE won't work, you need to modify existing data too - developers need to thing about what migrations are required and make sure they're scripted correctly (of course you need to test this carefully at some point in the release cycle).

Moreover, if you have any sense, you'll get your developers to script rollbacks for their changes as well so they can be reverted if need be. This should be tested as well, to ensure that their rollback not only executes without error, but leaves the DB in the same state as it was in previously (this is not always possible or desirable, but is a good rule most of the time).

How you hook that into a CI server, I don't know. Perhaps your CI server needs to have a known build snapshot on, which it reverts to each night and then applies all the changes since then. That's probably best, otherwise a broken migration script will break not just that night's build, but all subsequent ones.

LastEditorDisplayName: Matt Miller

OwnerDisplayName: MarkR

ContentLicense: CC BY-SA 2.5


问:
SQL count using multiple join
I have three tables related to each other in the following way:

host (has multiple sessions)

session (has multiple processes)

processes

The table structure is as follows:

host table - id, name

session table - id, host_id, name

process table - id, session_id, name

What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.

```<code>select host.id,
       count(sessions.id) as "session count",
       count(process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;
</code>```

Here's the SQLFiddle to the schema.

As per the data in the fiddle, the output should be:

```<code>id | session count | process count
----------------------------------
1  |     2         |   3
2  |     1         |   2
3  |     1         |   2
4  |     2         |   3
</code>```

But what I get is:

```<code>id | session count | process count
----------------------------------
1  |     3         |   3
2  |     2         |   2
3  |     2         |   2
4  |     3         |   3
</code>```

What can be the correct query to get the desired output?

答:
John Faz's answer is better, however as you asked for other ways, it is possible to do this with sub queries as well like this:

```<code>select
  host.id,
  (select count(*) from sessions where host_id = host.id) as "session count",
  (select count(*) from process join sessions on process.session_id = sessions.id where sessions.host_id = host.id)  as "process count"
 from
   host
</code>```

EDIT:

Actually I take back that bit about John Faz's answer being better. I just ran an execution plan over the two and my query took 28% and John's took 50% (22% set up and tear down). I was using only the very small amount of data from the SQL Fiddle example and with big data and different index choices things are likely to be different. However it does show that this query may be better in some circumstances.

Title: SQL count using multiple join

Body:
I have three tables related to each other in the following way:

host (has multiple sessions)

session (has multiple processes)

processes

The table structure is as follows:

host table - id, name

session table - id, host_id, name

process table - id, session_id, name

What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.

select host.id,
       count(sessions.id) as "session count",
       count(process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;

Here's the SQLFiddle to the schema.

As per the data in the fiddle, the output should be:

id | session count | process count
----------------------------------
1  |     2         |   3
2  |     1         |   2
3  |     1         |   2
4  |     2         |   3

But what I get is:

id | session count | process count
----------------------------------
1  |     3         |   3
2  |     2         |   2
3  |     2         |   2
4  |     3         |   3

What can be the correct query to get the desired output?

Body:
John Faz's answer is better, however as you asked for other ways, it is possible to do this with sub queries as well like this:

select
  host.id,
  (select count(*) from sessions where host_id = host.id) as "session count",
  (select count(*) from process join sessions on process.session_id = sessions.id where sessions.host_id = host.id)  as "process count"
 from
   host

EDIT:

Actually I take back that bit about John Faz's answer being better. I just ran an execution plan over the two and my query took 28% and John's took 50% (22% set up and tear down). I was using only the very small amount of data from the SQL Fiddle example and with big data and different index choices things are likely to be different. However it does show that this query may be better in some circumstances.


问:
Train Tensorflow Object Detection on own dataset
After spending a couple days trying to achieve this task, I would like to share my experience of how I went about answering the question:

How do I use TS Object Detection to train using my own dataset?

答:
This assumes the module is already installed. Please refer to their documentation if not.

Disclaimer

This answer is not meant to be the right or only way of training the object detection module. This is simply I sharing my experience and what has worked for me. I'm open to suggestions and learning more about this as I am still new to ML in general.

TL;DR

Create your own PASCAL VOC format dataset

Generate TFRecords from it

Configure a pipeline

Visualize

Each section of this answer consists of a corresponding Edit (see below). After reading each section, please read its Edit as well for clarifications. Corrections and tips were added for each section.

Tools used

LabelImg: A tool for creating PASCAL VOC format annotations.

1. Create your own PASCAL VOC dataset

PS: For simplicity, the folder naming convention of my answer follows that of Pascal VOC 2012

A peek into the May 2012 dataset, you'll notice the folder as having the following structure

+VOCdevkit
  +VOC2012
    +Annotations
    +ImageSets
      +Action
      +Layout
      +Main
      +Segmentation
    +JPEGImages
    +SegmentationClass
    +SegmentationObject

For the time being, amendments were made to the following folders:

Annotations: This is were all the images' corresponding XML files will be placed in. Use the suggested tool above to create the annotations. Do not worry about <truncated> and <difficulty> tags as they will be ignored by the training and eval binaries.

JPEGImages: Location of your actual images. Make sure they are of type JPEG because that's what is currently supported in order to create TFRecords using their provided script.

ImageSets->Main: This simply consists of text files. For each class, there exists a corresponding train.txt, trainval.txt and val.txt. Below is a sample of the contents of the aeroplane_train.txt in the VOC 2012 folder

```<code>2008_000008 -1
2008_000015 -1
2008_000019 -1
2008_000023 -1
2008_000028 -1
2008_000033  1
</code>```

The structure is basically image name followed by a boolean saying whether the corresponding object exists in that image or not. Take for example image 2008_000008 does not consist of an aeroplane hence marked with a -1 but image 2008_000033 does.

I wrote a small Python script to generate these text files. Simply iterate through the image names and assign a 1 or -1 next to them for object existence. I added some randomness among my text files by shuffling the image names.

The {classname}_val.txt files consist of the testing validation datasets. Think of this as the test data during training. You want to divide your dataset into training and validation. More info can be found here. The format of these files is similar to that of training.

At this point, your folder structure should be

+VOCdevkit
  +VOC2012
    +Annotations
     --(for each image, generated annotation)
    +ImageSets
      +Main
        --(for each class, generated *classname*_train.txt and *classname*_val.txt)
    +JPEGImages
     --(a bunch of JPEG images)

1.1 Generating label map

With the dataset prepared, we need to create the corresponding label maps.
Navigate to models/object_detection/data and open pascal_label_map.pbtxt.

This file consists of a JSON that assigns an ID and name to each item. Make amendments to this file to reflect your desired objects.

2. Generate TFRecords

If you look into their code especially this line, they explicitly grab the aeroplane_train.txt only. For curios minds, here's why. Change this file name to any of your class train text file.

Make sure VOCdevkit is inside models/object_detection then you can go ahead and generate the TFRecords.

Please go through their code first should you run into any problems. It is self explanatory and well documented.

3. Pipeline Configuration

The instructions should be self explanatory to cover this segment. Sample configs can be found in object_detection/samples/configs.

For those looking to train from scratch as I did, just make sure to remove the fine_tune_checkpoint and from_detection_checkpoint nodes. Here's what my config file looked like for reference.

From here on you can continue with the tutorial and run the training process.

4. Visualize

Be sure to run the eval in parallel to the training in order to be able to visualize the learning process. To quote Jonathan Huang

the best way is to just run the eval.py binary. We typically run this
  binary in parallel to training, pointing it at the directory holding
  the checkpoint that is being trained. The eval.py binary will write
  logs to an eval_dir that you specify which you can then point to
  with Tensorboard.

You want to see that the mAP has "lifted off" in the first few hours,
  and then you want to see when it converges. It's hard to tell without
  looking at these plots how many steps you need.

EDIT I (28 July '17):

I never expected my response to get this much attention so I decided to come back and review it.

Tools

For my fellow Apple users, you could actually use RectLabel for annotations.

Pascal VOC

After digging around, I finally realized that trainval.txt is actually the union of training and validation datasets.

Please look at their official development kit to understand the format even better.

Label Map Generation

At the time of my writing, ID 0 represents none_of_the_above. It is recommended that your IDs start from 1.

Visualize

After running your evaluation and directed tensorboard to your Eval directory, it'll show you the mAP of each category along with each category's performance. This is good but I like seeing my training data as well in parallel with Eval.

To do this, run tensorboard on a different port and point it to your train directory

```<code>tensorboard --logdir=${PATH_TO_TRAIN} --port=${DESIRED_NUMBER}
</code>```

Body:
This assumes the module is already installed. Please refer to their documentation if not.

Disclaimer

This answer is not meant to be the right or only way of training the object detection module. This is simply I sharing my experience and what has worked for me. I'm open to suggestions and learning more about this as I am still new to ML in general.

TL;DR

Create your own PASCAL VOC format dataset

Generate TFRecords from it

Configure a pipeline

Visualize

Each section of this answer consists of a corresponding Edit (see below). After reading each section, please read its Edit as well for clarifications. Corrections and tips were added for each section.

Tools used

LabelImg: A tool for creating PASCAL VOC format annotations.

1. Create your own PASCAL VOC dataset

PS: For simplicity, the folder naming convention of my answer follows that of Pascal VOC 2012

A peek into the May 2012 dataset, you'll notice the folder as having the following structure

+VOCdevkit
  +VOC2012
    +Annotations
    +ImageSets
      +Action
      +Layout
      +Main
      +Segmentation
    +JPEGImages
    +SegmentationClass
    +SegmentationObject

For the time being, amendments were made to the following folders:

Annotations: This is were all the images' corresponding XML files will be placed in. Use the suggested tool above to create the annotations. Do not worry about <truncated> and <difficulty> tags as they will be ignored by the training and eval binaries.

JPEGImages: Location of your actual images. Make sure they are of type JPEG because that's what is currently supported in order to create TFRecords using their provided script.

ImageSets->Main: This simply consists of text files. For each class, there exists a corresponding train.txt, trainval.txt and val.txt. Below is a sample of the contents of the aeroplane_train.txt in the VOC 2012 folder

2008_000008 -1
2008_000015 -1
2008_000019 -1
2008_000023 -1
2008_000028 -1
2008_000033  1

The structure is basically image name followed by a boolean saying whether the corresponding object exists in that image or not. Take for example image 2008_000008 does not consist of an aeroplane hence marked with a -1 but image 2008_000033 does.

I wrote a small Python script to generate these text files. Simply iterate through the image names and assign a 1 or -1 next to them for object existence. I added some randomness among my text files by shuffling the image names.

The {classname}_val.txt files consist of the testing validation datasets. Think of this as the test data during training. You want to divide your dataset into training and validation. More info can be found here. The format of these files is similar to that of training.

At this point, your folder structure should be

+VOCdevkit
  +VOC2012
    +Annotations
     --(for each image, generated annotation)
    +ImageSets
      +Main
        --(for each class, generated *classname*_train.txt and *classname*_val.txt)
    +JPEGImages
     --(a bunch of JPEG images)

1.1 Generating label map

With the dataset prepared, we need to create the corresponding label maps.
Navigate to models/object_detection/data and open pascal_label_map.pbtxt.

This file consists of a JSON that assigns an ID and name to each item. Make amendments to this file to reflect your desired objects.

2. Generate TFRecords

If you look into their code especially this line, they explicitly grab the aeroplane_train.txt only. For curios minds, here's why. Change this file name to any of your class train text file.

Make sure VOCdevkit is inside models/object_detection then you can go ahead and generate the TFRecords.

Please go through their code first should you run into any problems. It is self explanatory and well documented.

3. Pipeline Configuration

The instructions should be self explanatory to cover this segment. Sample configs can be found in object_detection/samples/configs.

For those looking to train from scratch as I did, just make sure to remove the fine_tune_checkpoint and from_detection_checkpoint nodes. Here's what my config file looked like for reference.

From here on you can continue with the tutorial and run the training process.

4. Visualize

Be sure to run the eval in parallel to the training in order to be able to visualize the learning process. To quote Jonathan Huang

the best way is to just run the eval.py binary. We typically run this
  binary in parallel to training, pointing it at the directory holding
  the checkpoint that is being trained. The eval.py binary will write
  logs to an eval_dir that you specify which you can then point to
  with Tensorboard.

You want to see that the mAP has "lifted off" in the first few hours,
  and then you want to see when it converges. It's hard to tell without
  looking at these plots how many steps you need.

EDIT I (28 July '17):

I never expected my response to get this much attention so I decided to come back and review it.

Tools

For my fellow Apple users, you could actually use RectLabel for annotations.

Pascal VOC

After digging around, I finally realized that trainval.txt is actually the union of training and validation datasets.

Please look at their official development kit to understand the format even better.

Label Map Generation

At the time of my writing, ID 0 represents none_of_the_above. It is recommended that your IDs start from 1.

Visualize

After running your evaluation and directed tensorboard to your Eval directory, it'll show you the mAP of each category along with each category's performance. This is good but I like seeing my training data as well in parallel with Eval.

To do this, run tensorboard on a different port and point it to your train directory

tensorboard --logdir=${PATH_TO_TRAIN} --port=${DESIRED_NUMBER}


问:
GIT: remove from 2nd to 5th commits in the remote branch
I'd like to fully remove several commits in the remote branch.

Reason: The branch with the only important (and the most recent) commit supposed to be forked from and merged into another branch.

Once I change the branch to a proper branch (via browser) I see several more commits that are not in that proper branch yet. I don't need them.

```<code>git reset --hard HEAD~5
</code>```

and by manually applying and commiting my recent changes didn't get the result. There are even more commits now.

So, what was a proper and clear algorythm?

Thank you.

答:
Ahhh... I didn't quite understand what you want. If what you want to do is "remove" a couple of revisions from the history of a branch (either local or remote), what you have to do is this:

Get the (sha1) IDs for both revisions you want to get rid of

Checkout the revision before the oldest of the couple

Cherry-pick revisions from the oldest to one revision before the newest of the couple (that will discard the oldest so it won't be applied)

Cherry-pick revisions from the newest to the tip of the original branch.

So... say the remote branch is foo/bar and revisions are rev1 (oldest) and rev2 (newest).

What you do is:

```<code>git checkout rev1~1
git cherry-pick rev1..rev2~1
git cherry-pick rev2..foo/bar
</code>```

When you reach this point, you could create a local branch on top of it or just push it into foo/bar if you want to replace it:

```<code>git push foo -f HEAD:bar
</code>```

Body:
I'd like to fully remove several commits in the remote branch.

Reason: The branch with the only important (and the most recent) commit supposed to be forked from and merged into another branch.

Once I change the branch to a proper branch (via browser) I see several more commits that are not in that proper branch yet. I don't need them.

git reset --hard HEAD~5

and by manually applying and commiting my recent changes didn't get the result. There are even more commits now.

So, what was a proper and clear algorythm?

Thank you.

Body:
Ahhh... I didn't quite understand what you want. If what you want to do is "remove" a couple of revisions from the history of a branch (either local or remote), what you have to do is this:

Get the (sha1) IDs for both revisions you want to get rid of

Checkout the revision before the oldest of the couple

Cherry-pick revisions from the oldest to one revision before the newest of the couple (that will discard the oldest so it won't be applied)

Cherry-pick revisions from the newest to the tip of the original branch.

So... say the remote branch is foo/bar and revisions are rev1 (oldest) and rev2 (newest).

What you do is:

git checkout rev1~1
git cherry-pick rev1..rev2~1
git cherry-pick rev2..foo/bar

When you reach this point, you could create a local branch on top of it or just push it into foo/bar if you want to replace it:

git push foo -f HEAD:bar


问:
Haxe for loop only uses last item
After some hours doing some testing I figured out that my map contains the correct values, but the loop that I am using only seems to be using the last added value in this map. Am I missing something obvious here?

The function that adds items to the map: (controls is the map variable)

```<code>public static function CreateThumbstick(mActorType:ActorType, mLocation:Int, mDirectionLock:Int)
    {
        var controllerName = "Thumbstick"+mLocation;
        if(!controls.exists(controllerName)){

            createRecycledActor(mActorType, 0, 0, Script.FRONT);
            var lastActor = getLastCreatedActor();
            var myPosition = GetPosition(controllerName, lastActor);
            lastActor.setX(myPosition.x);
            lastActor.setY(myPosition.y);
            var myPos = new Vector2(lastActor.getXCenter(), lastActor.getYCenter());
            var controlUnit = new ControlUnit(lastActor, myPos, -1);
            controls.set(controllerName, controlUnit);

            trace("added key: " + controllerName +" with value: "+ lastActor);
        } else {
            trace("!!WARNING!! Control unit already exists in this position. Command ignored!");
        }
    }
</code>```

Upon creating 3 thumbsticks, the log states the following:

```<code>added key: Thumbstick1 with value: [Actor 1,Thumbstick]
added key: Thumbstick2 with value: [Actor 2,Thumbstick]
added key: Thumbstick3 with value: [Actor 3,Thumbstick]
</code>```

When the screen is touched, it should loop through each item in my map, but it is using the last added item 3 times to check the distance with, rather then all 3 items once. Here is the Listener that is being called when the screen is touched:

```<code>addMultiTouchStartListener(function(event:TouchEvent, list:Array<Dynamic>):Void
        {
            for (unit in controls){
                trace(lastDebugLine + "checking distance to " + unit.GetActor());
                if(GetDistance(unit.GetCenter(), touch.GetPosition()) < 64){
                    break;
                }
            }
        });
// used "touch.GetPosition()" instead of actuall code for easy reading. This is not causing any problems!
</code>```

Upon touching the screen, the log states the following:

```<code>checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
</code>```

I am quite new to the Haxe language, so my guess is that I am missing something obvious, even after I have followed the Haxe API very closely. This is the example used from the Haxe API page:

```<code>var map4 = ["M"=>"Monday", "T"=>"Tuesday"];
for (value in map4) {
    trace(value); // Monday \n Tuesday
}
</code>```

All explanations are welcome!

Added ControlUnit class:

```<code>import com.stencyl.models.Actor;

class ControlUnit
{
    static var actor;
    static var center;
    static var touchID;

    public function new(mActor:Actor, mPosition:Vector2, mTouchID:Int)
    {
        actor = mActor;
        center = mPosition;
        touchID = mTouchID;
    }

    public function GetActor():Actor{
        return(actor);
    }

    public function GetCenter():Vector2{
        return(center);
    }

    public function GetTouchID():Int{
        return(touchID);
    }
}
</code>```

答:
You just used static for vars in class definitions - they aren't instance aware/based.
Check 'properties', getters, setters etc. in https://haxe.org/manual/class-field-property.html

Title: Haxe for loop only uses last item

Body:
After some hours doing some testing I figured out that my map contains the correct values, but the loop that I am using only seems to be using the last added value in this map. Am I missing something obvious here?

The function that adds items to the map: (controls is the map variable)

public static function CreateThumbstick(mActorType:ActorType, mLocation:Int, mDirectionLock:Int)
    {
        var controllerName = "Thumbstick"+mLocation;
        if(!controls.exists(controllerName)){

            createRecycledActor(mActorType, 0, 0, Script.FRONT);
            var lastActor = getLastCreatedActor();
            var myPosition = GetPosition(controllerName, lastActor);
            lastActor.setX(myPosition.x);
            lastActor.setY(myPosition.y);
            var myPos = new Vector2(lastActor.getXCenter(), lastActor.getYCenter());
            var controlUnit = new ControlUnit(lastActor, myPos, -1);
            controls.set(controllerName, controlUnit);

            trace("added key: " + controllerName +" with value: "+ lastActor);
        } else {
            trace("!!WARNING!! Control unit already exists in this position. Command ignored!");
        }
    }

Upon creating 3 thumbsticks, the log states the following:

added key: Thumbstick1 with value: [Actor 1,Thumbstick]
added key: Thumbstick2 with value: [Actor 2,Thumbstick]
added key: Thumbstick3 with value: [Actor 3,Thumbstick]

When the screen is touched, it should loop through each item in my map, but it is using the last added item 3 times to check the distance with, rather then all 3 items once. Here is the Listener that is being called when the screen is touched:

addMultiTouchStartListener(function(event:TouchEvent, list:Array<Dynamic>):Void
        {
            for (unit in controls){
                trace(lastDebugLine + "checking distance to " + unit.GetActor());
                if(GetDistance(unit.GetCenter(), touch.GetPosition()) < 64){
                    break;
                }
            }
        });
// used "touch.GetPosition()" instead of actuall code for easy reading. This is not causing any problems!

Upon touching the screen, the log states the following:

checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]

I am quite new to the Haxe language, so my guess is that I am missing something obvious, even after I have followed the Haxe API very closely. This is the example used from the Haxe API page:

var map4 = ["M"=>"Monday", "T"=>"Tuesday"];
for (value in map4) {
    trace(value); // Monday \n Tuesday
}

All explanations are welcome!

Added ControlUnit class:

import com.stencyl.models.Actor;

class ControlUnit
{
    static var actor;
    static var center;
    static var touchID;

    public function new(mActor:Actor, mPosition:Vector2, mTouchID:Int)
    {
        actor = mActor;
        center = mPosition;
        touchID = mTouchID;
    }

    public function GetActor():Actor{
        return(actor);
    }

    public function GetCenter():Vector2{
        return(center);
    }

    public function GetTouchID():Int{
        return(touchID);
    }
}

ContentLicense: CC BY-SA 4.0


答:
you can use keyup here better and checking for $(this).val().length would be better.

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    if ($(this).val().length > 0) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}</code>```

  <input type="text" class="search-hotels">

×

```

Title: How does the keydown event work?

Body:
you can use keyup here better and checking for $(this).val().length would be better.

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    if ($(this).val().length > 0) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>


答:
It should be if ($(this).val()) otherwise your checking if it's empty.
Also, use keyup as keydown is capturing your val() before it actually has a value.

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}</code>```

  <input type="text" class="search-hotels">

×

```

Title: How does the keydown event work?

Body:
It should be if ($(this).val()) otherwise your checking if it's empty.
Also, use keyup as keydown is capturing your val() before it actually has a value.

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>


问:
converting a timestamp to "X second(s) ago", "X minute(s) ago", "X hour(s) ago" etc
Does anyone if php has built in functionally to do this?

Thanks

答:
There is no built in function for this....but the following function will do it.</p>

```<code><?php
function nicetime($date)
{
    if(empty($date)) {
        return "No date provided";
    }

    $periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $lengths         = array("60","60","24","7","4.35","12","10");

    $now             = time();
    $unix_date         = strtotime($date);

       // check validity of date
    if(empty($unix_date)) {
        return "Bad date";
    }

    // is it future date or past date
    if($now > $unix_date) {
        $difference     = $now - $unix_date;
        $tense         = "ago";

    } else {
        $difference     = $unix_date - $now;
        $tense         = "from now";
    }

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }

    $difference = round($difference);

    if($difference != 1) {
        $periods[$j].= "s";
    }

    return "$difference $periods[$j] {$tense}";
}

$date = "2009-03-04 17:45";
$result = nicetime($date); // 2 days ago

?>
</code>```

Body:
There is no built in function for this....but the following function will do it.

<?php
function nicetime($date)
{
    if(empty($date)) {
        return "No date provided";
    }

    $periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $lengths         = array("60","60","24","7","4.35","12","10");

    $now             = time();
    $unix_date         = strtotime($date);

       // check validity of date
    if(empty($unix_date)) {
        return "Bad date";
    }

    // is it future date or past date
    if($now > $unix_date) {
        $difference     = $now - $unix_date;
        $tense         = "ago";

    } else {
        $difference     = $unix_date - $now;
        $tense         = "from now";
    }

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }

    $difference = round($difference);

    if($difference != 1) {
        $periods[$j].= "s";
    }

    return "$difference $periods[$j] {$tense}";
}

$date = "2009-03-04 17:45";
$result = nicetime($date); // 2 days ago

?>


问:
force ajax to return 200 on error
I want to hide the exceptions thrown in the console so I want to hard-code the status code to 200 for all exceptions. In my case, I want to change a 500 internal server error response.

I know it's a bad practise but there are cases that can be used..

答:
You'll need to use a try/catch. Here's a dummy example:</p>

```<code>try {

  return json_encode(array(
    'code' => '200',
    'result' => array()
  ));

} catch (MissingArgumentException $e) {

  // Known exception
  return json_encode(array(
    'code' => '400',
    'message' => 'Bad request: missing argument.',
    'result' => null
  ));

} catch (\Exception $e) {

  // Default exception
  return json_encode(array(
    'code' => '500',
    'message' => sprintf('An error occured: %s', $e->getMessage()),
    'result' => null
  ));

}
</code>```

Title: force ajax to return 200 on error

Body:
You'll need to use a try/catch. Here's a dummy example:

try {

  return json_encode(array(
    'code' => '200',
    'result' => array()
  ));

} catch (MissingArgumentException $e) {

  // Known exception
  return json_encode(array(
    'code' => '400',
    'message' => 'Bad request: missing argument.',
    'result' => null
  ));

} catch (\Exception $e) {

  // Default exception
  return json_encode(array(
    'code' => '500',
    'message' => sprintf('An error occured: %s', $e->getMessage()),
    'result' => null
  ));

}


问:
How can I pass a parameter from the xaml markup file to the UserControl constructor?
I have a StepsWnd window in which UserControl StepProp is used twice, declared in a separate file.

```<code> <Window x:Class="MyProject.StepsWnd"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:c1="http://schemas.componentone.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyProject"
    Height="550" Width="850">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <local:StepProp Grid.Column="0" DataContext="{Binding Path=PrevStepVM}" x:Name="m_PrevStep"/>
        <local:StepProp Grid.Column="1" DataContext="{Binding Path=CurStepVM}" x:Name="m_CurStep"/>
    </Grid>
</Window>
</code>```

When the StepsWnd window is created, the StepProp constructor is called twice - for m_PrevStep and for m_CurStep.

```<code>public class StepProp : UserControl
{
    public StepProp()
    {
        InitializeComponent();
    }
    //...
}
</code>```

How can I pass a parameter to the StepProp class constructor from the markup of the StepsWnd window, so that I can identify who is calling the constructor, m_PrevStep or m_CurStep? To get something like this?

```<code>public class StepProp : UserControl
{
    public StepProp(object parameter)
    {
        InitializeComponent();
        if ((string)parameter == "PrevStep")
        {
            //todo somthing
        }
        else if ((string)Param == "CurStep")
        {
            //todo somthing else
        }
    }
    //...
}
</code>```

答:
How can I pass a parameter to the StepProp class constructor from the markup of the StepsWnd window, so that I can identify who is calling the constructor, m_PrevStep or m_CurStep?

You can't. XAML is a markup language and you cannot create an instance of a UserControl using any other constructor than the default one that doesn't accept any arguments. So forget about using dependency injection in XAML.

If you want the constructor to behave differently depending on which instance you are creating, you should probably consider creating two different UserControl types that for example may share the same base class or inheriting from one another.

Alternatively you could define and set a property as suggested in the comments:

```<code><local:StepProp x:Name="m_PrevStep" YourProperty="m_PrevStep" />
</code>```

...and handle any logic in the setter or the property (or the callback if you are defining a dependency propery).

Note that the property value won't be available in the constructor though as the instance must be created before the XAML processer can actually set the property.

Body:
I have a StepsWnd window in which UserControl StepProp is used twice, declared in a separate file.

 <Window x:Class="MyProject.StepsWnd"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:c1="http://schemas.componentone.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyProject"
    Height="550" Width="850">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <local:StepProp Grid.Column="0" DataContext="{Binding Path=PrevStepVM}" x:Name="m_PrevStep"/>
        <local:StepProp Grid.Column="1" DataContext="{Binding Path=CurStepVM}" x:Name="m_CurStep"/>
    </Grid>
</Window>

When the StepsWnd window is created, the StepProp constructor is called twice - for m_PrevStep and for m_CurStep.

public class StepProp : UserControl
{
    public StepProp()
    {
        InitializeComponent();
    }
    //...
}

How can I pass a parameter to the StepProp class constructor from the markup of the StepsWnd window, so that I can identify who is calling the constructor, m_PrevStep or m_CurStep? To get something like this?

public class StepProp : UserControl
{
    public StepProp(object parameter)
    {
        InitializeComponent();
        if ((string)parameter == "PrevStep")
        {
            //todo somthing
        }
        else if ((string)Param == "CurStep")
        {
            //todo somthing else
        }
    }
    //...
}

Body:
How can I pass a parameter to the StepProp class constructor from the markup of the StepsWnd window, so that I can identify who is calling the constructor, m_PrevStep or m_CurStep?

You can't. XAML is a markup language and you cannot create an instance of a UserControl using any other constructor than the default one that doesn't accept any arguments. So forget about using dependency injection in XAML.

If you want the constructor to behave differently depending on which instance you are creating, you should probably consider creating two different UserControl types that for example may share the same base class or inheriting from one another.

Alternatively you could define and set a property as suggested in the comments:

<local:StepProp x:Name="m_PrevStep" YourProperty="m_PrevStep" />

...and handle any logic in the setter or the property (or the callback if you are defining a dependency propery).

Note that the property value won't be available in the constructor though as the instance must be created before the XAML processer can actually set the property.


问:
How to catch exceptions in SendMailAsync method
I have a C# wcf Windows service in .net 4.5 that sends emails to about 1000 different  customers daily. I would like to try sending the emails async using this snippet of code I found here on SO, but how should I wrap it to catch exceptions?

```<code>public async Task SendAsync(string subject, string body, string recipient)
{
    var mailMessage = new MailMessage("me@example.com", recipient, subject, body);
    mailMessage.IsBodyHtml = true;

    using(var client = new SmtpClient("mysmtpserver"))
    {
        try
        {
            await client.SendMailAsync(mailMessage);
        }
        catch (Exception ex)
        {
           // Log here
        }
    }
}
</code>```

I'm expecting exceptions from invalid e-mail adresses and server timeouts.

Should I just wrap the await Call in a try-catch? Not sure this will work.

Also where is the best place to put the foreach loop that runs through all mail adresses?

Thanks.

答:
I know that this is a old post and it is answered already but I am able to catch await calls using this method.

public async Task < JsonResult > UserDelete(string username) {
  // return obj
  MFFCommon retval = new MFFCommon();

  // get user
  var user = UserManager.FindByName(username);

  // starts a task
  Task removeUserFromAgency = await Task.Factory.StartNew(async() => {
    await removeUserFromCurrentAgency(user);
  });

  // optional, but this will wait 3 sec before checking if it is complete.
  removeUserFromAgency.Wait(3000);

  if (removeUserFromAgency.IsCompleted) {
    retval.taskResponse = "True";
    retval.taskError = null;
    return Json(retval, JsonRequestBehavior.AllowGet);
  } else {
    // This is where the exception is at.
    retval.taskResponse = "False";
    retval.taskError = removeUserFromAgency.Exception.Message;
    return Json(retval, JsonRequestBehavior.AllowGet);
  }
}```

Body:
I have a C# wcf Windows service in .net 4.5 that sends emails to about 1000 different  customers daily. I would like to try sending the emails async using this snippet of code I found here on SO, but how should I wrap it to catch exceptions?

public async Task SendAsync(string subject, string body, string recipient)
{
    var mailMessage = new MailMessage("me@example.com", recipient, subject, body);
    mailMessage.IsBodyHtml = true;

    using(var client = new SmtpClient("mysmtpserver"))
    {
        try
        {
            await client.SendMailAsync(mailMessage);
        }
        catch (Exception ex)
        {
           // Log here
        }
    }
}

I'm expecting exceptions from invalid e-mail adresses and server timeouts.

Should I just wrap the await Call in a try-catch? Not sure this will work.

Also where is the best place to put the foreach loop that runs through all mail adresses?

Thanks.


问:
Return both string and integer from a template function in C++
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

```<code>template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}
</code>```

and I would like to be able to call it like:

```<code>bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");
</code>```

as an alternative for the char*, a string would be also fine:

```<code>string sBrokerUrl = getEntry<string>(node, "BrokerUrl");
</code>```

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

答:
Like @tobi303 said in the comment, you should specialize the template.
There is no need for fancy SFINAE or other tricks.

```<code>#include <iostream>
#include <type_traits>

using namespace std;

template<typename entryType>
entryType getEntry(const char* entryKey);

template <>
int getEntry<int>(const char* entryKey)
{
    return 1;
}
template <>
bool getEntry<bool>(const char* entryKey)
{
    return false;
}
template <>
string getEntry<string>(const char* entryKey)
{
    return "asd";
}

int main() {
    bool bPublisher = getEntry<bool>("Publisher");
    int QoS = getEntry<int>("QualityOfService");
    string sBrokerUrl = getEntry<string>("BrokerUrl");

    cout << bPublisher << '\n' << QoS << '\n'<< sBrokerUrl << '\n';
}
</code>```

DEMO: https://wandbox.org/permlink/kyLuPyblb4zBi9fE

Body:
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}

and I would like to be able to call it like:

bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");

as an alternative for the char*, a string would be also fine:

string sBrokerUrl = getEntry<string>(node, "BrokerUrl");

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

Body:
Like @tobi303 said in the comment, you should specialize the template.
There is no need for fancy SFINAE or other tricks.

#include <iostream>
#include <type_traits>

using namespace std;

template<typename entryType>
entryType getEntry(const char* entryKey);

template <>
int getEntry<int>(const char* entryKey)
{
    return 1;
}
template <>
bool getEntry<bool>(const char* entryKey)
{
    return false;
}
template <>
string getEntry<string>(const char* entryKey)
{
    return "asd";
}

int main() {
    bool bPublisher = getEntry<bool>("Publisher");
    int QoS = getEntry<int>("QualityOfService");
    string sBrokerUrl = getEntry<string>("BrokerUrl");

    cout << bPublisher << '\n' << QoS << '\n'<< sBrokerUrl << '\n';
}

DEMO: https://wandbox.org/permlink/kyLuPyblb4zBi9fE