问:
Setting up setattr behavior of Django model without affecting instance initialization
I have a model called A. When b attribute is set of that model, I want to update that attribute like this:

```<code># Note that PGJSONField is a field that can store string or json.

class A(models.Model):
    description = PGJSONField(blank=True, null=True)
    def __setattr__(self, key, val):
        if key == 'description':
            val = {'description': val}
        super(A, self).__setattr__(key, val)
</code>```

This causes a side effect. When I get model instance from DB. It set's up description key as dict event if it's not.

```<code>>>> a = A.objects.first()
>>> a.description
..: {"description": "lorem ipsum"}
</code>```

My expected bahavior is something like this:

```<code>>>> a = A.objects.first()
>>> a.description
..: "lorem ipsum"
>>> a.description = "foo bar"
>>> a.description = {"description": "foo bar"}
</code>```

I think I must by pass _setattr method when model is being fetched but I couldn't find a way to do it. Any suggestions?

答:
Try this model structure it will make your storing efficient
if data security is not needed

```<code>class A(models.Model):
    name      = models.CharField(max_length=50)

class KeyVal(models.Model):
    container = models.ForeignKey(A)
    key       = models.CharField(max_length=240, db_index=True)
    value     = models.CharField(max_length=240, db_index=True)
</code>```

So if you know the name in A-table you can get all key-value pairs, key-list, value-list

Body:
I have a model called A. When b attribute is set of that model, I want to update that attribute like this:

# Note that PGJSONField is a field that can store string or json.

class A(models.Model):
    description = PGJSONField(blank=True, null=True)
    def __setattr__(self, key, val):
        if key == 'description':
            val = {'description': val}
        super(A, self).__setattr__(key, val)

This causes a side effect. When I get model instance from DB. It set's up description key as dict event if it's not.

>>> a = A.objects.first()
>>> a.description
..: {"description": "lorem ipsum"}

My expected bahavior is something like this:

>>> a = A.objects.first()
>>> a.description
..: "lorem ipsum"
>>> a.description = "foo bar"
>>> a.description = {"description": "foo bar"}

I think I must by pass _setattr method when model is being fetched but I couldn't find a way to do it. Any suggestions?

Body:
Try this model structure it will make your storing efficient
if data security is not needed

class A(models.Model):
    name      = models.CharField(max_length=50)

class KeyVal(models.Model):
    container = models.ForeignKey(A)
    key       = models.CharField(max_length=240, db_index=True)
    value     = models.CharField(max_length=240, db_index=True)

So if you know the name in A-table you can get all key-value pairs, key-list, value-list


来源: stackexchange

问:
Edit password of user in admin panel
I've overwrite "save_model" method to manage user's password in my admin's panel application. What I want is:

Create a new random password when I create new user (if password field is empty)

Encrypt the password (if I set it)

Use user's password (if I change user but not set the password)

How can I define the last condition?

```<code>    def save_model(self, request, obj, form, change):
    if not change and (not form.cleaned_data['password']) :
        password = User.objects.make_random_password()
        obj.set_password(password)
    elif form.cleaned_data['password'] :
        obj.set_password(form.cleaned_data['password'])
    else
        ?
    super(UserAdmin, self).save_model(request, obj, form, change)
</code>```

答:
You are doing all this a bit too late. The user creation form won't even allow you to post a form without fields password1 and password2 filled in. If those fields are empty you will never even get to UserAdmin.save_model() method.

But you can override the user creation form's save() method, in it allow password fields to be empty and set random password if fields are empty (or use user's password if entered).

As a bonus, this code keeps in place form validation if user entered the password (password mismatch) as well as checking AUTH_PASSWORD_VALIDATORS (all except 'django.contrib.auth.password_validation.MinimumLengthValidator' since empty password field mean 0 chars).

```<code>### admin.py

from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class CustomUserCreationForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].required = False
        self.fields['password2'].required = False

    def _clean_form(self):
        super()._clean_form()

        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")

        if password1 != password2:
            self.add_error('password2', self.error_messages['password_mismatch'])

    def save(self, commit=True):
        user = super().save(commit=False)

        user_password = self.cleaned_data["password1"]

        if not user_password:
            user_password = User.objects.make_random_password()

        user.set_password(user_password)

        if commit:
            user.save()
        return user

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Edit password of user in admin panel

Body:
I've overwrite "save_model" method to manage user's password in my admin's panel application. What I want is:

Create a new random password when I create new user (if password field is empty)

Encrypt the password (if I set it)

Use user's password (if I change user but not set the password)

How can I define the last condition?

    def save_model(self, request, obj, form, change):
    if not change and (not form.cleaned_data['password']) :
        password = User.objects.make_random_password()
        obj.set_password(password)
    elif form.cleaned_data['password'] :
        obj.set_password(form.cleaned_data['password'])
    else
        ?
    super(UserAdmin, self).save_model(request, obj, form, change)

Body:
You are doing all this a bit too late. The user creation form won't even allow you to post a form without fields password1 and password2 filled in. If those fields are empty you will never even get to UserAdmin.save_model() method.

But you can override the user creation form's save() method, in it allow password fields to be empty and set random password if fields are empty (or use user's password if entered).

As a bonus, this code keeps in place form validation if user entered the password (password mismatch) as well as checking AUTH_PASSWORD_VALIDATORS (all except 'django.contrib.auth.password_validation.MinimumLengthValidator' since empty password field mean 0 chars).

### admin.py

from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class CustomUserCreationForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].required = False
        self.fields['password2'].required = False

    def _clean_form(self):
        super()._clean_form()

        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")

        if password1 != password2:
            self.add_error('password2', self.error_messages['password_mismatch'])

    def save(self, commit=True):
        user = super().save(commit=False)

        user_password = self.cleaned_data["password1"]

        if not user_password:
            user_password = User.objects.make_random_password()

        user.set_password(user_password)

        if commit:
            user.save()
        return user

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)


问:
python date and datetime from multiple columns
I have some data that looks like:

```<code>        key  DATE - DAY  DATE - MONTH  DATE - YEAR  GMT HRS  GMT MINUTES
1        2          29             2         2016        2            2
2        3          29             2         2016        2            2
3        4          29             2         2016        2            2
4        5          29             2         2016        2            2
5        6          29             2         2016        2            2
6        7          29             2         2016        2            2
7        8          29             2         2016        2            3
8        9          29             2         2016        2            3
9       10          29             2         2016        2            3

   GMT SECONDS
1           54
2           55
3           56
4           57
5           58
6           59
7            0
8            1
9            2
</code>```

At first the data was type float and the year was in format 16 so I did:

```<code>t['DATE - MONTH'] = t['DATE - MONTH'].astype(int)
t['DATE - YEAR'] = t['DATE - YEAR'].astype(int)
t['DATE - YEAR'] = t['DATE - YEAR']+2000
t['DATE - DAY'] = t['DATE - DAY'].astype(int)
</code>```

^Note I was also confused why when using an index number rather than the column name you only work on what seems to be a temp table ie you can print the desired result but it didnt change the data frame.

Then I tried two methods:

```<code>t['Date'] = pd.to_datetime(dict(year=t['DATE - YEAR'], month = t['DATE - MONTH'], day = t['DATE - DAY']))

t['Date'] = pd.to_datetime((t['DATE - YEAR']*10000+t['DATE - MONTH']*100+t['DATE - DAY']).apply(str),format='%Y%m%d')
</code>```

Both return:

ValueError: cannot assemble the datetimes: time data 20000000 does not match format '%Y%m%d' (match)

I'd like to create a date column (and then after use a similar logic for a datetime column with the additional 3 columns).

What is the problem?

EDIT: I had bad data and added errors='coerce' to handle those rows

Body:
I have some data that looks like:

        key  DATE - DAY  DATE - MONTH  DATE - YEAR  GMT HRS  GMT MINUTES
1        2          29             2         2016        2            2
2        3          29             2         2016        2            2
3        4          29             2         2016        2            2
4        5          29             2         2016        2            2
5        6          29             2         2016        2            2
6        7          29             2         2016        2            2
7        8          29             2         2016        2            3
8        9          29             2         2016        2            3
9       10          29             2         2016        2            3

   GMT SECONDS
1           54
2           55
3           56
4           57
5           58
6           59
7            0
8            1
9            2

At first the data was type float and the year was in format 16 so I did:

t['DATE - MONTH'] = t['DATE - MONTH'].astype(int)
t['DATE - YEAR'] = t['DATE - YEAR'].astype(int)
t['DATE - YEAR'] = t['DATE - YEAR']+2000
t['DATE - DAY'] = t['DATE - DAY'].astype(int)

^Note I was also confused why when using an index number rather than the column name you only work on what seems to be a temp table ie you can print the desired result but it didnt change the data frame.

Then I tried two methods:

t['Date'] = pd.to_datetime(dict(year=t['DATE - YEAR'], month = t['DATE - MONTH'], day = t['DATE - DAY']))

t['Date'] = pd.to_datetime((t['DATE - YEAR']*10000+t['DATE - MONTH']*100+t['DATE - DAY']).apply(str),format='%Y%m%d')

Both return:

ValueError: cannot assemble the datetimes: time data 20000000 does not match format '%Y%m%d' (match)

I'd like to create a date column (and then after use a similar logic for a datetime column with the additional 3 columns).

What is the problem?

EDIT: I had bad data and added errors='coerce' to handle those rows

Body:
First rename all columns, filter by values of dict and use to_datetime:

Assembling a datetime from multiple columns of a DataFrame. The keys can be common abbreviations like ['year', 'month', 'day', 'minute', 'second', 'ms', 'us', 'ns']) or plurals of the same.

d = {'DATE - YEAR':'year','DATE - MONTH':'month','DATE - DAY':'day',
     'GMT HRS':'hour','GMT MINUTES':'minute','GMT SECONDS':'second'}

df['datetime'] = pd.to_datetime(df.rename(columns=d)[list(d.values())])

print (df)
   key  DATE - DAY  DATE - MONTH  DATE - YEAR  GMT HRS  GMT MINUTES  \
1    2          29             2         2016        2            2
2    3          29             2         2016        2            2
3    4          29             2         2016        2            2
4    5          29             2         2016        2            2
5    6          29             2         2016        2            2
6    7          29             2         2016        2            2
7    8          29             2         2016        2            3
8    9          29             2         2016        2            3
9   10          29             2         2016        2            3

   GMT SECONDS            datetime
1           54 2016-02-29 02:02:54
2           55 2016-02-29 02:02:55
3           56 2016-02-29 02:02:56
4           57 2016-02-29 02:02:57
5           58 2016-02-29 02:02:58
6           59 2016-02-29 02:02:59
7            0 2016-02-29 02:03:00
8            1 2016-02-29 02:03:01
9            2 2016-02-29 02:03:02

Detail:

print (df.rename(columns=d)[list(d.values())])
   day  month  second  year  minute  hour
1   29      2      54  2016       2     2
2   29      2      55  2016       2     2
3   29      2      56  2016       2     2
4   29      2      57  2016       2     2
5   29      2      58  2016       2     2
6   29      2      59  2016       2     2
7   29      2       0  2016       3     2
8   29      2       1  2016       3     2
9   29      2       2  2016       3     2


问:
c++1z dynamic exception specification error
I am trying to compile my project with new GCC version 7.2.1 and have a problem with dynamic exception specifications:

error: ISO C++1z does not allow dynamic exception specifications
  MEMORY_ALLOC_OPERATORS(SQLException)
```

