问:
Why does accessing globals work via import module, but not from module import var?
I've been reading and learning a ton about python, but all the import variations having different results is a tad confusing.

I was having an issue where a global variable I had imported was always the default value, even though I called a method in that module that manipulates it. I had imported it like so:

```<code>from fona import connect, disconnect, CON
</code>```

Where the first two are functions and the last the var. The first two either open or close the connection, to which I have access via the var CON. When I did it this way, CON would stay None, even though connect is initializing it successfully (I have a lot of verbose output to verify that). I messed around more and more and couldn't figure it out. Wrote a post very different to this one before I had one more idea.

```<code>import fona
</code>```

I then access everything via fona.connect/disco/CON. Then it works. I am struggling to fathom why and couldn't find any resources. What makes these imports different? I quite like from x import y as z, but it seems I cannot use that in this case.

答:
In Python, "global" means "module-level" (actually at runtime a "global" variable is an attribute of the module object instance).

Now this statement:

```<code>from fona import CON
</code>```

is syntactic sugar for:

```<code>import fona
CON = fona.CON
del fona
</code>```

so at this point we have two names pointing at the same object - fon.CON and <yourothermodule>.CON

Now if in fona we have a function that rebinds fona.CON, ie:

```<code>def foo():
    global CON
    con = "XXX"
</code>```

calling this function will ONLY rebind fona.CON, not the CON variable in <yourothermodule>.

If instead in  you import the whole fona module and use fona.CON you do see the effects of the rebiding after calling fona.foo() because you are actually accessing the fona module's attribute, not your local (local to ) attribute.

Actually you would have the very same situation with two dicts in the same  module:

```<code>d1 = {"a":1}
d2 = {}
d2["a"] = d1["a"]
d1["a"] = 42 # this won't change d2["a"]
print d1, d2
</code>```

In fact you don't even need dicts, just two names in the same namespace are enough:

```<code>Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>>> a = 1
>>> b = a
>>> print a
1
>>> print b
1
>>> b is a
True
</code>```

As you can see, at this point b is not a 'copy' of a, it's really just another name bound to the very same object. Now if we rebind a:

```<code>>>> a = 2
>>> print a
2
>>> print b
1
>>> b is a
False
>>>
</code>```

we can see that it doesn't affect b, it only makes a point to another object.

Body:
I've been reading and learning a ton about python, but all the import variations having different results is a tad confusing.

I was having an issue where a global variable I had imported was always the default value, even though I called a method in that module that manipulates it. I had imported it like so:

from fona import connect, disconnect, CON

Where the first two are functions and the last the var. The first two either open or close the connection, to which I have access via the var CON. When I did it this way, CON would stay None, even though connect is initializing it successfully (I have a lot of verbose output to verify that). I messed around more and more and couldn't figure it out. Wrote a post very different to this one before I had one more idea.

import fona

I then access everything via fona.connect/disco/CON. Then it works. I am struggling to fathom why and couldn't find any resources. What makes these imports different? I quite like from x import y as z, but it seems I cannot use that in this case.

Body:
In Python, "global" means "module-level" (actually at runtime a "global" variable is an attribute of the module object instance).

Now this statement:

from fona import CON

is syntactic sugar for:

import fona
CON = fona.CON
del fona

so at this point we have two names pointing at the same object - fon.CON and <yourothermodule>.CON

Now if in fona we have a function that rebinds fona.CON, ie:

def foo():
    global CON
    con = "XXX"

calling this function will ONLY rebind fona.CON, not the CON variable in <yourothermodule>.

If instead in  you import the whole fona module and use fona.CON you do see the effects of the rebiding after calling fona.foo() because you are actually accessing the fona module's attribute, not your local (local to ) attribute.

Actually you would have the very same situation with two dicts in the same  module:

d1 = {"a":1}
d2 = {}
d2["a"] = d1["a"]
d1["a"] = 42 # this won't change d2["a"]
print d1, d2

In fact you don't even need dicts, just two names in the same namespace are enough:

Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>>> a = 1
>>> b = a
>>> print a
1
>>> print b
1
>>> b is a
True

As you can see, at this point b is not a 'copy' of a, it's really just another name bound to the very same object. Now if we rebind a:

>>> a = 2
>>> print a
2
>>> print b
1
>>> b is a
False
>>>

we can see that it doesn't affect b, it only makes a point to another object.


来源: stackexchange

问:
$ctrl in data binding is not working
I want to make a dynamic page using angular where the user after  he logged-in see his user picture and some information charged by json file throught an http request.
This is the module where i do the http requestes:

```<code>         'user strict';

angular.
 module('userIssue').
 component('userIssue',{
    templateUrl: 'user-issue/user-issue.html',
    controller: 'userIssueCtrl'
 })

.controller('userIssueCtrl',['$scope','$http','$routeParams',function       userIssueCtrl($scope,$http,$routeParams){
var self = this;
var percorso;
$scope.utente=$routeParams.username;
document.title="Benvenuto"+" "+$routeParams.username;

$http.get('user/'+ $routeParams.username+'.json').then(function(response){
  self.utenti = response.data;

});

$http.get('user/'+$routeParams.username+'.info.json').then(function(qualcosa){
  self.d = qualcosa.data;
});

self.show = function(){
  $scope.showForm='false';
}

}]);
</code>```

and this is the part of the html page not working:

```<code> <div class="col-sm-4">
 <img  style="position:center;" ng-src="{{$ctrl.d.imgUrl}}" class="img-circle" alt="user image"></div>
</code>```

I'm using the same approch in this part of the code:

```<code><div  class="col-md-9 col-sm-9" id="issueColumn" >
<div id="issue" ng-repeat='utenti in $ctrl.utenti'>
               <li>
<dt>CODICE OPERAZIONE</dt>
<dd>{{utenti.id}}</dd>
<dt>DESCRIZIONE PROBLEMA</dt>
<dd>{{utenti.description}}</dd>
<dt>DATA SEGNALAZIONE</dt>
<dd>{{utenti.forward}}</dd>
<dt>IL PROBLEMA SARà RISOLTO ENTRO IL:</dt>
<dd>{{utenti.endstimed}}</dd>
<dt>STATO DEL PROBLEMA:</dt>
<dd>{{utenti.stato}}</dd>
</li> </br>
</div>
</div>
</code>```

and here it is working! So why does the data binding not work for the image?
Could someone gently explain me why?

Here is the json file I use for the image:

```<code>   [
 {
   "imgUrl": "img/Filippo.png",
   "ciao": "ciao_calro"
 }
   ]
</code>```

答:
Hi can you try the below changes from your code and let me know,

Introduced controllerAs with the controller object:

component('userIssue',{
      templateUrl: 'user-issue/user-issue.html',
      controllerAs: 'userCtrl'
      controller: 'userIssueCtrl'  })

Accessing through the controller object name:

Try to access through the controller object name like,

{{userCtrl.d.imgUrl}} in template.

ContentLicense: CC BY-SA 3.0

Title: $ctrl in data binding is not working

Body:
I want to make a dynamic page using angular where the user after  he logged-in see his user picture and some information charged by json file throught an http request.
This is the module where i do the http requestes:

         'user strict';

angular.
 module('userIssue').
 component('userIssue',{
    templateUrl: 'user-issue/user-issue.html',
    controller: 'userIssueCtrl'
 })

.controller('userIssueCtrl',['$scope','$http','$routeParams',function       userIssueCtrl($scope,$http,$routeParams){
var self = this;
var percorso;
$scope.utente=$routeParams.username;
document.title="Benvenuto"+" "+$routeParams.username;

$http.get('user/'+ $routeParams.username+'.json').then(function(response){
  self.utenti = response.data;

});

$http.get('user/'+$routeParams.username+'.info.json').then(function(qualcosa){
  self.d = qualcosa.data;
});

self.show = function(){
  $scope.showForm='false';
}

}]);

and this is the part of the html page not working:

I'm using the same approch in this part of the code:

CODICE OPERAZIONE

{{utenti.id}}

DESCRIZIONE PROBLEMA

{{utenti.description}}

DATA SEGNALAZIONE

{{utenti.forward}}

IL PROBLEMA SARà RISOLTO ENTRO IL:

{{utenti.endstimed}}

STATO DEL PROBLEMA:

{{utenti.stato}}

and here it is working! So why does the data binding not work for the image?
Could someone gently explain me why?

Here is the json file I use for the image:

   [
 {
   "imgUrl": "img/Filippo.png",
   "ciao": "ciao_calro"
 }
   ]


问:
Upload attachments to a page in Wordpress
I've installed a plugin that allows a user to upload an attachment to my Wordpress site. In doing so, I can see that the attachments get uploaded to the "wp-content" directory of my Wordpress directory path.

I can then see that the files are uploaded, but when I access the URL, I can see a page that doesn't have a very good design.

Essentially, I'd like to know how to use the above plugin to upload attachments, and then add these attachments to a page (like an "added attachments page") on Wordpress, that the user can then view.

答:
You can see all uploaded files through Dashboard > Media.
Also, Administrators can view all uploaded files together with associated field data from the plugin’s Settings in Dashboard. The Pro version of the plugin allows users to view their uploaded files, either from the Dashboard, or from a page or post.

Pro version link : WordPress File Upload Premium

Reference


问:
Resource not found error in MVC when posting using beginform
The below code is not working properly as expected.

The controller have an action method

```<code>[HttpPost]
        public ActionResult LoginResult()
        {
            string name = Request.Form["name"];
            return View("Dashboard");
        }
     public ActionResult Dashboard()
    {
        string strName = Request["username"].ToString();
        return View();
    }
</code>```

