问:
What is a more efficient way to accomplish validate/save()'ing a Django object while abstracting away the repetition?
I highly doubt that the way I put this together is best practice, or even secure.

It is a FBV that allows users to POST update their profiles by way of using the provided ModelForm.

The view:

```<code>def profile_edit(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST)

        if form.is_valid():
            instance = Profile.objects.get(user=request.user)
            instance.activity1 = form.cleaned_data.get("activity1")
            instance.activity2 = form.cleaned_data.get("activity2")
            instance.activity3 = form.cleaned_data.get("activity3")
            instance.subject1 = form.cleaned_data.get("subject1")
            instance.subject2 = form.cleaned_data.get("subject2")
            instance.subject3 = form.cleaned_data.get("subject3")
            instance.introduction = form.cleaned_data.get("introduction")

            instance = form.save(commit=False)

            instance.save()
            return redirect('/profile/edit')
    else:
        form = ProfileForm(instance=request.user, initial={
            'activity1': Profile.objects.get(user=request.user).activity1,
            'activity2': Profile.objects.get(user=request.user).activity2,
            'activity3': Profile.objects.get(user=request.user).activity3,
            'subject1': Profile.objects.get(user=request.user).subject1,
            'subject2': Profile.objects.get(user=request.user).subject2,
            'subject3': Profile.objects.get(user=request.user).subject3,
            'introduction': Profile.objects.get(user=request.user).introduction,
            })
        context = {
            'user': request.user,
            'form': form,
        }
        return render(request, 'profile_edit.html', context)
</code>```

The form:

```<code>class ProfileForm(forms.ModelForm):
    activity1 = forms.CharField(max_length=54, label='Activity 1')
    activity2 = forms.CharField(max_length=54)
    activity3 = forms.CharField(max_length=54)
    subject1 = forms.CharField(max_length=54)
    subject2 = forms.CharField(max_length=54)
    subject3 = forms.CharField(max_length=54)
    introduction = forms.CharField(widget=forms.Textarea)

    def clean(self):
        cleaned_data = super(ProfileForm, self).clean()
        return cleaned_data
</code>```

Is there a better way to get this accomplished? I would think there's a way to retrieve the entire cleaned form data at once, and then update the instance with the all new POSTed data in fewer statements as well.

And what about pre-populating a form with data already stored in the database? Is querying the DB one by one the usual way to make this work?

I'm not exactly trying to force/hack away the repetition--if it happens to be the conventional Django way of doing things, I'm all good! I simply think I'm misunderstanding something and not doing it in the most Django'ic way possible.
Help much appreciated!

答:
You could add Meta class to your form, and ModelForm would take care of the rest.

forms.py,

```<code>class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ('user',)
</code>```

views.py,

```<code>def profile_edit(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST)

        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('/profile/edit')
    else:
        form = ProfileForm(instance=request.user.profile)
    context = {
        'user': request.user,
        'form': form,
    }
    return render(request, 'profile_edit.html', context)
</code>```

Body:
I highly doubt that the way I put this together is best practice, or even secure.

It is a FBV that allows users to POST update their profiles by way of using the provided ModelForm.

The view:

def profile_edit(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST)

        if form.is_valid():
            instance = Profile.objects.get(user=request.user)
            instance.activity1 = form.cleaned_data.get("activity1")
            instance.activity2 = form.cleaned_data.get("activity2")
            instance.activity3 = form.cleaned_data.get("activity3")
            instance.subject1 = form.cleaned_data.get("subject1")
            instance.subject2 = form.cleaned_data.get("subject2")
            instance.subject3 = form.cleaned_data.get("subject3")
            instance.introduction = form.cleaned_data.get("introduction")

            instance = form.save(commit=False)

            instance.save()
            return redirect('/profile/edit')
    else:
        form = ProfileForm(instance=request.user, initial={
            'activity1': Profile.objects.get(user=request.user).activity1,
            'activity2': Profile.objects.get(user=request.user).activity2,
            'activity3': Profile.objects.get(user=request.user).activity3,
            'subject1': Profile.objects.get(user=request.user).subject1,
            'subject2': Profile.objects.get(user=request.user).subject2,
            'subject3': Profile.objects.get(user=request.user).subject3,
            'introduction': Profile.objects.get(user=request.user).introduction,
            })
        context = {
            'user': request.user,
            'form': form,
        }
        return render(request, 'profile_edit.html', context)

The form:

class ProfileForm(forms.ModelForm):
    activity1 = forms.CharField(max_length=54, label='Activity 1')
    activity2 = forms.CharField(max_length=54)
    activity3 = forms.CharField(max_length=54)
    subject1 = forms.CharField(max_length=54)
    subject2 = forms.CharField(max_length=54)
    subject3 = forms.CharField(max_length=54)
    introduction = forms.CharField(widget=forms.Textarea)

    def clean(self):
        cleaned_data = super(ProfileForm, self).clean()
        return cleaned_data

Is there a better way to get this accomplished? I would think there's a way to retrieve the entire cleaned form data at once, and then update the instance with the all new POSTed data in fewer statements as well.

And what about pre-populating a form with data already stored in the database? Is querying the DB one by one the usual way to make this work?

I'm not exactly trying to force/hack away the repetition--if it happens to be the conventional Django way of doing things, I'm all good! I simply think I'm misunderstanding something and not doing it in the most Django'ic way possible.
Help much appreciated!

Body:
You could add Meta class to your form, and ModelForm would take care of the rest.

forms.py,

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ('user',)

views.py,

def profile_edit(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST)

        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('/profile/edit')
    else:
        form = ProfileForm(instance=request.user.profile)
    context = {
        'user': request.user,
        'form': form,
    }
    return render(request, 'profile_edit.html', context)


来源: stackexchange

问:
Using display:flex property to create a responsive (horizontally laid out) nav bar
For a mobile website, I have to display 5 elements in a responsive navbar. For small resolutions, I want them to pile up vertically. But for larger ones, my aim to to lay out the 5 items like so:

I'm trying to use the display:flex attribute to make this work. But unfortunately, I currently have:

How do I achieve the effect I'm looking for? It's tricky to have an elegant looking responsive navbar for 5 items (which looks balanced as well). So in case you want to suggest stylistic tweaks to the way I'm doing this, I'm open to that as well.

My code is simply:

```<code><div style="width:93%; max-width:400px;border: 1px solid #ccc;border-radius:4px;padding:5px 5px 5px 5px;background-color:#E8E8E8;box-shadow:0 1px 4px rgba(0, 0, 0, 0.1);">

<div style="display:flex;">
    <span style="font-size:12px;">Option 1</span> <span style="color:purple; font-size:12px;">({{ item_count }} items)</span>
    <span style="font-size:12px;">Option 2</span> <span style="color:purple; font-size:12px;">(({{ item_count }} items)</span>
</div>
<div style="display:flex;">
    <span style="font-size:12px;">Option 3</span> <span style="color:purple; font-size:12px;">(({{ item_count }} items)</span>
    <span style="font-size:12px;">Option 4</span> <span style="color:purple; font-size:12px;">(({{ item_count }} items)</span>
</div>

<span style="font-size:12px;">{{ other_options }} other options</span>
</div>
</code>```

The {{ }} syntax is Django template tags and can be ignored. Note that all options displayed are dynamically generated and can be of variable length.

答:
Create an element to represent each item. Don't use two s which aren't related to each other beyond being next to each other.

Put each item into a single container. Don't force your rows manually.

Allow wrapping with flex-wrap: wrap;

Set a size on the items so they are the width you want

* {
  font-size: 12px
}