The problem is that these errors come from third-party libraries which I do not control.

Is there a some way to fix it? As far as I know I can't tell compiler to replace errors with warnings. Using --std=c++14 is not an option because I want to use new features from C++1z.

答:
C++17 removed dynamic exception specifications, as a result of P0003. Before that, they had been deprecated since C++11. They are no longer part of the language, so there isn't really a way to fix it. As long as you need that third party library, until it changes, you're stuck on C++14.

If you're desperate, you could try:

```<code>#define throw(...)
</code>```

but I wouldn't recommend it.

Body:
I am trying to compile my project with new GCC version 7.2.1 and have a problem with dynamic exception specifications:

error: ISO C++1z does not allow dynamic exception specifications
  MEMORY_ALLOC_OPERATORS(SQLException)

The problem is that these errors come from third-party libraries which I do not control.

Is there a some way to fix it? As far as I know I can't tell compiler to replace errors with warnings. Using --std=c++14 is not an option because I want to use new features from C++1z.

Body:
C++17 removed dynamic exception specifications, as a result of P0003. Before that, they had been deprecated since C++11. They are no longer part of the language, so there isn't really a way to fix it. As long as you need that third party library, until it changes, you're stuck on C++14.

If you're desperate, you could try:

#define throw(...)

but I wouldn't recommend it.


问:
how can I type check this particular function?
It turns out prompt always returns a string, how can I type check this. I'm attempting to check a name to see if it contains numbers.</p>

```<code>function getName(){
        try{
            let name=prompt("please type a name").toLowerCase();

            for(let i=0; i<name.length; i++){

                if( typeof name[i] != "string"){
                    throw Error("invalid response");
                }
            }
            return name;
        }
        catch(err){
                console.log(err);
                console.log("please try again");
                getName();
        }
    }
</code>```

答:
This function identifies integer even amongst strings</p>

```<code>function hasNumbers(t) {
   return /\d/.test(t);
}

hasNumbers ("name") //false
hasNumbers ("name123") //true
hasNumbers ("na124me") //true
</code>```

Body:
It turns out prompt always returns a string, how can I type check this. I'm attempting to check a name to see if it contains numbers.

function getName(){
        try{
            let name=prompt("please type a name").toLowerCase();

            for(let i=0; i<name.length; i++){

                if( typeof name[i] != "string"){
                    throw Error("invalid response");
                }
            }
            return name;
        }
        catch(err){
                console.log(err);
                console.log("please try again");
                getName();
        }
    }

Body:
This function identifies integer even amongst strings

function hasNumbers(t) {
   return /\d/.test(t);
}

hasNumbers ("name") //false
hasNumbers ("name123") //true
hasNumbers ("na124me") //true


问:
Vue Directive not updating it's value - Jquery Chosen
I am using Jquery Chosen along with Vue. This is my Vue directive:

```<code>Vue.component("chosen-select", {
    props: {
        value: [String, Array],
        multiple: Boolean
    },
    template: `<select :multiple="multiple"><slot></slot></select>`,
    mounted() {
        $(this.$el)
            .val(this.value)
            .chosen({ width: '100%' })
            .on("change", e => this.$emit('input', $(this.$el).val()))
    },
    watch: {
        value(val) {
            $(this.$el).val(val).trigger('chosen:updated');
        }
    },
    destroyed() {
        $(this.$el).chosen('destroy');
    }
});
</code>```

And using it like this:

```<code><chosen-select v-model="basicDetailsModel.stateID" v-validate="'required'" data-vv-as="state" :state="errors.has('stateID') ? 'invalid' : 'valid'" name="stateID">
                        <option :value="null">Please select an option</option>
                        <option v-for="(state, index) in states" :key="index" :value="state.sid">{{state.nm}}</option>
                    </chosen-select>
</code>```

If the states are assigned static value it works fine as per expectation but if I fetch the states value dynamically the chosen is not updated with latest values. It stays with the initial values.

How would I fix this issue?

Edit: This one works. Do you think this is the right way?

```<code>Vue.component("chosen-select", {
    data() {
        return { observer: null }
    },
    props: {
        value: [String, Array],
        multiple: Boolean
    },
    template: `<select :multiple="multiple"><slot></slot></select>`,
    mounted() {
        // Create the observer (and what to do on changes...)
        this.observer = new MutationObserver(function (mutations) {
            $(this.$el).trigger("chosen:updated");
        }.bind(this));

        // Setup the observer
        this.observer.observe(
            $(this.$el)[0],
            { childList: true }
        );
        $(this.$el)
            .val(this.value)
            .chosen({ width: '100%' })
            .on("change", e => this.$emit('input', $(this.$el).val()))
    },
    watch: {
        value(val) {
            $(this.$el).val(val);
        }
    },
    destroyed() {
        $(this.$el).chosen('destroy');
    }
});
</code>```

答:
I am not sure how you are fetching the states dynamically, but if you're using jQuery to get them, then I think that is your problem. Vue doesn't get notified if non-Vue things (like jQuery) change anything.
Even if that's not the case, this is worth reading to see why jQuery and Vue don't get along.
Can you add how you are fetching them dynamically?
Also, consider using a Vue framework like Vuetify which has a pretty good select control and is totally in Vue.</p>

Body:
I am using Jquery Chosen along with Vue. This is my Vue directive:

Vue.component("chosen-select", {
    props: {
        value: [String, Array],
        multiple: Boolean
    },
    template: `<select :multiple="multiple"><slot></slot></select>`,
    mounted() {
        $(this.$el)
            .val(this.value)
            .chosen({ width: '100%' })
            .on("change", e => this.$emit('input', $(this.$el).val()))
    },
    watch: {
        value(val) {
            $(this.$el).val(val).trigger('chosen:updated');
        }
    },
    destroyed() {
        $(this.$el).chosen('destroy');
    }
});

And using it like this:

<chosen-select v-model="basicDetailsModel.stateID" v-validate="'required'" data-vv-as="state" :state="errors.has('stateID') ? 'invalid' : 'valid'" name="stateID">
                        <option :value="null">Please select an option</option>
                        <option v-for="(state, index) in states" :key="index" :value="state.sid">{{state.nm}}</option>
                    </chosen-select>

If the states are assigned static value it works fine as per expectation but if I fetch the states value dynamically the chosen is not updated with latest values. It stays with the initial values.

How would I fix this issue?

Edit: This one works. Do you think this is the right way?

Vue.component("chosen-select", {
    data() {
        return { observer: null }
    },
    props: {
        value: [String, Array],
        multiple: Boolean
    },
    template: `<select :multiple="multiple"><slot></slot></select>`,
    mounted() {
        // Create the observer (and what to do on changes...)
        this.observer = new MutationObserver(function (mutations) {
            $(this.$el).trigger("chosen:updated");
        }.bind(this));

        // Setup the observer
        this.observer.observe(
            $(this.$el)[0],
            { childList: true }
        );
        $(this.$el)
            .val(this.value)
            .chosen({ width: '100%' })
            .on("change", e => this.$emit('input', $(this.$el).val()))
    },
    watch: {
        value(val) {
            $(this.$el).val(val);
        }
    },
    destroyed() {
        $(this.$el).chosen('destroy');
    }
});


问:
How to implement notification system like on SO in nodejs mongodb?
Sorry if my question is abstract but let me explain my problem. I've got a forum that looks like to StackOverflow and built on nodejs and mongodb. There is posts and comments. I need to implement notification system which allows to notify users about adding a new answer to a post, changing post content, adding a new comments.

My problem is I've never implemented this feature before so at now I'm looking for best practices before I start. What I'm primary interested in is generic pattern of implementing this system. In particular what schema for notifications collection is needed? How to determinate subscribers to a post to send an notification? and other nuances which might be in such system.

Just to clarify that I don't need real-time notifications such in facebook but list of notifications at the top (like in SO) and ability to notify by email.

Please give some whitepapers on such system in an internet or some advises on how to implement such system from scratch.

Thanks.

答: Look up websockets (i.e socket.io or faye)</p>