and in view i have a form

```<code> @using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }
</code>```

and im submitting this using a function

```<code><script>
    $(function () {
        $('#ajax_method').click(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "Dashboard/LoginResult",                             //Your Action name in the DropDownListConstroller.cs
                data: "{'AJAXParameter1':'" + $('#username').val() + "'}",  //Parameter in this function, Is case sensitive and also type must be string
                contentType: "application/json; charset=utf-8",
                dataType: "json"

            }).done(function (data) {
                //Successfully pass to server and get response
                if (data.result = "OK") {
                    alert("submit successfully.");
                }
            }).fail(function (response) {
                if (response.status != 0) {
                    alert(response.status + " " + response.statusText);
                }
            });
        });

    });
</script>
</code>```

but im getting 404 error  while clicking the button.

Even I tried adding that routerspecifications in route config.

```<code>   routes.MapRoute(
            name: "login",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Dashboard", action = "LoginResult", id = UrlParameter.Optional }
        );
</code>```

and modified the cshtml again. But this is also not working.

```<code> @using (Html.BeginForm("login", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }
</code>```

It may be a silly error but it spoil my day. Can anyone extend a hand to solve this issue.

答:
```<code>@using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post))
</code>```

I think you have to change the "Dashboard" to your controller name

Body:
The below code is not working properly as expected.

The controller have an action method

[HttpPost]
        public ActionResult LoginResult()
        {
            string name = Request.Form["name"];
            return View("Dashboard");
        }
     public ActionResult Dashboard()
    {
        string strName = Request["username"].ToString();
        return View();
    }

and in view i have a form

 @using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

and im submitting this using a function

but im getting 404 error  while clicking the button.

Even I tried adding that routerspecifications in route config.

   routes.MapRoute(
            name: "login",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Dashboard", action = "LoginResult", id = UrlParameter.Optional }
        );

and modified the cshtml again. But this is also not working.

 @using (Html.BeginForm("login", "Dashboard", FormMethod.Post))
    {
     @Html.EditorFor(model =>model.username)
    <button type="button" id="ajax_method">submit Via AJAX</button>

    }

It may be a silly error but it spoil my day. Can anyone extend a hand to solve this issue.

Body:
@using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post))

I think you have to change the "Dashboard" to your controller name


问:
Android checkboxes, how to implement if statement.
I am currently coding an android app but I encountered some difficulty.
I am able to receive some checkbox values from another activity using the getIntent().getExtras().getBoolean()function.

But my question is, how can i make sure that checkboxes with the characters 'wb' or 'ab' or 'alb' together with(or not) 'cs' appearing, a count is performed and the one with the greatest value between 'wb', 'ab' and 'alb' is chosen and a summary is displayed via a texfield.

e.g. if there appearances of 'wb' are greater than those of 'alb' and ab, then the result is displayed "you have a widened bronchus".

```<code>package com.example.vic.cdmes_;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class results extends AppCompatActivity {
private Button displayResult;

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

}

private void viewResults() {
    final Boolean wb1 = getIntent().getExtras().getBoolean("wb1");
    final Boolean wb2 = getIntent().getExtras().getBoolean("wb2");
    final Boolean wb3 = getIntent().getExtras().getBoolean("wb3");
    final Boolean wb4 = getIntent().getExtras().getBoolean("wb4");
    final Boolean wb5 = getIntent().getExtras().getBoolean("wb5");
    final Boolean wb6 = getIntent().getExtras().getBoolean("wb6");
    final Boolean wb7 = getIntent().getExtras().getBoolean("wb7");
    final Boolean cs1 = getIntent().getExtras().getBoolean("cs1");
    final Boolean cs2 = getIntent().getExtras().getBoolean("cs2");
    final Boolean vb1 = getIntent().getExtras().getBoolean("vb1");
    final Boolean vb2 = getIntent().getExtras().getBoolean("vb2");
    final Boolean vb3 = getIntent().getExtras().getBoolean("vb3");
    final Boolean vb4 = getIntent().getExtras().getBoolean("vb4");
    final Boolean vb5 = getIntent().getExtras().getBoolean("vb5");
    final Boolean alb1 = getIntent().getExtras().getBoolean("alb1");
    final Boolean alb2 = getIntent().getExtras().getBoolean("alb2");
    final Boolean alb3 = getIntent().getExtras().getBoolean("alb3");
    final Boolean ab1 = getIntent().getExtras().getBoolean("ab1");
    final Boolean ab2 = getIntent().getExtras().getBoolean("ab2");
    final Boolean ab3 = getIntent().getExtras().getBoolean("ab3");
    final Boolean ab4 = getIntent().getExtras().getBoolean("ab4");

    displayResult = (Button)findViewById(R.id.displayResults);
    displayResult.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Toast.makeText(results.this,.toString(),
              //      Toast.LENGTH_SHORT).show();
            if(wb1&&wb2&&wb3&&wb4&&wb5&&wb6&&wb7&&cs1&&cs2)
            {
                //if the number of checkboxes exceeds
            }
            else
                if (vb1&&vb2&&vb3&&vb4&&vb5&&cs1&&cs2)
                {
                    //display the person might be having a widened bronchus
                }
                else
                if (alb1&&alb2&&alb3&&cs1&&cs2)
                {
                    //display the person might be having a alb disease
                }
                else
                if (ab1&&ab2&&ab3&&ab4&&cs1&&cs2)
                {
                    //display the person might be having a airborne disease
                }

        }
    });
}
</code>```

}

thanks for the help in advance.

答:
You can get the count of wb, ab and alb below, using that you can write the if statement.</p>

```<code>int wbCount = 0,  abCount = 0, albCount = 0;
boolean cs = (cs1 && cs2);

        for(int i=1; i <= 7; i++) {
            if(getIntent().getExtras().getBoolean("wb"+i) && cs) {
                wbCount++;
            }
        }
        for(int i=1; i <= 3; i++) {
            if(getIntent().getExtras().getBoolean("alb"+i) && cs) {
                albCount++;
            }
        }
        for(int i=1; i <= 4; i++) {
            if(getIntent().getExtras().getBoolean("ab"+i) && cs) {
                abCount++;
            }
        }
</code>```

Body:
I am currently coding an android app but I encountered some difficulty.
I am able to receive some checkbox values from another activity using the getIntent().getExtras().getBoolean()function.

But my question is, how can i make sure that checkboxes with the characters 'wb' or 'ab' or 'alb' together with(or not) 'cs' appearing, a count is performed and the one with the greatest value between 'wb', 'ab' and 'alb' is chosen and a summary is displayed via a texfield.

e.g. if there appearances of 'wb' are greater than those of 'alb' and ab, then the result is displayed "you have a widened bronchus".

package com.example.vic.cdmes_;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class results extends AppCompatActivity {
private Button displayResult;

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

}

private void viewResults() {
    final Boolean wb1 = getIntent().getExtras().getBoolean("wb1");
    final Boolean wb2 = getIntent().getExtras().getBoolean("wb2");
    final Boolean wb3 = getIntent().getExtras().getBoolean("wb3");
    final Boolean wb4 = getIntent().getExtras().getBoolean("wb4");
    final Boolean wb5 = getIntent().getExtras().getBoolean("wb5");
    final Boolean wb6 = getIntent().getExtras().getBoolean("wb6");
    final Boolean wb7 = getIntent().getExtras().getBoolean("wb7");
    final Boolean cs1 = getIntent().getExtras().getBoolean("cs1");
    final Boolean cs2 = getIntent().getExtras().getBoolean("cs2");
    final Boolean vb1 = getIntent().getExtras().getBoolean("vb1");
    final Boolean vb2 = getIntent().getExtras().getBoolean("vb2");
    final Boolean vb3 = getIntent().getExtras().getBoolean("vb3");
    final Boolean vb4 = getIntent().getExtras().getBoolean("vb4");
    final Boolean vb5 = getIntent().getExtras().getBoolean("vb5");
    final Boolean alb1 = getIntent().getExtras().getBoolean("alb1");
    final Boolean alb2 = getIntent().getExtras().getBoolean("alb2");
    final Boolean alb3 = getIntent().getExtras().getBoolean("alb3");
    final Boolean ab1 = getIntent().getExtras().getBoolean("ab1");
    final Boolean ab2 = getIntent().getExtras().getBoolean("ab2");
    final Boolean ab3 = getIntent().getExtras().getBoolean("ab3");
    final Boolean ab4 = getIntent().getExtras().getBoolean("ab4");

    displayResult = (Button)findViewById(R.id.displayResults);
    displayResult.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Toast.makeText(results.this,.toString(),
              //      Toast.LENGTH_SHORT).show();
            if(wb1&&wb2&&wb3&&wb4&&wb5&&wb6&&wb7&&cs1&&cs2)
            {
                //if the number of checkboxes exceeds
            }
            else
                if (vb1&&vb2&&vb3&&vb4&&vb5&&cs1&&cs2)
                {
                    //display the person might be having a widened bronchus
                }
                else
                if (alb1&&alb2&&alb3&&cs1&&cs2)
                {
                    //display the person might be having a alb disease
                }
                else
                if (ab1&&ab2&&ab3&&ab4&&cs1&&cs2)
                {
                    //display the person might be having a airborne disease
                }

        }
    });
}

}

thanks for the help in advance.

Body:
You can get the count of wb, ab and alb below, using that you can write the if statement.

