问:
Picture to database uploading not working in Codeigniter
I'm making a website on the CodeIgniter framework so users can upload products on the website to the database. I'm trying to make a function so users can upload pictures to my database but its not really working.

Here some info:
DB table name: products
The DB table column name that I want the pictures to be stored in: product_foto
picture folder: upload

```<code>My controller:
    <?php
     defined('BASEPATH') OR exit('No direct script access allowed');
     class Product extends CI_Controller {

     var $data = array();

     public function __construct()
     {
      parent::__construct();
      $this->load->model('product_model');
      $this->load->helper(array('form', 'url'));
     }

     public function product_form()
     {
      $save = array(
          'product_naam'          => $this->input->post('product_naam'),
          'product_beschrijving'          => $this->input->post('product_beschrijving'),
          'product_categorie'   => $this->input->post('product_categorie'),
          'ophaal_plaats'   => $this->input->post('ophaal_plaats'),
          'product_foto'  => $this->input->post('product_foto'),
          'date_created' => date('Y-m-d'),
          'date_updated' => date('Y-m-d')
           );

      $this->product_model->saveProduct($save);
      redirect('https://kadokado-ferran10.c9users.io/AlleCadeausController');
     }

     public function upload(){
      $config['upload_path'] = './upload/';
      $config['allowed_types'] = 'jpg|jpeg|png';

      $this->load->library('upload', $config);
      if(!$this->upload->do_upload('file')){
        $this->db->insert('products', array(
           'product_foto' => $this->upload->file_name
           ));
       $error = array('error'=>$this->upload->display_errors());
       $this->load->view('product_form', $error);
      }else{
       $file_data = $this->upload->data();
       $data['img'] = base_url().'/upload/'.$file_data['file_name'];
       header('location:https://kadokado-ferran10.c9users.io/Product/');
       }
     }

    }
</code>```

My model file:

```<code><?php
 defined('BASEPATH') OR exit('No direct script access allowed');
 class Product extends CI_Controller {

    var $data = array();
</code>```

My view file:

```<code><?php echo form_open_multipart('Product/upload'); ?>
    <input type="file" name="userfile" />

    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" name="name">
    </div>

    <input type="submit" name="submit" value="test" />

</form>
</code>```

When I submit the form the picture only gets added to the upload folder but it doesn't get added into the database column..

答:
Change your upload() function as follow

```<code>public function upload(){
    $config['upload_path'] = './upload/';
    $config['allowed_types'] = 'jpg|jpeg|png';

    $this->load->library('upload', $config);

    if(!$this->upload->do_upload('userfile')){
        $error = array('error'=>$this->upload->display_errors());
        $this->load->view('product_form', $error);
    }else{
        $file_data = $this->upload->data();
        $this->db->insert('products', array(
            'product_foto' => $file_data['file_name']
            ));
        $data['img'] = base_url().'/upload/'.$file_data['file_name'];
        header('location:https://kadokado-ferran10.c9users.io/Product/');
    }
}
</code>```

Body:
I'm making a website on the CodeIgniter framework so users can upload products on the website to the database. I'm trying to make a function so users can upload pictures to my database but its not really working.

Here some info:
DB table name: products
The DB table column name that I want the pictures to be stored in: product_foto
picture folder: upload

My controller:
    <?php
     defined('BASEPATH') OR exit('No direct script access allowed');
     class Product extends CI_Controller {

     var $data = array();

     public function __construct()
     {
      parent::__construct();
      $this->load->model('product_model');
      $this->load->helper(array('form', 'url'));
     }

     public function product_form()
     {
      $save = array(
          'product_naam'          => $this->input->post('product_naam'),
          'product_beschrijving'          => $this->input->post('product_beschrijving'),
          'product_categorie'   => $this->input->post('product_categorie'),
          'ophaal_plaats'   => $this->input->post('ophaal_plaats'),
          'product_foto'  => $this->input->post('product_foto'),
          'date_created' => date('Y-m-d'),
          'date_updated' => date('Y-m-d')
           );

      $this->product_model->saveProduct($save);
      redirect('https://kadokado-ferran10.c9users.io/AlleCadeausController');
     }

     public function upload(){
      $config['upload_path'] = './upload/';
      $config['allowed_types'] = 'jpg|jpeg|png';

      $this->load->library('upload', $config);
      if(!$this->upload->do_upload('file')){
        $this->db->insert('products', array(
           'product_foto' => $this->upload->file_name
           ));
       $error = array('error'=>$this->upload->display_errors());
       $this->load->view('product_form', $error);
      }else{
       $file_data = $this->upload->data();
       $data['img'] = base_url().'/upload/'.$file_data['file_name'];
       header('location:https://kadokado-ferran10.c9users.io/Product/');
       }
     }

    }

My model file:

<?php
 defined('BASEPATH') OR exit('No direct script access allowed');
 class Product extends CI_Controller {

    var $data = array();

My view file:

<?php echo form_open_multipart('Product/upload'); ?>
    <input type="file" name="userfile" />

        Name
        <input type="text" name="name">

    <input type="submit" name="submit" value="test" />

</form>

When I submit the form the picture only gets added to the upload folder but it doesn't get added into the database column..

Body:
Change your upload() function as follow

public function upload(){
    $config['upload_path'] = './upload/';
    $config['allowed_types'] = 'jpg|jpeg|png';

    $this->load->library('upload', $config);

    if(!$this->upload->do_upload('userfile')){
        $error = array('error'=>$this->upload->display_errors());
        $this->load->view('product_form', $error);
    }else{
        $file_data = $this->upload->data();
        $this->db->insert('products', array(
            'product_foto' => $file_data['file_name']
            ));
        $data['img'] = base_url().'/upload/'.$file_data['file_name'];
        header('location:https://kadokado-ferran10.c9users.io/Product/');
    }
}


来源: stackexchange

问:
Parse Server Custom Domain On Heroku
I have set up a Parse Server on Heroku, with an MLab MongoDB.  Everything works fine, & when I visit https://myapp.herokuapp.com I see "Make sure to star the parse-server repo on GitHub!".

I can successfully perform API functions through my Postman Console, for example logging in via the following REST API call: https://myapp.herokuapp.com/parse/login?username=admin&password=password.

I can also perform other REST API POST, GET, etc. as you would expect.

I'm now trying to use my own domain "api.mydomain.net".  In the Heroku App > Settings > Custom Domains, I have set domain to "api.mydomain.net" & "myapp.herokuapp.com" as the DNS target.

I've also added a CNAME record to the DNS pointing "api" to "myapp.herokuapp.com".

When I visit https://api.mydomain.net I see the "Make sure to star the parse-server repo on GitHub!" message confirming that the CNAME record works, however when I go to perform the same REST API Login call https://api.mydomain.net/parse/login?username=admin&password=password I get the response:

Could not get any response.

This seems to be like an error connecting to
  https://api.mydomain.net/parse/login?username=admin&password=password.

What am I missing?

答:
You are trying to securely connect to the Parse Server with https. So you have to add a TSL certificate for your Heroku app in the Heroku dashboard.

Open Heroku app in Heroku dashboard

Open Settings tab

In section Domains and certificates click Configure SSL and choose Automatically configure using Automated Certificate Management.

Click Add domain to add the domain from which the request should be forwarded, e.g. api.example.com.

On your domain registrar's website set the CNAME for api.example.com to the domain in the Heroku app settings, e.g. api.example.com.herokudns.com

Wait until the status of the domain in the Heroku dashboard is Done

ContentLicense: CC BY-SA 3.0

Title: Parse Server Custom Domain On Heroku


问:
Calling String in Bean Class Returns Null
I have a bean class that successfully retrieves a string value from another class.= (It prints it just fine within the bean class)

When I try and call that class/string it returns as null.

Here is the relevant code:

```<code> public class cityModel implements Serializable {
    private String fajr;

    public void setFajr(String fajr) {
        this.fajr= fajr;

    }
    public String getFajr() {

        return fajr;
    }
}
 public void mutePrayerTime(View view) {
    cityModel cityObj= new cityModel();
    String fajr=cityObj.getFajr();
    Log.d("LOGCAT", "" + cityObj.getFajr());

    //StringBuilder newFajr = new StringBuilder(fajr);
    //newFajr.delete(2,5);
    //Log.d("newFajr", String.valueOf(newFajr));
  //  Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);

   //alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );

}
</code>```

the Log.d tag LOGCAT returns as null

edit:
Code that the bean class retrieves the string from:

```<code>  protected void outputTimings(JSONArray jsonArray) {
        String[] prayers = {"fajr", "shurooq", "dhuhr", "asr", "maghrib", "isha"};
        cityModel cityObj;
        try {
            cityObj= new cityModel();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject cityObject =
                        jsonArray.getJSONObject(i);
                result = result + "fajr" + " : "
                        + cityObject.getString("fajr") + "\n" + result + "shurooq" + " : "
                        + cityObject.getString("shurooq") + "\n" + result + "dhuhr" + " : "
                        + cityObject.getString("dhuhr") + "\n" + result + "asr" + " : "
                        + cityObject.getString("asr") + "\n" + result + "maghrib" + " : "
                        + cityObject.getString("maghrib") + "\n" + result + "isha" + " : "
                        + cityObject.getString("isha") + "\n";

                cityObj.setFajr(""+cityObject.getString("fajr"));

            }
</code>```

答:
Have a look in this method:

```<code>public void mutePrayerTime(View view) {
    cityModel cityObj= new cityModel();
    String fajr=cityObj.getFajr();
    Log.d("LOGCAT", "" + cityObj.getFajr());

    //StringBuilder newFajr = new StringBuilder(fajr);
    //newFajr.delete(2,5);
    //Log.d("newFajr", String.valueOf(newFajr));
  //  Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);

   //alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );

}
</code>```

You're just creating cityObj like this cityModel cityObj= new cityModel(); at that point all its properties are null that's why you're seeing null in your log. You should pass the cityObj from your outputTimings method to the mutePrayerTime method:

```<code>public void mutePrayerTime(View view,cityModel cityObj) {
    Log.d("LOGCAT", "" + cityObj.getFajr());

    //StringBuilder newFajr = new StringBuilder(fajr);
    //newFajr.delete(2,5);
    //Log.d("newFajr", String.valueOf(newFajr));
    //  Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);

   //alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );

}
</code>```

and then in outputTimings:

```<code>cityObj.setFajr(""+cityObject.getString("fajr"));
someObj.mutePrayerTime(view, cityObj);
</code>```

Body:
I have a bean class that successfully retrieves a string value from another class.= (It prints it just fine within the bean class)

When I try and call that class/string it returns as null.

Here is the relevant code:

 public class cityModel implements Serializable {
    private String fajr;

    public void setFajr(String fajr) {
        this.fajr= fajr;

    }
    public String getFajr() {

        return fajr;
    }
}
 public void mutePrayerTime(View view) {
    cityModel cityObj= new cityModel();
    String fajr=cityObj.getFajr();
    Log.d("LOGCAT", "" + cityObj.getFajr());

    //StringBuilder newFajr = new StringBuilder(fajr);
    //newFajr.delete(2,5);
    //Log.d("newFajr", String.valueOf(newFajr));
  //  Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);

   //alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );

}

the Log.d tag LOGCAT returns as null

edit:
Code that the bean class retrieves the string from:

  protected void outputTimings(JSONArray jsonArray) {
        String[] prayers = {"fajr", "shurooq", "dhuhr", "asr", "maghrib", "isha"};
        cityModel cityObj;
        try {
            cityObj= new cityModel();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject cityObject =
                        jsonArray.getJSONObject(i);
                result = result + "fajr" + " : "
                        + cityObject.getString("fajr") + "\n" + result + "shurooq" + " : "
                        + cityObject.getString("shurooq") + "\n" + result + "dhuhr" + " : "
                        + cityObject.getString("dhuhr") + "\n" + result + "asr" + " : "
                        + cityObject.getString("asr") + "\n" + result + "maghrib" + " : "
                        + cityObject.getString("maghrib") + "\n" + result + "isha" + " : "
                        + cityObject.getString("isha") + "\n";

                cityObj.setFajr(""+cityObject.getString("fajr"));

            }

Body:
Have a look in this method:

public void mutePrayerTime(View view) {
    cityModel cityObj= new cityModel();
    String fajr=cityObj.getFajr();
    Log.d("LOGCAT", "" + cityObj.getFajr());

    //StringBuilder newFajr = new StringBuilder(fajr);
    //newFajr.delete(2,5);
    //Log.d("newFajr", String.valueOf(newFajr));
  //  Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);

   //alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );

}

You're just creating cityObj like this cityModel cityObj= new cityModel(); at that point all its properties are null that's why you're seeing null in your log. You should pass the cityObj from your outputTimings method to the mutePrayerTime method:

public void mutePrayerTime(View view,cityModel cityObj) {
    Log.d("LOGCAT", "" + cityObj.getFajr());

    //StringBuilder newFajr = new StringBuilder(fajr);
    //newFajr.delete(2,5);
    //Log.d("newFajr", String.valueOf(newFajr));
    //  Intent alarm = new Intent(AlarmClock.ACTION_SET_ALARM);

   //alarm.putExtra(AlarmClock.EXTRA_HOUR, fajr );

}

and then in outputTimings:

cityObj.setFajr(""+cityObject.getString("fajr"));
someObj.mutePrayerTime(view, cityObj);


问:
facebook messenger an array of generic templates
I have noticed we have quick_reply and to send multiple of them, you can use quick_replies. https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies#quick_reply

How do I send multiple generic template attachments in one message. This is to enable a user scroll through and choose one of the templates.

I have seen one implemented by the Guardian bot. https://www.messenger.com/t/10513336322

答: You attach an array of elements as seen here: https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template</p>


问:
Inline initialization of two-dimensional typed array in IronPython
I have a question about typed array initialization in IronPython. I want to initialize inline typed two-dimensional array in IronPython.

In IronPython I discovered how to initialize simple typed array:

```<code>pythonTypedArray = Array[int]([0, 1, 2, 3, 4])
</code>```

and how to initialize typed array of arrays:

```<code>pythonTypedArrayOfArrays = Array[Array[int]]([Array[int]([0, 1]), Array[int]([2, 3])])
</code>```

For example, in C# I can do like so:

```<code>int[,] twoDimensionalArray = new int[,] { {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9} };
</code>```

Can I initialize inline two-dimensional typed array in IronPython? If no, what is the best way to initialize two-dimensional typed array in IronPython?

Body:
I have a question about typed array initialization in IronPython. I want to initialize inline typed two-dimensional array in IronPython.

In IronPython I discovered how to initialize simple typed array:

pythonTypedArray = Array[int]([0, 1, 2, 3, 4])

and how to initialize typed array of arrays:

pythonTypedArrayOfArrays = Array[Array[int]]([Array[int]([0, 1]), Array[int]([2, 3])])

For example, in C# I can do like so:

int[,] twoDimensionalArray = new int[,] { {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9} };

Can I initialize inline two-dimensional typed array in IronPython? If no, what is the best way to initialize two-dimensional typed array in IronPython?

Body:
import numpy
a = numpy.arange(12)
a.shape = 3,  4
print(a)
>>>
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


问:
when i redirect forcefully http to https it shows redirected you too many times
I apply like this

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^Product/Category/([^/]*)$ /Product/index.php?category=$1 [L]
RewriteRule ^Pages/([^/]*)$ /Allpages/?Pages=$1 [L]
RewriteRule ^Products/([^/]*)$ /Product/ProductPage.php?product=$1 [L]

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
</code>```

but, It shows www.example.com redirected you too many times.

答:
Okay @ravi i have got your problem so please use this solution.

New Code :

```<code>  <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^Product/Category/([^/]*)$ /Product/index.php?category=$1 [L]
  RewriteRule ^Pages/([^/]*)$ /Allpages/?Pages=$1 [L]
  RewriteRule ^Products/([^/]*)$ /Product/ProductPage.php?product=$1 [L]

  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI}
 </IfModule>
</code>```

Body:
I apply like this

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^Product/Category/([^/]*)$ /Product/index.php?category=$1 [L]
RewriteRule ^Pages/([^/]*)$ /Allpages/?Pages=$1 [L]
RewriteRule ^Products/([^/]*)$ /Product/ProductPage.php?product=$1 [L]

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

but, It shows www.example.com redirected you too many times.

Body:
Okay @ravi i have got your problem so please use this solution.

New Code :

  <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^Product/Category/([^/]*)$ /Product/index.php?category=$1 [L]
  RewriteRule ^Pages/([^/]*)$ /Allpages/?Pages=$1 [L]
  RewriteRule ^Products/([^/]*)$ /Product/ProductPage.php?product=$1 [L]

  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI}
 </IfModule>


问:
IGrouping, IEnumerable and Pairs
I am having some trouble. I am supposed to implement a definition of GroupBy.
I am not sure how to group the values in Pairs, can someone help me? Can't use LINQ

Definition of Pair:

```<code>class Pair<K, V> {
    public Pair(K key, V value) {
        Key = key;
        Value = value;
    }
    public K Key { get; set; }
    public V Value { get; set; }
}
</code>```

main:

```<code>string[] src = { "ola", "super", "isel", "ole", "mane", "xpto", "aliba" };
foreach (Pair<int, IEnumerable<string>> pair in src.GroupBy(s => s.Length))
{
    Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.Value));
}
</code>```

Output

```<code>/**
* Output:
* 3: ola, ole
* 5: super, aliba
* 4: isel, mane, xpto
*/
</code>```

答:
To make a Pair<int, IEnumerable<string>> from an IEnumerable<IGrouping<TKey, TSource>> you´ll need this:

```<code>foreach (Pair<int, IEnumerable<string>> pair in src.GroupBy(s => s.Length)
    .Select(x => new Pair<int, IEnumerable<string>>(x.Key, x.ToList()))
)
</code>```

But I´m not sure why anyone should use this.

Quite easier to use is just this:

```<code>foreach (var pair in src.GroupBy(s => s.Length))
{
    Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.ToList()));
}
</code>```

This way you dn´t even need your Pair-class.

Title: IGrouping, IEnumerable and Pairs

Body:
I am having some trouble. I am supposed to implement a definition of GroupBy.
I am not sure how to group the values in Pairs, can someone help me? Can't use LINQ

Definition of Pair:

class Pair<K, V> {
    public Pair(K key, V value) {
        Key = key;
        Value = value;
    }
    public K Key { get; set; }
    public V Value { get; set; }
}

main:

string[] src = { "ola", "super", "isel", "ole", "mane", "xpto", "aliba" };
foreach (Pair<int, IEnumerable<string>> pair in src.GroupBy(s => s.Length))
{
    Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.Value));
}

Output

/**
* Output:
* 3: ola, ole
* 5: super, aliba
* 4: isel, mane, xpto
*/

Body:
To make a Pair<int, IEnumerable<string>> from an IEnumerable<IGrouping<TKey, TSource>> you´ll need this:

foreach (Pair<int, IEnumerable<string>> pair in src.GroupBy(s => s.Length)
    .Select(x => new Pair<int, IEnumerable<string>>(x.Key, x.ToList()))
)

But I´m not sure why anyone should use this.

Quite easier to use is just this:

foreach (var pair in src.GroupBy(s => s.Length))
{
    Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.ToList()));
}

This way you dn´t even need your Pair-class.


问:
Unable to assign value to textbox in angularjs
Hi I am developing web application in angularjs. I have one textbox and i am trying to bind data using some API's. Below is my html code.

```<code>  <input class="with-icon" type="text" name="groupname" placeholder="{{ 'Group Name' | translate }}" ng-model="user.name" required my-maxlength="50" ng-readonly="groupname">
</code>```

Below is my Angular code.

```<code>function getgroupbyID(groupID) {
            var getsavedvechilceUrl = baseurl + "api/RolesPermission/getbyID/" + groupID;
            $http.get(getsavedvechilceUrl).then(function (response) {
                $scope.user.name = response.data.dataAPI.groupname;
            }, function (error) {

            })
        }