问:
Populate select options from database to dynamic select option using jQuery
From the database I have selected the names of the members as the select options. With jQuery, I have a dynamic Add button that adds new select field with the append function. But what could be the standard way to pass my select options generated by php in the append?

I have researched for a while but could not get it working. So any suggestions would be really helpful.

This is the page structure. It looks messy but please have a look at it. I have passed the $members as <?php echo $members; ?> in a static select that already is there from the beginning, but for the dynamic ones, I have created a variable var members and tried to pass it in the append but it is not working.

```<code><?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>
<script>
   var members = "<?php echo $members; ?>";

   $(document).ready(function() {
          var fixHelperModified = function(e, div) {
                var $originals = div.children();
                var $helper = div.clone();
                $helper.children().each(function(index) {
                   $(this).width($originals.eq(index).width())
                });
                return $helper;
             },
             updateIndex = function() {
                $('div.index').each(function(i) {
                   $(this).html(i + 1);
                });
             };
          $("#add").sortable({
             helper: fixHelperModified,
             stop: updateIndex
          }).disableSelection();
          $("#addNew").click(function() {
             $('#add').append("<div class='row rem' id='move'><div class='col-md-1 index'>1. </div><div class='col-md-9'><select name='members[]'><option value=''>Select member</option>"+members+"</select></div><div class='col-md-1'><button class='delete btn btn-warning btn-xs'>Delete</button></div></div>");
             updateIndex();
          });
          $("body").on('click', '#add .delete', function() {
             $(this).closest(".rem").remove();
             updateIndex();
          });
       });
</script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>
</code>```

Here is a snippet of the form without the php if you need to see the jQuery in action.

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<select name='members[]'><option value=''>Select member</option></select>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form></code>```

答:
If thats what you want? you can just echo the php into a javascript array

```<code><script>
var members = []; // this is the javascript array been initialized
<?php
require_once 'db_connect.php';

$members = '';
$query = "SELECT memberID, memberName FROM members";
$result = mysqli_query($connect, $query);

$i=0 // index for the array
while($row = mysqli_fetch_array($result))
{
$raw_option = '<option   value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
$option = htmlentities($raw_options); // there might be quotation that could break your javascript
echo "members[{$i}] = '{$option}';"; // echoing the javascript first semi column is for javascript and second for php

$i++; // incrementing the index for the array
}
?>
</script>
</code>```

Then the jquery add button can just pick each options from the members array

Body:
From the database I have selected the names of the members as the select options. With jQuery, I have a dynamic Add button that adds new select field with the append function. But what could be the standard way to pass my select options generated by php in the append?

I have researched for a while but could not get it working. So any suggestions would be really helpful.

This is the page structure. It looks messy but please have a look at it. I have passed the $members as <?php echo $members; ?> in a static select that already is there from the beginning, but for the dynamic ones, I have created a variable var members and tried to pass it in the append but it is not working.

<?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>

<form method="post">
   <fieldset>

            Members

1.

                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>

Here is a snippet of the form without the php if you need to see the jQuery in action.

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<select name='members[]'><option value=''>Select member</option></select>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });

<form method="post">
   <fieldset>

            Members

1.

                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>

Body:
If thats what you want? you can just echo the php into a javascript array

<script>
var members = []; // this is the javascript array been initialized
<?php
require_once 'db_connect.php';

$members = '';
$query = "SELECT memberID, memberName FROM members";
$result = mysqli_query($connect, $query);

$i=0 // index for the array
while($row = mysqli_fetch_array($result))
{
$raw_option = '<option   value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
$option = htmlentities($raw_options); // there might be quotation that could break your javascript
echo "members[{$i}] = '{$option}';"; // echoing the javascript first semi column is for javascript and second for php

$i++; // incrementing the index for the array
}
?>
</script>

Then the jquery add button can just pick each options from the members array


问:
a puzzle about definition of the time complexity
Wikipedia defines time complexity as

In computer science, the time complexity of an algorithm quantifies
  the amount of time taken by an algorithm to run as a function of the
  length of the string representing the input.

What's mean of the strong part?

I know algorithm may be treated as a function but why its input must be "the length of the string representing"?

答:
Summary

If there is some input, it is expressed as a string. So you have a length of that string. Then you have a function F that maps the length of the input (as a string) to the time needed by A to compute this input (in the worst case).

We call this F time complexity.

Say we have an algorithm A. What is its time complexity?

The very easy case

If A has constant complexity, the input doesn't matter. The input could be a single value, or a list, or a map from strings to lists of lists. The algorithm will run for the same amount of time. 3 seconds or 1000 ticks or a million years or whatever. Constant time values not depending on the input.

Not much complexity at all to be honest.

Adding complexity

Now let's say for example A is an algorithm for sorting list of integer numbers. It's clear that the time needed by A now depends on the length of the list. A list of length 0 is literally sorted in no time (but checking the length of the list) but this changes if the length of the input list grows.

You could say there exists a function F that maps the list length to the seconds needed by A to sort a list of that length. But wait! What if the list is already sorted? So for simplicity let's always assume a worst case scenario: F maps list length to the maximum of seconds needed by A to sort a list of that length.

You could measure in seconds, CPU cycles, ticks, or whatever. It doesn't depend on the units.

Generalizing a bit

What with all the other algorithms? How to measure time complexity for an algorithm that cooks me a nice meal?

If you cannot define any input parameter then we're back in the easy case: constant time. If there is some input it is expressed as a string. So you have a length of that string. And - similar to what has been said above - then you have a function F that maps the length of the input (as a string) to the time needed by A to compute this input (in the worst case).

We call this F time complexity.

That's too simple

Yeah, I know. There is the average case and the best case, there is the big O notation and asymptotic complexity. But for explaining the bold part in the original question this is sufficient, I think.


问:
Change directory in PowerShell
My PowerShell prompt's currently pointed to my C drive (PS C:\>).  How do I change directory to a folder on my Q (PS Q:\>) drive?

The folder name on my Q drive is "My Test Folder".

答:
Multiple posted answer here, but probably this can help who is newly using PowerShell

SO if any space is there in your directory path do not forgot to add double inverted commas "".

ContentLicense: CC BY-SA 4.0

Title: Change directory in PowerShell


问:
Specify construct when querying with Devart.Data.Linq.DataContext.Query<T>
I'm using Devart's Linq to sql in my project (not Entity Framework). Try to select from database with Query<T>, or ExecuteQuery<T>, but T deliberately don't have public parameterless constructor. Can I somehow overwrite how should a new instance of T created? For example giving an instance of AutoMapper.Profile at some point? Or giving a Func<T> that will create the T instance before it's overwritten with the value from the DB?

```<code>using( var DC = new SomeDevartDataContextBaseDerivative() )
{
    // exception because parameterless constructor
    var FM = DC.ExecuteQuery<SomeTypeWithoutParameterlessConstructor>( "Select 1 as Id" );
    return FM;
}
</code>```

答: There is no way to pass a type without public parameterless constructor.</p>

Body:
I'm using Devart's Linq to sql in my project (not Entity Framework). Try to select from database with Query<T>, or ExecuteQuery<T>, but T deliberately don't have public parameterless constructor. Can I somehow overwrite how should a new instance of T created? For example giving an instance of AutoMapper.Profile at some point? Or giving a Func<T> that will create the T instance before it's overwritten with the value from the DB?

using( var DC = new SomeDevartDataContextBaseDerivative() )
{
    // exception because parameterless constructor
    var FM = DC.ExecuteQuery<SomeTypeWithoutParameterlessConstructor>( "Select 1 as Id" );
    return FM;
}


问:
Dataweave transformation: Modify JSON value
I want to do the below dataweave transformation. "SourceValue" should go as
"Source" and "SrcVal" in the output payload. Could you please suggest how to do it.

Input:

```<code>{       "payload":[
      {
         "key":"stage",
         "value":"Completed"
      },
      {
         "key":"url",
         "value":"abc.com"
      },
      {
         "key":"SourceValue",
         "value":"abc"
      }
   ]
}
</code>```

答:
Use the following :</p>

```<code>%dw 1.0
%input payload application/json
%output application/json
%var a=2
---
{
    part1: payload.payload map ((payload01 , indexOfPayload01) -> {
        "key" : "Source" when payload01.key == "SourceValue" otherwise payload01.key,
        "value" : payload01.value

    }),
     part2: payload.payload filter ($.key == "url"  or $.key == "SourceValue") map ((payload01 , indexOfPayload01) ->
         {
         "key" : "SrcVal" when payload01.key == "SourceValue" otherwise payload01.key,
         "value" : payload01.value
         }
     )

}
</code>```

Body:
I want to do the below dataweave transformation. "SourceValue" should go as
"Source" and "SrcVal" in the output payload. Could you please suggest how to do it.

Input:

{       "payload":[
      {
         "key":"stage",
         "value":"Completed"
      },
      {
         "key":"url",
         "value":"abc.com"
      },
      {
         "key":"SourceValue",
         "value":"abc"
      }
   ]
}

Body:
Use the following :

%dw 1.0
%input payload application/json
%output application/json
%var a=2
---
{
    part1: payload.payload map ((payload01 , indexOfPayload01) -> {
        "key" : "Source" when payload01.key == "SourceValue" otherwise payload01.key,
        "value" : payload01.value

    }),
     part2: payload.payload filter ($.key == "url"  or $.key == "SourceValue") map ((payload01 , indexOfPayload01) ->
         {
         "key" : "SrcVal" when payload01.key == "SourceValue" otherwise payload01.key,
         "value" : payload01.value
         }
     )

}


问:
Deciphering text in python 3
I am trying to take a text as input, count the number of occurrences of each alphabetic letter in the string, so for example in "hello" h =1 , e =1 , l =2, o =1 . and then replace the highest occurring letter with E and second highest with T and so on from here (http://www.counton.org/explorer/codebreaking/frequency-analysis.php)
So am trying to do this in python 3 , and so far I made a code the takes the text as input and counts the number of occurrences of each alphabet, but my problem is in the replacing part. Can any one help me in doing this, how do I replace the highest occurring alphabet with the highest occurring one according to that website?

Here is my code (sorry about that):

```<code>def break_cipher(OriginalText = input()):
a=0
b=0
c=0
d=0
e=0
f=0
g=0
h=0
i=0
j=0
k=0
l=0
m=0
n=0
o=0
p=0
q=0
r=0
s=0
t=0
u=0
v=0
w=0
x=0
y=0
z=0
for charr in OriginalText:
    if charr  == 'a' :
        a +=1
    if charr  == 'b' :
        b +=1
    if charr  == 'c' :
        c +=1
    if charr  == 'd' :
        d +=1
    if charr  == 'e' :
        e +=1
    if charr  == 'f' :
        f +=1
    if charr  == 'g' :
        g +=1
    if charr  == 'h' :
        h +=1
    if charr  == 'i' :
        i +=1
    if charr  == 'j' :
        j +=1
    if charr  == 'k' :
        k +=1
    if charr  == 'l' :
        l +=1
    if charr  == 'm' :
        m +=1
    if charr  == 'n' :
        n +=1
    if charr  == 'o' :
        o +=1
    if charr  == 'p' :
        p +=1
    if charr  == 'q' :
        q +=1
    if charr  == 'r' :
        r +=1
    if charr  == 's' :
        s +=1
    if charr  == 't' :
        t +=1
    if charr  == 'u' :
        u +=1
    if charr  == 'v' :
        v +=1
    if charr  == 'w' :
        w +=1
    if charr  == 'x' :
        x +=1
    if charr  == 'y' :
        y +=1
    if charr  == 'z' :
        z +=1