int wbCount = 0,  abCount = 0, albCount = 0;
boolean cs = (cs1 && cs2);

        for(int i=1; i <= 7; i++) {
            if(getIntent().getExtras().getBoolean("wb"+i) && cs) {
                wbCount++;
            }
        }
        for(int i=1; i <= 3; i++) {
            if(getIntent().getExtras().getBoolean("alb"+i) && cs) {
                albCount++;
            }
        }
        for(int i=1; i <= 4; i++) {
            if(getIntent().getExtras().getBoolean("ab"+i) && cs) {
                abCount++;
            }
        }


问:
What's the simplest way of returning the larger of two numbers?
Let's say I have an entity that looks like this:

```<code>public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}
</code>```

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}
</code>```

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}
</code>```

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

```<code>public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}
</code>```

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

答:
```<code>public DateTime LastActivity
{
    get
    {
        var picturesMax = Pictures.Max(x => x.LastUpdated);
        return picturesMax > this.LastUpdated
          ? picturesMax
          : this.LastUpdated)
    };
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have an entity that looks like this:

public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.


问:
How to activate ActiveMQ persistence to resist restart?
I do get ActiveMQ supports data persistence (http://activemq.apache.org/persistence.html), but i cannot understand how to make it work, the result is when i restart ActiveMQ all the messages disappear, while queues and topics remain.

I've read about to enable persistence on a database but i want to keep data on the filesystem since my system is facing database perfomance issues.

This is my activemq.xml

```<code><!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- START SNIPPET: example -->
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
  http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core.xsd">

<!-- Allows us to use system properties as variables in this configuration file -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>file:${activemq.conf}/credentials.properties</value>
    </property>
</bean>
<!-- Allows accessing the server log -->
<bean id="logQuery" class="io.fabric8.insight.log.log4j.Log4jLogQuery"
      lazy-init="false" scope="singleton"
      init-method="start" destroy-method="stop">
</bean>

<!--
    The <broker> element is used to configure the ActiveMQ broker.
-->
<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}">

    <destinationPolicy>
        <policyMap>
          <policyEntries>
            <policyEntry topic=">" >
                <!-- The constantPendingMessageLimitStrategy is used to prevent
                     slow topic consumers to block producers and affect other consumers
                     by limiting the number of messages that are retained
                     For more information, see:

                     http://activemq.apache.org/slow-consumer-handling.html

                -->
              <pendingMessageLimitStrategy>
                <constantPendingMessageLimitStrategy limit="1000"/>
              </pendingMessageLimitStrategy>
            </policyEntry>
          </policyEntries>
        </policyMap>
    </destinationPolicy>

    <!--
        The managementContext is used to configure how ActiveMQ is exposed in
        JMX. By default, ActiveMQ uses the MBean server that is started by
        the JVM. For more information, see:

        http://activemq.apache.org/jmx.html
    -->
    <managementContext>
        <managementContext createConnector="false"/>
    </managementContext>

    <!--
        Configure message persistence for the broker. The default persistence
        mechanism is the KahaDB store (identified by the kahaDB tag).
        For more information, see:

        http://activemq.apache.org/persistence.html
    -->
    <persistenceAdapter>
        <kahaDB directory="${activemq.data}/kahadb"/>
    </persistenceAdapter>

      <!--
        The systemUsage controls the maximum amount of space the broker will
        use before disabling caching and/or slowing down producers. For more information, see:
        http://activemq.apache.org/producer-flow-control.html
      -->
      <systemUsage>
        <systemUsage>
            <memoryUsage>
                <memoryUsage percentOfJvmHeap="70" />
            </memoryUsage>
            <storeUsage>
                <storeUsage limit="100 gb"/>
            </storeUsage>
            <tempUsage>
                <tempUsage limit="50 gb"/>
            </tempUsage>
        </systemUsage>
    </systemUsage>

    <!--
        The transport connectors expose ActiveMQ over a given protocol to
        clients and other brokers. For more information, see:

        http://activemq.apache.org/configuring-transports.html
    -->
    <transportConnectors>
        <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
        <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
    </transportConnectors>

    <!-- destroy the spring context on shutdown to stop jetty -->
    <shutdownHooks>
        <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
    </shutdownHooks>

</broker>

<!--
    Enable web consoles, REST and Ajax APIs and demos
    The web consoles requires by default login, you can disable this in the jetty.xml file

    Take a look at ${ACTIVEMQ_HOME}/conf/jetty.xml for more details
-->
<import resource="jetty.xml"/>
</code>```

答: Thanks to all, what i was looking for is to set Quality of Service > 1 for the publisher client, since the default QoS is 0.</p>

Body:
I do get ActiveMQ supports data persistence (http://activemq.apache.org/persistence.html), but i cannot understand how to make it work, the result is when i restart ActiveMQ all the messages disappear, while queues and topics remain.

I've read about to enable persistence on a database but i want to keep data on the filesystem since my system is facing database perfomance issues.

This is my activemq.xml

<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
  http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core.xsd">

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>file:${activemq.conf}/credentials.properties</value>
    </property>
</bean>

<bean id="logQuery" class="io.fabric8.insight.log.log4j.Log4jLogQuery"
      lazy-init="false" scope="singleton"
      init-method="start" destroy-method="stop">
</bean>

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}">

    <destinationPolicy>
        <policyMap>
          <policyEntries>
            <policyEntry topic=">" >

              <pendingMessageLimitStrategy>
                <constantPendingMessageLimitStrategy limit="1000"/>
              </pendingMessageLimitStrategy>
            </policyEntry>
          </policyEntries>
        </policyMap>
    </destinationPolicy>

    <managementContext>
        <managementContext createConnector="false"/>
    </managementContext>

    <persistenceAdapter>
        <kahaDB directory="${activemq.data}/kahadb"/>
    </persistenceAdapter>

      <systemUsage>
        <systemUsage>
            <memoryUsage>
                <memoryUsage percentOfJvmHeap="70" />
            </memoryUsage>
            <storeUsage>
                <storeUsage limit="100 gb"/>
            </storeUsage>
            <tempUsage>
                <tempUsage limit="50 gb"/>
            </tempUsage>
        </systemUsage>
    </systemUsage>

    <transportConnectors>

        <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
        <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
    </transportConnectors>

    <shutdownHooks>
        <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
    </shutdownHooks>

</broker>

<import resource="jetty.xml"/>


问:
Handling several instances of page in Angular + some other stuff
I am building a new application using AngularJS and hereinafter is a simplified description of it.

There is a single working page into which I have pills and tabs (using Bootstrap) along with a side-pane from which I can select from a list of page types and, upon selection, a new pill-tab pair is added (the page is ng-inlcude-ed). Each sub-page type has its own controller (defined using ng-controller at the wrapping div of each page).

This is working OK so far.

Now, suppose that in this context there are three main (sub-)pages that can be invoked from the side-pane: Persons, Houses and Cars, each displaying a list of the relevant object types (i.e. persons, houses or cars).

When viewing, say, the list of persons, the user may click on one of the records and a new pill-tab needs to be created with the details of the person.

Here I have two questions:

How to I pass to the person-details page the unique ID of the selected person?

Since new tabs are created as I select different persons (didn't try this yet), does each INSTANCE of the person-details page have its own context, i.e. $scope, or all instances of person-details page share the same $scope (note that I'm opening several times the same sub-page with the same controller)?

The bottom line is that I need each instance of any sub-page type to be handled within its own context.

Is this the way AngularJS works or do I need to implement some special tricks?

Thank in advance.

答:
From what i have read, your business logic is quite advanced. You could achieve this using bare angular, but it will be hard and messy code. I suggest using ui-router because

Your business logic requires nested states (pills and tabs)

You will produce code that is neat and easy to maintain

It is according to best practices

You will be able to handle each page separately

And as to your questions, please refer to the docs, they will be more useful than mine

Hope, it is useful


问:
R group time column by condition eg. hourly
I have a time column like below.

```<code>Tcol <- as.data.table(c(1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326, "NA"))
Tcol$V1= as.numeric(gsub("\\D+", "", Tcol$V1))
Tcol$V1[is.na(Tcol$V1)] <- 100
Tcol$V1 <- chron::chron(times=Tcol$V1)

Glimpse(Tcol)
Observations: 12
Variables: 1
$ V1 <S3: times> 1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326,  100
</code>```

I would like to group them by 1 hour blocks or 2 hours blocks for plotting.  ie.

```<code>100   1
1200  2
1300  2
1700  3
1900  1
2300  1
</code>```

Searching other solutions on SO, it seems, I should be using cut().  But every time I apply cut(), I get an error.

```<code>table(cut(Tcol$V1, breaks="hour"))
Error in breaks + 1 : non-numeric argument to binary operator
</code>```

I'm unable to find another post with the same issue to solve my issue.  So I'm hoping someone can help.

Body:
I have a time column like below.

Tcol <- as.data.table(c(1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326, "NA"))
Tcol$V1= as.numeric(gsub("\\D+", "", Tcol$V1))
Tcol$V1[is.na(Tcol$V1)] <- 100
Tcol$V1 <- chron::chron(times=Tcol$V1)

Glimpse(Tcol)
Observations: 12
Variables: 1
$ V1 <S3: times> 1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326,  100

I would like to group them by 1 hour blocks or 2 hours blocks for plotting.  ie.

100   1
1200  2
1300  2
1700  3
1900  1
2300  1

Searching other solutions on SO, it seems, I should be using cut().  But every time I apply cut(), I get an error.

table(cut(Tcol$V1, breaks="hour"))
Error in breaks + 1 : non-numeric argument to binary operator

I'm unable to find another post with the same issue to solve my issue.  So I'm hoping someone can help.

Body: Tcol[,.(Count=length(.I)),by=.(Hour=100*floor(V1/100))]


问:
Get push notification as background app on iOS
I am making a certain application.

Which has these functions.

1 This application has push notification.

2 This application can stock the push notification log when it is active.

3 This application can stock the push notification log when it is not active.

1,2 is OK for me. 1 is normal, 2 is accomplished by push notification callback.

However 3...?

I guess on Android background job works and get the notification.

but is it impossible on iOS?

答:
In addition to the previous answer: about didFinishLaunchingWithOptions.
This only works when the program is launched by clicking on the notification/push message window. But if you run the app directly, by clicking on the app icon, even when the notification/push message arrives, you will not receive any data in launchOptions about push message.
So about the paragraph 3: you can know it only if user tap on push message window/bar.


问:
i want to save a list in dictionary in a way that it will have a key and attribute
please help </p>

```<code>value = 'http://localhost:8001/issues/load?project_name=react&since=2016-03-24&until=2017-03-25&state=closed&sort=created&direction=asc&per_page=100&labels=Type:%20Bug'
hashing = hash(value)
words = value.split('&')
for data in words:
    words2 = data.split('=')
    print(words2)