span+span {
  color: purple;
}

ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  flex: 0 0 50%;
  margin: 0;
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><span>Option 1</span> <span>({{ item_count }} items)</span></li>
  <li><span>Option 2</span> <span>(({{ item_count }} items)</span></li>
  <li><span>Option 3</span> <span>(({{ item_count }} items)</span></li>
  <li><span>Option 4</span> <span>(({{ item_count }} items)</span></li>
</ul>
<p>{{ other_options }} other options</p></code>```

For small resolutions, I want them to pile up vertically.

Use media queries to change the ul back to display: block to disable flexbox on narrow viewports.

ContentLicense: CC BY-SA 3.0

Body:
For a mobile website, I have to display 5 elements in a responsive navbar. For small resolutions, I want them to pile up vertically. But for larger ones, my aim to to lay out the 5 items like so:

I'm trying to use the display:flex attribute to make this work. But unfortunately, I currently have:

How do I achieve the effect I'm looking for? It's tricky to have an elegant looking responsive navbar for 5 items (which looks balanced as well). So in case you want to suggest stylistic tweaks to the way I'm doing this, I'm open to that as well.

My code is simply:

    Option 1 ({{ item_count }} items)
    Option 2 (({{ item_count }} items)

    Option 3 (({{ item_count }} items)
    Option 4 (({{ item_count }} items)

{{ other_options }} other options

The {{ }} syntax is Django template tags and can be ignored. Note that all options displayed are dynamically generated and can be of variable length.

Body:
Create an element to represent each item. Don't use two <span>s which aren't related to each other beyond being next to each other.

Put each item into a single container. Don't force your rows manually.

Allow wrapping with flex-wrap: wrap;

Set a size on the items so they are the width you want

* {
  font-size: 12px
}

span+span {
  color: purple;
}

ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  flex: 0 0 50%;
  margin: 0;
  padding: 0;
}

<ul>
  <li><span>Option 1</span> <span>({{ item_count }} items)</span></li>
  <li><span>Option 2</span> <span>(({{ item_count }} items)</span></li>
  <li><span>Option 3</span> <span>(({{ item_count }} items)</span></li>
  <li><span>Option 4</span> <span>(({{ item_count }} items)</span></li>
</ul>
<p>{{ other_options }} other options</p>

For small resolutions, I want them to pile up vertically.

Use media queries to change the ul back to display: block to disable flexbox on narrow viewports.


问:
isset is not working on submit
This is a 5-star rating form and I am trying to make it work.

```<code><div class="stars">
  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>
    <label class="star star-5" for="star-5"></label>
    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>
    <label class="star star-4" for="star-4"></label>
    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>
    <label class="star star-3" for="star-3"></label>
    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>
    <label class="star star-2" for="star-2"></label>
    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>
    <label class="star star-1" for="star-1"></label>
    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>
</div>
</code>```

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

```<code><?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>
</code>```

答:
You just missed to put form method and action in form.

Use this

<form method="post" action="" >

and on php code use

```<code>if(isset($_POST['star']))
</code>```

it will work

Title: isset is not working on submit

Body:
This is a 5-star rating form and I am trying to make it work.

  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>

    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>

    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>

    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>

    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>

    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

<?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>

Body:
You just missed to put form method and action in form.

Use this

<form method="post" action="" >

and on php code use

if(isset($_POST['star']))

it will work


问:
Method hashMapOf() in Kotlin
Can anybody please give me Concrete example of hashMapOf() method and when should I use it?

If i do something like this:

```<code>val map2 : HashMap<String, String>  = hashMapOf()
    map2["ok"] = "yes"
</code>```

It means to initialize map2 property I can use it.

But like other method in Kotlin for example:

```<code>val arr = arrayListOf<String>("1", "2", "3")
</code>```

Is there any way I can use this method like above?

答:
Yes, you can. First example from kotlinlang.org:</p>

```<code>val map: HashMap<Int, String> = hashMapOf(1 to "x", 2 to "y", -1 to "zz")
println(map) // {-1=zz, 1=x, 2=y}
</code>```

Title: Method hashMapOf() in Kotlin

Body:
Can anybody please give me Concrete example of hashMapOf() method and when should I use it?

If i do something like this:

val map2 : HashMap<String, String>  = hashMapOf()
    map2["ok"] = "yes"

It means to initialize map2 property I can use it.

But like other method in Kotlin for example:

val arr = arrayListOf<String>("1", "2", "3")

Is there any way I can use this method like above?

Body:
Yes, you can. First example from kotlinlang.org:

val map: HashMap<Int, String> = hashMapOf(1 to "x", 2 to "y", -1 to "zz")
println(map) // {-1=zz, 1=x, 2=y}


问:
where does back event is handel in swift 3.0
I want to refresh the whole page controller on back press.
I am navigating the viewcontroller using code.

My Code

```<code>let GTC = self.storyboard?.instantiateViewController(withIdentifier: "GoToCart")as! GoToCart
self.navigationController?.pushViewController(GTC, animated: true)
</code>```

答:
Using viewWillAppear to reload your UI. As you use navigationController?.pushViewController, the view will be retained and stored in stack.

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // Reload the UI
}
</code>```

Body:
I want to refresh the whole page controller on back press.
I am navigating the viewcontroller using code.

My Code

let GTC = self.storyboard?.instantiateViewController(withIdentifier: "GoToCart")as! GoToCart
self.navigationController?.pushViewController(GTC, animated: true)

Body:
Using viewWillAppear to reload your UI. As you use navigationController?.pushViewController, the view will be retained and stored in stack.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // Reload the UI
}


问:
Has reCaptcha been cracked / hacked / OCR'd / defeated / broken?
Have any programming methods have been used to defeat reCAPTCHA?

I'm interested in seeing evidence and potentially demonstrations that reCAPTCHA in particular has been made obsolete by completely automated, humanless methods.

To clarify, not looking for reCAPTCHA-cheating solutions that involve humans in any way, whether teams tasked with filling out CAPCHAs, porn-seekers, or Mechanical Turk.

I'm also not looking for alternatives to reCAPTCHA, like picking the type of animal, or background fields or javascript trickery.

答: There was a speech at Defcon last year that went into the problems with CAPTCHAs in general. One of the things they did is use multiple free OCR engines and had them vote on the best words. Doing this, they were able to achieve a somewhat decent chance of succeeding.  For one kind, it was 40% or so, I don't think it was reCaptcha, though.</p>

OwnerDisplayName: davebug

OwnerDisplayName: FryGuy

ContentLicense: CC BY-SA 2.5


问:
Is it possible to detect rejected calls in Android?
In my application, it would be nice to intercept when the user rejects a call, i.e. choose to send busy tone.
Is there any way, besides being notified when there is an incoming call, to do this?
I have not found anything in the docs regarding this.
Is this information stored in the call log, i.e. can I poll the call log to see if a call was rejected or answered?</p>

答:
Hey.
You could use the PhoneStateListener and CallLog classes to query the recent calls list to find rejected calls.

http://developer.android.com/reference/android/provider/CallLog.html
http://developer.android.com/reference/android/telephony/PhoneStateListener.html

Alternatively you can monitor broadcasts on android.intent.action.NEW_OUTGOING_CALL and android.intent.action.NEW_INCOMING_CALL
just put android.permission.PROCESS_INCOMING_CALLS and android.permission.PROCESS_OUTGOING_CALLS in your manifest.


问:
Reshape 59x16 double into 236x4?
How can I reshape a matrix in MATLAB, preferably using reshape?

A simple matrix setup:

```<code>A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
</code>```

that I want to reshape into

```<code>B = [1 4; 2 5; 3 6; 7 10; 8 11; 9 12]
</code>```

I've tried numerous settings of reshape, but I cannot figure it out.

```<code>1 2 3 4
5 6 7 8
</code>```

reshaped into

```<code>1 2
5 6
3 4
7 8
</code>```

答:
You can use reshape and permute:

```<code>reshape(permute(reshape(A,size(A,1),2,[]),[1 3 2]),[],2)
</code>```

Thanks to @LuisMendo that suggests a modification to the answer to avoid depending on the size of A.

Title: Reshape 59x16 double into 236x4?

Body:
How can I reshape a matrix in MATLAB, preferably using reshape?

A simple matrix setup:

A = [1 4 7 10; 2 5 8 11; 3 6 9 12]

that I want to reshape into

B = [1 4; 2 5; 3 6; 7 10; 8 11; 9 12]

I've tried numerous settings of reshape, but I cannot figure it out.

1 2 3 4
5 6 7 8

reshaped into

1 2
5 6
3 4
7 8

Body:
You can use reshape and permute:

reshape(permute(reshape(A,size(A,1),2,[]),[1 3 2]),[],2)

Thanks to @LuisMendo that suggests a modification to the answer to avoid depending on the size of A.


问:
Universal library for C++ strings
Please recommend me universal library for C++ strings. I want to manipulate ascii text and unicode text in one build without making two versions of builds for std::string/char and for std::wstring/wchar; Also I want to convert them to each other (where it is possible);

Thank you very much!!!

答: If you're doing cross-platform coding you could use  Qt4's QString / QByteArray.</p>

Title: Universal library for C++ strings


问:
Class Not found in AppKernel.php
I'm trying to deploy my Symfony2 project. When I run the command

```<code>php app/console cache:clear --env=prod --no-debug
</code>```

I get the following error:

```<code>PHP Fatal error: Class 'Acme\MainBundle\AcmeMainBundle' not found in /var/www/html/app/AppKernal.php on line 24
</code>```

This is the in AppKernal.php

```<code>public function registerBundles()
{
    $bundles = array(
        ...
        new Acme\MainBundle\AcmeMainBundle(),
    );
    ...
}
</code>```

It seems like there's a problem with the namespace?

答:
Had the same problem after adding a bundle with the code generator with Symfony 3.2. I had to add this new bundle in the autoload section of composer.json after the AppBundle :</p>

```<code>(...)
"autoload": {
    "psr-4": {
        "AppBundle\\": "src/AppBundle",
        "CoreBundle\\": "src/CoreBundle"
    },
(...)
</code>```

Title: Class Not found in AppKernel.php

Body:
I'm trying to deploy my Symfony2 project. When I run the command

php app/console cache:clear --env=prod --no-debug

I get the following error:

PHP Fatal error: Class 'Acme\MainBundle\AcmeMainBundle' not found in /var/www/html/app/AppKernal.php on line 24

This is the in AppKernal.php

public function registerBundles()
{
    $bundles = array(
        ...
        new Acme\MainBundle\AcmeMainBundle(),
    );
    ...
}

It seems like there's a problem with the namespace?

Body:
Had the same problem after adding a bundle with the code generator with Symfony 3.2. I had to add this new bundle in the autoload section of composer.json after the AppBundle :

(...)
"autoload": {
    "psr-4": {
        "AppBundle\\": "src/AppBundle",
        "CoreBundle\\": "src/CoreBundle"
    },
(...)


问:
describe() function over rows instead columns
As said in:
https://databricks.com/blog/2015/06/02/statistical-and-mathematical-functions-with-dataframes-in-spark.html

The describe() function works for each numerical column, It is possible to do it against rows? My DF size is 53 cols and 346,143 rows, so transpose is not an option. How can I do it?

I'm using Spark 2.11

答:
You can do your own UDF. Either you make an separate UDF for each quantity or put everything in 1 UDF returning a complex result:

```<code>val df = Seq(
  (1.0,2.0,3.0,4.0,5.0)
).toDF("x1","x2","x3","x4","x5")

val describe = udf(
  { xs : Seq[Double] =>

    val xmin = xs.min
    val xmax = xs.max
    val mean = xs.sum/xs.size.toDouble

    (xmin,xmax,mean)
  }
)

df
.withColumn("describe",describe(array("*")))
.withColumn("min",$"describe._1")
.withColumn("max",$"describe._2")
.withColumn("mean",$"describe._3")
.drop($"describe")
.show
</code>```

gives:

```<code>+---+---+---+---+---+---+---+----+
| x1| x2| x3| x4| x5|min|max|mean|
+---+---+---+---+---+---+---+----+
|1.0|2.0|3.0|4.0|5.0|1.0|5.0| 3.0|
+---+---+---+---+---+---+---+----+
</code>```

Body:
You can do your own UDF. Either you make an separate UDF for each quantity or put everything in 1 UDF returning a complex result:

val df = Seq(
  (1.0,2.0,3.0,4.0,5.0)
).toDF("x1","x2","x3","x4","x5")

val describe = udf(
  { xs : Seq[Double] =>

    val xmin = xs.min
    val xmax = xs.max
    val mean = xs.sum/xs.size.toDouble

    (xmin,xmax,mean)
  }
)

df
.withColumn("describe",describe(array("*")))
.withColumn("min",$"describe._1")
.withColumn("max",$"describe._2")
.withColumn("mean",$"describe._3")
.drop($"describe")
.show

gives:

+---+---+---+---+---+---+---+----+
| x1| x2| x3| x4| x5|min|max|mean|
+---+---+---+---+---+---+---+----+
|1.0|2.0|3.0|4.0|5.0|1.0|5.0| 3.0|
+---+---+---+---+---+---+---+----+


问:
Gmail API, cannot remove "SENT" label from email
I cannot remove the "SENT" label from any email.

I used PHP classes but it doesn't matter because it occurs even in test page of users_messages.modify.

This is my PHP code:

```<code>$mods = new Google_Service_Gmail_ModifyMessageRequest();
$mods->setAddLabelIds(['UNREAD']);
$mods->setRemoveLabelIds('SENT');
$message = $gmailService->users_messages->modify($userId, $messageId, $mods);
</code>```

I think it could be a general Gmail API error.

I can remove all the others labels but not "SENT". Try it with the follow "Request body":

```<code>{
  "removeLabelIds": ["SENT"],
  "addLabelIds": ["UNREAD"]
}
</code>```

I got this ERROR 400 reply from the server:

```<code>{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalidArgument",
    "message": "Invalid label: SENT"
   }
  ],
  "code": 400,
  "message": "Invalid label: SENT"
 }
}
</code>```

答: According to this google forum, there is no way of removing the SENT label in Gmail API.</p>

Body:
I cannot remove the "SENT" label from any email.

I used PHP classes but it doesn't matter because it occurs even in test page of users_messages.modify.

This is my PHP code:

$mods = new Google_Service_Gmail_ModifyMessageRequest();
$mods->setAddLabelIds(['UNREAD']);
$mods->setRemoveLabelIds('SENT');
$message = $gmailService->users_messages->modify($userId, $messageId, $mods);

I think it could be a general Gmail API error.

I can remove all the others labels but not "SENT". Try it with the follow "Request body":

{
  "removeLabelIds": ["SENT"],
  "addLabelIds": ["UNREAD"]
}

I got this ERROR 400 reply from the server:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalidArgument",
    "message": "Invalid label: SENT"
   }
  ],
  "code": 400,
  "message": "Invalid label: SENT"
 }
}