mylist = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v]
mylist.sort()
print(mylist)
print(mylist[-1])
str(OriginalText)
print("a = " + str(a))
print("b = " +str(b))
print("c = " +str(c))
print("d = " +str(d))
print("e = " +str(e))
print("f = " +str(f))
print("g = " +str(g))
print("h = " +str(h))
print("i = " +str(i))
print("j = " +str(j))
print("k = " +str(k))
print("l = " +str(l))
print("m = " +str(m))
print("n = " +str(n))
print("o = " +str(o))
print("p = " +str(p))
print("q = " +str(q))
print("r = " +str(r))
print("s = " +str(s))
print("t = " +str(t))
print("u = " +str(u))
print("v = " +str(v))
print("w = " +str(w))
print("x = " +str(x))
print("y = " +str(y))
print("z = " +str(z))
</code>```

break_cipher()

答:
Do not use a function call as default value, because what that means is you are calling input() when you DEFINE the function, not when you call it. This input() will be called once, and only once, and this will happen when you import the module, not when you call the function.

```<code>def break_cipher(OriginalText):
</code>```

Do not name a variable in CamelCase, nor start it in capital letters (that's the convention for classes)

```<code>def break_cipher(original_text)
</code>```

Use a dict instead of these many variables:

```<code>count_dict = {}
</code>```

Your task is to iterate through the string, use a loop:

```<code>for character in original_text:
    if character not in count_dict:
        count_dict[character] = 0
    count_dict += 1
</code>```

At the end of the loop you will have something like:

```<code>{
    'a': 5,
    'e': 7
 }
</code>```

Etc...

You can also use a defaultdict that will simplify your code further

```<code>from collections import defaultdict

count_dict = defaultdict(int)  # Note that new int's are 0

for character in original_text:
    count_dict[character] += 1
</code>```

There are many subtilities and improvements possible:

Is A == a? in that case you want to do:

```<code>count_dict[character.lower()] += 1
</code>```

Are you intended to only count english alphabet characters ? in that case you need to:

```<code>for character in [charr for charr in count_dict if 'a' < charr.lower() < 'z']
</code>```

(see list comprehensions for this one)

For the replacement part:

```<code>frequencies = count_dict.keys()  # This gives you a list of all the letters in the text
frequencies.sort(key=count_dict).reverse()  # This will sort them by frequency
</code>```

Then you just need to recreate the text from there

May the code be with you

Title: Deciphering text in python 3

Body:
I am trying to take a text as input, count the number of occurrences of each alphabetic letter in the string, so for example in "hello" h =1 , e =1 , l =2, o =1 . and then replace the highest occurring letter with E and second highest with T and so on from here (http://www.counton.org/explorer/codebreaking/frequency-analysis.php)
So am trying to do this in python 3 , and so far I made a code the takes the text as input and counts the number of occurrences of each alphabet, but my problem is in the replacing part. Can any one help me in doing this, how do I replace the highest occurring alphabet with the highest occurring one according to that website?

Here is my code (sorry about that):

def break_cipher(OriginalText = input()):
a=0
b=0
c=0
d=0
e=0
f=0
g=0
h=0
i=0
j=0
k=0
l=0
m=0
n=0
o=0
p=0
q=0
r=0
s=0
t=0
u=0
v=0
w=0
x=0
y=0
z=0
for charr in OriginalText:
    if charr  == 'a' :
        a +=1
    if charr  == 'b' :
        b +=1
    if charr  == 'c' :
        c +=1
    if charr  == 'd' :
        d +=1
    if charr  == 'e' :
        e +=1
    if charr  == 'f' :
        f +=1
    if charr  == 'g' :
        g +=1
    if charr  == 'h' :
        h +=1
    if charr  == 'i' :
        i +=1
    if charr  == 'j' :
        j +=1
    if charr  == 'k' :
        k +=1
    if charr  == 'l' :
        l +=1
    if charr  == 'm' :
        m +=1
    if charr  == 'n' :
        n +=1
    if charr  == 'o' :
        o +=1
    if charr  == 'p' :
        p +=1
    if charr  == 'q' :
        q +=1
    if charr  == 'r' :
        r +=1
    if charr  == 's' :
        s +=1
    if charr  == 't' :
        t +=1
    if charr  == 'u' :
        u +=1
    if charr  == 'v' :
        v +=1
    if charr  == 'w' :
        w +=1
    if charr  == 'x' :
        x +=1
    if charr  == 'y' :
        y +=1
    if charr  == 'z' :
        z +=1
mylist = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v]
mylist.sort()
print(mylist)
print(mylist[-1])
str(OriginalText)
print("a = " + str(a))
print("b = " +str(b))
print("c = " +str(c))
print("d = " +str(d))
print("e = " +str(e))
print("f = " +str(f))
print("g = " +str(g))
print("h = " +str(h))
print("i = " +str(i))
print("j = " +str(j))
print("k = " +str(k))
print("l = " +str(l))
print("m = " +str(m))
print("n = " +str(n))
print("o = " +str(o))
print("p = " +str(p))
print("q = " +str(q))
print("r = " +str(r))
print("s = " +str(s))
print("t = " +str(t))
print("u = " +str(u))
print("v = " +str(v))
print("w = " +str(w))
print("x = " +str(x))
print("y = " +str(y))
print("z = " +str(z))

break_cipher()

Body:
Do not use a function call as default value, because what that means is you are calling input() when you DEFINE the function, not when you call it. This input() will be called once, and only once, and this will happen when you import the module, not when you call the function.

def break_cipher(OriginalText):

Do not name a variable in CamelCase, nor start it in capital letters (that's the convention for classes)

def break_cipher(original_text)

Use a dict instead of these many variables:

count_dict = {}

Your task is to iterate through the string, use a loop:

for character in original_text:
    if character not in count_dict:
        count_dict[character] = 0
    count_dict += 1

At the end of the loop you will have something like:

{
    'a': 5,
    'e': 7
 }

Etc...

You can also use a defaultdict that will simplify your code further

from collections import defaultdict

count_dict = defaultdict(int)  # Note that new int's are 0

for character in original_text:
    count_dict[character] += 1

There are many subtilities and improvements possible:

Is A == a? in that case you want to do:

count_dict[character.lower()] += 1

Are you intended to only count english alphabet characters ? in that case you need to:

for character in [charr for charr in count_dict if 'a' < charr.lower() < 'z']

(see list comprehensions for this one)

For the replacement part:

frequencies = count_dict.keys()  # This gives you a list of all the letters in the text
frequencies.sort(key=count_dict).reverse()  # This will sort them by frequency

Then you just need to recreate the text from there

May the code be with you


问:
Migration with Liberty server- how to configure mail session in Liberty
Please refer below code snippet in liberty server.xml.

```<code><library id="objectFactoryLib">
      <fileset dir="" includes="naming-factory-5.5.15.jar"/>
     <fileset dir="" includes="javax.mail-1.5.5.jar"/>
 </library>

 <jndiObjectFactory  className="org.apache.naming.factory.MailSessionFactory" id="mailSessionFactory" libraryRef="objectFactoryLib" objectClassName="javax.mail.Session"/>
</code>```

Getting the below error while deploying application in liberty server version 8.5.5.7.

```<code>Cannot convert value of type [javax.mail.Session] to required type [javax.mail.Session] for property 'session': no matching editors or conversion strategy found.
</code>```

I have already removed the mail jar in other places and kept only in ear/web-inf/lib folder alone.but even getting the same error.
Can anyone tel how to configure mail session in Liberty .
Liberty 8.5.5.7 version not supporting java Mail 1.5 feature.

Note : My Application already running successfully in Tomcat /WAS .

答:
You should use <feature>javaMail-1.5</feature> in your server.xml and then configure session something like this:

```<code><mailSession
   description="Mail session for testing"
   from="Liberty2@itso.ibm.com"
   host="mailHost"
   jndiName="mail/itsoMailSession"
   mailSessionID="itsoMailSession"
   user="validUser@account.com"
   password="password"/>
