问:
angular wont reset form after ng-click?
My form won't reset after I do a ng-click, am I doing it right?

I can submit just fine, but the form will not reset, here is my log:

angular.js:12701 POST http://127.0.0.1:8000/auth/post 500 (Internal
  Server Error)

But my post submits fine, it just doesn't reset.

jsfiddle

https://jsfiddle.net/2fyynf6p/

main.js

```<code>var app = angular.module('eli', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');

});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.postform = "";

        });

    };

}]);
</code>```

html

```<code>            <form  name="postform" method="POST" novalidate>
                   {{ csrf_field() }}
                <div class="form-group">
                    <label for="post.title">Title</label>
                    <input ng-model="post.title"  class="form-control" type="text" name="title" placeholder="Enter a title" required/>
                </div>

                <div class="form-group">
                    <label for="post.title">Post</label>
                    <textarea ng-model="post.body" type="text" class="form-control" name="body" id="" cols="10" rows="5"></textarea>
                </div>

                <button id="eli-style-button" ng-click="addPost()" class="btn btn-primary" type="submit">Submit</button>
            </form>
</code>```

答:
Can do something like this</p>

```<code>$scope.addPost = function({
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
$scope.posts.push(data);
$scope.post.title = "";
$scope.post.body = "";
});
};
</code>```

Title: angular wont reset form after ng-click?

Body:
My form won't reset after I do a ng-click, am I doing it right?

I can submit just fine, but the form will not reset, here is my log:

angular.js:12701 POST http://127.0.0.1:8000/auth/post 500 (Internal
  Server Error)

But my post submits fine, it just doesn't reset.

jsfiddle

https://jsfiddle.net/2fyynf6p/

main.js

var app = angular.module('eli', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');

});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.postform = "";

        });

    };

}]);

html

            <form  name="postform" method="POST" novalidate>
                   {{ csrf_field() }}

                    Title
                    <input ng-model="post.title"  class="form-control" type="text" name="title" placeholder="Enter a title" required/>

                    Post
                    <textarea ng-model="post.body" type="text" class="form-control" name="body" id="" cols="10" rows="5"></textarea>

                <button id="eli-style-button" ng-click="addPost()" class="btn btn-primary" type="submit">Submit</button>
            </form>

Body:
Can do something like this

$scope.addPost = function({
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
$scope.posts.push(data);
$scope.post.title = "";
$scope.post.body = "";
});
};


来源: stackexchange

问:
Symfony Admin Generator Doctrine executeCreate
Thanks for any help with this, I'm very new to the Symfony framework so just trying to get my head around it.

I want to be able to intercept a submitted form from the admin area and modify the data.

Here's what I've got so far (in basic form)..

/apps/backend/modules/proposition/actions/action.class.php

```<code>class propositionActions extends autoPropositionActions {

  public function executeCreate(sfWebRequest $request) {
    // modify the name
    $name = $request->getParameter('name');
    $name = $name . ' is an idiot';
    $request->setParameter('name', $name);

    return parent::executeCreate($request);
  }

}</code>```

My form does contain a name field:

/apps/backend/modules/proposition/config/generator.yml

```<code>generator:
  class: sfDoctrineGenerator
  param:
    model_class:           Proposition
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              ~
    plural:                ~
    route_prefix:          proposition
    with_doctrine_route:   true
    actions_base_class:    sfActions

    config:
      actions: ~
      form:
        display: [name, icon, overview, published]
</code>```

I'm not sure if that's the file you need to see of not, but it's definitely in the HTML:

```<code><input type="text" id="proposition_name" name="proposition[name]"></code>```

When I submit the form it just saves my name. I want it to save my name appending ' is an idiot'.

Many thanks

答:
I think you are on the right track Peter, but modifying the $request too late for it to have any effect.

You could do this sort of modification of inbound data in the "doClean" part of the Form's validator.

Or, if you have special processing to do, it might make more sense to override the generated processForm() function.  Just copy it out of  cache/frontend/dev/modules/autoProposition/actions/actions.class.php into your apps/backend/modules/proposition/actions/action.class.php and start hacking.

ContentLicense: CC BY-SA 2.5

Body:
Thanks for any help with this, I'm very new to the Symfony framework so just trying to get my head around it.

I want to be able to intercept a submitted form from the admin area and modify the data.

Here's what I've got so far (in basic form)..

/apps/backend/modules/proposition/actions/action.class.php

class propositionActions extends autoPropositionActions {

  public function executeCreate(sfWebRequest $request) {
    // modify the name
    $name = $request->getParameter('name');
    $name = $name . ' is an idiot';
    $request->setParameter('name', $name);

    return parent::executeCreate($request);
  }

}

My form does contain a name field:

/apps/backend/modules/proposition/config/generator.yml

generator:
  class: sfDoctrineGenerator
  param:
    model_class:           Proposition
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              ~
    plural:                ~
    route_prefix:          proposition
    with_doctrine_route:   true
    actions_base_class:    sfActions

    config:
      actions: ~
      form:
        display: [name, icon, overview, published]

I'm not sure if that's the file you need to see of not, but it's definitely in the HTML:

<input type="text" id="proposition_name" name="proposition[name]">

When I submit the form it just saves my name. I want it to save my name appending ' is an idiot'.

Many thanks


问:
Group by with distinct query
Am using Oracle 12c, below is the column:

```<code>CENTER_ID     UNIT      EMPLOYEEID    LESSON  MINS_STUDIED  SECTION
I234          4         G01234         4.1        5            EX
I234          4         G01234         4.1        5            LN
I234          4         G01234         4.1        5            VO

I234          4         G0123          4.2        5            EX
I234          4         G0123          4.2        5            LN
I234          4         G0123          4.2        5            VO

I2345         5         G023           5.2       12            EX
I2345         5         G023           5.2       12            LN
I2345         5         G023           5.2       12            VO
</code>```

From record 1 to 6, it contains 2 distinct employee_id who studied unit 4. In this case, I need total minutes spent per unit (center_id wise).

But I want to add only distinct MINS_STUDIED based on EMPLOYEE_ID.

So, total minutes spent for center_id I234 for unit 4 is (5+5)=10 and for center_id I2345 for unit 5 is 12.

I used the below query

```<code>    SELECT
         COUNT(DISTINCT EMPLOYEE_ID),CENTER_ID,UNIT,
         SUM(DISTINCT MINS_STUDIED)
    FROM
         TEST_DATA
    GROUP BY
          CENTER_ID,DBD.UNIT;
</code>```

The above query returns

```<code>center_id    UNIT  DISTINCT(EMPLOYEE_ID) TOTAL_MINS_STUDIED
I234          4      2                       5
I2345         5      1                       12
</code>```

But, I need the output like below:

```<code>center_id    UNIT  DISTINCT(EMPLOYEE_ID) TOTAL_MINS_STUDIED
I234          4      2                       10
I2345         5      1                       12
</code>```

答:
The data appears to have repetition you need to ignore (caused by column "SECTION")</p>