</code>```

答:
Since words2 has each split into two like:

```<code>['http://localhost:8001/issues/load?project_name', 'react']
['since', '2016-03-24']
['until', '2017-03-25']
</code>```

Use that to add values to a dictionary:

```<code>>>> key_vals = {}
>>> for data in words:
...     words2 = data.split('=')
...     key_vals[words2[0]] = words2[1]
...
>>> pprint.pprint(key_vals)
{'direction': 'asc',
 'http://localhost:8001/issues/load?project_name': 'react',
 'labels': 'Type:%20Bug',
 'per_page': '100',
 'since': '2016-03-24',
 'sort': 'created',
 'state': 'closed',
 'until': '2017-03-25'}
</code>```

And the assignment to key_vals can be reduced to:

```<code>key_vals = {key: val for (key, val) in [data.split('=') for data in words]}
</code>```

Body:
please help

value = 'http://localhost:8001/issues/load?project_name=react&since=2016-03-24&until=2017-03-25&state=closed&sort=created&direction=asc&per_page=100&labels=Type:%20Bug'
hashing = hash(value)
words = value.split('&')
for data in words:
    words2 = data.split('=')
    print(words2)

Body:
Since words2 has each split into two like:

['http://localhost:8001/issues/load?project_name', 'react']
['since', '2016-03-24']
['until', '2017-03-25']

Use that to add values to a dictionary:

>>> key_vals = {}
>>> for data in words:
...     words2 = data.split('=')
...     key_vals[words2[0]] = words2[1]
...
>>> pprint.pprint(key_vals)
{'direction': 'asc',
 'http://localhost:8001/issues/load?project_name': 'react',
 'labels': 'Type:%20Bug',
 'per_page': '100',
 'since': '2016-03-24',
 'sort': 'created',
 'state': 'closed',
 'until': '2017-03-25'}

And the assignment to key_vals can be reduced to:

key_vals = {key: val for (key, val) in [data.split('=') for data in words]}


问:
How can I write the query as raw in Laravel?
Here is my query:

```<code>SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");
</code>```

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

```<code>DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();
</code>```

答:
Try This</p>

```<code>DB::table('relations')
->whereIn('rootid', [736, 781])
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();
</code>```

Body:
Here is my query:

SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();

Body:
Try This

DB::table('relations')
->whereIn('rootid', [736, 781])
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();


问:
Octopus gem not working with active record relation
Recently we thought of using slave databases for few of our search / read operations . We do not have any plans to send all our read request to slaves. We just want to few of our search queries to hit to slave databases

I tried almost all the available gems, octopus, octoshark, db-charmer, makara, knockoff , But none of them are working correctly.

For example on Octopus (other gems too), below is a big issue

Octopus.using(:slave1) do User.first end .

This works fine and uses "slave1".

But not sure why the below is not working .

Octopus.using(:slave1) do User.where(id: 1) end

This one is not using slave1 but it fires on master database and most of our search queries are in this format.

It's quite frustrating till now. Any help would be greatly appreciated.

答:
After a lot struggle, I found that User.where(id: 1) just creates a active record relation, but the query gets executed outside of the octopus. So when I did User.where(id: 1).to_a, magically everything started working fine for me.

I tried with multiple most of them works with this trick. It took a lot of time for me to figure out.


问:
slider not working inside tab inside tab content
Im building a web app using the NativeDroid . Everything seems to be working fine but inside a tab panel, when i add a slider it doesnt work.

But it works when i refresh. But when i click the link through the menu it doesnt work until i refresh it

I have uploaded the pages over here Demo from the menu when u click on profile you will see the slider is not working.. There are no jquery errors on my console too.

below is code that i have used for the slider and a chart

```<code>$(document).on("pagecreate", ".page_bubble", function () {
 $('.demo').percentcircle({

                animate: true,
                diameter: 100,
                guage: 2,
                coverBg: '#f4f8f9',
                bgColor: '#f4f8f9',
                fillColor: '#5c93c8',
                percentSize: '19px',
                percentWeight: 'normal'

            });
            $("#owl-demo").owlCarousel({

                navigation: true, // Show next and prev buttons
                slideSpeed: 300,
                paginationSpeed: 400,
                singleItem: true,
                navigationText: ['']

            });

        });