问:
Copy value of div and put in it another div
I would like to know how i am suppose to copy the value of a div (for instance, the first one), and paste it to a second div via a mouse click event.

Workflow:

Click on the first div (to copy the value number 1)

If i click again, it will become 2, if i click again, it will become 3 and so forth.

I'm looking forward to seeing your response.

Example : Image Link

ok

from copying here:

```<code>                  <li class="active">
                    <a href="#"  on-click="chip_amnt">
                      <img src="chip.jpg" alt="">
                      <span>250</span>
                    </a>
                  </li>

                  <li class="active">
                    <a href="#"  on-click="chip_amnt">
                      <img src="{{image_url}}" alt="">
                      <span>500/span>
                    </a>
                  </li>

                  <li class="active">
                    <a href="#"  on-click="chip_amnt">
                      <img src="{{image_url}}" alt="">
                      <span>100</span>
                    </a>
                  </li>
</code>```

to here:

```<code>            <li class="">
                  Player Pair
                </li>
                <li class="">
                  Tie
                </li>
                <li class="">
                  Banker Pair
                </li>
                <li class="">
                  Player
                </li>
                <li class="">
                  Banker
                </li>
</code>```

答:
1. give an id on each div for make it easy

```<code><div id="div1">Something here</div>
<div id="div2">Empty or something else</div>
</code>```

2. selection

```<code>const div1 = document.getElementById('div1');
const div2 = document.getElementById('div2');
</code>```

3. addEventListner

```<code>div1.addEventListener('click', function(e){
  div2.innerHTML = e.target.innerHTML;
});
</code>```

example:
http://jsbin.com/zasagerafi/edit?html,js,console,output

Body:
I would like to know how i am suppose to copy the value of a div (for instance, the first one), and paste it to a second div via a mouse click event.

Workflow:

Click on the first div (to copy the value number 1)

If i click again, it will become 2, if i click again, it will become 3 and so forth.

I'm looking forward to seeing your response.

Example : Image Link

ok

from copying here:

                      250

                      500/span>

                      100

to here:

                  Player Pair

                  Tie

                  Banker Pair

                  Player

                  Banker

Body:
1. give an id on each div for make it easy

<div id="div1">Something here</div>
<div id="div2">Empty or something else</div>

2. selection

const div1 = document.getElementById('div1');
const div2 = document.getElementById('div2');

3. addEventListner

div1.addEventListener('click', function(e){
  div2.innerHTML = e.target.innerHTML;
});

example:
http://jsbin.com/zasagerafi/edit?html,js,console,output


问:
Date Values changing
I'm trying to create a database based on lots of spreadsheets. I aim to go through a lot of spreadsheets pulling out the information needed into a nicely formatted table. I have just started so I'm writing some functions to pull out what I need. I'll store them in variables and then put them into a table.

The function I have written searches a range for a string and pulls out the information in the cell next to it. It seems to work fine for the strings.

Can anyone explain what is happening with the dates? I want it to output dates in UK format dd/mm/yyyy. Currently the date next to expiry 01/06/2018 is in UK format. If I debug it and put in a print it comes out in UK format. If I check the format of the cell it's stored in and the cell it is being returned to both are UK format. Yet it comes out as 06/01/2018.

If possible could an explanation of what is happening be included in the answer rather than a "Just change the code to this" solution so I can learn how it is actually interpreting it?

Any help would be appreciated.

Here's the code

```<code>Private Sub Main()

'Turn off screen updating
Application.ScreenUpdating = False

'Define the variables
Dim Coverholder As String
Dim SearchRange As Range

'set the range to search
Set SearchRange = Sheets("2017 Property").Range("A1:AZ100")

'testing
Range("A1").Value = GetNextTo(SearchRange, "*Expiry*")

Debug.Print GetNextTo(SearchRange, "*Expiry*")

'Reset the position of the selection
Range("A1").Select

'Turn on the screen updating
Application.ScreenUpdating = True

End Sub

'Function to return the value one cell to the right of a search value
Private Function GetNextTo(SearchRange As Range, FindString As String) As String

    'Define variables
    Dim Rng As Range

    'Clean the string
    If Trim(FindString) <> "" Then
        'use the search range
        With SearchRange
            Set Rng = .Find(What:=FindString, _
                            After:=.Cells(.Cells.Count), _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)
            'If value found
            If Not Rng Is Nothing Then

                Application.Goto Rng.Offset(0, 1)

            'If value not found
            Else

                MsgBox "Nothing found"

            End If
        End With
    End If

    GetNextTo = ActiveCell.Value

End Function
</code>```