```<code>SELECT
      CENTER_ID
    , UNIT
    , COUNT(DISTINCT EMPLOYEE_ID)
    , SUM(MINS_STUDIED)
FROM (
     select distinct CENTER_ID, UNIT, EMPLOYEEID , MINS_STUDIED
     from TEST_DATA
     ) t
GROUP BY
      CENTER_ID,UNIT;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Group by with distinct query

Body:
Am using Oracle 12c, below is the column:

CENTER_ID     UNIT      EMPLOYEEID    LESSON  MINS_STUDIED  SECTION
I234          4         G01234         4.1        5            EX
I234          4         G01234         4.1        5            LN
I234          4         G01234         4.1        5            VO

I234          4         G0123          4.2        5            EX
I234          4         G0123          4.2        5            LN
I234          4         G0123          4.2        5            VO

I2345         5         G023           5.2       12            EX
I2345         5         G023           5.2       12            LN
I2345         5         G023           5.2       12            VO

From record 1 to 6, it contains 2 distinct employee_id who studied unit 4. In this case, I need total minutes spent per unit (center_id wise).

But I want to add only distinct MINS_STUDIED based on EMPLOYEE_ID.

So, total minutes spent for center_id I234 for unit 4 is (5+5)=10 and for center_id I2345 for unit 5 is 12.

I used the below query

    SELECT
         COUNT(DISTINCT EMPLOYEE_ID),CENTER_ID,UNIT,
         SUM(DISTINCT MINS_STUDIED)
    FROM
         TEST_DATA
    GROUP BY
          CENTER_ID,DBD.UNIT;

The above query returns

center_id    UNIT  DISTINCT(EMPLOYEE_ID) TOTAL_MINS_STUDIED
I234          4      2                       5
I2345         5      1                       12

But, I need the output like below:

center_id    UNIT  DISTINCT(EMPLOYEE_ID) TOTAL_MINS_STUDIED
I234          4      2                       10
I2345         5      1                       12

Body:
The data appears to have repetition you need to ignore (caused by column "SECTION")

SELECT
      CENTER_ID
    , UNIT
    , COUNT(DISTINCT EMPLOYEE_ID)
    , SUM(MINS_STUDIED)
FROM (
     select distinct CENTER_ID, UNIT, EMPLOYEEID , MINS_STUDIED
     from TEST_DATA
     ) t
GROUP BY
      CENTER_ID,UNIT;


问:
Why is this way of randomly generating a graph unfair?
My aim is to generate a directed graph of n vertices such that each vertex has an edge going out and an edge coming in.  I thought one way of doing this would be to put all the vertices in a pot and for the vertices to take turns shuffling it and pulling out entries -- so for example if vertex 1 pulls out vertex 3 then that means there will be an edge going from 1 to 3.  If a vertex pulls itself out of the pot, it just puts it back and reshuffles.  If at the end, the last vertex finds that the pot only contains itself, then we need to start over.  Here's my Kotlin code:

```<code>fun generateGraph(n: Int): Map<Int, Int> {
    val vertices : List<Int> = (1..n).toList()
    while (true) {
        val pot = vertices.toMutableList()
        val result = mutableMapOf<Int, Int>()
        for (vertex in 1 until n) {
            do {
                java.util.Collections.shuffle(pot)
            } while (pot[0] == vertex)
            result.put(vertex, pot.removeAt(0))
        }
        if (pot[0] != n) {
            result.put(n, pot.removeAt(0))
            return result
        }
        else {
            // The last vertex left in the pot is also the last one unassigned.  Try again...
        }
    }
}
</code>```

It seems to work.  However when testing I'm finding it comes out with some graphs more than others.  When n is 3 the only valid graphs are the cycles

```<code>{1=3, 2=1, 3=2}
{1=2, 2=3, 3=1}
</code>```

but I'm finding the first comes up twice as many times as the second:

```<code>fun main(args: Array<String>) {
    val n = 3
    val patternCounts = mutableMapOf<Map<Int, Int>, Int>()
    val trials = 10000
    (1..trials).forEach({
        val graph = generateGraph(n)
        patternCounts[graph] = patternCounts.getOrDefault(graph, 0) + 1
    })
    println(patternCounts)
}
</code>```

A run of this just now printed

```<code>{{1=3, 2=1, 3=2}=6669, {1=2, 2=3, 3=1}=3331}
</code>```

What am I missing?  And, is there a way to make this fair?

答:
It's not difficult to see why that result occurs. Vertex 1 is matched with vertex 3 half the time. If that happens, the graph cannot be rejected because rejection only happens when the last remaining vertex is n (3 in this case) and that vertex has been used. So half the time you will get {(1,3), (2,1), (3,2)}.

The other half of the time, vertex 1 will be matched with vertex 2, but then half of those cases (i.e ¼ of the total) will be rejected after vertex 2 is matched with vertex 1. So {(1,2), (2,3), (3,1)} will be chosen a quarter of the time.

In the remaining quarter, the whole procedure will be repeated, which means that {(1,3), (2,1), (3,2)} will continue to be chosen twice as often.

One solution is to reject the entire graph as soon as you match a vertex with itself. In this case, there is no need to reshuffle before selecting; you only reshuffle if the graph is rejected.

The general problem is that the case of matching a vertex with itself is not independent of all the other choices. So just reshuffling after certain matches and rejecting after other ones leads to a bias.

Rejecting and restarting after any match might not be the most efficient solution, but it will work. One way to make the algorithm more efficient would be to shuffle incrementally, rather than doing the entire shuffle and then validating it. Another possibility is described in a paper referenced from this question on Mathematics Stack Exchange

Body:
My aim is to generate a directed graph of n vertices such that each vertex has an edge going out and an edge coming in.  I thought one way of doing this would be to put all the vertices in a pot and for the vertices to take turns shuffling it and pulling out entries -- so for example if vertex 1 pulls out vertex 3 then that means there will be an edge going from 1 to 3.  If a vertex pulls itself out of the pot, it just puts it back and reshuffles.  If at the end, the last vertex finds that the pot only contains itself, then we need to start over.  Here's my Kotlin code:

fun generateGraph(n: Int): Map<Int, Int> {
    val vertices : List<Int> = (1..n).toList()
    while (true) {
        val pot = vertices.toMutableList()
        val result = mutableMapOf<Int, Int>()
        for (vertex in 1 until n) {
            do {
                java.util.Collections.shuffle(pot)
            } while (pot[0] == vertex)
            result.put(vertex, pot.removeAt(0))
        }
        if (pot[0] != n) {
            result.put(n, pot.removeAt(0))
            return result
        }
        else {
            // The last vertex left in the pot is also the last one unassigned.  Try again...
        }
    }
}

It seems to work.  However when testing I'm finding it comes out with some graphs more than others.  When n is 3 the only valid graphs are the cycles

{1=3, 2=1, 3=2}
{1=2, 2=3, 3=1}

but I'm finding the first comes up twice as many times as the second:

fun main(args: Array<String>) {
    val n = 3
    val patternCounts = mutableMapOf<Map<Int, Int>, Int>()
    val trials = 10000
    (1..trials).forEach({
        val graph = generateGraph(n)
        patternCounts[graph] = patternCounts.getOrDefault(graph, 0) + 1
    })
    println(patternCounts)
}

A run of this just now printed

{{1=3, 2=1, 3=2}=6669, {1=2, 2=3, 3=1}=3331}

What am I missing?  And, is there a way to make this fair?


问:
Start Azure Web Job based on Timer AND new message on Service Bus?
I want to know if it is possible to have a web job run, triggered either by a new message on an Azure Service Bus (topic) OR when a timer occurs.  I know I could create two separate web jobs, but am hoping to combine the two since 99% of the logic will be the same.

Example on how we start a web job when message is ready in Service Bus:

```<code>[Singleton]
        public  void ProcessQueueMessage([ServiceBusTrigger("%TopicName%", "%SubscriptionName%")] BrokeredMessage message, TextWriter log)
        {
// Processing code here
}
</code>```

Example on how we start a web job based on a timer:

```<code>public static void ProcessByTimer([TimerTrigger("00:00:30", RunOnStartup = true)] TimerInfo timerInfo, TextWriter log)
        {
            // Processing code here
        }
</code>```

Note, I tried having the web job have both methods, but it never seemed to enter the timer method, only the service bus triggered method.

Kind regards,

Stefan

答: You can most certainly have both methods in a single WebJob, and that's the way to do it. If your TimerTrigger isn't firing, I suggest that you make sure that you have config.UseTimers() in your Program.cs file. If you do not call the UseTimers method, no TimerTrigger will ever fire. </p>

Body:
I want to know if it is possible to have a web job run, triggered either by a new message on an Azure Service Bus (topic) OR when a timer occurs.  I know I could create two separate web jobs, but am hoping to combine the two since 99% of the logic will be the same.

Example on how we start a web job when message is ready in Service Bus:

[Singleton]
        public  void ProcessQueueMessage([ServiceBusTrigger("%TopicName%", "%SubscriptionName%")] BrokeredMessage message, TextWriter log)
        {
// Processing code here
}

Example on how we start a web job based on a timer:

public static void ProcessByTimer([TimerTrigger("00:00:30", RunOnStartup = true)] TimerInfo timerInfo, TextWriter log)
        {
            // Processing code here
        }

Note, I tried having the web job have both methods, but it never seemed to enter the timer method, only the service bus triggered method.

Kind regards,

Stefan


问:
TypeError: get_serializer_class() missing 1 required positional argument: 'self'
I get error when I use the view's function, the bellow is my traceback:

```<code>File "/Users/xxx/Desktop/xxx/Project/xxx/qiyun_admin_usermanage/api/views.py", line 40, in <module>
    class UserListAPIView(ListAPIView):
  File "/Users/xxx/Desktop/xxx/Project/xxx/qiyun_admin_usermanage/api/views.py", line 59, in UserListAPIView
    serializer_class = get_serializer_class()
TypeError: get_serializer_class() missing 1 required positional argument: 'self'
</code>```

My views.py code ie bellow:

```<code>class UserListAPIView(ListAPIView):
    """

    """
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)

    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['username', 'qq', 'email']
    pagination_class = UserPageNumberPagination

    class Meta:
       ordering = ['-id']

    def get_serializer_class(self):
        if self.request.user.is_superuser:
            return UserAdminListSerializer
        else:
            return UserListSerializer

    serializer_class = get_serializer_class()  # this is the line 59
</code>```

And if I write this line serializer_class = get_serializer_class() to in the front of def get_serializer_class(self): method, I will
do not find error.

答:
You don't need to define the serializer_class attribute since you already overriding the get_serializer_class method. Remove the line 59.

From http://www.django-rest-framework.org/api-guide/generic-views/#attributes

serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method.

Body:
I get error when I use the view's function, the bellow is my traceback:

File "/Users/xxx/Desktop/xxx/Project/xxx/qiyun_admin_usermanage/api/views.py", line 40, in <module>
    class UserListAPIView(ListAPIView):
  File "/Users/xxx/Desktop/xxx/Project/xxx/qiyun_admin_usermanage/api/views.py", line 59, in UserListAPIView
    serializer_class = get_serializer_class()
TypeError: get_serializer_class() missing 1 required positional argument: 'self'

My views.py code ie bellow:

class UserListAPIView(ListAPIView):
    """

    """
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)

    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['username', 'qq', 'email']
    pagination_class = UserPageNumberPagination

    class Meta:
       ordering = ['-id']

    def get_serializer_class(self):
        if self.request.user.is_superuser:
            return UserAdminListSerializer
        else:
            return UserListSerializer

    serializer_class = get_serializer_class()  # this is the line 59

And if I write this line serializer_class = get_serializer_class() to in the front of def get_serializer_class(self): method, I will
do not find error.


问:
Where does Xcode store .m files of a framework?
In Xcode there are many frameworks (like mkmapkit.framework).

This framework contains only .h (header) files. Where can I find the corresponding .m (implementation) files.

答: The implementation files are not distributed with Xcode. Apple keeps them proprietary.</p>


问:
C# Microsoft.Office.Interop Word Doc not opening on first try
I am using the following code to open a Word doc

```<code>Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