</code>```

In application you request it like this:

```<code>@Resource(lookup="mail/itsoMailSession")
Session mailSession;
</code>```

Check the following resources:

WebSphere Liberty Redbook

How to write an application using JavaMail

Knowledge Center

Body:
Please refer below code snippet in liberty server.xml.

<library id="objectFactoryLib">
      <fileset dir="" includes="naming-factory-5.5.15.jar"/>
     <fileset dir="" includes="javax.mail-1.5.5.jar"/>
 </library>

 <jndiObjectFactory  className="org.apache.naming.factory.MailSessionFactory" id="mailSessionFactory" libraryRef="objectFactoryLib" objectClassName="javax.mail.Session"/>

Getting the below error while deploying application in liberty server version 8.5.5.7.

Cannot convert value of type [javax.mail.Session] to required type [javax.mail.Session] for property 'session': no matching editors or conversion strategy found.

I have already removed the mail jar in other places and kept only in ear/web-inf/lib folder alone.but even getting the same error.
Can anyone tel how to configure mail session in Liberty .
Liberty 8.5.5.7 version not supporting java Mail 1.5 feature.

Note : My Application already running successfully in Tomcat /WAS .

Body:
You should use <feature>javaMail-1.5</feature> in your server.xml and then configure session something like this:

<mailSession
   description="Mail session for testing"
   from="Liberty2@itso.ibm.com"
   host="mailHost"
   jndiName="mail/itsoMailSession"
   mailSessionID="itsoMailSession"
   user="validUser@account.com"
   password="password"/>

In application you request it like this:

@Resource(lookup="mail/itsoMailSession")
Session mailSession;

Check the following resources:

WebSphere Liberty Redbook

How to write an application using JavaMail

Knowledge Center


问:
How to access Request attributes and parameters on Symfony?
How to reach the parameters Array into the Request object? For example in doneAction(), I want to get the parameter from the url such as this example:

www.example.com/en/done?payum_token=76BQZfpdjV1rOGye_y5WZr0vOpkyCKm2vstkOsZvjOE

```<code>public function doneAction(Request $request)
{
    dump($request);
    dump($request->query);
    dump($request->query->getparameters());
}
</code>```

When I try with $request->query->getparameters() I have got an error:

I also tried $request->query->parameters

答:
You can do:

```<code>$request->query->get('payum_token');
</code>```

If you look at your debug, we see that the query is a ParameterBag object. So you can access the Symfony API and see what are the public methods provided by this class. For example for the get method:

http://api.symfony.com/3.4/Symfony/Component/HttpFoundation/ParameterBag.html#method_get

Note that this method returns null if the parameter isn't found. If you want to have another value if the parameter is not found, then pass it as the 2nd argument:

```<code>$request->query->get('payum_token', 'default_value');
</code>```

Body:
How to reach the parameters Array into the Request object? For example in doneAction(), I want to get the parameter from the url such as this example:

www.example.com/en/done?payum_token=76BQZfpdjV1rOGye_y5WZr0vOpkyCKm2vstkOsZvjOE

public function doneAction(Request $request)
{
    dump($request);
    dump($request->query);
    dump($request->query->getparameters());
}

When I try with $request->query->getparameters() I have got an error:

I also tried $request->query->parameters

Body:
You can do:

$request->query->get('payum_token');

If you look at your debug, we see that the query is a ParameterBag object. So you can access the Symfony API and see what are the public methods provided by this class. For example for the get method:

http://api.symfony.com/3.4/Symfony/Component/HttpFoundation/ParameterBag.html#method_get

Note that this method returns null if the parameter isn't found. If you want to have another value if the parameter is not found, then pass it as the 2nd argument:

$request->query->get('payum_token', 'default_value');


问:
Character Segmentation fails on 'W'
I am using OpenCV for OCR of printed codes containing arbitrary characters and numbers. My pipeline involves thresholding, denoising, gradient morphology, and then finding the contours in order to palce a bounding box around each letter.

It works very well except when a 'W' appears in the code. It usually places 2 or 3 bounding boxes such that the prediction is "VAV" or "VV", which is honestly a mistake my own eyes might make when I'm tired.

Does anyone have any ideas how best to address this issue? I can be fairly certain that a 'W' appears in many of these codes and it needs to be segmented properly. Thanks for any help!

答: Try running a morphological dilation on the image before finding the contours. This will help you merge all the parts of the letter W as a single blob, preventing it from being recognized as multiple letters. </p>

Title: Character Segmentation fails on 'W'


答:
If all you need to do is test that there are any numbers in the string, then you can just use a simple Regex to test that:

```<code>var regex = /\d+/g;
regex.test(name); // returns true if there are any numbers anywhere in the string
</code>```

If you want to see if there are only letters, you can do it this way instead:

```<code>var regex = /[a-zA-Z]+/g;
regex.test(name); // returns true only if all characters are letters
</code>```

Title: how can I type check this particular function?

Body:
If all you need to do is test that there are any numbers in the string, then you can just use a simple Regex to test that:

var regex = /\d+/g;
regex.test(name); // returns true if there are any numbers anywhere in the string

If you want to see if there are only letters, you can do it this way instead:

var regex = /[a-zA-Z]+/g;
regex.test(name); // returns true only if all characters are letters


问:
Saving an editable table in txt file
I have this editable table.

How I can save all data in a txt file (modified or not modified)?

var cell = null; //Focus Zero

function modify(obj) {
  if (cell == null) {
    cell = obj; //Create "Cell"
    obj.innerHTML = "<input type='text' id='newtext' value='" + obj.innerHTML + "' onChange='save();' style='border:none'></input>";
    document.getElementById("newtext").focus();
  }
}

function save() //function for save the focus
{
  var nuovoVal = document.getElementById("newtext").value;
  cell.innerHTML = nuovoVal;
  cell = null;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><TABLE border=2>
  <TR>
    <TD onclick="modify(this);">Denzel Washington</TD>
  </TR>
  <TR>
    <TD onclick="modify(this);">Robert De Niro</TD>
  </TR>

</TABLE></code>```

答:
Instead of modify function I used contenteditable...

And for .txt download I used Blob...

Hope this helps...

var cell = null; //Focus Zero