答:
This is what happens (as far as I know):

Dates in excel are displayed as (e.g.) dd.mm.jjjj, but not stored that way. You can test this by printing a date within a cell like this:

Create a new wb, enter 12.11.1985 into the first cell, then run:

```<code>Sub test()
 'returns value of cell properly formated (but not always as displayed in the cell)
 Debug.Print Cells(1, 1).Value
 'returns the actual value of the cell
 Debug.Print Cells(1, 1).Value2
End Sub
</code>```

.Value2 will return 31363, which is the actual value within the cell. This value will be interpreted in different ways, depending on various settings and the functions you extract it with.

As for a solution, see @Doomeniks comment.

Edit: Doomenik linked some excellent answers, far more in-depth than this one.

Title: Date Values changing

Body:
I'm trying to create a database based on lots of spreadsheets. I aim to go through a lot of spreadsheets pulling out the information needed into a nicely formatted table. I have just started so I'm writing some functions to pull out what I need. I'll store them in variables and then put them into a table.

The function I have written searches a range for a string and pulls out the information in the cell next to it. It seems to work fine for the strings.

Can anyone explain what is happening with the dates? I want it to output dates in UK format dd/mm/yyyy. Currently the date next to expiry 01/06/2018 is in UK format. If I debug it and put in a print it comes out in UK format. If I check the format of the cell it's stored in and the cell it is being returned to both are UK format. Yet it comes out as 06/01/2018.

If possible could an explanation of what is happening be included in the answer rather than a "Just change the code to this" solution so I can learn how it is actually interpreting it?

Any help would be appreciated.

Here's the code

Private Sub Main()

'Turn off screen updating
Application.ScreenUpdating = False

'Define the variables
Dim Coverholder As String
Dim SearchRange As Range

'set the range to search
Set SearchRange = Sheets("2017 Property").Range("A1:AZ100")

'testing
Range("A1").Value = GetNextTo(SearchRange, "*Expiry*")

Debug.Print GetNextTo(SearchRange, "*Expiry*")

'Reset the position of the selection
Range("A1").Select

'Turn on the screen updating
Application.ScreenUpdating = True

End Sub

'Function to return the value one cell to the right of a search value
Private Function GetNextTo(SearchRange As Range, FindString As String) As String

    'Define variables
    Dim Rng As Range

    'Clean the string
    If Trim(FindString) <> "" Then
        'use the search range
        With SearchRange
            Set Rng = .Find(What:=FindString, _
                            After:=.Cells(.Cells.Count), _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)
            'If value found
            If Not Rng Is Nothing Then

                Application.Goto Rng.Offset(0, 1)

            'If value not found
            Else

                MsgBox "Nothing found"

            End If
        End With
    End If

    GetNextTo = ActiveCell.Value

End Function

Body:
This is what happens (as far as I know):

Dates in excel are displayed as (e.g.) dd.mm.jjjj, but not stored that way. You can test this by printing a date within a cell like this:

Create a new wb, enter 12.11.1985 into the first cell, then run:

Sub test()
 'returns value of cell properly formated (but not always as displayed in the cell)
 Debug.Print Cells(1, 1).Value
 'returns the actual value of the cell
 Debug.Print Cells(1, 1).Value2
End Sub

.Value2 will return 31363, which is the actual value within the cell. This value will be interpreted in different ways, depending on various settings and the functions you extract it with.

As for a solution, see @Doomeniks comment.

Edit: Doomenik linked some excellent answers, far more in-depth than this one.


问:
How to return Multiple List<> values from a single function?
trying to return 2 List values from a single function

I am using this code:-

```<code>public KeyValuePair<int, int> encrypt(string password)
    {
        List<int> key = new List<int>();
        List<int> code = new List<int>();
        /*
           do stuff, do some more stuff and go!
        */

        return new KeyValuePair<List<int>,List<int>>(key,code);
    }
</code>```

here I am trying to return 2 List<int> values but error occurs. How to return 2 list values from a single function

UPDATE

the answer is found, we got 2 correct answers thats why i didn't just pick one cause both work great

answer by HadiRj

answer by Enigmativity

and if you want to use my code then, this is the correct version of it:-

```<code>public KeyValuePair<List<int>, List<int>> encrypt(string password)
    {
        List<int> key = new List<int>();
        List<int> code = new List<int>();
        /*
           do stuff, do some more stuff and go!
        */

        return new KeyValuePair<List<int>,List<int>>(key,code);
    }
</code>```

答:
Very Simple

```<code>[WebMethod]
public static List<Teacher>[] BindData()
{
   List<Teacher> list1 = new List<Teacher>();
   List<Teacher> list2 = new List<Teacher>();
   return new List<Teacher>[] { list1, list2 };
}
</code>```

Note: Both list will use same class as i used Teacher class in both list.

Body:
trying to return 2 List values from a single function

I am using this code:-

public KeyValuePair<int, int> encrypt(string password)
    {
        List<int> key = new List<int>();
        List<int> code = new List<int>();
        /*
           do stuff, do some more stuff and go!
        */

        return new KeyValuePair<List<int>,List<int>>(key,code);
    }

here I am trying to return 2 List<int> values but error occurs. How to return 2 list values from a single function

UPDATE

the answer is found, we got 2 correct answers thats why i didn't just pick one cause both work great

answer by HadiRj

answer by Enigmativity

and if you want to use my code then, this is the correct version of it:-

public KeyValuePair<List<int>, List<int>> encrypt(string password)
    {
        List<int> key = new List<int>();
        List<int> code = new List<int>();
        /*
           do stuff, do some more stuff and go!
        */

        return new KeyValuePair<List<int>,List<int>>(key,code);
    }

Body:
Very Simple

[WebMethod]
public static List<Teacher>[] BindData()
{
   List<Teacher> list1 = new List<Teacher>();
   List<Teacher> list2 = new List<Teacher>();
   return new List<Teacher>[] { list1, list2 };
}

Note: Both list will use same class as i used Teacher class in both list.


问:
Use ANT/SVNANT to delete files from SVN working copy if they don't exist in another folder
Scenario:

SVN Repo #1 with application code base

SVN Repo #2 with previously compiled milestones

I need an ANT build script which can do the following:

Export the code base from SVN repo #1 (done)

Compile the exported code base (done)

Check out the code base from SVN repo #2 (done)

Compare the compiled/exported code base from SVN repo #1 to the working copy from SVN repo #2
a. If any files have been added in SVN repo #1, they need to be added to the working copy
b. If any files have been updated in SVN repo #1, they overwrite what is in the working copy
c. If any files have been removed from SVN repo #2, they need to be deleted from the working copy

Check in the updated code base into SVN repo #2

Step #4 is where I am running into issues.  I believe I can accomplish 4a and 4b by just copying the compiled/exported code base from SVN repo #1 over the working copy that has been checked out from SVN repo #2.  I am not sure how do do the diff between the two code bases to determine which files need to be deleted from the SVN repo #2 working copy though.  I know I can use SVNANT delete to remove the files, but how do I build the fileset?

答:
I did similar tasks. In my cases ant code looks like that:

```<code>...
<svn.sync to="${svn_folder}" from="${deploy_directory_path}" />
...
<svn svnkit="true" javahl="false">
    <add dir="${svn_folder}" force="true" recurse="true" />
    <!--add>
        <svnFileSet dir="${svn_folder}">
            <svnUnversioned/>
        </svnFileSet>
    </add-->
    <delete>
        <svnFileSet dir="${svn_folder}">
            <svnMissing/>
        </svnFileSet>
    </delete>
</svn>
<svn verbose="true" username="${svn.username}" password="${svn.password}" svnkit="true">
    <commit dir="${svn_folder}" message="${version}"/>
</svn>
</code>```

where

```<code><macrodef name="svn.sync">
    <attribute name="to" />
    <attribute name="from" />
    <sequential>
        <mkdir dir="@{to}" />
        <sync todir="@{to}" includeemptydirs="true">
            <fileset dir="@{from}" />
            <fileset dir="@{to}" defaultexcludes="no">
                <include name="**/.svn/**/*" />
                <include name="**/.svn/**/*.*" />
            </fileset>
        </sync>
    </sequential>
</macrodef>
</code>```

Body:
I did similar tasks. In my cases ant code looks like that:

...
<svn.sync to="${svn_folder}" from="${deploy_directory_path}" />
...
<svn svnkit="true" javahl="false">
    <add dir="${svn_folder}" force="true" recurse="true" />
    <!--add>
        <svnFileSet dir="${svn_folder}">
            <svnUnversioned/>
        </svnFileSet>
    </add-->
    <delete>
        <svnFileSet dir="${svn_folder}">
            <svnMissing/>
        </svnFileSet>
    </delete>
</svn>
<svn verbose="true" username="${svn.username}" password="${svn.password}" svnkit="true">
    <commit dir="${svn_folder}" message="${version}"/>