Document document = app.Documents.Open("MyDocFile.doc");
</code>```

After the code runs, a MS Word process is started but I never see my document. If I run the code a second time, another process is started and this time I get prompted to open a read-only copy because it is already open. I choose read-only and the document opens. Can someone tell me what I am doing wrong and why the document does not open on the first run of the above code?

答:
Are you opening it with word for a particular reason?
If you just want to open and see the file you can do this:</p>

```<code>System.Diagnostics.Process.Start("YourSavedFilePath");
</code>```

Body:
I am using the following code to open a Word doc

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

Document document = app.Documents.Open("MyDocFile.doc");

After the code runs, a MS Word process is started but I never see my document. If I run the code a second time, another process is started and this time I get prompted to open a read-only copy because it is already open. I choose read-only and the document opens. Can someone tell me what I am doing wrong and why the document does not open on the first run of the above code?

Body:
Are you opening it with word for a particular reason?
If you just want to open and see the file you can do this:

System.Diagnostics.Process.Start("YourSavedFilePath");


问:
Mapping an ImmutableJS collection
I have an ImmutableJS structure that looks like this:

```<code>let state = fromJS({
  // ...
  foo: [{
    bar: ['id1', 'id2']
  },{
    bar: ['id2', 'id3']
  }]
});
</code>```

I want to map over foo and for each item, filter the associated bar against another array of ids to exclude (idsToExclude).

I have come up with this:

```<code>const idsToExclude = ['id3', 'id4'];
state = {
    ...state,
    foo: state.get('foo').map((i) =>
        i.set(['bar'], i.get(['bar']
            .filterNot(b => idsToExclude.some(id => id === b))))
};
</code>```

Is there a better, more idiomatic or terser way?

I ask because this seems quite verbose.

答:
There are several problems with your existing code:

state = {...state} is creating a plain JS object, not an Immutable.js Map, and it won't merge the new foo into the fields from state correctly.

I'm pretty sure get and set only accept a single key, not an array.  To use an array of keys as a path, use getIn or setIn.

If you can use immutable Sets in your data structure instead of Lists, then you can use set operations like subtract to simplify your code:

```<code>import {fromJS, Set} from 'immutable'

const initState = fromJS({
  // ...
  foo: [
    {bar: Set(['id1', 'id2'])},
    {bar: Set(['id2', 'id3'])}
  ]
})
const idsToExclude = fromJS(['id3', 'id4'])
const finalState = initState.update('foo', foo =>
  foo.map(element =>
    element.update('bar', set =>
      set.subtract(idsToExclude)
    )
  )
)
</code>```

Even if not storing Sets in your data structure, you could use them temporarily during the mutation:

```<code>const initState = fromJS({
  // ...
  foo: [
    {bar: ['id1', 'id2']},
    {bar: ['id2', 'id3']}
  ]
})
const idsToExclude = fromJS(['id3', 'id4'])
const finalState = initState.update('foo', foo =>
  foo.map(element =>
    element.update('bar', list =>
      list.toSet().subtract(idsToExclude).toList()
    )
  )
)
</code>```

Title: Mapping an ImmutableJS collection

Body:
I have an ImmutableJS structure that looks like this:

let state = fromJS({
  // ...
  foo: [{
    bar: ['id1', 'id2']
  },{
    bar: ['id2', 'id3']
  }]
});

I want to map over foo and for each item, filter the associated bar against another array of ids to exclude (idsToExclude).

I have come up with this:

const idsToExclude = ['id3', 'id4'];
state = {
    ...state,
    foo: state.get('foo').map((i) =>
        i.set(['bar'], i.get(['bar']
            .filterNot(b => idsToExclude.some(id => id === b))))
};

Is there a better, more idiomatic or terser way?

I ask because this seems quite verbose.

Body:
There are several problems with your existing code:

state = {...state} is creating a plain JS object, not an Immutable.js Map, and it won't merge the new foo into the fields from state correctly.

I'm pretty sure get and set only accept a single key, not an array.  To use an array of keys as a path, use getIn or setIn.

If you can use immutable Sets in your data structure instead of Lists, then you can use set operations like subtract to simplify your code:

import {fromJS, Set} from 'immutable'

const initState = fromJS({
  // ...
  foo: [
    {bar: Set(['id1', 'id2'])},
    {bar: Set(['id2', 'id3'])}
  ]
})
const idsToExclude = fromJS(['id3', 'id4'])
const finalState = initState.update('foo', foo =>
  foo.map(element =>
    element.update('bar', set =>
      set.subtract(idsToExclude)
    )
  )
)

Even if not storing Sets in your data structure, you could use them temporarily during the mutation:

const initState = fromJS({
  // ...
  foo: [
    {bar: ['id1', 'id2']},
    {bar: ['id2', 'id3']}
  ]
})
const idsToExclude = fromJS(['id3', 'id4'])
const finalState = initState.update('foo', foo =>
  foo.map(element =>
    element.update('bar', list =>
      list.toSet().subtract(idsToExclude).toList()
    )
  )
)


问:
Execution time of sparse matrix multiplication
A key step in a product diffusion study I am running involves the multiplication of a sparse matrix with a vector. The code below reproduces the code with versions in Rcpp and R.

```<code>#define ARMA_64BIT_WORD
#include <RcppArmadillo.h>
//[[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
arma::vec multiply(arma::sp_mat A, arma::vec nodes_status) {

  return A * nodes_status;
}

/***R

library(rbenchmark)
library(igraph)

g <- sample_smallworld(dim = 1, size = 1e5, nei = 12, p = 0.65)

nodes <- V(g)
A <- get.adjacency(g)

nodes.status <- sample(x = c(0, 1),
                       size = length(nodes),
                       replace = TRUE,
                       prob = c(0.9, 0.1))

multiplyR <- function(A, n) {return(as.vector(A %*% n))}

sum(multiply(A, nodes.status) == multiplyR(A, nodes.status)) == 1e5 # check if the results are the same

benchmark(multiply(A, nodes.status), multiplyR(A, nodes.status), order = "relative")[, 1:4]

*/
</code>```

When I run this code, the answers from both functions tally, but the execution times are as follows:

```<code>                    test     replications elapsed relative
2 multiplyR(A, nodes.status)          100    1.30    1.000
1  multiply(A, nodes.status)          100    3.66    2.815
</code>```

What is wrong with the code here? Is there a more efficient multiplication idiom in Rcpp for my case?

答:
No. The issue being documented here is two fold:

the conversion time required to transform a sparse matrix in R to an RcppArmadillo object is larger than Matrix's use of C routines.

the cost of copying vs. reference creation.

Regarding 2., the construction of the arma::sp_mat uses a copy since it does not have a reference (e.g. &) as a suffix. In particular, note:

```<code>#define ARMA_64BIT_WORD
#include <RcppArmadillo.h>

//[[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::vec sp_multiply_copy(arma::sp_mat A, arma::vec nodes_status) {
  return A * nodes_status;
}

// [[Rcpp::export]]
arma::vec sp_multiply_ref(const arma::sp_mat& A, const arma::vec& nodes_status) {
  return A * nodes_status;
}
</code>```

From here, the slight a slight performance difference between the two is noted:

```<code>benchmark(sp_multiply_copy(A, nodes.status),
          sp_multiply_ref(A, nodes.status),
          multiplyR(A, nodes.status), order = "relative")[, 1:4]

#                                test replications elapsed relative
# 3        multiplyR(A, nodes.status)          100   1.240    1.000
# 2  sp_multiply_ref(A, nodes.status)          100   2.766    2.231
# 1 sp_multiply_copy(A, nodes.status)          100   3.141    2.533
</code>```

With this being said, we return to the first point: the Matrix functions for sparse matrices are highly optimized and directly use C. Examples of said routines can be viewed at R/products.R, src/Csparse.c, src/dtrMatrix.c. As a result, Matrix operations will be far more efficient.

Now, that is not to say speed cannot be obtained in C++. In particular, if the matrix object is repetitively used in C++ for multiplication with an instantiation of pass-by-reference (e.g. &), then it should be faster than a call to Matrix's multiplication routine.

Body:
A key step in a product diffusion study I am running involves the multiplication of a sparse matrix with a vector. The code below reproduces the code with versions in Rcpp and R.

#define ARMA_64BIT_WORD
#include <RcppArmadillo.h>
//[[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
arma::vec multiply(arma::sp_mat A, arma::vec nodes_status) {

  return A * nodes_status;
}

/***R

library(rbenchmark)
library(igraph)

g <- sample_smallworld(dim = 1, size = 1e5, nei = 12, p = 0.65)

nodes <- V(g)
A <- get.adjacency(g)

nodes.status <- sample(x = c(0, 1),
                       size = length(nodes),
                       replace = TRUE,
                       prob = c(0.9, 0.1))

multiplyR <- function(A, n) {return(as.vector(A %*% n))}

sum(multiply(A, nodes.status) == multiplyR(A, nodes.status)) == 1e5 # check if the results are the same

benchmark(multiply(A, nodes.status), multiplyR(A, nodes.status), order = "relative")[, 1:4]

*/

When I run this code, the answers from both functions tally, but the execution times are as follows:

                    test     replications elapsed relative
2 multiplyR(A, nodes.status)          100    1.30    1.000
1  multiply(A, nodes.status)          100    3.66    2.815

What is wrong with the code here? Is there a more efficient multiplication idiom in Rcpp for my case?

Body:
No. The issue being documented here is two fold:

the conversion time required to transform a sparse matrix in R to an RcppArmadillo object is larger than Matrix's use of C routines.

the cost of copying vs. reference creation.

Regarding 2., the construction of the arma::sp_mat uses a copy since it does not have a reference (e.g. &) as a suffix. In particular, note:

#define ARMA_64BIT_WORD
#include <RcppArmadillo.h>

//[[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::vec sp_multiply_copy(arma::sp_mat A, arma::vec nodes_status) {
  return A * nodes_status;
}

// [[Rcpp::export]]
arma::vec sp_multiply_ref(const arma::sp_mat& A, const arma::vec& nodes_status) {
  return A * nodes_status;
}

From here, the slight a slight performance difference between the two is noted:

benchmark(sp_multiply_copy(A, nodes.status),
          sp_multiply_ref(A, nodes.status),
          multiplyR(A, nodes.status), order = "relative")[, 1:4]

#                                test replications elapsed relative
# 3        multiplyR(A, nodes.status)          100   1.240    1.000
# 2  sp_multiply_ref(A, nodes.status)          100   2.766    2.231
# 1 sp_multiply_copy(A, nodes.status)          100   3.141    2.533

With this being said, we return to the first point: the Matrix functions for sparse matrices are highly optimized and directly use C. Examples of said routines can be viewed at R/products.R, src/Csparse.c, src/dtrMatrix.c. As a result, Matrix operations will be far more efficient.

Now, that is not to say speed cannot be obtained in C++. In particular, if the matrix object is repetitively used in C++ for multiplication with an instantiation of pass-by-reference (e.g. &), then it should be faster than a call to Matrix's multiplication routine.


问:
Adding reference to ResourceLoader to roslyn compilation
I'm trying to find all calls to windows.applicationmodel.resources.resourceloader.getstring in an UWP application but compilation.GetSemanticModel().GetSymbolInfo().Symbol is always null. Can someone tell me what Metadatareference I have to add so that Roslyn can correctly look up the symbol type?

Here's part of the code I have:

```<code>    var workspace = MSBuildWorkspace.Create();
    var project = await workspace.OpenProjectAsync(projectFilepath);
    var compilation = await project.GetCompilationAsync();
    foreach (var tree in compilation.SyntaxTrees) {
        var sm = compilation.GetSemanticModel(tree, true);
        var root = await tree.GetRootAsync();
        FindCall(root, sm, calls);
    }