</code>```

Can someone tell me what might be causing it?

答:
```<code>el.on("click",".nd2Tabs-nav-item:not('.nd2Tabs-active')",function(e) {
    e.preventDefault();
    _self.switchTab($(this),$(this).data('tab'),$(".nd2Tabs-nav-item").index($(this)[0]));
});
</code>```

This is the event in nativedroid2.js where you need to add your percentcircle and owlCarousel binding event as below as @rory-mccrossan said on page load content doesn't exist that's reason it's not working change you js like below

```<code>el.on("click",".nd2Tabs-nav-item:not('.nd2Tabs-active')",function(e) {
    e.preventDefault();
    _self.switchTab($(this),$(this).data('tab'),$(".nd2Tabs-nav-item").index($(this)[0]));
    $('.demo').percentcircle({

     animate: true,
     diameter: 100,
     guage: 2,
     coverBg: '#f4f8f9',
     bgColor: '#f4f8f9',
     fillColor: '#5c93c8',
     percentSize: '19px',
     percentWeight: 'normal'
   });
   $("#owl-demo").owlCarousel({
      navigation: true,
      slideSpeed: 300,
      paginationSpeed: 400,
      singleItem: true,
      navigationText: ['']
  });

});
</code>```

Or You can make a delegate event and trigger that event here for more info please find This Answer

Body:
Im building a web app using the NativeDroid . Everything seems to be working fine but inside a tab panel, when i add a slider it doesnt work.

But it works when i refresh. But when i click the link through the menu it doesnt work until i refresh it

I have uploaded the pages over here Demo from the menu when u click on profile you will see the slider is not working.. There are no jquery errors on my console too.

below is code that i have used for the slider and a chart

$(document).on("pagecreate", ".page_bubble", function () {
 $('.demo').percentcircle({

                animate: true,
                diameter: 100,
                guage: 2,
                coverBg: '#f4f8f9',
                bgColor: '#f4f8f9',
                fillColor: '#5c93c8',
                percentSize: '19px',
                percentWeight: 'normal'

            });
            $("#owl-demo").owlCarousel({

                navigation: true, // Show next and prev buttons
                slideSpeed: 300,
                paginationSpeed: 400,
                singleItem: true,
                navigationText: ['']

            });

        });

Can someone tell me what might be causing it?

Body:
el.on("click",".nd2Tabs-nav-item:not('.nd2Tabs-active')",function(e) {
    e.preventDefault();
    _self.switchTab($(this),$(this).data('tab'),$(".nd2Tabs-nav-item").index($(this)[0]));
});

This is the event in nativedroid2.js where you need to add your percentcircle and owlCarousel binding event as below as @rory-mccrossan said on page load content doesn't exist that's reason it's not working change you js like below

el.on("click",".nd2Tabs-nav-item:not('.nd2Tabs-active')",function(e) {
    e.preventDefault();
    _self.switchTab($(this),$(this).data('tab'),$(".nd2Tabs-nav-item").index($(this)[0]));
    $('.demo').percentcircle({

     animate: true,
     diameter: 100,
     guage: 2,
     coverBg: '#f4f8f9',
     bgColor: '#f4f8f9',
     fillColor: '#5c93c8',
     percentSize: '19px',
     percentWeight: 'normal'
   });
   $("#owl-demo").owlCarousel({
      navigation: true,
      slideSpeed: 300,
      paginationSpeed: 400,
      singleItem: true,
      navigationText: ['']
  });

});

Or You can make a delegate event and trigger that event here for more info please find This Answer


问:
FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri()) return null on Facebook
I've developed an mvc 5 application using nopcommerce and i use facebook login using External callback it was working but now it is not working and i can't find out actual problem. And using this below code

this.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

and it's returning me always null and authentication status failed i searched on web an do every thing and followed that steps but still i can't login with facebook.

My code is like this in FacebookProviderAuthorizer.cs

```<code>private AuthorizeState VerifyAuthentication(string returnUrl)
{
   var authResult = DotNetOpenAuth.AspNet.Clients.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

   if (authResult.IsSuccessful)
   {
   }
}
</code>```

And then write Call back method

```<code>private Uri GenerateLocalCallbackUri()
{
    string url = string.Format("{0}plugins/externalauthFacebook/logincallback/", _webHelper.GetStoreLocation());
    return new Uri(url);
}
</code>```

Then generate service login url

```<code>private Uri GenerateServiceLoginUrl()
{
   //code copied from DotNetOpenAuth.AspNet.Clients.FacebookClient file
   var builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
   var args = new Dictionary<string, string>();
   args.Add("client_id", _facebookExternalAuthSettings.ClientKeyIdentifier);
   args.Add("redirect_uri", GenerateLocalCallbackUri().AbsoluteUri);
   args.Add("response_type", "token");
   args.Add("scope", "email");
   AppendQueryArgs(builder, args);
   return builder.Uri;
}
</code>```

答:
I solve my issue I will do the same thing as @Adam described in his answer, As per the @Adam, @SteveTerry and @Adeem's answer i change my code and create custom FacebookClient class with different name. and replace with original reference of FacebookClient in nopCommerce.

```<code>public class FacebookOAuth2Client : OAuth2Client
    {
        #region Constants and Fields

        /// <summary>
        /// The authorization endpoint.
        /// </summary>
        private const string AuthorizationEndpoint = "https://www.facebook.com/dialog/oauth";

        /// <summary>
        /// The token endpoint.
        /// </summary>
        private const string TokenEndpoint = "https://graph.facebook.com/oauth/access_token";

        /// <summary>
        /// The user info endpoint.
        /// </summary>
        private const string UserInfoEndpoint = "https://graph.facebook.com/me";

        /// <summary>
        /// The app id.
        /// </summary>
        private readonly string _appId;

        /// <summary>
        /// The app secret.
        /// </summary>
        private readonly string _appSecret;

        /// <summary>
        /// The requested scopes.
        /// </summary>
        private readonly string[] _requestedScopes;

        #endregion

        /// <summary>
        /// Creates a new Facebook OAuth2 client, requesting the default "email" scope.
        /// </summary>
        /// <param name="appId">The Facebook App Id</param>
        /// <param name="appSecret">The Facebook App Secret</param>
        public FacebookClient(string appId, string appSecret)
            : this(appId, appSecret, new[] { "email" }) { }

        /// <summary>
        /// Creates a new Facebook OAuth2 client.
        /// </summary>
        /// <param name="appId">The Facebook App Id</param>
        /// <param name="appSecret">The Facebook App Secret</param>
        /// <param name="requestedScopes">One or more requested scopes, passed without the base URI.</param>
        public FacebookClient(string appId, string appSecret, params string[] requestedScopes)
            : base("facebook")
        {
            if (string.IsNullOrWhiteSpace(appId))
                throw new ArgumentNullException("appId");

            if (string.IsNullOrWhiteSpace(appSecret))
                throw new ArgumentNullException("appSecret");

            if (requestedScopes == null)
                throw new ArgumentNullException("requestedScopes");

            if (requestedScopes.Length == 0)
                throw new ArgumentException("One or more scopes must be requested.", "requestedScopes");

            _appId = appId;
            _appSecret = appSecret;
            _requestedScopes = requestedScopes;
        }

        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var state = string.IsNullOrEmpty(returnUrl.Query) ? string.Empty : returnUrl.Query.Substring(1);

            return BuildUri(AuthorizationEndpoint, new NameValueCollection
                {
                    { "client_id", _appId },
                    { "scope", string.Join(" ", _requestedScopes) },
                    { "redirect_uri", returnUrl.GetLeftPart(UriPartial.Path) },
                    { "state", state },
                });
        }

        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            var uri = BuildUri(UserInfoEndpoint, new NameValueCollection { { "access_token", accessToken } });

            var webRequest = (HttpWebRequest)WebRequest.Create(uri);

            using (var webResponse = webRequest.GetResponse())
            using (var stream = webResponse.GetResponseStream())
            {
                if (stream == null)
                    return null;

                using (var textReader = new StreamReader(stream))
                {
                    var json = textReader.ReadToEnd();
                    var extraData = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                    var data = extraData.ToDictionary(x => x.Key, x => x.Value.ToString());

                    data.Add("picture", string.Format("https://graph.facebook.com/{0}/picture", data["id"]));

                    return data;
                }
            }
        }

        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            var uri = BuildUri(TokenEndpoint, new NameValueCollection
                {
                    { "code", authorizationCode },
                    { "client_id", _appId },
                    { "client_secret", _appSecret },
                    { "redirect_uri", returnUrl.GetLeftPart(UriPartial.Path) },
                });

            var webRequest = (HttpWebRequest)WebRequest.Create(uri);
            string accessToken = null;
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            // handle response from FB
            // this will not be a url with params like the first request to get the 'code'
            Encoding rEncoding = Encoding.GetEncoding(response.CharacterSet);

            using (StreamReader sr = new StreamReader(response.GetResponseStream(), rEncoding))
            {
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
                var jConvert = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(jsonObject));

                Dictionary<string, object> desirializedJsonObject = JsonConvert.DeserializeObject<Dictionary<string, object>>(jConvert.ToString());
                accessToken = desirializedJsonObject["access_token"].ToString();
            }
            return accessToken;
        }

        private static Uri BuildUri(string baseUri, NameValueCollection queryParameters)
        {
            var keyValuePairs = queryParameters.AllKeys.Select(k => HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(queryParameters[k]));
            var qs = String.Join("&", keyValuePairs);

            var builder = new UriBuilder(baseUri) { Query = qs };
            return builder.Uri;
        }

        /// <summary>
        /// Facebook works best when return data be packed into a "state" parameter.
        /// This should be called before verifying the request, so that the url is rewritten to support this.
        /// </summary>
        public static void RewriteRequest()
        {
            var ctx = HttpContext.Current;

            var stateString = HttpUtility.UrlDecode(ctx.Request.QueryString["state"]);
            if (stateString == null || !stateString.Contains("__provider__=facebook"))
                return;

            var q = HttpUtility.ParseQueryString(stateString);
            q.Add(ctx.Request.QueryString);
            q.Remove("state");

            ctx.RewritePath(ctx.Request.Path + "?" + q);
        }
    }