</svn>

where

<macrodef name="svn.sync">
    <attribute name="to" />
    <attribute name="from" />
    <sequential>
        <mkdir dir="@{to}" />
        <sync todir="@{to}" includeemptydirs="true">
            <fileset dir="@{from}" />
            <fileset dir="@{to}" defaultexcludes="no">
                <include name="**/.svn/**/*" />
                <include name="**/.svn/**/*.*" />
            </fileset>
        </sync>
    </sequential>
</macrodef>


问:
Get iOS device ip address in xamarin
hi can you please tell me how to access iOS device ip address using xamarin. we are building iOS app in which we want to show device local ip address. I used many other solutions but they didnt work for me. </p>

答:
I found a post about it here: https://forums.xamarin.com/discussion/348/acquire-device-ip-addresses-monotouch-since-ios6-0

it goes as follow:
Try using System.Net.NetworkInformation.NetworkInterface:

```<code>foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces()) {
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
    netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
    foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses) {
        if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork) {
            var ipAddress = addrInfo.Address;

            // use ipAddress as needed ...
        }
    }
}
</code>```

}

Title: Get iOS device ip address in xamarin

Body:
I found a post about it here: https://forums.xamarin.com/discussion/348/acquire-device-ip-addresses-monotouch-since-ios6-0

it goes as follow:
Try using System.Net.NetworkInformation.NetworkInterface:

foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces()) {
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
    netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
    foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses) {
        if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork) {
            var ipAddress = addrInfo.Address;

            // use ipAddress as needed ...
        }
    }
}

}


问:
Spring @AutoWired always null
I'm trying to call SOAP service from another system on my program. I've generated the java classes needed from WSDL by using wsimport command.

Here's my program's configuration

 web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>PTDAM Promo Engine</display-name>
    <description>Promo Engine using Elastic Search</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/cxf-servlet.xml</param-value>

    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>promoengine</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <display-name>CXF Servlet</display-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

and here's my xml configuration file where i store the config location

UPDATE: added ESCreditRunner class as a bean below, and still got the same error

cxf-servlet.xml

```<code>    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
           xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws"
           xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration"
           xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"

           xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://cxf.apache.org/transports/http/configuration
                      http://cxf.apache.org/schemas/configuration/http-conf.xsd
                  http://cxf.apache.org/configuration/security
                  http://cxf.apache.org/schemas/configuration/security.xsd
                  http://cxf.apache.org/jaxrs
                  http://cxf.apache.org/schemas/jaxrs.xsd
                  http://cxf.apache.org/core
                  http://cxf.apache.org/schemas/core.xsd
                  http://cxf.apache.org/jaxws
                  http://cxf.apache.org/schemas/jaxws.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

         <!-- use this to enable @AutoWired -->
         <context:annotation-config />
         <context:component-scan base-package="ptdam.emoney.webservice.transactions" />

         <import resource="classpath:META-INF/cxf/cxf.xml" />
         <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
         <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

        <!-- Client -->
        <jaxws:client id="topupWebService"
            serviceClass="ptdam.emoney.webservice.transactions.TopupWebService"
            address="http://localhost:8080/ecash-core-engine-dev-mitigasi/services/emoneytopup"

<!-- Beans -->
    <bean id="esCreditRunner" class="com.ptdam.promo.services.ESCreditRunner" />
        />
    </beans>
</code>```

and here's how i use the @AutoWired, to call the SOAP service topupWebService.. on the testCall() method

ESCreditRunner.java

```<code>package ptdam.emoney.webservice.transactions;
public class ESCreditRunner {
        private File statusFile;
        private Properties status;
        private static final Logger logger = Logger.getLogger(ESCreditRunner.class);

        @Autowired
        private TopupWebService topupWebService;
        public void setTopupWebService(TopupWebService topupWebService) {
            this.topupWebService = topupWebService;
        }

        // testing 04/07/2017
        public void testCall(){
            topupWebService.echoTest("Luki");
        }
    }
</code>```

when i run the testCall() method, i always get NullPointerException on the topupWebService variable. It looks like it's not injected properly..

what i'm missing here?

Update:
i've made another thread as a continuation of this thread. Kindly check it here :) Spring WebService with Endpoint vs no Endpoint

答:
You can try to use:

```<code> @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(locations = "cxf-servlet.xml")
</code>```

If your xml isn't in classpath, then you can use classpath:**/cxf-servlet.xml

Title: Spring @AutoWired always null

Body:
I'm trying to call SOAP service from another system on my program. I've generated the java classes needed from WSDL by using wsimport command.

Here's my program's configuration

 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>PTDAM Promo Engine</display-name>
    <description>Promo Engine using Elastic Search</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/cxf-servlet.xml</param-value>

    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>promoengine</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <display-name>CXF Servlet</display-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

and here's my xml configuration file where i store the config location

UPDATE: added ESCreditRunner class as a bean below, and still got the same error

cxf-servlet.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
           xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws"
           xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration"
           xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"

           xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://cxf.apache.org/transports/http/configuration
                      http://cxf.apache.org/schemas/configuration/http-conf.xsd
                  http://cxf.apache.org/configuration/security
                  http://cxf.apache.org/schemas/configuration/security.xsd
                  http://cxf.apache.org/jaxrs
                  http://cxf.apache.org/schemas/jaxrs.xsd
                  http://cxf.apache.org/core
                  http://cxf.apache.org/schemas/core.xsd
                  http://cxf.apache.org/jaxws
                  http://cxf.apache.org/schemas/jaxws.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

         <context:annotation-config />
         <context:component-scan base-package="ptdam.emoney.webservice.transactions" />

         <import resource="classpath:META-INF/cxf/cxf.xml" />
         <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
         <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

        <jaxws:client id="topupWebService"
            serviceClass="ptdam.emoney.webservice.transactions.TopupWebService"
            address="http://localhost:8080/ecash-core-engine-dev-mitigasi/services/emoneytopup"

    <bean id="esCreditRunner" class="com.ptdam.promo.services.ESCreditRunner" />
        />
    </beans>

and here's how i use the @AutoWired, to call the SOAP service topupWebService.. on the testCall() method

ESCreditRunner.java

package ptdam.emoney.webservice.transactions;
public class ESCreditRunner {
        private File statusFile;
        private Properties status;
        private static final Logger logger = Logger.getLogger(ESCreditRunner.class);

        @Autowired
        private TopupWebService topupWebService;
        public void setTopupWebService(TopupWebService topupWebService) {
            this.topupWebService = topupWebService;
        }

        // testing 04/07/2017
        public void testCall(){
            topupWebService.echoTest("Luki");
        }
    }

when i run the testCall() method, i always get NullPointerException on the topupWebService variable. It looks like it's not injected properly..

what i'm missing here?

Update:
i've made another thread as a continuation of this thread. Kindly check it here :) Spring WebService with Endpoint vs no Endpoint

Body:
You can try to use:

 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(locations = "cxf-servlet.xml")

If your xml isn't in classpath, then you can use classpath:**/cxf-servlet.xml


问:
Create a figure of figures with matplotlib
I would like to know if there is a way to combined several figures created with matplotlib in one unique figure.

Most of the existing topics are related to multiple plots within one figure. But here, I have several functions which all create one elaborated figure (not just a plot, the figure itself is a multiple plot with texts, title, legends,...)

So instead of just doing the layout of those several figures using a software like Word, is there a way to directly combined all my figures in one unique figure under python ?

Thank you in advance !

答:
The concept of figure in matplotlib does not allow to have a figure inside a figure. The figure is the canvas for other artists, like axes. You may of course add as many axes to a figure as you like. So for example instead of one figure with 4 axes and another figure with 6 axes, you can create a figure with 10 axes.

A good choice may be to use the gridspec, as detailed on the respecive matplotlib page.


答:
You did not post your code.This is my assumption that you expecting like this. Just try the below one:

$(function(){
$('.firstdiv').on('click',function(){
$('#store').text($(this).text());
});

$('.seconddiv').on('click',function(){
if($(this).text()){
$(this).text(parseInt($(this).text())+1);
}
else{
$(this).text($('.firstdiv').text());
}
});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
border:1px solid;
width:100px;
height:100px;
}</code>```

1

<textarea id='store' style='display:none;'></textarea>```

Title: Copy value of div and put in it another div

Body:
You did not post your code.This is my assumption that you expecting like this. Just try the below one:

$(function(){
$('.firstdiv').on('click',function(){
$('#store').text($(this).text());
});

$('.seconddiv').on('click',function(){
if($(this).text()){
$(this).text(parseInt($(this).text())+1);
}
else{
$(this).text($('.firstdiv').text());
}
});
});

div{
border:1px solid;
width:100px;
height:100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class='firstdiv'>1</div>
<div class='seconddiv'></div>
<textarea id='store' style='display:none;'></textarea>


问:
.NetCore WebAPI methods Async or Not with EFCore query
What is considered best(or better) practice to have as default state and why, and what are the real benefits of either?

For example if we have Get method in controller should it be:

```<code>public virtual IActionResult Get(int page = 1, int pageSize = 100)
{
    var q = repository.Query().AsNoTracking().ProjectTo<UserViewModel>();
    q = q.Skip((page - 1) * pageSize).Take(pageSize);
    return new OkObjectResult(q);
}
</code>```

or

```<code>public virtual async Task<IActionResult> Get(int page = 1, int pageSize = 100)
{
    var q = repository.Query().AsNoTracking().ProjectTo<UserViewModel>();
    q = q.Skip((page - 1) * pageSize).Take(pageSize);
    return new OkObjectResult(await q.ToListAsync());
}
</code>```

If async is prefered is this code good for it and enough?

Also Query() in repository is simply

public virtual IQueryable<User> Query() { return context.Set<User>().AsQueryable(); }

I have found here that async was in fact slower:
https://github.com/aspnet/EntityFramework/issues/5816

That bug was apparently fixed, but I don't know what are performance comparison in the latest version.

答:
The benefits of async/await over regular, synchronized code, is biggest when your server is under heavy enough load that freeing up threads on the thread pool makes a difference. Before then, the overhead of context tracking and switching can easily be bigger than the performance gains of freeing up threads.

I tend to favor using the asynchronous API over the synchronous, mainly because I've been in a few projects where high load and synchronous code was a high enough problem that someone decided it was time to refactor and move to async, and it was a pain every time. It's also becoming more and more common to only expose async API:s (for example, the Azure SDK has many async actions which don't have synchronous counterparts), which means that you might have to perform such a re-write later, if you end up using such an API.

But if performance is the only thing you want to take into account, you need to profile your application under realistic load and see which approach works best.

Addendum:

It's quite easy to introduce more of the async/await overhead than necessary. A good rule-of-thumb I like to use is to think of three types of methods that can return Task or Task<T>, and follow one of these patterns for each, respectively:

Methods that are actually synchronous (but return Task or Task<T>, e.g. in order to allow for overloading with asynchronous variants): return with Task.FromResult.

```<code>public Task<string> ActuallySynchronousGetter()
{
    return Task.FromResult("foo");
}
</code>```

Methods that forward to an asynchronous method, but don't do anything else: just return the Task, no need to await it.

```<code>// note: no async/await, just Task<T>
public Task<string> ForwardingGetter()
{
     return SomeOtherGetter(); // also with return type Task<string>
}
</code>```

Actual asynchronous methods, that both do something asynchronous (usually I/O) and then work with the result of that asynchronous operation: this is the only time you actually need the async and await keywords.

```<code>public async Task<string> GetStringAsynchronously()
{
     var str = await SomeOtherGetter();
     return str.Replace("foo", "bar"); // note: we need the actual string here
}
</code>```

Your code seems to fall in the third case - you need the result of .ToListAsync() in order to pass it to the OkObjectResult constructor. I would probably have written the entire thing as one statement, but it's mostly a matter of taste:

```<code>var data = await repository.Query()
    .AsNoTracking()
    .ProjectTo<UserViewModel>()
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();
return new OkObjectResult(data);
</code>```

Stephen Cleary writes a lot and in depth about how async and await works, and how you should (and should not) use it.

Body:
What is considered best(or better) practice to have as default state and why, and what are the real benefits of either?

For example if we have Get method in controller should it be:

public virtual IActionResult Get(int page = 1, int pageSize = 100)
{
    var q = repository.Query().AsNoTracking().ProjectTo<UserViewModel>();
    q = q.Skip((page - 1) * pageSize).Take(pageSize);
    return new OkObjectResult(q);
}

or

public virtual async Task<IActionResult> Get(int page = 1, int pageSize = 100)
{
    var q = repository.Query().AsNoTracking().ProjectTo<UserViewModel>();
    q = q.Skip((page - 1) * pageSize).Take(pageSize);
    return new OkObjectResult(await q.ToListAsync());
}

If async is prefered is this code good for it and enough?

Also Query() in repository is simply

public virtual IQueryable<User> Query() { return context.Set<User>().AsQueryable(); }

I have found here that async was in fact slower:
https://github.com/aspnet/EntityFramework/issues/5816

That bug was apparently fixed, but I don't know what are performance comparison in the latest version.

Body:
The benefits of async/await over regular, synchronized code, is biggest when your server is under heavy enough load that freeing up threads on the thread pool makes a difference. Before then, the overhead of context tracking and switching can easily be bigger than the performance gains of freeing up threads.

I tend to favor using the asynchronous API over the synchronous, mainly because I've been in a few projects where high load and synchronous code was a high enough problem that someone decided it was time to refactor and move to async, and it was a pain every time. It's also becoming more and more common to only expose async API:s (for example, the Azure SDK has many async actions which don't have synchronous counterparts), which means that you might have to perform such a re-write later, if you end up using such an API.

But if performance is the only thing you want to take into account, you need to profile your application under realistic load and see which approach works best.

Addendum:

It's quite easy to introduce more of the async/await overhead than necessary. A good rule-of-thumb I like to use is to think of three types of methods that can return Task or Task<T>, and follow one of these patterns for each, respectively:

Methods that are actually synchronous (but return Task or Task<T>, e.g. in order to allow for overloading with asynchronous variants): return with Task.FromResult.

public Task<string> ActuallySynchronousGetter()
{
    return Task.FromResult("foo");
}

Methods that forward to an asynchronous method, but don't do anything else: just return the Task, no need to await it.

// note: no async/await, just Task<T>
public Task<string> ForwardingGetter()
{
     return SomeOtherGetter(); // also with return type Task<string>
}

Actual asynchronous methods, that both do something asynchronous (usually I/O) and then work with the result of that asynchronous operation: this is the only time you actually need the async and await keywords.

public async Task<string> GetStringAsynchronously()
{
     var str = await SomeOtherGetter();
     return str.Replace("foo", "bar"); // note: we need the actual string here
}

Your code seems to fall in the third case - you need the result of .ToListAsync() in order to pass it to the OkObjectResult constructor. I would probably have written the entire thing as one statement, but it's mostly a matter of taste:

var data = await repository.Query()
    .AsNoTracking()
    .ProjectTo<UserViewModel>()
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();
return new OkObjectResult(data);

Stephen Cleary writes a lot and in depth about how async and await works, and how you should (and should not) use it.


问:
Parallel programming with threads in Java

Parallel programming was possible in Java only from Java 7 with the
  advent of Join/Fork framework.

Let's say in Java, using ExecutorService I create a thread pool of say 4 threads and submit to it say 10 tasks which means 4 threads will start executing the 4 tasks and other 6 tasks will be picked up by threads as and when any thread finishes its task.

Let's assume I have a quad processor having 4 cores, I know a thread can be run on a single core(not taking hyper-threading concept here) so will all my 4 threads work in parallel, 1 thread running on 1 core? Isn't it a parallel programming?

EDIT: Source of reading  - This is the Java 8 playlist where in chapter 1 it was referred that parallel programming was possible from Java 7 onwards.

答:
Parallel programming was possible in Java only from Java 7 with the advent of Join/Fork framework.

Parallel programming exists in java since early versions. It was enhanced with Java 5 java.util.concurrent package classes and Java 7 ForkJoinPool further enhanced parallel programming to new level.

You can find answer to your questions in this article by oracle.

Java Platform, Standard Edition (Java SE) 5 and then Java SE 6 introduced a set of packages providing powerful concurrency building blocks. Java SE 7 further enhanced them by adding support for parallelism

Example of divide and conquer problem:

Find sum of integers in large array

Instead of sequentially computing the sum, divide array into multiple partitions and assign computation task on each partition to different task.

The problem with the executors for implementing divide and conquer algorithms is not related to creating subtasks, because a Callable is free to submit a new subtask to its executor and wait for its result in a synchronous or asynchronous fashion.

The issue is that of parallelism: When a Callable waits for the result of another Callable, it is put in a waiting state, thus wasting an opportunity to handle another Callable queued for execution.

The fork/join framework added to the java.util.concurrent package in Java SE 7

Additions for Supporting Parallelism:

The core addition is a new ForkJoinPool executor that is dedicated to running instances implementing ForkJoinTask. ForkJoinTask objects support the creation of subtasks plus waiting for the subtasks to complete. With those clear semantics, the executor is able to dispatch tasks among its internal threads pool by “stealing” jobs when a task is waiting for another task to complete and there are pending tasks to be run.

ForkJoinTask objects feature two specific methods:

The fork() method allows a ForkJoinTask to be planned for asynchronous execution. This allows a new ForkJoinTask to be launched from an existing one.

In turn, the join() method allows a ForkJoinTask to wait for the completion of another one.


问:
How to get the element clicked (for the whole document)?
I would like to get the current element (whatever element that is) in an HTML document that I clicked. I am using:

```<code>$(document).click(function () {
    alert($(this).text());
});
</code>```

But very strangely, I get the text of the whole(!) document, not the clicked element.

How to get only the element I clicked on?

Example

```<code><body>
    <div class="myclass">test</div>
    <p>asdfasfasf</p>
</body>
</code>```

If I click on the "test" text, I would like to be able to read the attribute with $(this).attr("myclass") in jQuery.

答:
event.target to get the element

```<code>window.onclick = e => {
    console.log(e.target);  // to get the element
    console.log(e.target.tagName);  // to get the element tag name alone
}
</code>```

to get the text from clicked element

```<code>window.onclick = e => {
    console.log(e.target.innerText);
}
</code>```

Body:
I would like to get the current element (whatever element that is) in an HTML document that I clicked. I am using:

$(document).click(function () {
    alert($(this).text());
});

But very strangely, I get the text of the whole(!) document, not the clicked element.

How to get only the element I clicked on?

Example

test

asdfasfasf

If I click on the "test" text, I would like to be able to read the attribute with $(this).attr("myclass") in jQuery.

Body:
event.target to get the element

window.onclick = e => {
    console.log(e.target);  // to get the element
    console.log(e.target.tagName);  // to get the element tag name alone
}

to get the text from clicked element

window.onclick = e => {
    console.log(e.target.innerText);
}

ContentLicense: CC BY-SA 4.0


答:
(function(){
var d1 = document.getElementById("d1"),
    d2 = document.getElementById("d2"),
    tmp;

    d1.onmousedown = function(){
      tmp = Number(this.innerHTML);
    };

    d2.onmousedown = function(){
      var v = (Number(this.innerHTML) || 0) +(tmp || 0);

      v && (this.innerHTML = v);
    }

})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{border:1px solid;width:200px;height:200px; float:left;}
#d1{border-color:red;}
#d2{border-color:blue;}</code>```

 1

```

Body:
(function(){
var d1 = document.getElementById("d1"),
    d2 = document.getElementById("d2"),
    tmp;

    d1.onmousedown = function(){
      tmp = Number(this.innerHTML);
    };

    d2.onmousedown = function(){
      var v = (Number(this.innerHTML) || 0) +(tmp || 0);

      v && (this.innerHTML = v);
    }

})();

div{border:1px solid;width:200px;height:200px; float:left;}
#d1{border-color:red;}
#d2{border-color:blue;}

<div id="d1">
 1
</div>
<div id="d2">
</div>


问:
Spring not autowiring using annotation a bean declared on the XML
I'm trying to inject a bean that was defined on a XML into an annotated,  It is only annotated and not declared on XML, I think that is just something that I'm missing here is my *context.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
...
<bean id="userBusiness" class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
    <property name="jndiName" value="java:global/app-common/app-common-core/UserBusinessImpl" />
    <property name="businessInterface" value="com.app.common.business.UserBusiness" />
</bean>
...
<context:annotation-config/>
<context:component-scan base-package="com.app.common.jsf" />
</beans>
</code>```

Here's the component:

```<code>@Component
public class AppAuthorization {

    @Autowired
    private UserBusiness userBusiness;

    @Autowired
    private AppLogin sabiusLogin;
...

@Local
public interface UserBusiness {
    User listUserByFilter(User user) throws UserBusinessException;
...

@Stateless
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
@Interceptors({SpringBeanAutowiringInterceptor.class})
public class UserBusinessImpl implements UserBusiness {

    @Autowired
    private ProgramasUsuariosDao programasUsuariosDao;
...
</code>```

When I try to access the AppAuthorization Spring says that:

```<code>Could not autowire field: private com.app.common.business.UserBusiness com.app.common.jsf.AppAuthorization.userBusiness"
</code>```

Seems that the annotated bean can't see the declared one, but search and seems that I only needed to add the annotation-config to the XML, is this right? Hope some can help me.

EDIT

I think that this is the most important part of the stack trace:

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.app.common.business.UserBusiness] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:997)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:867)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:779)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:503)
    ... 201 more