$('#save-link').click(function ()
{
  var retContent = [];
  var retString = '';
  $('tr').each(function (idx, elem)
  {
    var elemText = [];
    $(elem).children('td').each(function (childIdx, childElem)
    {
      elemText.push($(childElem).text());
    });
    retContent.push(`(${elemText.join(',')})`);
  });
  retString = retContent.join(',\r\n');
 var file = new Blob([retString], {type: 'text/plain'});
  var btn = $('#save-link');
  btn.attr("href", URL.createObjectURL(file));
  btn.prop("download", "data.txt");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<TABLE border=2>
  <TR>
    <TD contenteditable="true">Denzel Washington</TD>
  </TR>
  <TR>
    <TD contenteditable="true">Robert De Niro</TD>
  </TR>

</TABLE>
Download</code>```

Title: Saving an editable table in txt file

Body:
I have this editable table.

How I can save all data in a txt file (modified or not modified)?

var cell = null; //Focus Zero

function modify(obj) {
  if (cell == null) {
    cell = obj; //Create "Cell"
    obj.innerHTML = "<input type='text' id='newtext' value='" + obj.innerHTML + "' onChange='save();' style='border:none'></input>";
    document.getElementById("newtext").focus();
  }
}

function save() //function for save the focus
{
  var nuovoVal = document.getElementById("newtext").value;
  cell.innerHTML = nuovoVal;
  cell = null;
}

    Denzel Washington

    Robert De Niro

Body:
Instead of modify function I used contenteditable...

And for .txt download I used Blob...

Hope this helps...

var cell = null; //Focus Zero

$('#save-link').click(function ()
{
  var retContent = [];
  var retString = '';
  $('tr').each(function (idx, elem)
  {
    var elemText = [];
    $(elem).children('td').each(function (childIdx, childElem)
    {
      elemText.push($(childElem).text());
    });
    retContent.push(`(${elemText.join(',')})`);
  });
  retString = retContent.join(',\r\n');
 var file = new Blob([retString], {type: 'text/plain'});
  var btn = $('#save-link');
  btn.attr("href", URL.createObjectURL(file));
  btn.prop("download", "data.txt");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<TABLE border=2>
  <TR>
    <TD contenteditable="true">Denzel Washington</TD>
  </TR>
  <TR>
    <TD contenteditable="true">Robert De Niro</TD>
  </TR>

</TABLE>
<a href="#" id="save-link">Download</a>


问:
OSError: [Errno 99] Cannot assign requested address - py
I just copied this code for a client/server example:

http://www.bogotobogo.com/python/python_network_programming_server_client.php

and when I run the code I get this error:

```<code>OSError: [Errno 99] Cannot assign requested address
</code>```

Server:

```<code># server.py
import socket
import time

# create a socket object
serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()

port = 9999

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)

while True:
    # establish a connection
    clientsocket,addr = serversocket.accept()

    print("Got a connection from %s" % str(addr))
    currentTime = time.ctime(time.time()) + "\r\n"
    clientsocket.send(currentTime.encode('ascii'))
    clientsocket.close()
</code>```

Client:

```<code># client.py
import socket

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()

port = 9999

# connection to hostname on the port.
s.connect((host, port))

# Receive no more than 1024 bytes
tm = s.recv(1024)

s.close()

print("The time got from the server is %s" % tm.decode('ascii'))
</code>```

答:
Replace host = socket.gethostname() with host = '127.0.0.1' and it should work.

Check this

Hope this wil help :)

Body:
I just copied this code for a client/server example:

http://www.bogotobogo.com/python/python_network_programming_server_client.php

and when I run the code I get this error:

OSError: [Errno 99] Cannot assign requested address

Server:

# server.py
import socket
import time

# create a socket object
serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()

port = 9999

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)

while True:
    # establish a connection
    clientsocket,addr = serversocket.accept()

    print("Got a connection from %s" % str(addr))
    currentTime = time.ctime(time.time()) + "\r\n"
    clientsocket.send(currentTime.encode('ascii'))
    clientsocket.close()

Client:

# client.py
import socket

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()

port = 9999

# connection to hostname on the port.
s.connect((host, port))

# Receive no more than 1024 bytes
tm = s.recv(1024)

s.close()

print("The time got from the server is %s" % tm.decode('ascii'))


问:
Wamp Server icon is red
I recently installed wamp server 2.2 in my system. But the icon is red for some weird reason.
I am able to see phpmyadmin but when I open MySQL(http://localhost/phpmyadmin) it says

MySQL said:

#2002 - The server is not responding (or the local MySQL server's socket is not     correctly configured)

I checked the task manager and I can only see wampmanager.exe running.
I tested port 80 and it says

Your port 80 is actually used by:
  server:  Apache/2.2.17(Wind32) PHP/5.3.5

Also in Apache>Service start/resume service, stop service, restart service are disabled.

Please tell me what is the issue.

答:
Solution that worked for me:

Access services.msc (Control Panel -> Administrative Tools -> Services);

Find all the services that start with "wamp". In my case: wampapache64 and wampmysqld64;

Double click on each of them and set the start-up type as: "automatic";

Restart all services of wamp, by clicking once on its tray icon and selecting the option "Restart All Services".

I don't know why, but, somehow, the services start-up types where marked as "Disabled". Maybe some other software made it without my consent. Because of that, the Wamp was with a red icon, but showing online when hoovering the mouse over it.

Title: Wamp Server icon is red


问:
Does Ignite on YARN support Node Labels?
I know Ignite still does not support setting up custom YARN queues from this JIRA ticket - https://issues.apache.org/jira/browse/IGNITE-2738 . I cannot find any information on whether Ignite supports running its containers within specified YARN node labels?

Currently in our cluster we have labelled all of our nodes and in attempting to start an Ignite applicaiton, the app is stuck in Pending stage because it is waiting for resources to be assigned from AM, with the AM container Node Label expression defaulting to <DEFAULT_PARTITION> .

Is there a way to supply node labels for Ignite on YARN?

答:
ignite-yarn doesn't seem to set node labels.

Have you tried specifying them externally?


问:
unable to run 'aws' from cygwin
I'm using cygwin installed on Windows 10 and trying to access awscli from it.

I used pip install awscli to install awscli. This installed awscli. I then tried to run only aws to see if it is installed and I get the following error:

```<code>-bash: /cygdrive/c/Program Files/Anaconda2/Scripts/aws: C:\Program: bad interpreter: No such file or directory
</code>```

I'm not sure why this is happening. Any help in this regard would be highly apreciated.

答:
In Windows:

cd .. to go to home directory which shows pwd as /.
Now, cd to /cygdrive/c/Program\ Files/Anaconda2/Scripts

Now, run: python aws configure

Example:

```<code>user@user /cygdrive/c/Program Files/Anaconda2/Scripts
$python aws configure
</code>```

Title: unable to run 'aws' from cygwin

Body:
I'm using cygwin installed on Windows 10 and trying to access awscli from it.

I used pip install awscli to install awscli. This installed awscli. I then tried to run only aws to see if it is installed and I get the following error:

-bash: /cygdrive/c/Program Files/Anaconda2/Scripts/aws: C:\Program: bad interpreter: No such file or directory

I'm not sure why this is happening. Any help in this regard would be highly apreciated.

Body:
In Windows:

cd .. to go to home directory which shows pwd as /.
Now, cd to /cygdrive/c/Program\ Files/Anaconda2/Scripts

Now, run: python aws configure

Example:

user@user /cygdrive/c/Program Files/Anaconda2/Scripts
$python aws configure


问:
Retrieving and saving data
Need some help to understand below sample code to connect and retreive data from database usind odbc.  i do understand sql query.. thats not an issue </p>

```<code> function getObject($query, $params, &$output)
        {
            global $connect;
            $result = odbc_prepare($connect, $query);
            odbc_execute($result, $params);

            $j=0;

            while($object = odbc_fetch_array($result))
            {
                $output[$j++] = $object;
            }
        }

    function _getDeviceByIdentification($identification)
        {
            $query =
                "SELECT * FROM Device"
                ." WHERE Identification = ?'".$identification."'";
            $params = array(
                    $identification);
            getObject($query, $params, $ret);
            return $ret;
</code>```

答:
Your query is incorrect. Don't pass the value in the query, that is what the placeholder ? is for.

```<code>function _getDeviceByIdentification($identification) {
    $query = "SELECT * FROM Device WHERE Identification = ?";
    $params = array($identification);
    getObject($query, $params, $ret);
    return $ret;
</code>```

The driver swaps the placeholder ? with the value (whatever $identification contains) and escapes any characters that are special.

So for example say you had $identification = "olde' iphone";. Passing that to the query directly:

```<code>$query ="SELECT * FROM Device WHERE Identification = '$identification'";
</code>```

would make an incorrect query because it comes out as:

```<code>SELECT * FROM Device WHERE Identification = 'olde' iphone';
                                                 ^ string closed, the rest of the query is unexpected
</code>```

however when the driver sees the ' it knows to escape it.

```<code>SELECT * FROM Device WHERE Identification = 'olde\' iphone';
</code>```

so the ' isn't an encapsulation character anymore.

The $params = array($identification); makes an array of terms that map to the placeholders (they map in the order they are presented in the array, and the order the fall in the query). If you follow the code execution you can see the array ends up being used in the http://php.net/manual/en/function.odbc-execute.php (which is what actually does the binding).

Title: Retrieving and saving data

Body:
Need some help to understand below sample code to connect and retreive data from database usind odbc.  i do understand sql query.. thats not an issue

 function getObject($query, $params, &$output)
        {
            global $connect;
            $result = odbc_prepare($connect, $query);
            odbc_execute($result, $params);

            $j=0;

            while($object = odbc_fetch_array($result))
            {
                $output[$j++] = $object;
            }
        }

    function _getDeviceByIdentification($identification)
        {
            $query =
                "SELECT * FROM Device"
                ." WHERE Identification = ?'".$identification."'";
            $params = array(
                    $identification);
            getObject($query, $params, $ret);
            return $ret;

Body:
Your query is incorrect. Don't pass the value in the query, that is what the placeholder ? is for.

function _getDeviceByIdentification($identification) {
    $query = "SELECT * FROM Device WHERE Identification = ?";
    $params = array($identification);
    getObject($query, $params, $ret);
    return $ret;

The driver swaps the placeholder ? with the value (whatever $identification contains) and escapes any characters that are special.

So for example say you had $identification = "olde' iphone";. Passing that to the query directly:

$query ="SELECT * FROM Device WHERE Identification = '$identification'";

would make an incorrect query because it comes out as:

SELECT * FROM Device WHERE Identification = 'olde' iphone';
                                                 ^ string closed, the rest of the query is unexpected

however when the driver sees the ' it knows to escape it.

SELECT * FROM Device WHERE Identification = 'olde\' iphone';

so the ' isn't an encapsulation character anymore.

The $params = array($identification); makes an array of terms that map to the placeholders (they map in the order they are presented in the array, and the order the fall in the query). If you follow the code execution you can see the array ends up being used in the http://php.net/manual/en/function.odbc-execute.php (which is what actually does the binding).


问:
anyone who has used Atlassian's Elastic Bamboo to build .NET projects - what AMI do I need to use?
This whole setup process is fairly perplexing, and I feel like the documentation is written for CI and cloud experts. Can anybody lend some inght into their setup?</p>

答:
I've detailed how to set up your own AMI to use at :
http://consultingblogs.emc.com/gracemollison/archive/2011/01/18/how-to-set-up-a-windows-ami-to-use-with-elastic-bamboo.aspx</p>

ContentLicense: CC BY-SA 2.5


问:
switch-case in Java 1.8 with Eclipse not possible?
I have re-installed my Java 8 and get a new and fresh Eclipse version.

If I write the following code:

```<code>String a = "001100";

switch(a) {
   case "5": a = "25"; break;
   default: System.exit(0);
}
</code>```

then Eclipse underlines the "a" in the switch-brackets red and says "Change project compliance and JRE to 1.7".
I have not tried this because I'm using Java 1.8 and this should work? I don't want to use Java 1.7.

My Eclipse is setting up with Java 1.8, also this Project. There is no lower Java version in the settings....

Where is the problem?

答:
Strings in switch statements are available only post JDK 1.7

https://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html

You need to check your java compiler level and change it to JDK 1.8 or 1.7.

(Right Click on project, go to preferences then look for "Java Compiler" and change "Compiler Compliance Level")

Body:
I have re-installed my Java 8 and get a new and fresh Eclipse version.

If I write the following code:

String a = "001100";

switch(a) {
   case "5": a = "25"; break;
   default: System.exit(0);
}

then Eclipse underlines the "a" in the switch-brackets red and says "Change project compliance and JRE to 1.7".
I have not tried this because I'm using Java 1.8 and this should work? I don't want to use Java 1.7.

My Eclipse is setting up with Java 1.8, also this Project. There is no lower Java version in the settings....

Where is the problem?


问:
Update observable from promise based on other observable
I have a service which returns filters from our backend. This service has a method getForPage which returns a promise, and a getForPage$ which returns an observable.

On the service there is also the method onEvent which is an observable which emits when there was a change on a filter.

Now I want that the getForPage$ observable is updated when the onEvent emits an event. Which is done with the following code.

```<code>getForPage(page: string): Promise<DashboardPageFilter[]> {
    return this.service.call(
        'dashboard.page.filter.getForPage',
        {page}
    );
}

getForPage$(page: string): Observable<DashboardPageFilter[]> {
    let subject = new Subject<DashboardPageFilter[]>();

    this.getForPage(page).then(
        response => subject.next(response),
        response => subject.error(response)
    );

    this.onEvent().subscribe(() => {
        console.log(page);
        this.getForPage(page).then(
            response => subject.next(response),
            response => subject.error(response)
        );
    });

    return subject.asObservable();
}
</code>```

However when I can the route the subscription on onEvent won't be closed. So the log will be called even when there is not an active subscription any more on the subject observable.

How do you make an observable from a promise which can be to be updated and is completed on route change?

答:
After more attempts to fix the issue, some ideas from the comments and a relook at the code I came to a solution for the problem. However this still has an other minor issue

Before the code was living outside the observable for updating. With the code below the updating live inside the observer.

```<code>return Observable.create((observer: Observer<DashboardPageFilter[]>) => {
    this.getForPage(page).then(
        response => observer.next(response),
        response => observer.error(response)
    );

    let sub = this.onEvent().subscribe(() => {
        console.log(page);
        this.getForPage(page).then(
            response => observer.next(response),
            response => observer.error(response)
        );
    });

    return function () {
        sub.unsubscribe();
    };
});
</code>```

The main thing is the callback, which cancels the subscription on unsubscribe.

However in angular you need a route change to an other route (so not the same with different parameters) before the unsubscribe is called.

Body:
I have a service which returns filters from our backend. This service has a method getForPage which returns a promise, and a getForPage$ which returns an observable.

On the service there is also the method onEvent which is an observable which emits when there was a change on a filter.

Now I want that the getForPage$ observable is updated when the onEvent emits an event. Which is done with the following code.

getForPage(page: string): Promise<DashboardPageFilter[]> {
    return this.service.call(
        'dashboard.page.filter.getForPage',
        {page}
    );
}

getForPage$(page: string): Observable<DashboardPageFilter[]> {
    let subject = new Subject<DashboardPageFilter[]>();

    this.getForPage(page).then(
        response => subject.next(response),
        response => subject.error(response)
    );

    this.onEvent().subscribe(() => {
        console.log(page);
        this.getForPage(page).then(
            response => subject.next(response),
            response => subject.error(response)
        );
    });

    return subject.asObservable();
}

However when I can the route the subscription on onEvent won't be closed. So the log will be called even when there is not an active subscription any more on the subject observable.

How do you make an observable from a promise which can be to be updated and is completed on route change?

Body:
After more attempts to fix the issue, some ideas from the comments and a relook at the code I came to a solution for the problem. However this still has an other minor issue

Before the code was living outside the observable for updating. With the code below the updating live inside the observer.

return Observable.create((observer: Observer<DashboardPageFilter[]>) => {
    this.getForPage(page).then(
        response => observer.next(response),
        response => observer.error(response)
    );

    let sub = this.onEvent().subscribe(() => {
        console.log(page);
        this.getForPage(page).then(
            response => observer.next(response),
            response => observer.error(response)
        );
    });

    return function () {
        sub.unsubscribe();
    };
});

The main thing is the callback, which cancels the subscription on unsubscribe.

However in angular you need a route change to an other route (so not the same with different parameters) before the unsubscribe is called.


问:
Why does Powershell's Format-List * not output all properties
When I do a ... | Format-List one of the properties is Path.

When I do a ... | Format-List * the Path property is missing.

Why?

```<code>[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List

Name        :
CommandType : Script
Definition  : $MyInvocation.MyCommand | Format-List
Path        :

[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List *

HelpUri            :
ScriptBlock        : $MyInvocation.MyCommand | Format-List *
Definition         : $MyInvocation.MyCommand | Format-List *
OutputType         : {}
Name               :
CommandType        : Script
Visibility         : Public
ModuleName         :
Module             :
RemotingCapability : PowerShell
Parameters         :
ParameterSets      : {}
</code>```

答:
To compliment gms0ulman's answer...

PowerShell displays objects to console based on format.ps1xml files. From Formatting File Overview

The display format for the objects that are returned by commands (cmdlets, functions, and scripts) are defined by using formatting files (format.ps1xml files). Several of these files are provided by Windows PowerShell to define the display format for those objects returned by Windows PowerShell–provided commands ...

PowerShell, when instructed, has a specific way of displaying objects when not told otherwise. In your case this comes from the file PowerShellCore.format.ps1xml. From checking the type of $MyInvocation.MyCommand we know that it is a System.Management.Automation.ScriptInfo object. Knowing that we can pull the format details from the above file.

```<code><View>
    <Name>System.Management.Automation.ScriptInfo</Name>
    <ViewSelectedBy>
        <TypeName>System.Management.Automation.ScriptInfo</TypeName>
    </ViewSelectedBy>

    <ListControl>
        <ListEntries>
            <ListEntry>
               <ListItems>
                    <ListItem>
                        <PropertyName>Name</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>CommandType</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>Definition</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>Path</PropertyName>
                    </ListItem>
                </ListItems>
            </ListEntry>
        </ListEntries>
    </ListControl>
</View>
</code>```

So we see that it will try to display Name, CommandType, Definition and Path. As you know specifying * for all properties will show all present properties for an object1

Path is null of course because of where you ran it from.

1 Minor exception to that statement in that some common object properties are hidden to *. Use -Force to show all in that case. They are accessible regardless if you know their name.

Body:
When I do a ... | Format-List one of the properties is Path.

When I do a ... | Format-List * the Path property is missing.

Why?

[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List

Name        :
CommandType : Script
Definition  : $MyInvocation.MyCommand | Format-List
Path        :

[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List *

HelpUri            :
ScriptBlock        : $MyInvocation.MyCommand | Format-List *
Definition         : $MyInvocation.MyCommand | Format-List *
OutputType         : {}
Name               :
CommandType        : Script
Visibility         : Public
ModuleName         :
Module             :
RemotingCapability : PowerShell
Parameters         :
ParameterSets      : {}

Body:
To compliment gms0ulman's answer...

PowerShell displays objects to console based on format.ps1xml files. From Formatting File Overview

The display format for the objects that are returned by commands (cmdlets, functions, and scripts) are defined by using formatting files (format.ps1xml files). Several of these files are provided by Windows PowerShell to define the display format for those objects returned by Windows PowerShell–provided commands ...

PowerShell, when instructed, has a specific way of displaying objects when not told otherwise. In your case this comes from the file PowerShellCore.format.ps1xml. From checking the type of $MyInvocation.MyCommand we know that it is a System.Management.Automation.ScriptInfo object. Knowing that we can pull the format details from the above file.

<View>
    <Name>System.Management.Automation.ScriptInfo</Name>
    <ViewSelectedBy>
        <TypeName>System.Management.Automation.ScriptInfo</TypeName>
    </ViewSelectedBy>

    <ListControl>
        <ListEntries>
            <ListEntry>
               <ListItems>
                    <ListItem>
                        <PropertyName>Name</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>CommandType</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>Definition</PropertyName>
                    </ListItem>
                    <ListItem>
                        <PropertyName>Path</PropertyName>
                    </ListItem>
                </ListItems>
            </ListEntry>
        </ListEntries>
    </ListControl>
</View>

So we see that it will try to display Name, CommandType, Definition and Path. As you know specifying * for all properties will show all present properties for an object1

Path is null of course because of where you ran it from.

1 Minor exception to that statement in that some common object properties are hidden to *. Use -Force to show all in that case. They are accessible regardless if you know their name.


问:
CUDA installation on Windows
I installed CUDA Toolkit 3.2, CUDA SDK and MS Visual Studio  2008 (not necessarily in this order) on my Windows 7 that does not have an nvidia graphics card.
But when I try running my CUDA code, the CUDA keywords are'nt identified.
I am a beginner. Pls tell me what I am doing wrong here.

Thanks

答: Are you building using nvcc? If not, Visual C++ will choke on the CUDA-specific syntax.</p>

Title: CUDA installation on Windows


问:
How to use gdb with LD_PRELOAD
I run a program with LD_PRELOADing a specific library. Like this.

```<code>LD_PRELOAD=./my.so ./my_program
</code>```

How do I run this program with gdb?

答:
You can supply env as an exec-wrapper on the command line using the -iex flag:

```<code>gdb -iex "set exec-wrapper env LD_PRELOAD=./my.so" ./my_program
</code>```

Title: How to use gdb with LD_PRELOAD

Body:
I run a program with LD_PRELOADing a specific library. Like this.

LD_PRELOAD=./my.so ./my_program

How do I run this program with gdb?

Body:
You can supply env as an exec-wrapper on the command line using the -iex flag:

gdb -iex "set exec-wrapper env LD_PRELOAD=./my.so" ./my_program


问:
How to get an ALAsset URL from a PHAsset?
You can do it sneakily† using the undocumented PHAsset.ALAssetURL property, but I'm looking for something documented.

† In Objective-C, this will help

```<code>@interface PHAsset (Sneaky)

@property (nonatomic, readonly) NSURL *ALAssetURL;

@end
</code>```

答:
Here is working code tested on iOS 11 both simulator and device</p>

```<code>PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PHAsset *asset = (PHAsset *)obj;
        [asset requestContentEditingInputWithOptions:nil completionHandler:^(PHContentEditingInput * _Nullable contentEditingInput, NSDictionary * _Nonnull info) {
            NSLog(@"URL:%@",  contentEditingInput.fullSizeImageURL.absoluteString);
            NSString* path = [contentEditingInput.fullSizeImageURL.absoluteString substringFromIndex:7];//screw all the crap of file://
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL isExist = [fileManager fileExistsAtPath:path];
            if (isExist)
                NSLog(@"oh yeah");
            else {
                NSLog(@"damn");
            }
        }];
    }];
</code>```

Body:
You can do it sneakily† using the undocumented PHAsset.ALAssetURL property, but I'm looking for something documented.

† In Objective-C, this will help

@interface PHAsset (Sneaky)

@property (nonatomic, readonly) NSURL *ALAssetURL;

@end

Body:
Here is working code tested on iOS 11 both simulator and device

PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PHAsset *asset = (PHAsset *)obj;
        [asset requestContentEditingInputWithOptions:nil completionHandler:^(PHContentEditingInput * _Nullable contentEditingInput, NSDictionary * _Nonnull info) {
            NSLog(@"URL:%@",  contentEditingInput.fullSizeImageURL.absoluteString);
            NSString* path = [contentEditingInput.fullSizeImageURL.absoluteString substringFromIndex:7];//screw all the crap of file://
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL isExist = [fileManager fileExistsAtPath:path];
            if (isExist)
                NSLog(@"oh yeah");
            else {
                NSLog(@"damn");
            }
        }];
    }];


问:
Trying to convert jquery AJAX to Fetch API, how to setRequestHeader?
I have jQuery AJAX call to Wordpress API and I need to set Nonce in requestHeader for authentication.

```<code>$.ajax({
  url: '/wp-json/app/v1/get_data/',
  method: 'POST',
  beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-WP-Nonce', NONCE ); // NONCE is global var
  },
  data: {},
}).done(onSuccess);
</code>```

Then I want to convert that code to Fetch API, so I tried this:

```<code>window.fetch('/wp-json/app/v1/get_data/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': NONCE
  },
  body: {},
}).then(onSuccess)
</code>```

But I get 403 Forbidden as if my Nonce isn't detected. I'm not sure whether it is the right way to set requestHeader.

I can't find much info about Fetch API, so anyone have experience with this?

Thanks

答:
I solved it by adding credentials: 'same-origin' to the arguments

```<code>window.fetch('/wp-json/app/v1/get_data/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': NONCE
  },
  credentials: 'same-origin',
  body: {},
}).then(onSuccess)
</code>```

Body:
I have jQuery AJAX call to Wordpress API and I need to set Nonce in requestHeader for authentication.

$.ajax({
  url: '/wp-json/app/v1/get_data/',
  method: 'POST',
  beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-WP-Nonce', NONCE ); // NONCE is global var
  },
  data: {},
}).done(onSuccess);

Then I want to convert that code to Fetch API, so I tried this:

window.fetch('/wp-json/app/v1/get_data/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': NONCE
  },
  body: {},
}).then(onSuccess)

But I get 403 Forbidden as if my Nonce isn't detected. I'm not sure whether it is the right way to set requestHeader.

I can't find much info about Fetch API, so anyone have experience with this?

Thanks

Body:
I solved it by adding credentials: 'same-origin' to the arguments

window.fetch('/wp-json/app/v1/get_data/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': NONCE
  },
  credentials: 'same-origin',
  body: {},
}).then(onSuccess)


问:
Jackson: how to convert flat json into nested json
How can I convert a json string like

```<code>{
    "a.b": 1,
    "a.c.d": 2
}
</code>```

into json string

```<code>{
    "a": {
        "b": 1,
        "c": {
            "d": 2
        }
    }
}
</code>```

by using ObjectMapper?

答:
The easiest option is to create custom deserializer or custom been with @JsonAnySetter and @JsonAnyGetter Here is example:

```<code>public static final String json = "{\"a.b\": 1,\"a.c.d\": 2}";
public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    HelperBean bean = mapper.readValue(json, HelperBean.class);
    System.out.println(mapper.writeValueAsString(bean));
    // result: {"a":{"b":1,"c":{"d":2}}}
}
public static class HelperBean{
    @JsonIgnore
    private Map<String, Object> data = new TreeMap<>();