</code>```

in this code i have no reference of JsonHelper so i use simple jsonConvert. Thanx again @Adam, @SteveTerry and @Adeem's for help.

Body:
I've developed an mvc 5 application using nopcommerce and i use facebook login using External callback it was working but now it is not working and i can't find out actual problem. And using this below code

this.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

and it's returning me always null and authentication status failed i searched on web an do every thing and followed that steps but still i can't login with facebook.

My code is like this in FacebookProviderAuthorizer.cs

private AuthorizeState VerifyAuthentication(string returnUrl)
{
   var authResult = DotNetOpenAuth.AspNet.Clients.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

   if (authResult.IsSuccessful)
   {
   }
}

And then write Call back method

private Uri GenerateLocalCallbackUri()
{
    string url = string.Format("{0}plugins/externalauthFacebook/logincallback/", _webHelper.GetStoreLocation());
    return new Uri(url);
}

Then generate service login url

private Uri GenerateServiceLoginUrl()
{
   //code copied from DotNetOpenAuth.AspNet.Clients.FacebookClient file
   var builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
   var args = new Dictionary<string, string>();
   args.Add("client_id", _facebookExternalAuthSettings.ClientKeyIdentifier);
   args.Add("redirect_uri", GenerateLocalCallbackUri().AbsoluteUri);
   args.Add("response_type", "token");
   args.Add("scope", "email");
   AppendQueryArgs(builder, args);
   return builder.Uri;
}

Body:
I solve my issue I will do the same thing as @Adam described in his answer, As per the @Adam, @SteveTerry and @Adeem's answer i change my code and create custom FacebookClient class with different name. and replace with original reference of FacebookClient in nopCommerce.

public class FacebookOAuth2Client : OAuth2Client
    {
        #region Constants and Fields

        /// <summary>
        /// The authorization endpoint.
        /// </summary>
        private const string AuthorizationEndpoint = "https://www.facebook.com/dialog/oauth";

        /// <summary>
        /// The token endpoint.
        /// </summary>
        private const string TokenEndpoint = "https://graph.facebook.com/oauth/access_token";

        /// <summary>
        /// The user info endpoint.
        /// </summary>
        private const string UserInfoEndpoint = "https://graph.facebook.com/me";

        /// <summary>
        /// The app id.
        /// </summary>
        private readonly string _appId;

        /// <summary>
        /// The app secret.
        /// </summary>
        private readonly string _appSecret;

        /// <summary>
        /// The requested scopes.
        /// </summary>
        private readonly string[] _requestedScopes;

        #endregion

        /// <summary>
        /// Creates a new Facebook OAuth2 client, requesting the default "email" scope.
        /// </summary>
        /// <param name="appId">The Facebook App Id</param>
        /// <param name="appSecret">The Facebook App Secret</param>
        public FacebookClient(string appId, string appSecret)
            : this(appId, appSecret, new[] { "email" }) { }

        /// <summary>
        /// Creates a new Facebook OAuth2 client.
        /// </summary>
        /// <param name="appId">The Facebook App Id</param>
        /// <param name="appSecret">The Facebook App Secret</param>
        /// <param name="requestedScopes">One or more requested scopes, passed without the base URI.</param>
        public FacebookClient(string appId, string appSecret, params string[] requestedScopes)
            : base("facebook")
        {
            if (string.IsNullOrWhiteSpace(appId))
                throw new ArgumentNullException("appId");

            if (string.IsNullOrWhiteSpace(appSecret))
                throw new ArgumentNullException("appSecret");

            if (requestedScopes == null)
                throw new ArgumentNullException("requestedScopes");

            if (requestedScopes.Length == 0)
                throw new ArgumentException("One or more scopes must be requested.", "requestedScopes");

            _appId = appId;
            _appSecret = appSecret;
            _requestedScopes = requestedScopes;
        }

        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var state = string.IsNullOrEmpty(returnUrl.Query) ? string.Empty : returnUrl.Query.Substring(1);

            return BuildUri(AuthorizationEndpoint, new NameValueCollection
                {
                    { "client_id", _appId },
                    { "scope", string.Join(" ", _requestedScopes) },
                    { "redirect_uri", returnUrl.GetLeftPart(UriPartial.Path) },
                    { "state", state },
                });
        }

        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            var uri = BuildUri(UserInfoEndpoint, new NameValueCollection { { "access_token", accessToken } });

            var webRequest = (HttpWebRequest)WebRequest.Create(uri);

            using (var webResponse = webRequest.GetResponse())
            using (var stream = webResponse.GetResponseStream())
            {
                if (stream == null)
                    return null;

                using (var textReader = new StreamReader(stream))
                {
                    var json = textReader.ReadToEnd();
                    var extraData = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                    var data = extraData.ToDictionary(x => x.Key, x => x.Value.ToString());

                    data.Add("picture", string.Format("https://graph.facebook.com/{0}/picture", data["id"]));

                    return data;
                }
            }
        }

        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            var uri = BuildUri(TokenEndpoint, new NameValueCollection
                {
                    { "code", authorizationCode },
                    { "client_id", _appId },
                    { "client_secret", _appSecret },
                    { "redirect_uri", returnUrl.GetLeftPart(UriPartial.Path) },
                });

            var webRequest = (HttpWebRequest)WebRequest.Create(uri);
            string accessToken = null;
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            // handle response from FB
            // this will not be a url with params like the first request to get the 'code'
            Encoding rEncoding = Encoding.GetEncoding(response.CharacterSet);

            using (StreamReader sr = new StreamReader(response.GetResponseStream(), rEncoding))
            {
                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
                var jConvert = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(jsonObject));

                Dictionary<string, object> desirializedJsonObject = JsonConvert.DeserializeObject<Dictionary<string, object>>(jConvert.ToString());
                accessToken = desirializedJsonObject["access_token"].ToString();
            }
            return accessToken;
        }

        private static Uri BuildUri(string baseUri, NameValueCollection queryParameters)
        {
            var keyValuePairs = queryParameters.AllKeys.Select(k => HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(queryParameters[k]));
            var qs = String.Join("&", keyValuePairs);

            var builder = new UriBuilder(baseUri) { Query = qs };
            return builder.Uri;
        }

        /// <summary>
        /// Facebook works best when return data be packed into a "state" parameter.
        /// This should be called before verifying the request, so that the url is rewritten to support this.
        /// </summary>
        public static void RewriteRequest()
        {
            var ctx = HttpContext.Current;

            var stateString = HttpUtility.UrlDecode(ctx.Request.QueryString["state"]);
            if (stateString == null || !stateString.Contains("__provider__=facebook"))
                return;

            var q = HttpUtility.ParseQueryString(stateString);
            q.Add(ctx.Request.QueryString);
            q.Remove("state");

            ctx.RewritePath(ctx.Request.Path + "?" + q);
        }
    }

in this code i have no reference of JsonHelper so i use simple jsonConvert. Thanx again @Adam, @SteveTerry and @Adeem's for help.


问:
Where is Smalltalk-80 best used?
I want to know in which applications/programming domain are most suitable for Smalltalk. Could anyone please provide me some useful links that could answer my query?

Through googling I learned that some companies use it for:

logistics and foreign trade application

desktop, server and script development

data processing and logistics, scripts and presentations

but I cant find documents/research papers that can tell me which programming domain Smalltalk-80 (or Smalltalk) is best suited.

Some of the programming domains are:
 - Artificial intelligence reasoning
 - General purpose applications
 - Financial time series analysis
 - Natural language processing
 - Relational database querying
 - Application scripting
 - Internet
 - Symbolic mathematics
 - Numerical mathematics
 - Statistical applications
 - Text processing
 - Matrix algorithms

I hope you guys can help me. I am doing this for my case study. Thanks in advance.

答:
The domains you named are all suitable for Smalltalk. Smalltalk shows its strengths in development for systems that are engineering-time limited, instead of hardware-limited.

The Seaside web framework allows us to create complex web applications in a fraction of the time needed in other technologies. The Gemstone object-oriented database allows us to nearly ignore persistence issues.

Title: Where is Smalltalk-80 best used?


答:
You can use very fast numpy.argsort for change columns names by sorted values per row:

```<code>print (np.argsort(-df.values, axis=1))
[[4 3 2 1 0]
 [4 3 1 2 0]
 [3 0 1 2 4]
 [3 4 1 2 0]
 [1 2 4 3 0]
 [0 2 1 3 4]
 [0 3 2 1 4]
 [1 3 0 4 2]
 [1 4 0 3 2]
 [0 2 4 3 1]]

print (df.columns[np.argsort(-df.values, axis=1)])
Index([['TWTR', 'TSLA', 'ATVI', 'GOOG', 'DB'],
       ['TWTR', 'TSLA', 'GOOG', 'ATVI', 'DB'],
       ['TSLA', 'DB', 'GOOG', 'ATVI', 'TWTR'],
       ['TSLA', 'TWTR', 'GOOG', 'ATVI', 'DB'],
       ['GOOG', 'ATVI', 'TWTR', 'TSLA', 'DB'],
       ['DB', 'ATVI', 'GOOG', 'TSLA', 'TWTR'],
       ['DB', 'TSLA', 'ATVI', 'GOOG', 'TWTR'],
       ['GOOG', 'TSLA', 'DB', 'TWTR', 'ATVI'],
       ['GOOG', 'TWTR', 'DB', 'TSLA', 'ATVI'],
       ['DB', 'ATVI', 'TWTR', 'TSLA', 'GOOG']],
      dtype='object')
</code>```

```<code>df = pd.DataFrame(df.columns[np.argsort(-df.values, axis=1)][:,[0,1,-1]], index=df.index)
df.columns = ['largest','second largest','smallest']
print (df)
     largest second largest smallest
1.0     TWTR           TSLA       DB
2.0     TWTR           TSLA       DB
3.0     TSLA             DB     TWTR
4.0     TSLA           TWTR       DB
5.0     GOOG           ATVI       DB
6.0       DB           ATVI     TWTR
7.0       DB           TSLA     TWTR
8.0     GOOG           TSLA     ATVI
9.0     GOOG           TWTR     ATVI
10.0      DB           ATVI     GOOG
</code>```

Another solutions (slowier) with apply and custom function where sort each row and get indexes:

```<code>def f(x):
    x = x.sort_values()
    return pd.Series([x.index[-1], x.index[-2], x.index[0]],
                     index=['largest','second largest','smallest'])

df = df.apply(f ,axis=1)
print (df)
     largest second largest smallest
1.0     TWTR           TSLA       DB
2.0     TWTR           TSLA       DB
3.0     TSLA             DB     TWTR
4.0     TSLA           TWTR       DB
5.0     GOOG           ATVI       DB
6.0       DB           ATVI     TWTR
7.0       DB           TSLA     TWTR
8.0     GOOG           TSLA     ATVI
9.0     GOOG           TWTR     ATVI
10.0      DB           ATVI     GOOG
</code>```

```<code>df = df.apply(lambda x: x.sort_values().index ,axis=1)
df = df.iloc[:, [-1,-2,0]]
df.columns = ['largest','second largest','smallest']
print (df)
     largest second largest smallest
1.0     TWTR           TSLA       DB
2.0     TWTR           TSLA       DB
3.0     TSLA             DB     TWTR
4.0     TSLA           TWTR       DB
5.0     GOOG           ATVI       DB
6.0       DB           ATVI     TWTR
7.0       DB           TSLA     TWTR
8.0     GOOG           TSLA     ATVI
9.0     GOOG           TWTR     ATVI
10.0      DB           ATVI     GOOG
</code>```

Timings:

```<code>#[10000 rows x 5 columns]
df = pd.concat([df]*1000).reset_index(drop=True)
</code>```

```<code>In [357]: %timeit pd.DataFrame(df.columns[np.argsort(-df.values, axis=1)][:,[0,1,-1]], index=df.index, columns=['largest','second largest','smallest'])
1000 loops, best of 3: 974 µs per loop

In [358]: %timeit df.apply(f ,axis=1)
1 loop, best of 3: 3.91 s per loop

In [361]: %timeit df.apply(lambda x: x.sort_values().index ,axis=1).iloc[:, [-1,-2,0]]
1 loop, best of 3: 1.88 s per loop

In [362]: %timeit df.apply(lambda x: x.sort_values().index.to_series().iloc[0], axis=1)
1 loop, best of 3: 2.47 s per loop

In [363]: %timeit df.apply(lambda x: x.sort_values(ascending=False).index.to_series().iloc[0], axis=1)
1 loop, best of 3: 2.51 s per loop

In [364]: %timeit df.apply(lambda x: x.sort_values(ascending=False).index.to_series().iloc[1], axis=1)
1 loop, best of 3: 2.52 s per loop