</code>```

When the above code runs i ended up in error  Cannot set property 'name' of undefined in the $scope.user.name. May i know hwy i am getting this error? Any help would be appreciated. Thank you

答:
use this text box ng-init="user={}"

```<code> <input class="with-icon" type="text" ng-init="user={}" name="groupname"
placeholder="{{ 'Group Name' | translate }}" ng-model="user.name" required
my-maxlength="50" ng-readonly="groupname">
</code>```

Body:
Hi I am developing web application in angularjs. I have one textbox and i am trying to bind data using some API's. Below is my html code.

  <input class="with-icon" type="text" name="groupname" placeholder="{{ 'Group Name' | translate }}" ng-model="user.name" required my-maxlength="50" ng-readonly="groupname">

Below is my Angular code.

function getgroupbyID(groupID) {
            var getsavedvechilceUrl = baseurl + "api/RolesPermission/getbyID/" + groupID;
            $http.get(getsavedvechilceUrl).then(function (response) {
                $scope.user.name = response.data.dataAPI.groupname;
            }, function (error) {

            })
        }

When the above code runs i ended up in error  Cannot set property 'name' of undefined in the $scope.user.name. May i know hwy i am getting this error? Any help would be appreciated. Thank you

Body:
use this text box ng-init="user={}"

 <input class="with-icon" type="text" ng-init="user={}" name="groupname"
placeholder="{{ 'Group Name' | translate }}" ng-model="user.name" required
my-maxlength="50" ng-readonly="groupname">


问:
Using margin:auto to vertically-align a div
So I know we can center a div horizontally if we use margin:0 auto;. Should margin:auto auto; work how I think it should work? Centering it vertically as well?

Why doesn't vertical-align:middle; work either?

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    background:yellow;
    width:200px;
    margin:auto auto;
    padding:10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div></code>```

JSFiddle