    @JsonAnySetter
    public void setDays(String key, Object value){
        String[] parts = key.split("\\.");
        Map<String, Object> currMap  = data;
        for (int i = 0; i< parts.length; i++){
            String part = parts[i];
            Object subMap  = currMap.get(part);
            if (i == parts.length - 1) // last node
                currMap.put(part, value);
            else if(subMap == null){ // new node
                subMap = new TreeMap<>();
                currMap.put(part, subMap);
                currMap = (Map<String, Object>) subMap;
            }else if (subMap instanceof Map){ // existing node
                currMap.put(part, subMap);
                currMap = (Map<String, Object>) subMap;
            } else { // node conflict
                // handle exception when a.b = 1 and a.b.c = 1
            }
        }
    }
    @JsonAnyGetter
    public Map<String, Object> getData() {
        return data;
    }
}
</code>```

Body:
How can I convert a json string like

{
    "a.b": 1,
    "a.c.d": 2
}

into json string

{
    "a": {
        "b": 1,
        "c": {
            "d": 2
        }
    }
}

by using ObjectMapper?

Body:
The easiest option is to create custom deserializer or custom been with @JsonAnySetter and @JsonAnyGetter Here is example:

public static final String json = "{\"a.b\": 1,\"a.c.d\": 2}";
public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    HelperBean bean = mapper.readValue(json, HelperBean.class);
    System.out.println(mapper.writeValueAsString(bean));
    // result: {"a":{"b":1,"c":{"d":2}}}
}
public static class HelperBean{
    @JsonIgnore
    private Map<String, Object> data = new TreeMap<>();

    @JsonAnySetter
    public void setDays(String key, Object value){
        String[] parts = key.split("\\.");
        Map<String, Object> currMap  = data;
        for (int i = 0; i< parts.length; i++){
            String part = parts[i];
            Object subMap  = currMap.get(part);
            if (i == parts.length - 1) // last node
                currMap.put(part, value);
            else if(subMap == null){ // new node
                subMap = new TreeMap<>();
                currMap.put(part, subMap);
                currMap = (Map<String, Object>) subMap;
            }else if (subMap instanceof Map){ // existing node
                currMap.put(part, subMap);
                currMap = (Map<String, Object>) subMap;
            } else { // node conflict
                // handle exception when a.b = 1 and a.b.c = 1
            }
        }
    }
    @JsonAnyGetter
    public Map<String, Object> getData() {
        return data;
    }
}


问:
Sequence generator by entity in JPA
I'm trying to make a sequencial generator field in MySQL with JPA, the "prod_generator_id" must start in "1" for any entity.
Example:

Here is my java object:

```<code>//this one is working fine, the id is unique...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "pro_id")
private Long id;