</code>```

FindCall looks for InvocationExpressions that resemble resourceLoader.GetString. But all those calls are missing type information, that is, there's no way of knowing if it's actually a call to windows.applicationmodel.resources.resourceloader.getstring.

答:
All MetadataReferences you need should already be loaded by MSBuildWorkspace from the information in your project file.  Check the Workspace.Diagnostics collection to see if there were any errors when opening the project that may cause you not to have correct symbols.

If you are looking for references to specific API's you'll need to find the corresponding Roslyn symbols for those first.  You can do this using the Compilation object you can get from the project. If its a type you are looking for you can get it using the Compilation.GetTypeByMetadataName() method. If not, you can use the ISymbol API to find the member you are looking for.

Body:
I'm trying to find all calls to windows.applicationmodel.resources.resourceloader.getstring in an UWP application but compilation.GetSemanticModel().GetSymbolInfo().Symbol is always null. Can someone tell me what Metadatareference I have to add so that Roslyn can correctly look up the symbol type?

Here's part of the code I have:

    var workspace = MSBuildWorkspace.Create();
    var project = await workspace.OpenProjectAsync(projectFilepath);
    var compilation = await project.GetCompilationAsync();
    foreach (var tree in compilation.SyntaxTrees) {
        var sm = compilation.GetSemanticModel(tree, true);
        var root = await tree.GetRootAsync();
        FindCall(root, sm, calls);
    }

FindCall looks for InvocationExpressions that resemble resourceLoader.GetString. But all those calls are missing type information, that is, there's no way of knowing if it's actually a call to windows.applicationmodel.resources.resourceloader.getstring.


问:
Docusign Going live to another account
I have a sandbox developer account with an integrator key that has already passed the review process. My client has purchased a production account under his email. How can I upgrade my integrator key to his production account? </p>

答: You would need to select Actions drop down in your Integrator Key, On of the option is Go Live, on selecting "Go Live" option, it will open a popup to enter your PROD credential (here your client needs to enter the PROD Admin credentials). For further details, please check https://www.docusign.com/developer-center/api-overview#go-live, it has all the steps to move Integrator Key from Demo to a PROD Account. Just make sure that PopUp blocker is disabled in your browser.</p>

Title: Docusign Going live to another account


问:
.net SQL Server stored procs wrapper class structure
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

```<code>void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}
</code>```

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

答:
Just a fun exercise for me, and not necessarily the way you'd want to implement it. I wrote a quick fluent interface for building and executing SqlCommands.

A couple of sample usages:

```<code>    int i = Sql.UsingConnection("sample")
        .GetTextCommandFor("Select Top 1 ActorID From Actor Where FirstName = @fname")
        .AddParameters(new {fname = "Bob"})
        .OnException(e => Console.WriteLine(e.Message))
        .ExecuteScalar<int>();

    var q = Sql.UsingConnection("sample")
        .GetTextCommandFor("Select * From Actor Where FirstName=@fname and ActorID > @id")
        .AddParameters(new {id = 1000, fname = "Bob"});

    using(var reader = q.ExecuteReader())
    {
        while(reader.Read())
        {
            // do something
        }
    }