答:
.black {
    display:flex;
    flex-direction: column;
    height: 200px;
    background:grey
}
.message {
    background:yellow;
    width:200px;
    padding:10px;
    margin: auto auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div></code>```

Body:
So I know we can center a div horizontally if we use margin:0 auto;. Should margin:auto auto; work how I think it should work? Centering it vertically as well?

Why doesn't vertical-align:middle; work either?

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    background:yellow;
    width:200px;
    margin:auto auto;
    padding:10px;
}

        This is a popup message.

JSFiddle

Body:
.black {
    display:flex;
    flex-direction: column;
    height: 200px;
    background:grey
}
.message {
    background:yellow;
    width:200px;
    padding:10px;
    margin: auto auto;
}

<div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div>


问:
How to install/load iptables “rpfilter” module in a bash script?
Platform: Asuswrt-Merlin using kernel 2.6.36

How do you install/load the iptables "rpfilter" module in a bash script ?

答:
As far as I know that netfilter module is not supported on kernels 2.6.x. The support was added starting with kernel 3.x

Please check the link bellow:
https://www.snbforums.com/threads/how-to-load-iptables-rpfilter-module.39842/

OwnerDisplayName: uihdff


问:
Pre-/suffixing a Source stream in Play 2.5
Lets say I have a Play Controller with this method -

```<code>def persons(): Action[AnyContent] =
  Action { _ =>
    Ok.chunked(personSource.map { p => JsObject(p) }
  )
}
</code>```

The Akka Source stream is a large but finite stream of Persons from, say our db. Loading all of it into memory at once would lead to out of memory exceptions.

The code above works fine, I get a long stream of json objects:

```<code>{"name": "TestPerson1}{"name": "TestPerson2"}
</code>```

But now a client has requested the response has this format:

```<code>[{"name": "TestPerson1},{"name": "TestPerson2"}]
</code>```

I am having troubles finding how to emit prefix/suffix to the stream. Maybe a filter, or nesting Actions? But the examples I find of that tend to operate on the Request such as redirecting, or having side-effecting operations such as logging something before handing over processing to the inner Action.

I would like to emit "[" at the start of the http response, keep the Source async chunked processing in the middle, and then emit a "]" at the end.

答:
Solution found thanks to @cchantep

```<code>val persons = source.map { p => JsObject(p).toString }.intersperse(",")
Action { _ =>
  Ok.chunked(Source(List("[")).concat(persons).concat(Source(List("]"))))
}
</code>```

Or even simpler (thanks to this page, which I didn't find before):

```<code>Ok.chunked(source.map { p => JsObject(p).toString }.intersperse("[", ",", "]") )
</code>```

Body:
Lets say I have a Play Controller with this method -

def persons(): Action[AnyContent] =
  Action { _ =>
    Ok.chunked(personSource.map { p => JsObject(p) }
  )
}

The Akka Source stream is a large but finite stream of Persons from, say our db. Loading all of it into memory at once would lead to out of memory exceptions.

The code above works fine, I get a long stream of json objects:

{"name": "TestPerson1}{"name": "TestPerson2"}

But now a client has requested the response has this format:

[{"name": "TestPerson1},{"name": "TestPerson2"}]

I am having troubles finding how to emit prefix/suffix to the stream. Maybe a filter, or nesting Actions? But the examples I find of that tend to operate on the Request such as redirecting, or having side-effecting operations such as logging something before handing over processing to the inner Action.

I would like to emit "[" at the start of the http response, keep the Source async chunked processing in the middle, and then emit a "]" at the end.

Body:
Solution found thanks to @cchantep

val persons = source.map { p => JsObject(p).toString }.intersperse(",")
Action { _ =>
  Ok.chunked(Source(List("[")).concat(persons).concat(Source(List("]"))))
}

Or even simpler (thanks to this page, which I didn't find before):

Ok.chunked(source.map { p => JsObject(p).toString }.intersperse("[", ",", "]") )


问:
How can I print all incoming data in Pythons Tornado?
I'm trying to get a basic grasp on what the communication is like between an ajax request and tornado, but I can't find any functions which give me something I can pass to print()

I've checked the API http://www.tornadoweb.org/en/stable/web.html and every function with the word "get" in it seems to require that I first know the name of the thing I'm trying to get.

I'm not quite there yet with my understanding, and would like to start by just printing everything there is to print.  All the headers, all the data, going in and out.

How do I do this?

```<code>#pseudo code
class MainHandler(tornado.web.RequestHandler):

    def get(self):
        everything = self.getIncomingHeaders + self.getDataSentByAjaxCall
        print(everything)
</code>```

答:
Do this:

```<code>def get(self):
    print("%r %s" % (self.request, self.request.body.decode()))
</code>```

For a "get" there is no request body, but you can put the same code in a "put" or "post" method and see the full request body along with headers, path, and so on.

Body:
I'm trying to get a basic grasp on what the communication is like between an ajax request and tornado, but I can't find any functions which give me something I can pass to print()

I've checked the API http://www.tornadoweb.org/en/stable/web.html and every function with the word "get" in it seems to require that I first know the name of the thing I'm trying to get.

I'm not quite there yet with my understanding, and would like to start by just printing everything there is to print.  All the headers, all the data, going in and out.

How do I do this?

#pseudo code
class MainHandler(tornado.web.RequestHandler):

    def get(self):
        everything = self.getIncomingHeaders + self.getDataSentByAjaxCall
        print(everything)

Body:
Do this:

def get(self):
    print("%r %s" % (self.request, self.request.body.decode()))

For a "get" there is no request body, but you can put the same code in a "put" or "post" method and see the full request body along with headers, path, and so on.


问:
Use cases of makePrisms with examples
It's not clear to me the difference between makeLense and makePrisms?

I'm aware that when we want to access a nested structure/data then use makeLense like this:

```<code>data Point = Point { _x :: Int, _y :: Int}
data Test= Test {_name :: String, _position :: Point}

makeLenses ''Point
makeLenses ''Test
</code>```

Then we can access or modify the component of Test or Point. For instance, we define a function:

```<code>modify :: Test -> Test
modify = over (position . x) (*8)
</code>```

So we can have:

```<code>let t1 = Test {_name= "Me", _position = Point {_x = 3, _y = 8}}
</code>```

then

```<code>modify t1
</code>```

would be:

```<code>Test {_name = "Me", _position = Point {_x = 24, _y = 8}}
</code>```

But, I don't know when and how to use makePrisms in the above example!

答:
In order to understand this, you must understand types, type variables, algebraic data types (sum and product types) and you must also understand typeclasses and the Functor typeclass in particular. If you don't understand these things, bookmark this page, then go off and understand them, possibly with this resource that I helped work on for precisely this purpose, to illustrate and explain these basics: http://happylearnhaskelltutorial.com

So before we get to Prisms, you first need to know what a Lens is.

A Lens is often described as a functional getter/setter, but that's more about the implementation and so forth.

I'd like to try an experiment of description here with you now.

Say I have a page of very small text with some words on it. Now, I hand you a piece of cardboard the same size as that page, only it has hole for a magnifying glass set up to focus on a particular word. That word is in a specific place in that page.

So we have these two things: a page, and a magnifying glass "card" without a magnifying glass... if we put a glass in, it focusses on a particular place on the page. Now someone comes along with another page with different words on it, but in the same layout as the first page.

It's easy to image that you can take that card, put it on the new page and it will focus on the different word in that same place.

As well as a magnifying glass, you also have a special "eraser/printer" glass that when you put it into the card allows you erase and type words over that page.

So to now apply this to Lens, you can see with this example how if we take one piece of data (a page of text), a lens that fits that data (a card with a hole in it that matches the shape of the page) and a function that can "get" or "set" (or maybe other things) (that is, the magnifying glass or the eraser/printer glass, or other types of glasses), well, from this we can view the smaller piece of data (the word) in the larger piece of data (the page) to extract it... or perhaps we can set a different matching piece of data into the spot on that page...

lens :: :: Functor f => (s -> a) -> (s -> b -> t) -> (a -> f b) -> s -> f t

What does this function do? It creates a lens from some functions. Now we have the framework above to understand what a lens is, we can undertsand this function. I say to you that the s variable stands for "state" and it corresponds to the type of the piece of paper that is the context that the lens will focus within. Next I can say the a type variable corresponds to the word on the page that the lens will focus on. What about b and t? They are the transformed a and s values if we decide to change the value of the a, and that change changes its type.

What is the Functor for then? we'll find out in a while. Well, first up let's make a lens to make this practical. So, back to our lens function, its first argument is the "getter" function, the second argument is the "setter" function (hence the types). Then there's one other argument. Well, because Haskell functions are curried that's actually the return type: a function s -> f t. Let's make that lens now.

Let's say we have a list of values [(1,(5,9)), (2,(3,6))] and we'd like to make a lens that focusses on the second value in the second nested tuple. That's silly, though, because you could just use snd . snd right? Yeah, you could, so it's not a great example, but all the better examples are more complex, so bear with me - we'll get to them, and besides, can your snd.snd function also SET, or have a function applied to it? No, I didn't think so! :) (okay okay I know you could use fmap (const val) to set, but can it also change the type? well this line of thought is actually what you end up with Lens with if you continue it to its logical conclusion as Edward Kmett did - that's where the Functor comes in!)

sndOfSndLens = lens (snd.snd) (\(x,(y,z)) newZ -> (x,(y,newZ)))

So what did we get? we got a function of this type sndOfSndLens :: Functor f => (a -> f t2) -> (t, (t1, a)) -> f (t, (t1, t2)).

So let's get our values out: map (view sndOfSnd) [(1,(5,9)), (2,(3,6))] -> [9,6] Nice! That works... let's set new values in: map (set sndOfSnd 2000) [(1,(5,9)), (2,(3,6))] -> [(1,(5,2000)),(2,(3,2000))] okay fine...

If it was just getters or setters, that's boring, but there's also a function called over which will take a lens and a transforming function and run that transformation on the function of the focus of the lens... so let's subtract 10 from each: map (over sndOfSnd (flip (-) 10)) [(1,(5,9)), (2,(3,6))] -> [(1,(5,-1)),(2,(3,-4))] that's cool! well I'll let you read the rest of the lens documentation to understand all the other functions, because they're deep and lenses compose, and you can do all sorts of other things with them, too.

Prism

I promised we'd get to Prism, and look we're here... A Lens is a specific "optic" (while also, sometimes confusingly referring to the entire set of optics in total, too, so watch out for that), and Prism is another optic, thankfully completely specific. If a Lens is an optic that works for focussing on a particular part of a product algebraic data type, then a Prims does the same thing for sum types. That's why we were able to make a lens that talked about pairs ((,)) because they're a product type... that is they combine two types into one. Lens lets you focus on one piece, or a path through those pieces. By the way, our lens we created above can easily be defined by composing the more generic built in lenses: _2 . _2. There are also operator versions of all the lens functions we were talking about. They look pretty crazy, but they have a logic to them. Read up about them!

Prism lets you focus on one path through a sum type. What's a good example? Well, let's say we have think about the Either data type. It's Either a b where it's defined as data Either a b = Left a | Right b. So there's a corresponding prism function that lets us build a Prism the same as our above value. What happens if we use the built in _Left which focusses on the left side of an Either, but we only have a Right 10 value? Let's see... but first, we should let you know that we can't use view any more because it might not work, so we need to use preview which will return a value that might fail (sorry, spoilers!):

preview _Left (Left 10) -> Just 10 and then the Right one? preview _Left (Right 10) -> Nothing. Okay that's sweet.

The set function works fine, because it can fail silently if it doesn't make sense: set _Left 30 (Left 10) -> Left 30. What happens when it doesn't work? set _Right 30 (Left 10) -> Left 10 that's right, nothing.

Cool... hopefully this explains Lenses and Prims. They're two really useful optics. The Lens library is full of them so I encourage you to look at them

What about the original question tho?

The original question was about makeLenses and makePrisms. These are template haskell expressions (that is, they're meta programming / similar to macros, but typed macros), and they let you automatically build your own lenses and/or prisms from your own data types. Hopefully it makes more sense now when you would pick one over the other and how they differ. This will give you at least an inkling into how they're different. To really understand, you should read the documentation and look up all the other functions and optics that are possible.

Welcome to the amazingly cool world of Lenses!

Title: Use cases of makePrisms with examples

Body:
It's not clear to me the difference between makeLense and makePrisms?

I'm aware that when we want to access a nested structure/data then use makeLense like this:

data Point = Point { _x :: Int, _y :: Int}
data Test= Test {_name :: String, _position :: Point}

makeLenses ''Point
makeLenses ''Test

Then we can access or modify the component of Test or Point. For instance, we define a function:

modify :: Test -> Test
modify = over (position . x) (*8)

So we can have:

let t1 = Test {_name= "Me", _position = Point {_x = 3, _y = 8}}

then

modify t1

would be:

Test {_name = "Me", _position = Point {_x = 24, _y = 8}}

But, I don't know when and how to use makePrisms in the above example!


问:
Print all routes from ZF2 modules
I'm trying to print all routes from my modules on "some page" with var_dump() or whatever debug function.

I have found lots of posts and samples but I can't get them printed and most examples fail in my code.

So far I think this is the best way to do so but where to use this code ?

```<code>// $sl instanceof Zend\ServiceManager\ServiceManager
$config = $sl->get('Config');
$routes = $config['router']['routes'];
</code>```

If you want to view all routes just for debugging purposes, you can use var_dump or similar on the router object:

```<code>// $sl instanceof Zend\ServiceManager\ServiceManager
$router = $sl->get('Router');
var_dump($router);
</code>```

答:
You may print all routes from in your controller's method. Look at the following example

module/Application/src/Application/Controller/IndexController.php

```<code><?php
namespace Application\Controller;

use Zend\View\Model\ViewModel;
use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    /**
     * @var array
     */
    protected $routes;

    /**
     * @param array $routes
     */
    public function __construct(array $routes)
    {
        // Here is the catch
        $this->routes = $routes;
    }

    public function indexAction()
    {
        // Thus you may print all routes
        $routes = $this->routes;

        echo '```';
        print_r($routes);
        echo '```';
        exit;

        return new ViewModel();
    }
}
</code>```

As we passed an array of routes to the constructor of IndexController. We need to make an factory of this controller. A factory is a class that creates instances of other classes.

module/Application/src/Application/Controller/IndexControllerFactory.php

```<code><?php
namespace Application\Controller;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class IndexControllerFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $serviceManager = $serviceLocator->getServiceLocator();
        $config = $serviceManager->get('Config');
        $routes = $config['router'];

        return new IndexController($routes);
    }
}
</code>```

A invokable class can not be constructed with arguments. Our controller would not work as invokables because we know we already passed an argument to its constructor. So we need to configure that in factories key under controllers key of our module.config.php

module/Application/config/module.config.php

```<code>'controllers' => [
    'invokables' => [
        // This would not work any more as we created a factory of it
        // 'Application\Controller\Index' => 'Application\Controller\IndexController',
    ],

    // We should do it thus
    'factories' => [
        'Application\Controller\Index' => 'Application\Controller\IndexControllerFactory',
    ],
],
</code>```

This answer has been edited for good practice as @av3 suggested!

Title: Print all routes from ZF2 modules

Body:
I'm trying to print all routes from my modules on "some page" with var_dump() or whatever debug function.

I have found lots of posts and samples but I can't get them printed and most examples fail in my code.

So far I think this is the best way to do so but where to use this code ?

// $sl instanceof Zend\ServiceManager\ServiceManager
$config = $sl->get('Config');
$routes = $config['router']['routes'];

If you want to view all routes just for debugging purposes, you can use var_dump or similar on the router object:

// $sl instanceof Zend\ServiceManager\ServiceManager
$router = $sl->get('Router');
var_dump($router);

Body:
You may print all routes from in your controller's method. Look at the following example

module/Application/src/Application/Controller/IndexController.php

<?php
namespace Application\Controller;

use Zend\View\Model\ViewModel;
use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    /**
     * @var array
     */
    protected $routes;

    /**
     * @param array $routes
     */
    public function __construct(array $routes)
    {
        // Here is the catch
        $this->routes = $routes;
    }

    public function indexAction()
    {
        // Thus you may print all routes
        $routes = $this->routes;

        echo '<pre>';
        print_r($routes);
        echo '</pre>';
        exit;

        return new ViewModel();
    }
}

As we passed an array of routes to the constructor of IndexController. We need to make an factory of this controller. A factory is a class that creates instances of other classes.

module/Application/src/Application/Controller/IndexControllerFactory.php

<?php
namespace Application\Controller;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class IndexControllerFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $serviceManager = $serviceLocator->getServiceLocator();
        $config = $serviceManager->get('Config');
        $routes = $config['router'];

        return new IndexController($routes);
    }
}

A invokable class can not be constructed with arguments. Our controller would not work as invokables because we know we already passed an argument to its constructor. So we need to configure that in factories key under controllers key of our module.config.php

module/Application/config/module.config.php

'controllers' => [
    'invokables' => [
        // This would not work any more as we created a factory of it
        // 'Application\Controller\Index' => 'Application\Controller\IndexController',
    ],

    // We should do it thus
    'factories' => [
        'Application\Controller\Index' => 'Application\Controller\IndexControllerFactory',
    ],
],

This answer has been edited for good practice as @av3 suggested!


问:
Async post request and assigning returned data
So I am learning AngularJS and I am trying to replace my not-so-pretty method of getting data from a webservice and realtime assinging it to a variable that is binded using ng-repeat. The thing I want to achieve mostly is to have asynchronous call. I can't use it now because AJAX is returning data after data is returned to a scope variable.

My current code looks like this:

```<code>var app = angular.module("Listt", []);

    app.controller(
        "ListtController",
    function ($scope) {
        $scope.results = {
            response: [{
                name: '',
                surname: '',
                age: ''
            }]
        };
        $scope.searchListt = function () {
            loadingAnimationStart();
            $scope.results = getListt();
            loadingAnimationStop();
        };

        function getListt() {
            var returnData;
            $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                    returnData = JSON.parse(data);
                }
            });
            return returnData;
        }
    }
);
</code>```

And in HTML I indicate search function by using ng-click

```<code><button ng-click="searchListt()">Search</button>
</code>```

答:
If you are using angularJs then you should use $http.post

```<code>var app = angular.module("Listt", []);

        app.controller(
            "ListtController",
        function ($scope) {
            $scope.results = {
                response: [{
                    name: '',
                    surname: '',
                    age: ''
                }]
            };
            $scope.searchListt = function () {
                loadingAnimationStart();
                $scope.results = getListt();
                loadingAnimationStop();
            };

            function getListt() {
                $scope.returnData;
                $http.post(url, data, config).then(function (response) {
                 $scope.returnData = JSON.parse(response)
                },function (response) {
                alert("ERROR")
                });
            }
        }
    );