//here is the problem, must start in "1" by entity
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seq")
@SequenceGenerator(name="seq", sequenceName="pro_id_tenancy", initialValue=1, allocationSize=1)
@Column(name = "pro_id_tenancy")
private Long idTenancyProjeto;
</code>```

I'm using spring boot, but when I save the object, the idTenancyProjeto is going null.

The most simple solution I've found: Just count the number of products of that company, and add+1 in my product.save(), nothing more, is working. Thanks for all.

答:
Solution:

As the most simple solution, I made another table that make a total, and before save I get the value e add+1.

Title: Sequence generator by entity in JPA

Body:
I'm trying to make a sequencial generator field in MySQL with JPA, the "prod_generator_id" must start in "1" for any entity.
Example:

Here is my java object:

//this one is working fine, the id is unique...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "pro_id")
private Long id;

//here is the problem, must start in "1" by entity
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seq")
@SequenceGenerator(name="seq", sequenceName="pro_id_tenancy", initialValue=1, allocationSize=1)
@Column(name = "pro_id_tenancy")
private Long idTenancyProjeto;

I'm using spring boot, but when I save the object, the idTenancyProjeto is going null.

The most simple solution I've found: Just count the number of products of that company, and add+1 in my product.save(), nothing more, is working. Thanks for all.


问:
Best way to implement save field in DataGrid when user tabs out or field looses focus
I have a page with .Net grid view with about 12 text fields per row and about 250 rows. Right now there is a save all button at the bottom of the page that sends all the fields 12x250 to the server where they are entered into db 1 by one.  Which ends up being very slow and some times does not go through at all. I didnt come up with this but ended up with a role of someone to improve it.  What I think would be best in this case is to save the field when it looses focus. What is the best way to implement this in .Net with gridview ?

There is already jquery library loaded on the page. There is no ajax currently implemented on the page.

答:
If you have JQUERY you can call a "Page Method" read through this post, be sure to check the comments I'm not sure if he updated his article:-)

Edit

Additionally you can call a webservice, here's a sample from my code showing me calling a WCF service:

```<code>$.ajax({
  type: "POST",
  url: "../Services/Utilities.svc/IsPrintDownloadDone",
  data: "{}", //This should be a JSON representation of yoru inputs that the WCF can serialize into objects
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {//msg.d has the response from server
        },
  error: function (xhr, textStatus, errorThrown) {

}
});
</code>```

OwnerDisplayName: Salt Packets

Body:
If you have JQUERY you can call a "Page Method" read through this post, be sure to check the comments I'm not sure if he updated his article:-)

Edit

Additionally you can call a webservice, here's a sample from my code showing me calling a WCF service:

$.ajax({
  type: "POST",
  url: "../Services/Utilities.svc/IsPrintDownloadDone",
  data: "{}", //This should be a JSON representation of yoru inputs that the WCF can serialize into objects
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {//msg.d has the response from server
        },
  error: function (xhr, textStatus, errorThrown) {

}
});

OwnerDisplayName: Josh

LastEditorDisplayName: Josh