</code>```

Following the steps on the context creation I see no bean registered tha can be seen by annotations just when springs creates the context based on the xml is that I can see all the beans that wre created.

EDIT 2

This is the beanRefContext.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="contexts" class="com.app.common.spring.ClassPathXmlApplicationContext" />
</beans>
</code>```

This is the class that loads the XML context files:

```<code>public class ClassPathXmlApplicationContext extends org.springframework.context.support.ClassPathXmlApplicationContext {

    public ClassPathXmlApplicationContext() {
        super((System.getProperty("module.context.file").split(";")));
    }

}
</code>```

As I said, the annotated beans cannot see the XML ones so, spring cannot autowire them.

EDIT 3

I don't have a @Configuration bean (I'm not using AnnotationConfigApplicationContext), all the config is in the XML and if I try to create one the server doesn't start, it's a legacy system with spring 3.2 and EJB 3.0 and I can't change this aspect now.

Thanks in advance!

答:
What seems to work was create a @Configuration import the xml that have the bean declaration (with @ImportResource) and don't scan it's package in XML.
For some reason if I declare the file in the XML the server don't start, it's strange because I have no definition anywhere that I'm using an annotation configuration.

Body:
I'm trying to inject a bean that was defined on a XML into an annotated,  It is only annotated and not declared on XML, I think that is just something that I'm missing here is my *context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
...
<bean id="userBusiness" class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
    <property name="jndiName" value="java:global/app-common/app-common-core/UserBusinessImpl" />
    <property name="businessInterface" value="com.app.common.business.UserBusiness" />
</bean>
...
<context:annotation-config/>
<context:component-scan base-package="com.app.common.jsf" />
</beans>

Here's the component:

@Component
public class AppAuthorization {

    @Autowired
    private UserBusiness userBusiness;

    @Autowired
    private AppLogin sabiusLogin;
...

@Local
public interface UserBusiness {
    User listUserByFilter(User user) throws UserBusinessException;
...

@Stateless
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
@Interceptors({SpringBeanAutowiringInterceptor.class})
public class UserBusinessImpl implements UserBusiness {

    @Autowired
    private ProgramasUsuariosDao programasUsuariosDao;
...

When I try to access the AppAuthorization Spring says that:

Could not autowire field: private com.app.common.business.UserBusiness com.app.common.jsf.AppAuthorization.userBusiness"

Seems that the annotated bean can't see the declared one, but search and seems that I only needed to add the annotation-config to the XML, is this right? Hope some can help me.

EDIT

I think that this is the most important part of the stack trace:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.app.common.business.UserBusiness] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:997)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:867)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:779)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:503)
    ... 201 more

Following the steps on the context creation I see no bean registered tha can be seen by annotations just when springs creates the context based on the xml is that I can see all the beans that wre created.

EDIT 2

This is the beanRefContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="contexts" class="com.app.common.spring.ClassPathXmlApplicationContext" />
</beans>

This is the class that loads the XML context files:

public class ClassPathXmlApplicationContext extends org.springframework.context.support.ClassPathXmlApplicationContext {

    public ClassPathXmlApplicationContext() {
        super((System.getProperty("module.context.file").split(";")));
    }

}

As I said, the annotated beans cannot see the XML ones so, spring cannot autowire them.

EDIT 3

I don't have a @Configuration bean (I'm not using AnnotationConfigApplicationContext), all the config is in the XML and if I try to create one the server doesn't start, it's a legacy system with spring 3.2 and EJB 3.0 and I can't change this aspect now.

Thanks in advance!


问:
Send Intent from Activity to another Activity with RecyclerView
I have an Activity where I enter a phone number and a message and when I click on the send Button, I want to display the message and number I entered in the layout of another Activity which has a RecyclerView. I have tried to use an Intent but it displays "NUMBER" and "NUMBER" in both TextViews.
This is some of the code below.

```<code>public class NewMessageActivity extends AppCompatActivity {

private String message, number;
private EditText mComposeMessage, mPhoneNumber;
private Button mSendButton, mCancelButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new_message_layout);

    mPhoneNumber = (EditText) findViewById(R.id.phone_number_et);
    mComposeMessage = (EditText) findViewById(R.id.compose_et);
    mSendButton = (Button) findViewById(R.id.send_button);
    mCancelButton = (Button) findViewById(R.id.cancel_button);

    number = mPhoneNumber.getText().toString();
    message = mComposeMessage.getText().toString();

    mSendButton.setOnClickListener(mButtonClickListener);
    mCancelButton.setOnClickListener(mButtonClickListener);
}

private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.send_button:
                Intent intent = new Intent(v.getContext(), SentActivity.class);
                intent.putExtra(getString(R.string.key_message), message);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
                break;

            case R.id.cancel_button:
                break;
        }
    }
};

}
</code>```

This is my Adapter