</code>```

Body:
So I am learning AngularJS and I am trying to replace my not-so-pretty method of getting data from a webservice and realtime assinging it to a variable that is binded using ng-repeat. The thing I want to achieve mostly is to have asynchronous call. I can't use it now because AJAX is returning data after data is returned to a scope variable.

My current code looks like this:

var app = angular.module("Listt", []);

    app.controller(
        "ListtController",
    function ($scope) {
        $scope.results = {
            response: [{
                name: '',
                surname: '',
                age: ''
            }]
        };
        $scope.searchListt = function () {
            loadingAnimationStart();
            $scope.results = getListt();
            loadingAnimationStop();
        };

        function getListt() {
            var returnData;
            $.ajax({
                url: 'listt',
                type: "POST",
                async: false,
                data: {
                    age_from: $('[name="age-start"]').val(),
                    age_to: $('[name="age-end"]').val()
                },
                success: function (data) {
                    returnData = JSON.parse(data);
                }
            });
            return returnData;
        }
    }
);

And in HTML I indicate search function by using ng-click

<button ng-click="searchListt()">Search</button>

Body:
If you are using angularJs then you should use $http.post

var app = angular.module("Listt", []);

        app.controller(
            "ListtController",
        function ($scope) {
            $scope.results = {
                response: [{
                    name: '',
                    surname: '',
                    age: ''
                }]
            };
            $scope.searchListt = function () {
                loadingAnimationStart();
                $scope.results = getListt();
                loadingAnimationStop();
            };

            function getListt() {
                $scope.returnData;
                $http.post(url, data, config).then(function (response) {
                 $scope.returnData = JSON.parse(response)
                },function (response) {
                alert("ERROR")
                });
            }
        }
    );


问:
Wordpress - Show different menus
I've got a problem programming a website for a customer. I a couple of normal pages on a wordpress installation. One page needs to be a different theme. I have used the Multiple Themes plugin for that. Now i need to display a different menu from the first site.
Since I have multiple function.php i made a short change that grabs the wpb_custom_new_menu() function from a seperate file by require_once.
Then in the header.php where it is supposed to be shown, I have a normal wp_nav_menu(). I changed both themes to work on this system, my normal theme workes fine, but on the second one the menu isn't shown. It's not the themes fault, since both themes are basicly the same exept a couple of color changes. Don't know if anyone can help me, but I thought I'd give it a shot.
Thanks!</p>

答:
Problem solved.

p.s. There is no solution. It just doesn't work, it's a limitation  of how wordpress themes work. I spoke to a good friend and he suggested this plugin and it works great:
https://de.wordpress.org/plugins/wp-different-navigation-on-each-page-and-post/

Title: Wordpress - Show different menus


问:
Sessions and storing objects
If return an object from the session (HttpContext.Current.Session) to a private member of the objects type and then modify it, e.g. you rename an attribute or add something to the objects internal list member. Are those changes persisted if on another page you request the same object from the session...will it be updated with the values updated on the previous page. In other words is the object persisted, or do you have to re-save the object back to the session once you change anything on every page. Any help is much appreciated. Thanks</p>

答:
If you modify an instance which is stored in session state, the instance will be modified.

If you modify a copy of an instance, the original will not be affected.  (unless the copy references the original and updates it, which is unlikely)

ContentLicense: CC BY-SA 2.5

Title: Sessions and storing objects


问:
How to check if a big decimal number can be divided by 2^x or 5^x
I have a big decimal number N (up to 100.000 digits) and I need to check if N can be divided by 2^X or 5^X ( 0 < X < 5 ).

```<code>bignumber % (2^x) == 0
</code>```

Can I get a tip? I don't have any idea.

答:
You are faced with 2 issues:

How to store a large number.

How to compute a division on that number and get the remainder.

Storing such a large number on a computer is a challenge.  But any number can be represented as a polynomial.

```<code>ex: 10235
base 10 -->  10235 = f(10) = 1x10^5 + 0x10^4 + 2x10^3 + 3x10^2 + 3x10 + 5
base 16 --> 0x37FB = g(16) = 2x16^3 + 7x16^2 + 15x16^1 + 11
</code>```

Using this concept, one can readily use polynomial addition, subtraction, multiplication and division to compute very large values with no accuracy loss.  The polynomial's coefficients only need to be set so they are all of the same sign when printing the number.

To print a number store in base N to base 10, one has to compute f so f(10) = g(N).

This concept can be optimized with numbers larger than 10, to reduce computation time, but you need to keep in mind that a 31-bits x 32-bits (multiplication takes 64.  Negative coefficients or coefficients larger than your base can be reduced using the same carry/borrow techniques we routinely use when doing arithmetic operations by hand.

You can develop your own polynomials library, and deal with the loops and the maths, or use an open-source library, like GMP.

Some info on polynomial division remainder:

https://en.wikipedia.org/wiki/Polynomial_remainder_theorem

I'd go with using GMP.

Body:
I have a big decimal number N (up to 100.000 digits) and I need to check if N can be divided by 2^X or 5^X ( 0 < X < 5 ).

bignumber % (2^x) == 0

Can I get a tip? I don't have any idea.

Body:
You are faced with 2 issues:

How to store a large number.

How to compute a division on that number and get the remainder.

Storing such a large number on a computer is a challenge.  But any number can be represented as a polynomial.

ex: 10235
base 10 -->  10235 = f(10) = 1x10^5 + 0x10^4 + 2x10^3 + 3x10^2 + 3x10 + 5
base 16 --> 0x37FB = g(16) = 2x16^3 + 7x16^2 + 15x16^1 + 11

Using this concept, one can readily use polynomial addition, subtraction, multiplication and division to compute very large values with no accuracy loss.  The polynomial's coefficients only need to be set so they are all of the same sign when printing the number.

To print a number store in base N to base 10, one has to compute f so f(10) = g(N).

This concept can be optimized with numbers larger than 10, to reduce computation time, but you need to keep in mind that a 31-bits x 32-bits (multiplication takes 64.  Negative coefficients or coefficients larger than your base can be reduced using the same carry/borrow techniques we routinely use when doing arithmetic operations by hand.

You can develop your own polynomials library, and deal with the loops and the maths, or use an open-source library, like GMP.

Some info on polynomial division remainder:

https://en.wikipedia.org/wiki/Polynomial_remainder_theorem

I'd go with using GMP.


问:
Programmatically login admin in magento
i am new with magento, yet given the task to make custom api's with admin authentication. i am done with the api's but stucked in the admin authentication. the main problem i am facing is that: the passwords in magento are md5 encrypted and i dont know what to do with that. Help in this regard will be appriciated. my authentication code is below:

public function indexAction()
    {

```<code>require_once 'app/Mage.php';
umask(0);
$app = Mage::app('default');
$array = $_GET;
$username = $_GET['username'];
$password = $_GET['password'];
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$user = Mage::getModel('admin/user')->loadByUsername($username); // user your admin username
$user_id = $user->getId();
// echo $user_id;
if(($user->getId())>=1)
{
    echo "User Name: True";
    echo "<br>";
    $dbpassword = $user->getData('password');
    // echo $dbpassword."  ----  ";
    // echo md5($username.$pass).":".$username;
    // echo "```";
    // $a = Mage::helper('core')->validateHash($password, $dbpassword);
    // print_r($a);
    if($password == $dbpassword)
    {
        echo "
";
        echo "Password: True";echo "
";
        echo "Authenticated :) Here we go!!";
    }
    else
    {
        echo "Password: False";
    }
}
else
{
    echo "User Name: False";
}

}
```

答:
Use this function to validate your password against the magento hashed password

```<code>public function validateHash($password, $hash){
    $hashArr = explode(':', $hash);
    switch (count($hashArr)) {
        case 1:
            return md5($password) === $hash;
        case 2:
            return md5($hashArr[1] . $password) === $hashArr[0];
    }
}
</code>```

To check if the password is valid, do as below

```<code>if(validateHash($password, $user->getData('password'))){
    echo 1;
}else{
    echo 0;
}
</code>```

Title: Programmatically login admin in magento

Body:
i am new with magento, yet given the task to make custom api's with admin authentication. i am done with the api's but stucked in the admin authentication. the main problem i am facing is that: the passwords in magento are md5 encrypted and i dont know what to do with that. Help in this regard will be appriciated. my authentication code is below:

public function indexAction()
    {

require_once 'app/Mage.php';
umask(0);
$app = Mage::app('default');
$array = $_GET;
$username = $_GET['username'];
$password = $_GET['password'];
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$user = Mage::getModel('admin/user')->loadByUsername($username); // user your admin username
$user_id = $user->getId();
// echo $user_id;
if(($user->getId())>=1)
{
    echo "User Name: True";
    echo "
";
    $dbpassword = $user->getData('password');
    // echo $dbpassword."  ----  ";
    // echo md5($username.$pass).":".$username;
    // echo "
";
    // $a = Mage::helper('core')->validateHash($password, $dbpassword);
    // print_r($a);
    if($password == $dbpassword)
    {
        echo "
";
        echo "Password: True";echo "
";
        echo "Authenticated :) Here we go!!";
    }
    else
    {
        echo "Password: False";
    }
}
else
{
    echo "User Name: False";
}

}

Body:
Use this function to validate your password against the magento hashed password

public function validateHash($password, $hash){
    $hashArr = explode(':', $hash);
    switch (count($hashArr)) {
        case 1:
            return md5($password) === $hash;
        case 2:
            return md5($hashArr[1] . $password) === $hashArr[0];
    }
}

To check if the password is valid, do as below

if(validateHash($password, $user->getData('password'))){
    echo 1;
}else{
    echo 0;
}


问:
How to scroll to bottom of div element Selenium Webdriver
I have a use case wherein there's a div element on the webpage, it appears like a popup dialog as soon as you click a link (its not an actual popup, its something like dialog boxes which opens in Facebook when you click a link to check reactions on your posts etc.)

I'm using Selenium WebDriver with Java to automate tests for this application, my use case involves me to scroll to the bottom of the dialog box where there is a link to show more items, when user clicks show more, it populates another 10 items in the list and so on until there are no other items left for the user to visit.

So basically I have to scroll down on that particular div element till I keep seeing Show More link and when driver is not able to find show more link it should stop.

Note - I can't just scroll to bottom of the page using javascript window.scrollTo() as it will scroll down through whole webpage, however I just want to scroll to bottom of that division element only.

If anybody have any idea on how to achieve this please let me know.

Thanks for the help in advance !

答:
I have had this kind of issue and I resolved this using a similar question asked on SQA SO. Here is the post.

Please see the last answer by Sagar007, which uses a separate function scroll_Page() to achieve this.

Code taken directly from his answer

Some HTML page have internal (custom) scroll bar. We have to handle with little bit different way.
  Javascript is not working here.

Solution :

```<code>WebElement scrollArea =
driver.findElement(By.cssSelector("div.slimScrollBar"));
</code>```

I added a new step, where I clicked on the div element , using click() method and then proceeded to next step.

Create method scroll_Page as given below. Call this method as

```<code> scroll_Page(scrollArea ,100);
</code>```

Where scrollArea is your dragged(scroll) element and 100 is scroll points.

```<code>  public static boolean scroll_Page(WebElement webelement, int scrollPoints)
{
try
{
    Actions dragger = new Actions(driver);
    // drag downwards
    int numberOfPixelsToDragTheScrollbarDown = 10;
    for (int i = 10; i < scrollPoints; i = i + numberOfPixelsToDragTheScrollbarDown)
    {
        dragger.moveToElement(webelement).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release(webelement).build().perform();
    }
    Thread.sleep(500);
    return true;
}
catch (Exception e)
{
    e.printStackTrace();
    return false;
}
</code>```

Body:
I have had this kind of issue and I resolved this using a similar question asked on SQA SO. Here is the post.

Please see the last answer by Sagar007, which uses a separate function scroll_Page() to achieve this.

Code taken directly from his answer

Some HTML page have internal (custom) scroll bar. We have to handle with little bit different way.
  Javascript is not working here.

Solution :

WebElement scrollArea =
driver.findElement(By.cssSelector("div.slimScrollBar"));

I added a new step, where I clicked on the div element , using click() method and then proceeded to next step.

Create method scroll_Page as given below. Call this method as

 scroll_Page(scrollArea ,100);

Where scrollArea is your dragged(scroll) element and 100 is scroll points.

  public static boolean scroll_Page(WebElement webelement, int scrollPoints)
{
try
{
    Actions dragger = new Actions(driver);
    // drag downwards
    int numberOfPixelsToDragTheScrollbarDown = 10;
    for (int i = 10; i < scrollPoints; i = i + numberOfPixelsToDragTheScrollbarDown)
    {
        dragger.moveToElement(webelement).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release(webelement).build().perform();
    }
    Thread.sleep(500);
    return true;
}
catch (Exception e)
{
    e.printStackTrace();
    return false;
}


问:
Angular 4: Bind once only to method which returns promises
I am new to Angular so please forgive me if I don;t use the correct terminology.

I am trying to create a table dynamically by binding the td data to a method call. Like this:

```<code><tbody>
  <tr *ngFor="let rw of ParameterRowData" >
    <td *ngFor="let field of fields" class="lalign" [innerHTML]="getCellData(field, rw.ParameterData)" ></td>
    <td><a  >Edit</a> </td>
  </tr>
</tbody>
</code>```

I am doing this because I won't know the avaliable columns and data until it's returned from the server. My problem is that the getCellData method is being called over and over and over. The browser freezes, but in the console, I can see that it is being called again and again up to infinity. I just want it to be called once.

the getCellData method is as follows:

```<code>getCellData(field: ParamField, fields : ParameterRowFieldContract[]) : Promise<string>
  {
        for(var i=0; i<fields.length; i++)
        {
            if(fields[i].Name===field.DisplayName)
            {
                console.log('a');
                if(field.DataType == "FOREIGNKEYLIST")
                {
                    //getforeign key value to display
                    console.log('b');
                    var value = this.paramService.getParameterDataWithId(field.ForeignParameter, fields[i].Value)
                    .then(para => {
                        for(var k=0; k<para.ParameterData.length; k++)
                        {
                            console.log('c');
                            if(para.ParameterData[k].Name===field.ForeignField)
                            {
                                console.log('foreign ='+ para.ParameterData[k].Value);
                                return para.ParameterData[k].Value;
                            }
                        }
                    });
                    return value;

                }
                else
                {
                    return Promise.resolve(fields[i].Value);
                }
            }
        }
  }
</code>```

At the end of the day I just want to display the returned value from the service in the HTML td element. I am willing to go an alternative route to solve this problem. The data won't be edited once it is loaded into the table, but I am not sure if one-way binding can help me and I don't yet understand how to implement one-way or two-way binding.

Thank you in advance for your assistance.

答:
Found a workaround solution.

First of all I was binding to an expression that that returns a promise. At this link Angular Docs, the angular team discourages the use of complex epressions here:

The expression could call something like getFoo(). Only you know what getFoo() does. If getFoo() changes something and you happen to be binding to that something, you risk an unpleasant experience. Angular may or may not display the changed value. Angular may detect the change and throw a warning error. In general, stick to data properties and to methods that return values and do no more.

So to keep it simple, my method had to return a string.

As for the foreign data, I prefetched it on ngOnInit and stored it in a multidimensional (2D) array, foreigners.

```<code>foreigners = [];
foreignParamNames : string[];
</code>```

Then in ngOnInit I fill it up with data. The foreignParamNames is to keep track of the index for the multi-demnsional array.

```<code>ngOnInit() {
this.foreigners = [];
this.foreignParamNames = [];
this.fields = this.param.Fields;
this.paramService.getParameterData(this.parameterName)
                 .then(
                   data => this.processData(data),
                   error =>  {console.log(error)});

var foren = this.fields.filter(a=> a.DataType == 'FOREIGNKEYLIST');
for(var i = 0; i< foren.length; i++)
{
    this.foreignParamNames.push(foren[i].DisplayName);
    this.foreigners.push([]);
}

for(var j =0; j< foren.length; j++)
{
    var that = this;
    var ogfield = foren[j];
    //get foreign field data
    this.paramService.getParameterData(foren[j].ForeignParameter)
                 .then(
                   foreignRows => {
                        var values : StringKeyValuePair[]
                        values =[];
                        for(var i=0; i<foreignRows.length; i++)
                        {
                            var foreignFields =  foreignRows[i].ParameterData;
                            var sk = new StringKeyValuePair();
                            for(var j =0; j<foreignFields.length; j++)
                            {
                                if(foreignFields[j].Name=="Id")
                                {
                                    sk.Key = foreignFields[j].Value;
                                }
                                if(foreignFields[j].Name==ogfield.ForeignField)
                                {
                                    sk.Value = foreignFields[j].Value;
                                }
                            }
                            values.push(sk);
                        }
                        var ii = that.foreignParamNames.indexOf(ogfield.DisplayName);
                        if(ii>=0)
                        {
                            that.foreigners[ii]=(values);
                        }
                   },
                   error =>  {console.log(error)});
    }
}
</code>```

and then finally, the getCellData method no longer needs to fetch from the service, but can now fetch from the multi-dimensional array for its data. Here is the code.

```<code>getCellData(field: ParamField, fields : ParameterRowFieldContract[]) :
string
{
    for(var i=0; i<fields.length; i++)
    {
        if(fields[i].Name==field.DisplayName)
        {

            if(field.DataType == "FOREIGNKEYLIST")
            {
                //getforeign key value to display
                var ii = this.foreignParamNames.indexOf(field.DisplayName);

                var foreignfields= <StringKeyValuePair[]>this.foreigners[ii];

                for(var k=0; k<foreignfields.length; k++)
                {
                    if(foreignfields[k].Key===fields[i].Value)
                    {
                        return foreignfields[k].Value;
                    }
                }

            }
            else
            {
                return fields[i].Value;
            }
        }
    }
    return "N/A";
  }
</code>```

The HTML template's code still stays the same. I hope this can help someone else who needs it. This is more like an alternative from my original line of thinking, but if anyone has a better way to do it, please feel free to assist

Body:
I am new to Angular so please forgive me if I don;t use the correct terminology.

I am trying to create a table dynamically by binding the td data to a method call. Like this:

    Edit

I am doing this because I won't know the avaliable columns and data until it's returned from the server. My problem is that the getCellData method is being called over and over and over. The browser freezes, but in the console, I can see that it is being called again and again up to infinity. I just want it to be called once.

the getCellData method is as follows:

getCellData(field: ParamField, fields : ParameterRowFieldContract[]) : Promise<string>
  {
        for(var i=0; i<fields.length; i++)
        {
            if(fields[i].Name===field.DisplayName)
            {
                console.log('a');
                if(field.DataType == "FOREIGNKEYLIST")
                {
                    //getforeign key value to display
                    console.log('b');
                    var value = this.paramService.getParameterDataWithId(field.ForeignParameter, fields[i].Value)
                    .then(para => {
                        for(var k=0; k<para.ParameterData.length; k++)
                        {
                            console.log('c');
                            if(para.ParameterData[k].Name===field.ForeignField)
                            {
                                console.log('foreign ='+ para.ParameterData[k].Value);
                                return para.ParameterData[k].Value;
                            }
                        }
                    });
                    return value;

                }
                else
                {
                    return Promise.resolve(fields[i].Value);
                }
            }
        }
  }

At the end of the day I just want to display the returned value from the service in the HTML td element. I am willing to go an alternative route to solve this problem. The data won't be edited once it is loaded into the table, but I am not sure if one-way binding can help me and I don't yet understand how to implement one-way or two-way binding.

Thank you in advance for your assistance.

Body:
Found a workaround solution.

First of all I was binding to an expression that that returns a promise. At this link Angular Docs, the angular team discourages the use of complex epressions here:

The expression could call something like getFoo(). Only you know what getFoo() does. If getFoo() changes something and you happen to be binding to that something, you risk an unpleasant experience. Angular may or may not display the changed value. Angular may detect the change and throw a warning error. In general, stick to data properties and to methods that return values and do no more.

So to keep it simple, my method had to return a string.

As for the foreign data, I prefetched it on ngOnInit and stored it in a multidimensional (2D) array, foreigners.

foreigners = [];
foreignParamNames : string[];

Then in ngOnInit I fill it up with data. The foreignParamNames is to keep track of the index for the multi-demnsional array.

ngOnInit() {
this.foreigners = [];
this.foreignParamNames = [];
this.fields = this.param.Fields;
this.paramService.getParameterData(this.parameterName)
                 .then(
                   data => this.processData(data),
                   error =>  {console.log(error)});

var foren = this.fields.filter(a=> a.DataType == 'FOREIGNKEYLIST');
for(var i = 0; i< foren.length; i++)
{
    this.foreignParamNames.push(foren[i].DisplayName);
    this.foreigners.push([]);
}

for(var j =0; j< foren.length; j++)
{
    var that = this;
    var ogfield = foren[j];
    //get foreign field data
    this.paramService.getParameterData(foren[j].ForeignParameter)
                 .then(
                   foreignRows => {
                        var values : StringKeyValuePair[]
                        values =[];
                        for(var i=0; i<foreignRows.length; i++)
                        {
                            var foreignFields =  foreignRows[i].ParameterData;
                            var sk = new StringKeyValuePair();
                            for(var j =0; j<foreignFields.length; j++)
                            {
                                if(foreignFields[j].Name=="Id")
                                {
                                    sk.Key = foreignFields[j].Value;
                                }
                                if(foreignFields[j].Name==ogfield.ForeignField)
                                {
                                    sk.Value = foreignFields[j].Value;
                                }
                            }
                            values.push(sk);
                        }
                        var ii = that.foreignParamNames.indexOf(ogfield.DisplayName);
                        if(ii>=0)
                        {
                            that.foreigners[ii]=(values);
                        }
                   },
                   error =>  {console.log(error)});
    }
}

and then finally, the getCellData method no longer needs to fetch from the service, but can now fetch from the multi-dimensional array for its data. Here is the code.

getCellData(field: ParamField, fields : ParameterRowFieldContract[]) :
string
{
    for(var i=0; i<fields.length; i++)
    {
        if(fields[i].Name==field.DisplayName)
        {

            if(field.DataType == "FOREIGNKEYLIST")
            {
                //getforeign key value to display
                var ii = this.foreignParamNames.indexOf(field.DisplayName);

                var foreignfields= <StringKeyValuePair[]>this.foreigners[ii];

                for(var k=0; k<foreignfields.length; k++)
                {
                    if(foreignfields[k].Key===fields[i].Value)
                    {
                        return foreignfields[k].Value;
                    }
                }

            }
            else
            {
                return fields[i].Value;
            }
        }
    }
    return "N/A";
  }

The HTML template's code still stays the same. I hope this can help someone else who needs it. This is more like an alternative from my original line of thinking, but if anyone has a better way to do it, please feel free to assist


问:
java.lang.ClassCastException: org.ksoap2.serialization.SoapPrimitive?
I am calling a web service from my android client application. After getting response when i am trying to display it i am getting ClassCastException. Following is my code:

```<code>public void onClick(View v) {
  setContentView(R.layout.report);
  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  EpcDetails epcdetails=new EpcDetails();
  epcdetails.setEpcId(input_val.getText().toString());

        request.addProperty("id", id
        SoapSerializationEnvelope sse=new SoapSerializationEnvelope(SoapEnvelope.VER11);
        sse.setOutputSoapObject(request);

        sse.addMapping(NAMESPACE,
        ProductDetailsRequest.ProductDetailsRequest.getSimpleName(),
        ProductDetailsRequest.ProductDetailsRequest);

        sse.implicitTypes=true;
        sse.setAddAdornments(false);
        AndroidHttpTransport aht=new AndroidHttpTransport(URL);

        try
        {
         aht.call(SOAP_ACTION, sse);
         SoapObject response= (SoapObject) sse.getResponse();
         item_code.setText((CharSequence)(response.getProperty(6)));
         desc.setText((CharSequence) (response.getProperty(5)));
         price.setText(calc_price.toString());

        } catch (IOException e)
        {
         e.printStackTrace();
        } catch (XmlPullParserException e)
        {
          e.printStackTrace();
       }
</code>```

I am getting Exception at item_code.setText((CharSequence)(response.getProperty(6)));
as

```<code>12-20 19:26:12.864: ERROR/AndroidRuntime(811): FATAL EXCEPTION: main
12-20 19:26:12.864: ERROR/AndroidRuntime(811): java.lang.ClassCastException: org.ksoap2.serialization.SoapPrimitive
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at com.trueVUE.modules.report.MainSimulation.onClick(MainSimulation.java:123)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.view.View.performClick(View.java:2408)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.view.View$PerformClick.run(View.java:8816)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.os.Handler.handleCallback(Handler.java:587)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.os.Looper.loop(Looper.java:123)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.app.ActivityThread.main(ActivityThread.java:4627)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at java.lang.reflect.Method.invokeNative(Native Method)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at java.lang.reflect.Method.invoke(Method.java:521)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at dalvik.system.NativeStart.main(Native Method)
</code>```

Please suggest some soln ASAP.

Regards,
Rahul

答:
This question will be helpful to you.

You need to use getString() to convert a returned property into a String:

```<code>item_code.setText(response.getProperty(6).toString());
</code>```

Body:
I am calling a web service from my android client application. After getting response when i am trying to display it i am getting ClassCastException. Following is my code:

public void onClick(View v) {
  setContentView(R.layout.report);
  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  EpcDetails epcdetails=new EpcDetails();
  epcdetails.setEpcId(input_val.getText().toString());

        request.addProperty("id", id
        SoapSerializationEnvelope sse=new SoapSerializationEnvelope(SoapEnvelope.VER11);
        sse.setOutputSoapObject(request);

        sse.addMapping(NAMESPACE,
        ProductDetailsRequest.ProductDetailsRequest.getSimpleName(),
        ProductDetailsRequest.ProductDetailsRequest);

        sse.implicitTypes=true;
        sse.setAddAdornments(false);
        AndroidHttpTransport aht=new AndroidHttpTransport(URL);

        try
        {
         aht.call(SOAP_ACTION, sse);
         SoapObject response= (SoapObject) sse.getResponse();
         item_code.setText((CharSequence)(response.getProperty(6)));
         desc.setText((CharSequence) (response.getProperty(5)));
         price.setText(calc_price.toString());

        } catch (IOException e)
        {
         e.printStackTrace();
        } catch (XmlPullParserException e)
        {
          e.printStackTrace();
       }

I am getting Exception at item_code.setText((CharSequence)(response.getProperty(6)));
as

12-20 19:26:12.864: ERROR/AndroidRuntime(811): FATAL EXCEPTION: main
12-20 19:26:12.864: ERROR/AndroidRuntime(811): java.lang.ClassCastException: org.ksoap2.serialization.SoapPrimitive
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at com.trueVUE.modules.report.MainSimulation.onClick(MainSimulation.java:123)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.view.View.performClick(View.java:2408)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.view.View$PerformClick.run(View.java:8816)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.os.Handler.handleCallback(Handler.java:587)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.os.Looper.loop(Looper.java:123)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at android.app.ActivityThread.main(ActivityThread.java:4627)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at java.lang.reflect.Method.invokeNative(Native Method)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at java.lang.reflect.Method.invoke(Method.java:521)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-20 19:26:12.864: ERROR/AndroidRuntime(811):     at dalvik.system.NativeStart.main(Native Method)

Please suggest some soln ASAP.

Regards,
Rahul

Body:
This question will be helpful to you.

You need to use getString() to convert a returned property into a String:

item_code.setText(response.getProperty(6).toString());


问:
Space is not allowed mysql column name
I have a table testnew:

```<code>    +---------------------+
    | v_id | name         |
    +---------------------+
    |   1  | Productivity |
    |   2  | Work Quality |
    |   3  | Knowldge     |
    |   4  | Comm know    |
    +------+--------------+
</code>```

Which is added by admin and I am going to create another table (Expected)

```<code>    +---------------+--------------+------------+----------+
    |  Productivity |Work Quality  | Knowldge   |Comm know |
    +------------+-----------------+------------------------
    |                                                      |
    |                                                      |
    |                                                      |
    |                                                      |
    +------------+-----------------------------------------+
</code>```

Query:

```<code>SELECT
  CONCAT(
    'CREATE TABLE new (',
    GROUP_CONCAT(DISTINCT
      CONCAT(name, ' VARCHAR(50)')
      SEPARATOR ','),
    ');')
FROM
  testnew
INTO @sql;

PREPARE stmt FROM @sql;
EXECUTE stmt;
</code>```

Work Quality and Comm know has space so I can't get output.

How do I fix this?

答:
I opposed putting special characters in column names.  But if you must, use the MySQL escape character (a backtick) or double quotes:

```<code>SELECT CONCAT('CREATE TABLE new (',
              GROUP_CONCAT(DISTINCT CONCAT('`', name, '` VARCHAR(50)')
                           SEPARATOR ','),
              ');')
       FROM testnew
INTO @sql;
</code>```

As a note:  The CONCAT() in GROUP_CONCAT() is redundant.  A little known fact is that GROUP_CONCAT() takes multiple arguments:

```<code>SELECT CONCAT('CREATE TABLE new (',
              GROUP_CONCAT(DISTINCT '`', name, '` VARCHAR(50)'
                           SEPARATOR ','),
              ');')
       FROM testnew
INTO @sql;
</code>```

Title: Space is not allowed mysql column name

Body:
I have a table testnew:

    +---------------------+
    | v_id | name         |
    +---------------------+
    |   1  | Productivity |
    |   2  | Work Quality |
    |   3  | Knowldge     |
    |   4  | Comm know    |
    +------+--------------+

Which is added by admin and I am going to create another table (Expected)

    +---------------+--------------+------------+----------+
    |  Productivity |Work Quality  | Knowldge   |Comm know |
    +------------+-----------------+------------------------
    |                                                      |
    |                                                      |
    |                                                      |
    |                                                      |
    +------------+-----------------------------------------+

Query:

SELECT
  CONCAT(
    'CREATE TABLE new (',
    GROUP_CONCAT(DISTINCT
      CONCAT(name, ' VARCHAR(50)')
      SEPARATOR ','),
    ');')
FROM
  testnew
INTO @sql;

PREPARE stmt FROM @sql;
EXECUTE stmt;

Work Quality and Comm know has space so I can't get output.

How do I fix this?

Body:
I opposed putting special characters in column names.  But if you must, use the MySQL escape character (a backtick) or double quotes:

SELECT CONCAT('CREATE TABLE new (',
              GROUP_CONCAT(DISTINCT CONCAT('`', name, '` VARCHAR(50)')
                           SEPARATOR ','),
              ');')
       FROM testnew
INTO @sql;

As a note:  The CONCAT() in GROUP_CONCAT() is redundant.  A little known fact is that GROUP_CONCAT() takes multiple arguments:

SELECT CONCAT('CREATE TABLE new (',
              GROUP_CONCAT(DISTINCT '`', name, '` VARCHAR(50)'
                           SEPARATOR ','),
              ');')
       FROM testnew
INTO @sql;


问:
VSTS-GITHUB Workflow
Please elaborate the steps to create a workflow of Visual
    Studio Team Services and Github.
    Integration of Github with VSTS and creating a workflow.

    Once we create user stories in vsts, is there any way to create a
    transition from one state to another(New->Active->resolved),
    based on repository update(github).

答:
Automatically is only using VSTS git repo.
If you like update this, you need to create a manual integration, possible using the VSTS Rest Api.</p>

Title: VSTS-GITHUB Workflow


问:
DB Migration in iOS?
I have an app in which I haven't set the SQLite version in and now I want to upgrade the app but I have some column changes in the new iPA. How can I implement the DB Migration in iOS? I am using FMDB for the database.</p>

答:
Keep a constant which version point to the version increments.
Each time the database updates increment the counter.

On app launch call the following code :

```<code>DatabaseMigrator *dbMigrator = [[DatabaseMigrator alloc]
                                initWithDatabaseFile:
                                [AbstractRepository databaseFilename]];

//for development only - toggle this to force the new database over
//dbMigrator.overwriteDatabase = YES;

[dbMigrator moveDatabaseToUserDirectoryIfNeeded];

[dbMigrator migrateToVersion:CURRENT_SCHEMA_VERSION];

BOOL marked = [FileUtils addSkipBackupAttributeToItemAtURL:[AbstractRepository databasePath]];

if (marked) {

    NSLog(@"succesfully Marked do not back up");

} else {

    NSLog(@"failed Marked do not back up");
}
</code>```

Title: DB Migration in iOS?

Body:
Keep a constant which version point to the version increments.
Each time the database updates increment the counter.

On app launch call the following code :

DatabaseMigrator *dbMigrator = [[DatabaseMigrator alloc]
                                initWithDatabaseFile:
                                [AbstractRepository databaseFilename]];

//for development only - toggle this to force the new database over
//dbMigrator.overwriteDatabase = YES;

[dbMigrator moveDatabaseToUserDirectoryIfNeeded];

[dbMigrator migrateToVersion:CURRENT_SCHEMA_VERSION];

BOOL marked = [FileUtils addSkipBackupAttributeToItemAtURL:[AbstractRepository databasePath]];

if (marked) {

    NSLog(@"succesfully Marked do not back up");

} else {

    NSLog(@"failed Marked do not back up");
}


问:
How to import configurations to dockerfile.
I have a docker-compose.yaml file and then dockerfiles. Now, I don't want to write all the host, port, password in this docker-compose/dockerfile. Rather, I would like to keep all these configurations in a different file. I know, half of the requirement could be achieved by using .env file, where I can keep my environment variables, but then it will be good to keep all configurations in a single file (main.cfg), which could used by other components. </p>

答:
You can use volumes to share a file or a entire folder to  a docker service. Here is an example of a mysql which shares a  database to docker:

```<code>version: '3'
services:
  mysql-database:
    image: mysql
    container_name: mysql-database
    volumes:
      - ./mysql/docker-entrypoint-initdb.d/:/docker-entrypoint-initdb.d
    env_file:
      - .env
    ports:
      - 3306:3306
</code>```

The directory structure is as follows:

```<code>BaseDirectory
|____docker-compose.yml
|    mysql
|    |____docker-entrypoint-initdb.d
|         |____sqldb1.gz
|         |____sqldb2.gz
</code>```

In above example, all files inside docker-entrypoint-initdb.d from host, are shared to the docker container, and can be accessed from inside the container also at /docker-entrypoint-initdb.d. You can mount individual files also by giving exact filename. For example:

```<code>volumes:
  - ./mysql/docker-entrypoint-initdb.d/sqldb1.gz:/docker-entrypoint-initdb.d/sqldb1.gz
</code>```

As I have shared a database, similarly you can share a config file and place it at the exact location you want inside the docker.

Body:
You can use volumes to share a file or a entire folder to  a docker service. Here is an example of a mysql which shares a  database to docker:

version: '3'
services:
  mysql-database:
    image: mysql
    container_name: mysql-database
    volumes:
      - ./mysql/docker-entrypoint-initdb.d/:/docker-entrypoint-initdb.d
    env_file:
      - .env
    ports:
      - 3306:3306

The directory structure is as follows:

BaseDirectory
|____docker-compose.yml
|    mysql
|    |____docker-entrypoint-initdb.d
|         |____sqldb1.gz
|         |____sqldb2.gz

In above example, all files inside docker-entrypoint-initdb.d from host, are shared to the docker container, and can be accessed from inside the container also at /docker-entrypoint-initdb.d. You can mount individual files also by giving exact filename. For example:

volumes:
  - ./mysql/docker-entrypoint-initdb.d/sqldb1.gz:/docker-entrypoint-initdb.d/sqldb1.gz

As I have shared a database, similarly you can share a config file and place it at the exact location you want inside the docker.


问:
books to recommend to study WPF

Possible Duplicate:

  What WPF books would you recommend?

Is there any good book to recommend for learning WPF?

答: I would recommend WPF in Action with Visual Studio 2008 for an introduction (it covers .NET 3.5 SP1), but for me the best WPF book out there is Matthew MacDonald's 'Pro WPF in C# 2010: Windows Presentation Foundation in .NET 4' (http://apress.com/book/view/9781430272052), which is more advanced.</p>

Title: books to recommend to study WPF


问:
Create columns based on the level on another table
This is similar to the question i created

Split table into different level columns

I have two tables one which indicates the level of SETTLUNIT and one the raw data. By comparing one table i have to create 3 new columns .

like

Table 1 :

Table 2 :

By seeing the level from table 1 i need to add 3 columns in table 2.

If it is level 2 i need to bring level 1 and level 2 and so on.

Output: Row 1 has only level 1 and level 2 because it has level as 2 in master level table.

Could you please help me how to create a query . I tried with UNION but some how not getting the required output

答:
Sounds like you're looking for a pivot query:

https://www.techonthenet.com/oracle/pivot.php

http://www.dba-oracle.com/t_pivot_examples.htm

https://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1

http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html


问:
JS can't call function when content is dynamically added
Ok, I have this HTML:

```<code><td class="text-left"><button type="button" onclick="addImage('<?php echo $language['language_id']; ?>');" data-toggle="tooltip" title="<?php echo $button_banner_add; ?>" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button></td>
</code>```

On click I call JS function addImage.

```<code><script type="text/javascript">
function addImage(language_id) {
html = '<td class="text-left"><div class="row"><div class="col-sm-6"><div class="form-group"><label class="col-sm-2 control-label" for="date-ended"><?php echo 'Date Started' ?></label><div class="input-group date" id="datetimepicker1"><input name="background_images_date_ended" type="text" id="date-ended" class="form-control" /><span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div></div></td>';

$('#images' + language_id + ' tbody').append(html);
</script>
</code>```

After that I want to call function on this div

This function:

```<code><script type="text/javascript">
  $(function () {
    $('#datetimepicker1').datetimepicker();
  });
</script>
</code>```

But this div is dynamically added and I don't know, but the function is not running.

答:
Why you just dont init the datetimepicker at the bottom of the addImage function, or call another function from there?

```<code>function addImage(language_id) {
        html = '  <td class="text-left"><div class="row"><div class="col-sm-6"><div class="form-group"><label class="col-sm-2 control-label" for="date-ended"><?php echo 'Date Started' ?></label><div class="input-group date" id="datetimepicker1"><input name="background_images_date_ended" type="text" id="date-ended" class="form-control" /><span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div></div></td>';

$('#images' + language_id + ' tbody').append(html);
$('#datetimepicker1').datetimepicker();
}
</code>```

or

```<code>function addImage(language_id) {
  ....
  initDatepicker();
}

function initDatepicker () {
    $('#datetimepicker1').datetimepicker();
}
</code>```

Body:
Ok, I have this HTML:

<button type="button" onclick="addImage('<?php echo $language['language_id']; ?>');" data-toggle="tooltip" title="<?php echo $button_banner_add; ?>" class="btn btn-primary"></button>

On click I call JS function addImage.

After that I want to call function on this div

This function:

But this div is dynamically added and I don't know, but the function is not running.

Body:
Why you just dont init the datetimepicker at the bottom of the addImage function, or call another function from there?

function addImage(language_id) {
        html = '  <td class="text-left"><div class="row"><div class="col-sm-6"><div class="form-group"><label class="col-sm-2 control-label" for="date-ended"><?php echo 'Date Started' ?></label><div class="input-group date" id="datetimepicker1"><input name="background_images_date_ended" type="text" id="date-ended" class="form-control" /><span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div></div></td>';

$('#images' + language_id + ' tbody').append(html);
$('#datetimepicker1').datetimepicker();
}

or

function addImage(language_id) {
  ....
  initDatepicker();
}

function initDatepicker () {
    $('#datetimepicker1').datetimepicker();
}