In [365]: %timeit [df.T.sort_values(by=k).T.keys()[-1] for k in df.T.keys()]
1 loop, best of 3: 6.42 s per loop
</code>```

Title: Select column of pandas dataframe based on value

Body:
I have a quite simple issue which I can't get solved:

I have a dataframe which looks like the following:

               DB         GOOG        ATVI         TSLA        TWTR
1.0    -0.0129755  -0.00463688 -0.00408223    0.0653678   0.0779629
2.0     -0.052772  -0.00712359  -0.0120323    0.0230537   0.0245435
3.0    0.00875274   0.00762426  0.00176186    0.0834672  -0.0017326
4.0    -0.0125196   0.00657628 -0.00235884    0.0502074   0.0157572
5.0    -0.0470443  -0.00382168  -0.0153009   -0.0325997  -0.0235564
6.0     0.0140261  -0.00630647 -0.00265291    -0.037598  -0.0454938
7.0   0.000624415  -0.00429897 -0.00088587 -9.73558e-05  -0.0216945
8.0    -0.0138933  -0.00455289   -0.027357  -0.00682128  -0.0186916
9.0   -0.00311624 -0.000168211  -0.0100577  -0.00894537 -0.00181214
10.0    0.0864933    0.0151531     0.05061    0.0294589   0.0395802

For every row I want to find the column name corresponding to the largest, second largest and smallest value.

Example:

For the first row (index 1.0) I want to extract TWTR (largest value), TSLA (second largest value) and DB (smallest value).

...

For the fifth row (index 5.0) I want to extract GOOG (largest value), ATVI (second largest value) and DB (smallest value)

.. and so on.

What is the simplest way to do this? Thanks!

Body:
You can use very fast numpy.argsort for change columns names by sorted values per row:

print (np.argsort(-df.values, axis=1))
[[4 3 2 1 0]
 [4 3 1 2 0]
 [3 0 1 2 4]
 [3 4 1 2 0]
 [1 2 4 3 0]
 [0 2 1 3 4]
 [0 3 2 1 4]
 [1 3 0 4 2]
 [1 4 0 3 2]
 [0 2 4 3 1]]

print (df.columns[np.argsort(-df.values, axis=1)])
Index([['TWTR', 'TSLA', 'ATVI', 'GOOG', 'DB'],
       ['TWTR', 'TSLA', 'GOOG', 'ATVI', 'DB'],
       ['TSLA', 'DB', 'GOOG', 'ATVI', 'TWTR'],
       ['TSLA', 'TWTR', 'GOOG', 'ATVI', 'DB'],
       ['GOOG', 'ATVI', 'TWTR', 'TSLA', 'DB'],
       ['DB', 'ATVI', 'GOOG', 'TSLA', 'TWTR'],
       ['DB', 'TSLA', 'ATVI', 'GOOG', 'TWTR'],
       ['GOOG', 'TSLA', 'DB', 'TWTR', 'ATVI'],
       ['GOOG', 'TWTR', 'DB', 'TSLA', 'ATVI'],
       ['DB', 'ATVI', 'TWTR', 'TSLA', 'GOOG']],
      dtype='object')

df = pd.DataFrame(df.columns[np.argsort(-df.values, axis=1)][:,[0,1,-1]], index=df.index)
df.columns = ['largest','second largest','smallest']
print (df)
     largest second largest smallest
1.0     TWTR           TSLA       DB
2.0     TWTR           TSLA       DB
3.0     TSLA             DB     TWTR
4.0     TSLA           TWTR       DB
5.0     GOOG           ATVI       DB
6.0       DB           ATVI     TWTR
7.0       DB           TSLA     TWTR
8.0     GOOG           TSLA     ATVI
9.0     GOOG           TWTR     ATVI
10.0      DB           ATVI     GOOG

Another solutions (slowier) with apply and custom function where sort each row and get indexes:

def f(x):
    x = x.sort_values()
    return pd.Series([x.index[-1], x.index[-2], x.index[0]],
                     index=['largest','second largest','smallest'])

df = df.apply(f ,axis=1)
print (df)
     largest second largest smallest
1.0     TWTR           TSLA       DB
2.0     TWTR           TSLA       DB
3.0     TSLA             DB     TWTR
4.0     TSLA           TWTR       DB
5.0     GOOG           ATVI       DB
6.0       DB           ATVI     TWTR
7.0       DB           TSLA     TWTR
8.0     GOOG           TSLA     ATVI
9.0     GOOG           TWTR     ATVI
10.0      DB           ATVI     GOOG

df = df.apply(lambda x: x.sort_values().index ,axis=1)
df = df.iloc[:, [-1,-2,0]]
df.columns = ['largest','second largest','smallest']
print (df)
     largest second largest smallest
1.0     TWTR           TSLA       DB
2.0     TWTR           TSLA       DB
3.0     TSLA             DB     TWTR
4.0     TSLA           TWTR       DB
5.0     GOOG           ATVI       DB
6.0       DB           ATVI     TWTR
7.0       DB           TSLA     TWTR
8.0     GOOG           TSLA     ATVI
9.0     GOOG           TWTR     ATVI
10.0      DB           ATVI     GOOG

Timings:

#[10000 rows x 5 columns]
df = pd.concat([df]*1000).reset_index(drop=True)

In [357]: %timeit pd.DataFrame(df.columns[np.argsort(-df.values, axis=1)][:,[0,1,-1]], index=df.index, columns=['largest','second largest','smallest'])
1000 loops, best of 3: 974 µs per loop

In [358]: %timeit df.apply(f ,axis=1)
1 loop, best of 3: 3.91 s per loop

In [361]: %timeit df.apply(lambda x: x.sort_values().index ,axis=1).iloc[:, [-1,-2,0]]
1 loop, best of 3: 1.88 s per loop

In [362]: %timeit df.apply(lambda x: x.sort_values().index.to_series().iloc[0], axis=1)
1 loop, best of 3: 2.47 s per loop

In [363]: %timeit df.apply(lambda x: x.sort_values(ascending=False).index.to_series().iloc[0], axis=1)
1 loop, best of 3: 2.51 s per loop

In [364]: %timeit df.apply(lambda x: x.sort_values(ascending=False).index.to_series().iloc[1], axis=1)
1 loop, best of 3: 2.52 s per loop

In [365]: %timeit [df.T.sort_values(by=k).T.keys()[-1] for k in df.T.keys()]
1 loop, best of 3: 6.42 s per loop


问:
C# Short , Byte Takes 4 Byte in x86
This is the code i use in x86 and x64

```<code>static unsafe void Main(string[] args)
    {
        short a = 4;

        short b = 5;

        short* x = &a;
        short* y = &b;

        Console.WriteLine((int)x);
        Console.WriteLine((int)y);

        Console.ReadLine();

    }
</code>```

for x86 i am getting answer like " xxxxx224  xxxxx220"
for x64 i am getting answer like " xxxxx000  xxxxx002"

Why is the Short , Byte , Bool Taking 4 bytes in x86 and Normal on x64

答: That is the memory address of the short values that you are outputting. You are getting 32-bit values as presumably your program is compiled as a 32-bit application.</p>

Title: C# Short , Byte Takes 4 Byte in x86

Body:
This is the code i use in x86 and x64

static unsafe void Main(string[] args)
    {
        short a = 4;

        short b = 5;

        short* x = &a;
        short* y = &b;

        Console.WriteLine((int)x);
        Console.WriteLine((int)y);

        Console.ReadLine();

    }

for x86 i am getting answer like " xxxxx224  xxxxx220"
for x64 i am getting answer like " xxxxx000  xxxxx002"

Why is the Short , Byte , Bool Taking 4 bytes in x86 and Normal on x64


问:
Open 2 bootstrap dropdown within single parent dropdown class but 2 different dropdowns
I have 2 dropdown menu items under single parent dropdown class. But when I click dropdown action 1 then it is showing the body of dropdown menu 2 items.

```<code><!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">     </script>
</head>
<body>

<div class="container">
  <h2>Dropdown Example</h2>
  <p>The <strong>toggle</strong> method toggles the dropdown.</p>

  <div class="dropdown">

    <button class="btn btn-primary dropdown-toggle" id="menu1" type="button" data-toggle="dropdown">Dropdown Example 1
    <span class="caret"></span></button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">HTML</a></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">CSS</a></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">JavaScript</a></li>
      <li role="presentation" class="divider"></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">About Us</a></li>
    </ul>
    <br>
    <br>

    <button class="btn btn-primary dropdown-toggle" id="menu2" type="button" data-toggle="dropdown">Dropdown Example 2
    <span class="caret"></span></button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu2">
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">HTML</a></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">CSS</a></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">JavaScript</a></li>
      <li role="presentation" class="divider"></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">About Us</a></li>
    </ul>
  </div><br>
  <p><strong>Note:</strong> For dropdowns, you should always include the data-toggle="dropdown" attribute. Do not rely solely on the toggle method, as it may not work as expected in all browsers.</p>
</div>

<script>
$(document).ready(function(){
    $(".dropdown-toggle").dropdown("toggle");
});
</script>