</code>```

The actual class(es) and Interfaces are below:

```<code>public class Sql
{
    public static ISqlCommandTypeSelector UsingConnection(string connection)
    {
        return new SqlBuilder(connection);
    }

    private class SqlBuilder : ISqlCommandTypeSelector, ISqlParameterManager, ISqlExecutor
    {
        private string _connection;
        private string _sqltext;
        private CommandType _commandtype;
        private Action<Exception> _exceptionBehavior = DefaultExceptionBehavior;

        private IList<SqlParameter> _inParams;

        public SqlBuilder(string connection)
        {
            _connection = ConfigurationManager.ConnectionStrings[connection].ConnectionString;
            _inParams = new List<SqlParameter>();
        }

        public ISqlParameterManager GetTextCommandFor(string text)
        {
            _sqltext = text;
            _commandtype = CommandType.Text;
            return this;
        }

        public ISqlParameterManager GetProcCommandFor(string proc)
        {
            _sqltext = proc;
            _commandtype = CommandType.StoredProcedure;
            return this;
        }

        public ISqlExecutor OnException(Action<Exception> action)
        {
            _exceptionBehavior = action;
            return this;
        }

        public void ExecuteNonQuery()
        {
            try
            {
                using (var connection = new SqlConnection(_connection))
                using (var cmd = connection.CreateCommand())
                {
                    ConfigureCommand(cmd);
                    PopulateParameters(cmd);
                    connection.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch(Exception ex)
            {
                _exceptionBehavior(ex);
            }
        }

        public T ExecuteScalar<T>()
        {
            T result = default(T);
            try
            {
                using (var connection = new SqlConnection(_connection))
                using (var cmd = connection.CreateCommand())
                {
                    ConfigureCommand(cmd);
                    PopulateParameters(cmd);
                    connection.Open();
                    result = (T) cmd.ExecuteScalar();
                    return result;
                }
            }
            catch(InvalidCastException ex)
            {
                // rethrow?
            }
            catch(Exception ex)
            {
                _exceptionBehavior(ex);
            }
            return result;
        }

        public IDataReader ExecuteReader()
        {
            try
            {
                var connection = new SqlConnection(_connection);
                var cmd = connection.CreateCommand();
                ConfigureCommand(cmd);
                PopulateParameters(cmd);
                connection.Open();
                var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return reader;
            }
            catch(Exception ex)
            {
                _exceptionBehavior(ex);
            }
            return null;
        }

        public ISqlExecutor AddParameters(object @params)
        {
            var type = @params.GetType();
            var props = type.GetProperties();
            foreach (var propertyInfo in props)
            {
                var param = new SqlParameter("@" + propertyInfo.Name, propertyInfo.GetValue(@params, null));
                param.Direction = ParameterDirection.Input;
                _inParams.Add(param);
            }
            return this;
        }

        public ISqlExecutor WithoutParams()
        {
            return this;
        }

        private void ConfigureCommand(SqlCommand cmd)
        {
            cmd.CommandText = _sqltext;
            cmd.CommandType = _commandtype;
        }

        private void PopulateParameters(SqlCommand cmd)
        {
            cmd.Parameters.AddRange(_inParams.ToArray());
        }

        private static void DefaultExceptionBehavior(Exception e)
        {
            // do something
        }
    }

}

public interface ISqlCommandTypeSelector
{
    ISqlParameterManager GetTextCommandFor(string text);
    ISqlParameterManager GetProcCommandFor(string proc);
}

public interface ISqlExecutor
{
    ISqlExecutor OnException(Action<Exception> action);

    void ExecuteNonQuery();
    T ExecuteScalar<T>();
    IDataReader ExecuteReader();
}

public interface ISqlParameterManager
{
    ISqlExecutor AddParameters(object @params);
    ISqlExecutor WithoutParams();
}
</code>```

There is some repeated code that could probably be refactored some more if you really hate repeated code. This is just a fun exercise, and probably not how you want to do your data access however. This also doesn't support out parameters as it is written.

Body:
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

Body:
Just a fun exercise for me, and not necessarily the way you'd want to implement it. I wrote a quick fluent interface for building and executing SqlCommands.

A couple of sample usages:

    int i = Sql.UsingConnection("sample")
        .GetTextCommandFor("Select Top 1 ActorID From Actor Where FirstName = @fname")
        .AddParameters(new {fname = "Bob"})
        .OnException(e => Console.WriteLine(e.Message))
        .ExecuteScalar<int>();

    var q = Sql.UsingConnection("sample")
        .GetTextCommandFor("Select * From Actor Where FirstName=@fname and ActorID > @id")
        .AddParameters(new {id = 1000, fname = "Bob"});

    using(var reader = q.ExecuteReader())
    {
        while(reader.Read())
        {
            // do something
        }
    }

The actual class(es) and Interfaces are below:

public class Sql
{
    public static ISqlCommandTypeSelector UsingConnection(string connection)
    {
        return new SqlBuilder(connection);
    }

    private class SqlBuilder : ISqlCommandTypeSelector, ISqlParameterManager, ISqlExecutor
    {
        private string _connection;
        private string _sqltext;
        private CommandType _commandtype;
        private Action<Exception> _exceptionBehavior = DefaultExceptionBehavior;

        private IList<SqlParameter> _inParams;

        public SqlBuilder(string connection)
        {
            _connection = ConfigurationManager.ConnectionStrings[connection].ConnectionString;
            _inParams = new List<SqlParameter>();
        }

        public ISqlParameterManager GetTextCommandFor(string text)
        {
            _sqltext = text;
            _commandtype = CommandType.Text;
            return this;
        }

        public ISqlParameterManager GetProcCommandFor(string proc)
        {
            _sqltext = proc;
            _commandtype = CommandType.StoredProcedure;
            return this;
        }

        public ISqlExecutor OnException(Action<Exception> action)
        {
            _exceptionBehavior = action;
            return this;
        }

        public void ExecuteNonQuery()
        {
            try
            {
                using (var connection = new SqlConnection(_connection))
                using (var cmd = connection.CreateCommand())
                {
                    ConfigureCommand(cmd);
                    PopulateParameters(cmd);
                    connection.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch(Exception ex)
            {
                _exceptionBehavior(ex);
            }
        }

        public T ExecuteScalar<T>()
        {
            T result = default(T);
            try
            {
                using (var connection = new SqlConnection(_connection))
                using (var cmd = connection.CreateCommand())
                {
                    ConfigureCommand(cmd);
                    PopulateParameters(cmd);
                    connection.Open();
                    result = (T) cmd.ExecuteScalar();
                    return result;
                }
            }
            catch(InvalidCastException ex)
            {
                // rethrow?
            }
            catch(Exception ex)
            {
                _exceptionBehavior(ex);
            }
            return result;
        }

        public IDataReader ExecuteReader()
        {
            try
            {
                var connection = new SqlConnection(_connection);
                var cmd = connection.CreateCommand();
                ConfigureCommand(cmd);
                PopulateParameters(cmd);
                connection.Open();
                var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return reader;
            }
            catch(Exception ex)
            {
                _exceptionBehavior(ex);
            }
            return null;
        }

        public ISqlExecutor AddParameters(object @params)
        {
            var type = @params.GetType();
            var props = type.GetProperties();
            foreach (var propertyInfo in props)
            {
                var param = new SqlParameter("@" + propertyInfo.Name, propertyInfo.GetValue(@params, null));
                param.Direction = ParameterDirection.Input;
                _inParams.Add(param);
            }
            return this;
        }

        public ISqlExecutor WithoutParams()
        {
            return this;
        }

        private void ConfigureCommand(SqlCommand cmd)
        {
            cmd.CommandText = _sqltext;
            cmd.CommandType = _commandtype;
        }

        private void PopulateParameters(SqlCommand cmd)
        {
            cmd.Parameters.AddRange(_inParams.ToArray());
        }

        private static void DefaultExceptionBehavior(Exception e)
        {
            // do something
        }
    }

}

public interface ISqlCommandTypeSelector
{
    ISqlParameterManager GetTextCommandFor(string text);
    ISqlParameterManager GetProcCommandFor(string proc);
}

public interface ISqlExecutor
{
    ISqlExecutor OnException(Action<Exception> action);

    void ExecuteNonQuery();
    T ExecuteScalar<T>();
    IDataReader ExecuteReader();
}

public interface ISqlParameterManager
{
    ISqlExecutor AddParameters(object @params);
    ISqlExecutor WithoutParams();
}

There is some repeated code that could probably be refactored some more if you really hate repeated code. This is just a fun exercise, and probably not how you want to do your data access however. This also doesn't support out parameters as it is written.


问:
Issues programming an FPGA by comp sci major, unexpected output
Context:

I am a computer science major, filling a gap left by our computer engineering guy. I am in school, and this is part of my senior project. I am attempting to program an FPGA for use in an electronic board game being created by my group. The FPGA is simply an IO extender to the Raspberry Pi, which controls all logic. The verilog code below is running on an Altera Max V 570 devkit, with intentions of migrating to a Max V 40 for the production units. Each FPGA will control a group of 4 game tiles, and there will be 4 groups of tiles for the final product.

Problem:

I am creating an FPGA that will interface with a raspberry pi to control MOSFETs (now LEDs) in our system. The issues I am having is that, no matter what command I send to the tile, the LEDs are always toggled like so:

for tile0, only the 0th LED will toggle

for tile1, only the 1st LED will toggle

for tile2, only the 2nd LED will toggle

for tile3, only the 3rd LED will toggle

Here is a link to a photo of this in action:

https://drive.google.com/open?id=0B7P773tnBnRybHhGRmZMX3hScGFrNXpKUDN2c0tBbkFZaTVJ

(Ignore the final LED in each group, that will be input from a capacitive sensor)

This is true of the LED toggle command (2'b11 in code below) and for the solenoid toggle (2'b01 in code below).

During simulation with Altera ModelSim, everything works perfectly! But with everything hooked up to the breadboard, I see the situation above.

My thoughts on the problem

I initially thought the issue was with assigning to the same register I was reading from, but I added another step (haphazardly...) to read the register, then assign, but I saw worse behavior (LEDs would not toggle). HELP! :)

Here is my verilog code:

```<code>module comm_protocol(clock, bus, t0, t1, t2, t3, t0cap, t1cap, t2cap, t3cap, capOut);

parameter [1:0] my_address = 2'b11;

input clock;
input [3:0] bus;

output reg [4:0] t0;
output reg [4:0] t1;
output reg [4:0] t2;
output reg [4:0] t3;

input wire t0cap, t1cap, t2cap, t3cap;
output reg capOut;

reg start;
reg [1:0] tickCounter;

reg gotFpgaAddress;
reg [1:0] fpgaAddress;
reg[1:0] tileAddress;

reg gotCommand;
reg [3:0] command;

initial begin

    start <= 0;

    t0 <= 5'b11111;
    t1 <= 5'b11111;
    t2 <= 5'b11111;
    t3 <= 5'b11111;

end

always @ (posedge clock) begin

    // check if we have recieved the start condition, which is just a positive edge on the clock
    if (~start) begin

        start <= 1;
        tickCounter <= 0;
        gotFpgaAddress <= 0;
        gotCommand <= 0;

    end
    else begin // we have received the start condition, so continue into the logic

        // increment the counter
        // this counter controls when a reset of the logic is performed
        // the entire protocol should take place in 4 cycles, so when our counter hits 3 we are done
        tickCounter <= tickCounter + 1;
        if (tickCounter == 3) begin

            start <= 0;

        end
        else begin // no reset, continue into logic

            // here, we will read the address of the fpga the pi is talking to
            // first check if we have recieved the address or not
            if (~gotFpgaAddress) begin

                fpgaAddress <= bus[3:2]; //[3:0];
                tileAddress <= bus[1:0];

                gotFpgaAddress <= 1;
                //gotTileAddress <= 1;

            end
            else begin // we got the address, now compare it to see if it matches our address

                if (fpgaAddress == my_address) begin

                    // the message is intended for us, so next we check if the command has been received
                    if (~gotCommand) begin

                        //tileAddress <= bus[3:0];
                        command <= bus;
                        gotCommand <= 1;

                    end
                    else begin  // we have received the command, now decode it and perform the action

                        // decode the command that has been sent
                        // leading 11xx : toggle an led specified by the 2 least significant bits
                        // leading 00xx : read from the capactive sensor and write it onto the bus
                        // leading 01xx : toggle the solenoid for the popup

                        // implement logic to toggle leds
                        if (command[3:2] == 2'b11) begin

                            // route to appropriate tile
                            case (tileAddress)

                                // tile 0
                                2'b00: begin
                                    case (command[1:0])
                                        2'b00: t0[0] <= ~t0[0];
                                        2'b01: t0[1] <= ~t0[1];
                                        2'b10: t0[2] <= ~t0[2];
                                        2'b11: t0[3] <= ~t0[3];
                                    endcase
                                end
                                // tile 1
                                2'b01: begin
                                    case (command[1:0])
                                        2'b00: t1[0] <= ~t1[0];
                                        2'b01: t1[1] <= ~t1[1];
                                        2'b10: t1[2] <= ~t1[2];
                                        2'b11: t1[3] <= ~t1[3];
                                    endcase
                                end
                                // tile 2
                                2'b10: begin
                                    case (command[1:0])
                                        2'b00: t2[0] <= ~t2[0];
                                        2'b01: t2[1] <= ~t2[1];
                                        2'b10: t2[2] <= ~t2[2];
                                        2'b11: t2[3] <= ~t2[3];
                                    endcase
                                end
                                // tile 3
                                2'b11: begin
                                    case (command[1:0])
                                        2'b00: t3[0] <= ~t3[0];
                                        2'b01: t3[1] <= ~t3[1];
                                        2'b10: t3[2] <= ~t3[2];
                                        2'b11: t3[3] <= ~t3[3];
                                    endcase
                                end

                            endcase

                        end
                        // implement logic to read from the capacitive sensor and write it onto the bus
                        else if (command[3:2] == 2'b00) begin

                            case (tileAddress)

                                2'b00: capOut <= t0cap;
                                2'b01: capOut <= t1cap;
                                2'b10: capOut <= t2cap;
                                2'b11: capOut <= t3cap;

                            endcase

                        end
                        // implement logic to toggle the solenoid
                        else if (command[3:2] == 2'b01) begin

                            case (tileAddress)

                                2'b00: t0[4] <= ~t0[4];
                                2'b01: t1[4] <= ~t1[4];
                                2'b10: t2[4] <= ~t2[4];
                                2'b11: t3[4] <= ~t3[4];

                            endcase

                        end

                    end

                end

            end

        end

    end

end

endmodule
</code>```

BONUS

Currently I have consumed 42 logic elements, if anyone can give me pointers on how to reduce this to exactly 40 LEs or less, I will be eternally grateful! Not a big deal, the 80 element Max V is only 70 cents more than the MaxV40

答:
Glad you found the issue in your python code. One thing that might have helped is adding one more input pin as a qualifier to sampling the bus. Otherwise would will need make sure all FPGAs are fully synchronized.

Now for your bonus question:

Without change any behavior of your code you can eliminate 3 flops (start, gotFpgaAddress, and gotCommand) and a tiny bit of logic gates by converting tickCounter into a FSM. I noticed that when tickCounter is 0, you are always in an initileal/reset state. When it is 1, you are getting the address. When it is 2, you may collect the command if it is the target fpga address. And when it is 3, you toggle the LEDs if at the target fpga address.

```<code>localparam INIT=2'b0, GETADDR=2'b01, GETCMD=2'b10, TOGGLELED=2'b11;
reg [1:0] state;

reg [1:0] fpgaAddress;
reg [1:0] tileAddress;
reg [3:0] command;

initial begin
    state = INIT; // Note: initial blocks should use blocking statements
    t0 = 5'b11111;
    t1 = 5'b11111;
    t2 = 5'b11111;
    t3 = 5'b11111;
end

always @ (posedge clock) begin
  case(state)
    INIT :
      begin
        state <= GETADDR;
        // technically this is a dummy state, but needed to match behavior
      end
    GETADDR :
      begin
        state <= GETCMD;
        fpgaAddress <= bus[3:2];
        tileAddress <= bus[1:0];
      end
    GETCMD :
      begin
        state <= TOGGLELED;
        /* No output is effected in this state,
         * so it doesn't matter what the address is.
         * Preventing assignment to command would add logic.
         */
        command <= bus;
      end
    TOGGLELED :
      begin
        state <= INIT;
        // Here we care about the address
        if (fpgaAddress == MY_ADDRESS) begin
          // ... your assignments to t0-t3 here ...
          /* There are tricks to reduce the number of lines of code here,
           * but nothing I can immanently think of that will reduce gate count.
           */
        end
      end
  endcase
end
</code>```

If really want to squeeze the area, you can bring it down to two states by removing the INIT and GETCMD states. Just remember that bus is now your command in the TOGGLELED state. Also note that this changes your design from a 4 cycles down to 2 cycles. So you would need to change stimulus (your python code) as well.

If you add the qualifier input pin I mentioned above then it is a tweak to the state assignment (ex: if (start_fsm) begin state <= NEXT_STATE ; /*... other stuff ...*/ end else begin state <= CURRENT_STATE; end).

One another topic, your module header is written in an somewhat outdated style called Non-ANSI. A more strict version of Non-ANSI is required with Verilog-1995 (ex output [4:0] t0; reg[4:0] t0; instead of output reg[4:0] t0;) but has lost popularity since Verilog-2001 became wildly supported. The modern header style is referred to as ANSI. With the ANSI style you declare the port order, direction, and type on the same line (where Non-ANSI required 2 to 3 separate lines). It is cleaner an less prone to typos.

```<code>module comm_protocol #(parameter [1:0] MY_ADDRESS = 2'b11) (
    input clock,
    input [3:0] bus,

    output reg [4:0] t0,
    output reg [4:0] t1,
    output reg [4:0] t2,
    output reg [4:0] t3,

    input wire t0cap, t1cap, t2cap, t3cap,
    output reg capOut );
</code>```

Body:
Context:

I am a computer science major, filling a gap left by our computer engineering guy. I am in school, and this is part of my senior project. I am attempting to program an FPGA for use in an electronic board game being created by my group. The FPGA is simply an IO extender to the Raspberry Pi, which controls all logic. The verilog code below is running on an Altera Max V 570 devkit, with intentions of migrating to a Max V 40 for the production units. Each FPGA will control a group of 4 game tiles, and there will be 4 groups of tiles for the final product.

Problem:

I am creating an FPGA that will interface with a raspberry pi to control MOSFETs (now LEDs) in our system. The issues I am having is that, no matter what command I send to the tile, the LEDs are always toggled like so:

for tile0, only the 0th LED will toggle

for tile1, only the 1st LED will toggle

for tile2, only the 2nd LED will toggle

for tile3, only the 3rd LED will toggle

Here is a link to a photo of this in action:

https://drive.google.com/open?id=0B7P773tnBnRybHhGRmZMX3hScGFrNXpKUDN2c0tBbkFZaTVJ

(Ignore the final LED in each group, that will be input from a capacitive sensor)

This is true of the LED toggle command (2'b11 in code below) and for the solenoid toggle (2'b01 in code below).

During simulation with Altera ModelSim, everything works perfectly! But with everything hooked up to the breadboard, I see the situation above.

My thoughts on the problem

I initially thought the issue was with assigning to the same register I was reading from, but I added another step (haphazardly...) to read the register, then assign, but I saw worse behavior (LEDs would not toggle). HELP! :)

Here is my verilog code:

module comm_protocol(clock, bus, t0, t1, t2, t3, t0cap, t1cap, t2cap, t3cap, capOut);

parameter [1:0] my_address = 2'b11;

input clock;
input [3:0] bus;

output reg [4:0] t0;
output reg [4:0] t1;
output reg [4:0] t2;
output reg [4:0] t3;

input wire t0cap, t1cap, t2cap, t3cap;
output reg capOut;

reg start;
reg [1:0] tickCounter;

reg gotFpgaAddress;
reg [1:0] fpgaAddress;
reg[1:0] tileAddress;

reg gotCommand;
reg [3:0] command;

initial begin

    start <= 0;

    t0 <= 5'b11111;
    t1 <= 5'b11111;
    t2 <= 5'b11111;
    t3 <= 5'b11111;

end

always @ (posedge clock) begin

    // check if we have recieved the start condition, which is just a positive edge on the clock
    if (~start) begin

        start <= 1;
        tickCounter <= 0;
        gotFpgaAddress <= 0;
        gotCommand <= 0;

    end
    else begin // we have received the start condition, so continue into the logic

        // increment the counter
        // this counter controls when a reset of the logic is performed
        // the entire protocol should take place in 4 cycles, so when our counter hits 3 we are done
        tickCounter <= tickCounter + 1;
        if (tickCounter == 3) begin

            start <= 0;

        end
        else begin // no reset, continue into logic

            // here, we will read the address of the fpga the pi is talking to
            // first check if we have recieved the address or not
            if (~gotFpgaAddress) begin

                fpgaAddress <= bus[3:2]; //[3:0];
                tileAddress <= bus[1:0];

                gotFpgaAddress <= 1;
                //gotTileAddress <= 1;

            end
            else begin // we got the address, now compare it to see if it matches our address

                if (fpgaAddress == my_address) begin

                    // the message is intended for us, so next we check if the command has been received
                    if (~gotCommand) begin

                        //tileAddress <= bus[3:0];
                        command <= bus;
                        gotCommand <= 1;

                    end
                    else begin  // we have received the command, now decode it and perform the action

                        // decode the command that has been sent
                        // leading 11xx : toggle an led specified by the 2 least significant bits
                        // leading 00xx : read from the capactive sensor and write it onto the bus
                        // leading 01xx : toggle the solenoid for the popup

                        // implement logic to toggle leds
                        if (command[3:2] == 2'b11) begin

                            // route to appropriate tile
                            case (tileAddress)

                                // tile 0
                                2'b00: begin
                                    case (command[1:0])
                                        2'b00: t0[0] <= ~t0[0];
                                        2'b01: t0[1] <= ~t0[1];
                                        2'b10: t0[2] <= ~t0[2];
                                        2'b11: t0[3] <= ~t0[3];
                                    endcase
                                end
                                // tile 1
                                2'b01: begin
                                    case (command[1:0])
                                        2'b00: t1[0] <= ~t1[0];
                                        2'b01: t1[1] <= ~t1[1];
                                        2'b10: t1[2] <= ~t1[2];
                                        2'b11: t1[3] <= ~t1[3];
                                    endcase
                                end
                                // tile 2
                                2'b10: begin
                                    case (command[1:0])
                                        2'b00: t2[0] <= ~t2[0];
                                        2'b01: t2[1] <= ~t2[1];
                                        2'b10: t2[2] <= ~t2[2];
                                        2'b11: t2[3] <= ~t2[3];
                                    endcase
                                end
                                // tile 3
                                2'b11: begin
                                    case (command[1:0])
                                        2'b00: t3[0] <= ~t3[0];
                                        2'b01: t3[1] <= ~t3[1];
                                        2'b10: t3[2] <= ~t3[2];
                                        2'b11: t3[3] <= ~t3[3];
                                    endcase
                                end

                            endcase

                        end
                        // implement logic to read from the capacitive sensor and write it onto the bus
                        else if (command[3:2] == 2'b00) begin

                            case (tileAddress)

                                2'b00: capOut <= t0cap;
                                2'b01: capOut <= t1cap;
                                2'b10: capOut <= t2cap;
                                2'b11: capOut <= t3cap;

                            endcase

                        end
                        // implement logic to toggle the solenoid
                        else if (command[3:2] == 2'b01) begin

                            case (tileAddress)

                                2'b00: t0[4] <= ~t0[4];
                                2'b01: t1[4] <= ~t1[4];
                                2'b10: t2[4] <= ~t2[4];
                                2'b11: t3[4] <= ~t3[4];

                            endcase

                        end

                    end

                end

            end

        end

    end

end

endmodule

BONUS

Currently I have consumed 42 logic elements, if anyone can give me pointers on how to reduce this to exactly 40 LEs or less, I will be eternally grateful! Not a big deal, the 80 element Max V is only 70 cents more than the MaxV40

Body:
Glad you found the issue in your python code. One thing that might have helped is adding one more input pin as a qualifier to sampling the bus. Otherwise would will need make sure all FPGAs are fully synchronized.

Now for your bonus question:

Without change any behavior of your code you can eliminate 3 flops (start, gotFpgaAddress, and gotCommand) and a tiny bit of logic gates by converting tickCounter into a FSM. I noticed that when tickCounter is 0, you are always in an initileal/reset state. When it is 1, you are getting the address. When it is 2, you may collect the command if it is the target fpga address. And when it is 3, you toggle the LEDs if at the target fpga address.

localparam INIT=2'b0, GETADDR=2'b01, GETCMD=2'b10, TOGGLELED=2'b11;
reg [1:0] state;

reg [1:0] fpgaAddress;
reg [1:0] tileAddress;
reg [3:0] command;

initial begin
    state = INIT; // Note: initial blocks should use blocking statements
    t0 = 5'b11111;
    t1 = 5'b11111;
    t2 = 5'b11111;
    t3 = 5'b11111;
end

always @ (posedge clock) begin
  case(state)
    INIT :
      begin
        state <= GETADDR;
        // technically this is a dummy state, but needed to match behavior
      end
    GETADDR :
      begin
        state <= GETCMD;
        fpgaAddress <= bus[3:2];
        tileAddress <= bus[1:0];
      end
    GETCMD :
      begin
        state <= TOGGLELED;
        /* No output is effected in this state,
         * so it doesn't matter what the address is.
         * Preventing assignment to command would add logic.
         */
        command <= bus;
      end
    TOGGLELED :
      begin
        state <= INIT;
        // Here we care about the address
        if (fpgaAddress == MY_ADDRESS) begin
          // ... your assignments to t0-t3 here ...
          /* There are tricks to reduce the number of lines of code here,
           * but nothing I can immanently think of that will reduce gate count.
           */
        end
      end
  endcase
end

If really want to squeeze the area, you can bring it down to two states by removing the INIT and GETCMD states. Just remember that bus is now your command in the TOGGLELED state. Also note that this changes your design from a 4 cycles down to 2 cycles. So you would need to change stimulus (your python code) as well.

If you add the qualifier input pin I mentioned above then it is a tweak to the state assignment (ex: if (start_fsm) begin state <= NEXT_STATE ; /*... other stuff ...*/ end else begin state <= CURRENT_STATE; end).

One another topic, your module header is written in an somewhat outdated style called Non-ANSI. A more strict version of Non-ANSI is required with Verilog-1995 (ex output [4:0] t0; reg[4:0] t0; instead of output reg[4:0] t0;) but has lost popularity since Verilog-2001 became wildly supported. The modern header style is referred to as ANSI. With the ANSI style you declare the port order, direction, and type on the same line (where Non-ANSI required 2 to 3 separate lines). It is cleaner an less prone to typos.

module comm_protocol #(parameter [1:0] MY_ADDRESS = 2'b11) (
    input clock,
    input [3:0] bus,

    output reg [4:0] t0,
    output reg [4:0] t1,
    output reg [4:0] t2,
    output reg [4:0] t3,

    input wire t0cap, t1cap, t2cap, t3cap,
    output reg capOut );


问:
Javascript Round function
```<code>a                formula       b
31,283,700,000   round(a,-6)   31,284,000,000
60,204,605       round(a,-4)   60,200,000
</code>```

I have an excel formula to process the currency value,
but I have difficulties to achieve the same result by using javascript,
any ideas to solve this?

Thanks.

答:
Rounding is easy to implement:

function excelRound(n, e) {
  let f = Math.pow(10, e);
  return Math.round(n * f) / f;
}

console.log(31283700000, -6, excelRound(31283700000, -6));
console.log(60204605, -4, excelRound(60204605, -4));```

Title: Javascript Round function

Body:
a                formula       b
31,283,700,000   round(a,-6)   31,284,000,000
60,204,605       round(a,-4)   60,200,000

I have an excel formula to process the currency value,
but I have difficulties to achieve the same result by using javascript,
any ideas to solve this?

Thanks.


问:
Need help displaying min/max values of integers entered by user
I need help with a c++ program that:

"Prompts  users  for  N  integers  and  determines/displays  the  integer
with  the  highest  and  lowest  value  –  use  separate  functions  to  return  the  highest  and lowest value.  N is a random number from 5 to 10 (both inclusive)."

This is what I have so far:

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void randNumGenerator();
void smallestNum(int);
void largestNum(int);

int smallNum;
int largeNum;
int randomNum;
int num[10];

int main()
{
    smallestNum(smallNum);
    largestNum(largeNum);

    system("pause");
    return 0;
}

void randNumGenerator()
{
    srand(time(0));
    randomNum = 5 + (rand() % 10);

    for (int x = 1; x <= randomNum; x++) {
        cout << "Enter an integer: ";
        cin >> num[randomNum];
    }
}

void smallestNum(int smallNum)
{
    randNumGenerator();

    smallNum = num[randomNum];
    for (int i = 0; randomNum <= i; i++)
        if (num[randomNum] < smallNum)
        {
            smallNum = num[randomNum];
        }
    cout << "The smallest integer is: " << smallNum << endl;
}

void largestNum(int largeNum)
{
    randNumGenerator();

    largeNum = num[randomNum];
    for (int i = 0; i <= i; i++)
        if (num[randomNum] > largeNum)
        {
            largeNum = num[randomNum];
        }
    cout << "The largest integer is: " << largeNum << endl;
}
</code>```

But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!

答:
There are several issues:

First, with randomNum = 5 + (rand() % 10);, you generate random numbers between 5 and 14, inclusive, which may exceed int num[10]. Use randomNum = 5 + (rand() % 6); to get values between 5..10.

In your loops for (int i = 0; randomNum <= i; i++), with random <= i, you exceed array bounds since randomNum can go up to 10 and num[10] is already out of bounds for int num[10]. Write ... randomNum < i instead.

The same problem with smallNum = num[randomNum]; it exceeds array bounds; use smallNum = num[0] instead.

BTW: I'd interpret your assignment such that you enter the numbers once and then find the smallest and largest number in two different functions. In your code, you enter the numbers twice...

And: It's useless passing the smallNum into the function that overrides its value then. I'd rather use a function like int smallestNum() { ... return smallNum; } instead.

Hope it helps.

Body:
I need help with a c++ program that:

"Prompts  users  for  N  integers  and  determines/displays  the  integer
with  the  highest  and  lowest  value  –  use  separate  functions  to  return  the  highest  and lowest value.  N is a random number from 5 to 10 (both inclusive)."

This is what I have so far:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void randNumGenerator();
void smallestNum(int);
void largestNum(int);

int smallNum;
int largeNum;
int randomNum;
int num[10];

int main()
{
    smallestNum(smallNum);
    largestNum(largeNum);

    system("pause");
    return 0;
}

void randNumGenerator()
{
    srand(time(0));
    randomNum = 5 + (rand() % 10);

    for (int x = 1; x <= randomNum; x++) {
        cout << "Enter an integer: ";
        cin >> num[randomNum];
    }
}

void smallestNum(int smallNum)
{
    randNumGenerator();

    smallNum = num[randomNum];
    for (int i = 0; randomNum <= i; i++)
        if (num[randomNum] < smallNum)
        {
            smallNum = num[randomNum];
        }
    cout << "The smallest integer is: " << smallNum << endl;
}

void largestNum(int largeNum)
{
    randNumGenerator();

    largeNum = num[randomNum];
    for (int i = 0; i <= i; i++)
        if (num[randomNum] > largeNum)
        {
            largeNum = num[randomNum];
        }
    cout << "The largest integer is: " << largeNum << endl;
}

But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!


问:
Is it possible to remove touch screen requirement from UWP app?
I published a Windows 10 app in Store, and I am using the default appxmanifest file. Problem is - on the app store page Touch is listed in System Requirements/Minimum, which can mislead users (especially on desktops): the app does not require touch, you can do everything with mouse.

How do I (if possible), specify, that Touch is not required?

答:
How do I (if possible), specify, that Touch is not required?

When you create your new submission in Dev Center, you could uncheck the Minimum hardware for TouchScreen feature under System Requirements in Property and you could check Mouse if you want customer to know it's needed:

After your new submission passes certification, your Store listing will be changed so that customers on devices without a touch screen will not see a warning if they try to download your app.


问:
Sending Status Codes in NodeJS when serving static content
I am building a simple nodejs server to serve static content for a webpage. I want to send status codes back but when I try to create a function for the app.use() the content is not served.

```<code>var express = require('express')
var app = express();

app.listen(3000, function() {
  console.log("We are now listening on Port:3000")

  app.use(express.static('public'));

  app.use('*', express.static('public/404.html'));

});
</code>```

The content is served when I run this, but I cannot get the status codes as I need. Any help is appreciated.

答:
I don't know exactly what you want. This is my suggest solution:</p>

```<code>var express = require('express')
var app = express();

    app.listen(3000, function() {
      console.log("We are now listening on Port:3000")

      app.use(express.static('public'));

      app.use('*', function(req, res) {
        // change your status code here
        res.status(404).sendFile(__dirname + "/public/404.html");
      });

    });
</code>```

Body:
I am building a simple nodejs server to serve static content for a webpage. I want to send status codes back but when I try to create a function for the app.use() the content is not served.

var express = require('express')
var app = express();

app.listen(3000, function() {
  console.log("We are now listening on Port:3000")

  app.use(express.static('public'));

  app.use('*', express.static('public/404.html'));

});

The content is served when I run this, but I cannot get the status codes as I need. Any help is appreciated.

Body:
I don't know exactly what you want. This is my suggest solution:

var express = require('express')
var app = express();

    app.listen(3000, function() {
      console.log("We are now listening on Port:3000")

      app.use(express.static('public'));

      app.use('*', function(req, res) {
        // change your status code here
        res.status(404).sendFile(__dirname + "/public/404.html");
      });

    });


问:
Spring Boot WebSecurityConfigurerAdapter Login Redirect
I am using the following WebSecurityConfigurerAdapter code in a Spring Boot application:

```<code>    @Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/user/**").hasRole("USER").anyRequest().permitAll()
            .antMatchers("/admin/**").hasRole("EADM").anyRequest().permitAll()
            .and()
                .formLogin()
                .loginPage("/login")
                    .usernameParameter("personContactEmail").passwordParameter("personRegPwd")
                    .successHandler(secureAuthenticationSuccessHandler)
            .and()
                .logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/")
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true)
            .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}
</code>```

When I try to access the /user page without authenticating, the app redirects me to the login page, but when I try to access the /admin page without authenticating, the app takes me to the admin home page?

I have setup a custom AuthenticationSuccessHandler. When I debug and call the /user page, it goes in here, but with /admin it does not even reach this method. I am not sure what I am missing here?

```<code>  protected String determineTargetUrl(Authentication authentication) {
  boolean isUser = false;
  boolean isAdmin = false;
  Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

  for (GrantedAuthority grantedAuthority : authorities) {
      if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
          isUser = true;
          break;
      } else if (grantedAuthority.getAuthority().equals("ROLE_EADM")) {
          isAdmin = true;
          break;
      }
  }

  if (isUser)
  {
      return "/user";
  }
  else if (isAdmin)
  {
      return "/admin";
  }
  else
  {
      throw new IllegalStateException();
  }
}
</code>```

Any Help Please?

答:
.authorizeRequests()
              .antMatchers("/user/**").hasRole("USER").anyRequest().permitAll()
              .antMatchers("/admin/**").hasRole("EADM").anyRequest().permitAll()

antMatchers() and anyRequest() both create RequestMatchers (AntPathRequestMatcher and AnyRequestMatcher respectively) and return a RequestMatcherConfigurer. The RequestMatchers in a given RequestMatcherConfigurer are then applied sequentially when a request is processed. The first valid match is used to determine whether or not the user will be able to access the page. For this reason, your matchers should be ordered from most specific to least specific

.antMatchers("/user/**").hasRole("USER") is processed first, so /user/** requires ROLE_USER. .anyRequest().permitAll() is second, so when a request to /admin/** is processed, this request will match permitAll() and the user will be granted access to the page and  .antMatchers("/admin/**").hasRole("EADM") will never be processed.

This should be resolved by removing the first .anyRequest().permitAll(). like this:

```<code>...
http
    .authorizeRequests()
        .antMatchers("/user/**").hasRole("USER")
        .antMatchers("/admin/**").hasRole("EADM")
        .anyRequest().permitAll()
    .and()
...
</code>```

Body:
I am using the following WebSecurityConfigurerAdapter code in a Spring Boot application:

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/user/**").hasRole("USER").anyRequest().permitAll()
            .antMatchers("/admin/**").hasRole("EADM").anyRequest().permitAll()
            .and()
                .formLogin()
                .loginPage("/login")
                    .usernameParameter("personContactEmail").passwordParameter("personRegPwd")
                    .successHandler(secureAuthenticationSuccessHandler)
            .and()
                .logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/")
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true)
            .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}

When I try to access the /user page without authenticating, the app redirects me to the login page, but when I try to access the /admin page without authenticating, the app takes me to the admin home page?

I have setup a custom AuthenticationSuccessHandler. When I debug and call the /user page, it goes in here, but with /admin it does not even reach this method. I am not sure what I am missing here?

  protected String determineTargetUrl(Authentication authentication) {
  boolean isUser = false;
  boolean isAdmin = false;
  Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

  for (GrantedAuthority grantedAuthority : authorities) {
      if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
          isUser = true;
          break;
      } else if (grantedAuthority.getAuthority().equals("ROLE_EADM")) {
          isAdmin = true;
          break;
      }
  }

  if (isUser)
  {
      return "/user";
  }
  else if (isAdmin)
  {
      return "/admin";
  }
  else
  {
      throw new IllegalStateException();
  }
}

Any Help Please?

Body:
.authorizeRequests()
              .antMatchers("/user/**").hasRole("USER").anyRequest().permitAll()
              .antMatchers("/admin/**").hasRole("EADM").anyRequest().permitAll()

antMatchers() and anyRequest() both create RequestMatchers (AntPathRequestMatcher and AnyRequestMatcher respectively) and return a RequestMatcherConfigurer. The RequestMatchers in a given RequestMatcherConfigurer are then applied sequentially when a request is processed. The first valid match is used to determine whether or not the user will be able to access the page. For this reason, your matchers should be ordered from most specific to least specific

.antMatchers("/user/**").hasRole("USER") is processed first, so /user/** requires ROLE_USER. .anyRequest().permitAll() is second, so when a request to /admin/** is processed, this request will match permitAll() and the user will be granted access to the page and  .antMatchers("/admin/**").hasRole("EADM") will never be processed.

This should be resolved by removing the first .anyRequest().permitAll(). like this:

...
http
    .authorizeRequests()
        .antMatchers("/user/**").hasRole("USER")
        .antMatchers("/admin/**").hasRole("EADM")
        .anyRequest().permitAll()
    .and()
...


问:
Xamarin.Android : ListView not scrolling correctly in Coordinator Layout and CollapsingToolbarLayout
Good morning everyone!

I'm facing a scrolling issue in my app. I have a Coordinator Layout and a Listview. I want the top layout to be collapsing when I scroll in my listview.
I searched and found that this is not possible without a NestedScrollView so I added one.

The problem is that when I scroll, only the coordinator layout is scrolling.

As an example, when I scroll to the down, the listview is stuck like that:

I also tried to set the layout_height of my Listview to match_parent but it doesn't change anything.

Here is my code:

main.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ActionBarNoShadowLight"
        android:fitsSystemWindows="true"
        app:elevation="0dp">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            android:fitsSystemWindows="true">
            <ImageView
                android:id="@+id/mainImage"
                android:layout_width="175dp"
                android:layout_height="175dp"
                android:layout_marginTop="50dp"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/ic_document"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />
            <android.support.v7.widget.Toolbar
                android:id="@+id/edit_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/BackgroundWhite"
                app:layout_collapseMode="pin"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:clipToPadding="false"
        android:scrollbars="none"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <ListView
                android:id="@+id/lstTask"
                android:layout_height="match_parent"
                android:layout_width="fill_parent"
                android:nestedScrollingEnabled="true"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:divider="@null"
                />
            <ImageView
                android:id="@+id/empty"
                android:layout_height="200dp"
                android:layout_width="200dp"
                android:layout_marginTop="50dp"
                android:scaleType="fitCenter"
                android:gravity="center"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                app:srcCompat="@drawable/bg_notasks" />
        </FrameLayout>
    </android.support.v4.widget.NestedScrollView>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_plus" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Thanks a lot for your future help,
Clément.

答:
Just help you to convert Ayush Khare's code to C#, if this can help you, you could mark
@Ayush Khare's answer.

```<code>public class NonScrollListView : ListView
{
    public NonScrollListView(Context context) : base(context)
    {
    }

    public NonScrollListView(Context context, IAttributeSet attrs) : base(context, attrs)
    {
    }

    public NonScrollListView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
    {
    }

    protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int heightMeasureSpec_custom = MeasureSpec.MakeMeasureSpec(int.MaxValue >> 2, MeasureSpecMode.AtMost);
        base.OnMeasure(widthMeasureSpec, heightMeasureSpec);

        ViewGroup.LayoutParams params2 = LayoutParameters;
        params2.Height = MeasuredHeight;
    }
}
</code>```

Disable nested scrolling :

```<code>if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
{
    listView.NestedScrollingEnabled = false;
}
else
{
    ViewCompat.SetNestedScrollingEnabled(listView, false);
}
</code>```

Body:
Good morning everyone!

I'm facing a scrolling issue in my app. I have a Coordinator Layout and a Listview. I want the top layout to be collapsing when I scroll in my listview.
I searched and found that this is not possible without a NestedScrollView so I added one.

The problem is that when I scroll, only the coordinator layout is scrolling.

As an example, when I scroll to the down, the listview is stuck like that:

I also tried to set the layout_height of my Listview to match_parent but it doesn't change anything.

Here is my code:

main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ActionBarNoShadowLight"
        android:fitsSystemWindows="true"
        app:elevation="0dp">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            android:fitsSystemWindows="true">
            <ImageView
                android:id="@+id/mainImage"
                android:layout_width="175dp"
                android:layout_height="175dp"
                android:layout_marginTop="50dp"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/ic_document"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />
            <android.support.v7.widget.Toolbar
                android:id="@+id/edit_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/BackgroundWhite"
                app:layout_collapseMode="pin"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:clipToPadding="false"
        android:scrollbars="none"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <ListView
                android:id="@+id/lstTask"
                android:layout_height="match_parent"
                android:layout_width="fill_parent"
                android:nestedScrollingEnabled="true"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:divider="@null"
                />
            <ImageView
                android:id="@+id/empty"
                android:layout_height="200dp"
                android:layout_width="200dp"
                android:layout_marginTop="50dp"
                android:scaleType="fitCenter"
                android:gravity="center"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                app:srcCompat="@drawable/bg_notasks" />
        </FrameLayout>
    </android.support.v4.widget.NestedScrollView>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_plus" />
</android.support.design.widget.CoordinatorLayout>

Thanks a lot for your future help,
Clément.

Body:
Just help you to convert Ayush Khare's code to C#, if this can help you, you could mark
@Ayush Khare's answer.

public class NonScrollListView : ListView
{
    public NonScrollListView(Context context) : base(context)
    {
    }

    public NonScrollListView(Context context, IAttributeSet attrs) : base(context, attrs)
    {
    }

    public NonScrollListView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
    {
    }

    protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int heightMeasureSpec_custom = MeasureSpec.MakeMeasureSpec(int.MaxValue >> 2, MeasureSpecMode.AtMost);
        base.OnMeasure(widthMeasureSpec, heightMeasureSpec);

        ViewGroup.LayoutParams params2 = LayoutParameters;
        params2.Height = MeasuredHeight;
    }
}

Disable nested scrolling :

if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
{
    listView.NestedScrollingEnabled = false;
}
else
{
    ViewCompat.SetNestedScrollingEnabled(listView, false);
}

ContentLicense: CC BY-SA 4.0