```<code>public class SentMessageAdapter extends RecyclerView.Adapter<SentMessageAdapter.MessageHolder> {
private List<String> mMessages;

public static class MessageHolder extends RecyclerView.ViewHolder {
    private TextView mSentMessageTv;
    private TextView mRecipientNumberTv;
    private TextView mRecipientTv;

    public MessageHolder(View v){
        super(v);
        mSentMessageTv = (TextView) v.findViewById(R.id.sent_message_tv);
        mRecipientNumberTv = (TextView) v.findViewById(R.id.recipient_number_tv);
        mRecipientTv = (TextView) v.findViewById(R.id.recipient_tv);
    }
}

public SentMessageAdapter(List<String> messages){
    mMessages = messages;
}

@Override
public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sent_list_item, parent, false);
    MessageHolder vH = new MessageHolder(v);
    return vH;
}

@Override
public void onBindViewHolder(MessageHolder holder, int position) {
    holder.mSentMessageTv.setText(mMessages.get(position));
    holder.mRecipientNumberTv.setText(mMessages.get(position));
    holder.mRecipientTv.setText(R.string.to);
}

@Override
public int getItemCount() {
    return mMessages.size();
}

}
</code>```

Activity where the text should be displayed

```<code>public class SentActivity extends AppCompatActivity {

private static final String LOG_TAG = SentActivity.class.getSimpleName();

private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

final ArrayList<String> messages = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.message_recycler_list);

    Bundle extras = getIntent().getExtras();
    String message = null;

    if (extras != null){
        message = extras.getString(String.valueOf(R.string.key_message), String.valueOf("NUMBER"));
    }

    if (message == null){
        message = "text";
    }
    Log.d(LOG_TAG, message);
    messages.add(0, message);

    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    mRecyclerView = (RecyclerView) findViewById(R.id.message_recycler_view);
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new SentMessageAdapter(messages);
    mRecyclerView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();
}

}
</code>```

Layout for the Activity

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">

<TextView
    android:id="@+id/sent_message_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    tools:text="Hello world"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/recipient_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="@string/to"/>

    <TextView
        android:id="@+id/recipient_number_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="4dp"
        android:paddingStart="4dp"
        android:paddingRight="4dp"
        android:paddingEnd="4dp" />
</LinearLayout>

</LinearLayout>
</code>```

答:
You are Not getting value that you entered is because you are accessing edittext values in onCreate method where it has default value so you should use

```<code>    number = mPhoneNumber.getText().toString();
    message = mComposeMessage.getText().toString();
</code>```

this in onClick Methods

```<code>   private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();

            switch (id) {
                case R.id.send_button:
                    number = mPhoneNumber.getText().toString();
                    message = mComposeMessage.getText().toString();
                    Intent intent = new Intent(v.getContext(), SentActivity.class);
                    intent.putExtra(getString(R.string.key_message), message);
                    intent.putExtra("NUMBER", number);
                    startActivity(intent);
                    break;

                case R.id.cancel_button:
                    break;
            }
        }
    };
</code>```

Body:
I have an Activity where I enter a phone number and a message and when I click on the send Button, I want to display the message and number I entered in the layout of another Activity which has a RecyclerView. I have tried to use an Intent but it displays "NUMBER" and "NUMBER" in both TextViews.
This is some of the code below.

public class NewMessageActivity extends AppCompatActivity {

private String message, number;
private EditText mComposeMessage, mPhoneNumber;
private Button mSendButton, mCancelButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new_message_layout);

    mPhoneNumber = (EditText) findViewById(R.id.phone_number_et);
    mComposeMessage = (EditText) findViewById(R.id.compose_et);
    mSendButton = (Button) findViewById(R.id.send_button);
    mCancelButton = (Button) findViewById(R.id.cancel_button);

    number = mPhoneNumber.getText().toString();
    message = mComposeMessage.getText().toString();

    mSendButton.setOnClickListener(mButtonClickListener);
    mCancelButton.setOnClickListener(mButtonClickListener);
}

private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.send_button:
                Intent intent = new Intent(v.getContext(), SentActivity.class);
                intent.putExtra(getString(R.string.key_message), message);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
                break;

            case R.id.cancel_button:
                break;
        }
    }
};

}

This is my Adapter

public class SentMessageAdapter extends RecyclerView.Adapter<SentMessageAdapter.MessageHolder> {
private List<String> mMessages;

public static class MessageHolder extends RecyclerView.ViewHolder {
    private TextView mSentMessageTv;
    private TextView mRecipientNumberTv;
    private TextView mRecipientTv;

    public MessageHolder(View v){
        super(v);
        mSentMessageTv = (TextView) v.findViewById(R.id.sent_message_tv);
        mRecipientNumberTv = (TextView) v.findViewById(R.id.recipient_number_tv);
        mRecipientTv = (TextView) v.findViewById(R.id.recipient_tv);
    }
}

public SentMessageAdapter(List<String> messages){
    mMessages = messages;
}

@Override
public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sent_list_item, parent, false);
    MessageHolder vH = new MessageHolder(v);
    return vH;
}

@Override
public void onBindViewHolder(MessageHolder holder, int position) {
    holder.mSentMessageTv.setText(mMessages.get(position));
    holder.mRecipientNumberTv.setText(mMessages.get(position));
    holder.mRecipientTv.setText(R.string.to);
}

@Override
public int getItemCount() {
    return mMessages.size();
}

}

Activity where the text should be displayed

public class SentActivity extends AppCompatActivity {

private static final String LOG_TAG = SentActivity.class.getSimpleName();

private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

final ArrayList<String> messages = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.message_recycler_list);

    Bundle extras = getIntent().getExtras();
    String message = null;

    if (extras != null){
        message = extras.getString(String.valueOf(R.string.key_message), String.valueOf("NUMBER"));
    }

    if (message == null){
        message = "text";
    }
    Log.d(LOG_TAG, message);
    messages.add(0, message);

    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    mRecyclerView = (RecyclerView) findViewById(R.id.message_recycler_view);
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new SentMessageAdapter(messages);
    mRecyclerView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();
}

}

Layout for the Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">

<TextView
    android:id="@+id/sent_message_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    tools:text="Hello world"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/recipient_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="@string/to"/>

    <TextView
        android:id="@+id/recipient_number_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="4dp"
        android:paddingStart="4dp"
        android:paddingRight="4dp"
        android:paddingEnd="4dp" />
</LinearLayout>

</LinearLayout>

Body:
You are Not getting value that you entered is because you are accessing edittext values in onCreate method where it has default value so you should use

    number = mPhoneNumber.getText().toString();
    message = mComposeMessage.getText().toString();

this in onClick Methods

   private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();

            switch (id) {
                case R.id.send_button:
                    number = mPhoneNumber.getText().toString();
                    message = mComposeMessage.getText().toString();
                    Intent intent = new Intent(v.getContext(), SentActivity.class);
                    intent.putExtra(getString(R.string.key_message), message);
                    intent.putExtra("NUMBER", number);
                    startActivity(intent);
                    break;

                case R.id.cancel_button:
                    break;
            }
        }
    };


问:
isset is not working on submit
This is a 5-star rating form and I am trying to make it work.

```<code><div class="stars">
  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>
    <label class="star star-5" for="star-5"></label>
    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>
    <label class="star star-4" for="star-4"></label>
    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>
    <label class="star star-3" for="star-3"></label>
    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>
    <label class="star star-2" for="star-2"></label>
    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>
    <label class="star star-1" for="star-1"></label>
    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>
</div>
</code>```

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

```<code><?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>
</code>```

答:
To use super global variable $_POST, u need to specify method attribute to the form tag with submit button.
Change your form tag and your submit button tag to :</p>

```<code><div class="stars">
<form method="POST" name="starRatingForm" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input class="star star-5" id="star-5" type="radio" name="star" value="5"/>
<label class="star star-5" for="star-5"></label>
<input class="star star-4" id="star-4" type="radio" name="star" value="4"/>
<label class="star star-4" for="star-4"></label>
<input class="star star-3" id="star-3" type="radio" name="star" value="3"/>
<label class="star star-3" for="star-3"></label>
<input class="star star-2" id="star-2" type="radio" name="star" value="2"/>
<label class="star star-2" for="star-2"></label>
<input class="star star-1" id="star-1" type="radio" name="star" value="1"/>
<label class="star star-1" for="star-1"></label>
<input type="submit" name="submit" value="submit"/>
</form>
</div>
</code>```

Title: isset is not working on submit

Body:
This is a 5-star rating form and I am trying to make it work.

  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>

    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>

    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>

    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>

    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>

    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

<?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>

Body:
To use super global variable $_POST, u need to specify method attribute to the form tag with submit button.
Change your form tag and your submit button tag to :

<div class="stars">
<form method="POST" name="starRatingForm" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input class="star star-5" id="star-5" type="radio" name="star" value="5"/>
<label class="star star-5" for="star-5"></label>
<input class="star star-4" id="star-4" type="radio" name="star" value="4"/>
<label class="star star-4" for="star-4"></label>
<input class="star star-3" id="star-3" type="radio" name="star" value="3"/>
<label class="star star-3" for="star-3"></label>
<input class="star star-2" id="star-2" type="radio" name="star" value="2"/>
<label class="star star-2" for="star-2"></label>
<input class="star star-1" id="star-1" type="radio" name="star" value="1"/>
<label class="star star-1" for="star-1"></label>
<input type="submit" name="submit" value="submit"/>
</form>
</div>