</body>
</html>
</code>```

Here is the fiddle link: https://jsfiddle.net/ajay1008/jumpgkfc/

So I want to open their respective body dropdown-menus.

答:
you must wrap each dropdown button in another .btn-group.

```<code> <div class="btn-group">  <button class="btn btn-primary dropdown-toggle" id="menu1" type="button" data-toggle="dropdown" open'">Dropdown Example 1
<span class="caret"></span></button>...</div>
</code>```

mycode(you can copy this code):
https://jsfiddle.net/rezajafari2a/c1yw3hbv/

Body:
I have 2 dropdown menu items under single parent dropdown class. But when I click dropdown action 1 then it is showing the body of dropdown menu 2 items.

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dropdown Example

The toggle method toggles the dropdown.

    <button class="btn btn-primary dropdown-toggle" id="menu1" type="button" data-toggle="dropdown">Dropdown Example 1
    </button>

HTML

CSS

JavaScript

About Us

    <button class="btn btn-primary dropdown-toggle" id="menu2" type="button" data-toggle="dropdown">Dropdown Example 2
    </button>

HTML

CSS

JavaScript

About Us

Note: For dropdowns, you should always include the data-toggle="dropdown" attribute. Do not rely solely on the toggle method, as it may not work as expected in all browsers.

Here is the fiddle link: https://jsfiddle.net/ajay1008/jumpgkfc/

So I want to open their respective body dropdown-menus.

Body:
you must wrap each dropdown button in another .btn-group.

 <div class="btn-group">  <button class="btn btn-primary dropdown-toggle" id="menu1" type="button" data-toggle="dropdown" open'">Dropdown Example 1
<span class="caret"></span></button>...</div>

mycode(you can copy this code):
https://jsfiddle.net/rezajafari2a/c1yw3hbv/


问:
Mapping through an array of objects in javascript
i have an array of objects like this:

```<code>[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]
</code>```

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)

答:
Use any iterator like forEach, for etc to iterate the data, and use two object variables, one will store the buy data and other will store sell data.

Write it like this:

var data = [{side: 'Buy', price: 100}, {side: 'Buy', price: 110}, {side: 'Sell', price: 200}, {side: 'Buy', price: 150} ];

var buy = {}, sell = {};

data.forEach(el => {
    if(el.side == 'Buy'){
          buy['count'] = (buy['count'] || 0) + 1;
          buy['total'] = (buy['total'] || 0) + el.price;
    }else{
         sell['count'] = (sell['count'] || 0) + 1;
         sell['total'] = (sell['total'] || 0) + el.price;
    }
})

console.log(buy.total/buy.count, sell.total/sell.count);```

Body:
i have an array of objects like this:

[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)


答:
How about this?</p>

```<code>public DateTime LastActivity
{
    get
    {
         DateTime lastPicture = Pictures.Max(x => x.LastUpdated);
         return lastPicture > this.LastUpdated ? lastPicture : this.LastUpdated;
     }
}
</code>```

Title: What's the simplest way of returning the larger of two numbers?

Body:
Let's say I have an entity that looks like this:

public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

Body:
How about this?

public DateTime LastActivity
{
    get
    {
         DateTime lastPicture = Pictures.Max(x => x.LastUpdated);
         return lastPicture > this.LastUpdated ? lastPicture : this.LastUpdated;
     }
}


问:
How to update a subitem in a json file using jq?
Using jq I tried to update this json document:

```<code>{
"git_defaults": {
    "branch": "master",
    "email": "jenkins@host",
    "user": "Jenkins"
},
"git_namespaces": [
{
    "name": "NamespaceX",
        "modules": [
            "moduleA",
            "moduleB",
            "moduleC",
            "moduleD"
        ]
},
{
    "name": "NamespaceY",
    "modules": [
        "moduleE"
    ]
}
]
}
</code>```

with adding moduleF to NamespaceY. I need to write the file back again to the original source file.

I came close (but no cigar) with:

```<code>jq  '. | .git_namespaces[] | select(.name=="namespaceY").modules |= (.+ ["moduleF"])' config.json
</code>```

and

```<code>jq '. | select(.git_namespaces[].name=="namespaceY").modules |= (.+ ["moduleF"])' config.json
</code>```

答:
The following filter should perform the update you want:

```<code>(.git_namespaces[] | select(.name=="NamespaceY").modules) += ["moduleF"]
</code>```

Note that the initial '.|' in your attempt is not needed; that "NamespaceY" is capitalized in config.json; that the parens as shown are the keys to success; and that += can be used here.

One way to write back to the original file would perhaps be to use 'sponge'; other possibilities are discussed on the jq FAQ https://github.com/stedolan/jq/wiki/FAQ

Body:
Using jq I tried to update this json document:

{
"git_defaults": {
    "branch": "master",
    "email": "jenkins@host",
    "user": "Jenkins"
},
"git_namespaces": [
{
    "name": "NamespaceX",
        "modules": [
            "moduleA",
            "moduleB",
            "moduleC",
            "moduleD"
        ]
},
{
    "name": "NamespaceY",
    "modules": [
        "moduleE"
    ]
}
]
}

with adding moduleF to NamespaceY. I need to write the file back again to the original source file.

I came close (but no cigar) with:

jq  '. | .git_namespaces[] | select(.name=="namespaceY").modules |= (.+ ["moduleF"])' config.json

and

jq '. | select(.git_namespaces[].name=="namespaceY").modules |= (.+ ["moduleF"])' config.json

Body:
The following filter should perform the update you want:

(.git_namespaces[] | select(.name=="NamespaceY").modules) += ["moduleF"]

Note that the initial '.|' in your attempt is not needed; that "NamespaceY" is capitalized in config.json; that the parens as shown are the keys to success; and that += can be used here.

One way to write back to the original file would perhaps be to use 'sponge'; other possibilities are discussed on the jq FAQ https://github.com/stedolan/jq/wiki/FAQ


问:
How to get array format in javascript?
I am getting an array in AngularJs with factory function. This is the console

```<code>Array[0]
  0: "value1"
  1: "value2"
  length:2
</code>```

But when i want to get the length of the array

```<code>console.log(array.length)
</code>```

getting data from mysql in loopback

```<code> app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});
</code>```

The controller look like:

```<code>app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])
</code>```

I get that the length is 0. Why is that?

答:
You mix async with sync approaches here.

Communications.find is async but you use it in getCommi like sync function.

When you call getCommi the function return immediately with empty array.

Please change according below.

```<code>app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id, cb){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    cb(null, array);
        });
      }
  }
});
</code>```

and

```<code>app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
getFoo.getCommi(3,1, function(err, emails){
  $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
});
}])
</code>```

DISCLAIMER : I don't know angular.

Title: How to get array format in javascript?

Body:
I am getting an array in AngularJs with factory function. This is the console

Array[0]
  0: "value1"
  1: "value2"
  length:2

But when i want to get the length of the array

console.log(array.length)

getting data from mysql in loopback

 app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});

The controller look like:

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])

I get that the length is 0. Why is that?

Body:
You mix async with sync approaches here.

Communications.find is async but you use it in getCommi like sync function.

When you call getCommi the function return immediately with empty array.

Please change according below.

app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id, cb){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    cb(null, array);
        });
      }
  }
});

and

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
getFoo.getCommi(3,1, function(err, emails){
  $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
});
}])

DISCLAIMER : I don't know angular.


问:
Resizing Highchart based on window size
Hi i have left navigation menu, and content on right side which is a highchart.
Following is my Highchart config,

```<code>this.InputData = {

            chart: { type: 'column' },
            title : { text : 'Overview' },

            xAxis: {
                categories: this._weekValues
            },
            yAxis: {
                allowDecimals: false,
                title: { text: 'some title'},
                min: 0,
                max: 100,
                labels: {
                    formatter:function() {
                        var pcnt = (this.value / 100) * 100;
                        return Highcharts.numberFormat(pcnt, 0) + '%';
                    }
                }
            }
        }
</code>```

And I have a function which will be triggered on change the size of my left menu,

```<code>this.menuEvent.onChangeLeftMenu().subscribe(()=>{
            Observable.timer().subscribe(()=>{
                console.log('highchart redraw?');
            });
        });
</code>```

How can I redraw or resize my chart on changing my leftmenu size? Currently the chart is overflowing from my div wrapper. Thanks in advance guys.

答:
reflow ()

Reflows the chart to its container. By default, the chart reflows automatically to its container following a window.resize event, as per the chart.reflow option. However, there are no reliable events for div resize, so if the container is resized without a window resize event, this must be called explicitly.

```<code>$('#reflow-chart').click(function () {
    chart.reflow();
});
</code>```

Fiddle

It will be helpful to sort problem, if you provide the actual demo  may be some plunker link

Title: Resizing Highchart based on window size

Body:
Hi i have left navigation menu, and content on right side which is a highchart.
Following is my Highchart config,

this.InputData = {

            chart: { type: 'column' },
            title : { text : 'Overview' },

            xAxis: {
                categories: this._weekValues
            },
            yAxis: {
                allowDecimals: false,
                title: { text: 'some title'},
                min: 0,
                max: 100,
                labels: {
                    formatter:function() {
                        var pcnt = (this.value / 100) * 100;
                        return Highcharts.numberFormat(pcnt, 0) + '%';
                    }
                }
            }
        }

And I have a function which will be triggered on change the size of my left menu,

this.menuEvent.onChangeLeftMenu().subscribe(()=>{
            Observable.timer().subscribe(()=>{
                console.log('highchart redraw?');
            });
        });

How can I redraw or resize my chart on changing my leftmenu size? Currently the chart is overflowing from my div wrapper. Thanks in advance guys.

Body:
reflow ()

Reflows the chart to its container. By default, the chart reflows automatically to its container following a window.resize event, as per the chart.reflow option. However, there are no reliable events for div resize, so if the container is resized without a window resize event, this must be called explicitly.

$('#reflow-chart').click(function () {
    chart.reflow();
});

Fiddle

It will be helpful to sort problem, if you provide the actual demo  may be some plunker link


问:
Media is not fetching with Instagram API
I am trying to fetch media in a particular place with Instagram API, I am following this link: https://www.instagram.com/developer/endpoints/media/#get_media_search to get media in a particular location and trying this: https://api.instagram.com/v1/media/search?lat=48.858844&lng=2.294351&access_token=XXXXX

But this is given me empty data {"meta": {"code": 200}, "data": []}

Can someone tell me why I am getting empty data, even in example they showing the data in response.

答: This will show only public to read any public profile info and media on a user’s behalf not private</p>