问:
Pythonic way to merge keys with common values for a single dictionary
How do I merge the keys of a dictionary with common values into a tuple. For example:

```<code>A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}
</code>```

My attempt:

```<code>A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {}
seen = []
for k, v in A.items():
    if v not in [s[1] for s in seen]: # not seen this value yet
        print('NOT SEEN')
        print(k, v)
        seen.append([k,v])
        output[k] = v
    else: # already seen it
        print('SEEN')
        print(k, v)
        # determine where we've seen it
        where = [x for x in seen if x[1]==v]
        output.pop(where[0][0])
        output[(where[0][0], k)] = v

print('OUTPUT = ', output)
</code>```

This prints:

```<code>OUTPUT =  {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}
</code>```

答:
You can try this:

```<code>from collections import defaultdict

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

second_new = defaultdict(list)

for a, b in A.items():
    second_new[tuple(b)].append(a)

final_dict = {tuple(b):set(a) for a, b in second_new.items()}
</code>```

Output:

```<code>{('E8', 'E3'): {'8', '4'}, ('E5', 'E2'): {'5', '7'}}
</code>```

Body:
How do I merge the keys of a dictionary with common values into a tuple. For example:

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}

My attempt:

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {}
seen = []
for k, v in A.items():
    if v not in [s[1] for s in seen]: # not seen this value yet
        print('NOT SEEN')
        print(k, v)
        seen.append([k,v])
        output[k] = v
    else: # already seen it
        print('SEEN')
        print(k, v)
        # determine where we've seen it
        where = [x for x in seen if x[1]==v]
        output.pop(where[0][0])
        output[(where[0][0], k)] = v

print('OUTPUT = ', output)

This prints:

OUTPUT =  {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}

Body:
You can try this:

from collections import defaultdict

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

second_new = defaultdict(list)

for a, b in A.items():
    second_new[tuple(b)].append(a)

final_dict = {tuple(b):set(a) for a, b in second_new.items()}

Output:

{('E8', 'E3'): {'8', '4'}, ('E5', 'E2'): {'5', '7'}}


来源: stackexchange

问:
I can't edit a object in an array, ng-model doesn't change with ng-click
I am making a movie library. I use ng-repeat to show the movies and, for each movie there is a button to edit it and another one to remove it. The remove button works just fine, but the edit button doesn't.
It should open a panel and fill it with the movie data, but it only opens the panel with the first value I defined for the index.

```<code>button
<i class="glyphicon glyphicon-pencil small btnEdit" ng-click="i =(movies.indexOf(movie));"></i>

input
<input type="text" class="form-control" placeholder="Title" id="title" ng-model="movies[i].title">
</code>```

the whole code is here: https://jsfiddle.net/victoorns/mwgcnsno/2/

答:
Approach is putting too much business logic in the view.

Pass whole object back to controller when you do things like this. Then do any splicing, copying etc in controller:

Simplified example:

```<code><div ng-repeat="movie in movies">
  <button ng-click="edit(movie)">
  <button ng-click="delete(movie)">
</div>
</code>```

In controller:

```<code>  $scope.delete = function(movie){
    var idx = $scope.movies.indexOf(movie);
    if(idx !=-1){
       $scope.movies.splice(idx,1)
    }
  }

  $scope.edit = function(movie){
     $scope.selectedMovie = movie;
  }
</code>```

Also get rid of all the jQuery and get rid of bootstrap.js and replace with angular-ui-bootstrap

ContentLicense: CC BY-SA 3.0

Body:
I am making a movie library. I use ng-repeat to show the movies and, for each movie there is a button to edit it and another one to remove it. The remove button works just fine, but the edit button doesn't.
It should open a panel and fill it with the movie data, but it only opens the panel with the first value I defined for the index.

button

input
<input type="text" class="form-control" placeholder="Title" id="title" ng-model="movies[i].title">

the whole code is here: https://jsfiddle.net/victoorns/mwgcnsno/2/

Body:
Approach is putting too much business logic in the view.

Pass whole object back to controller when you do things like this. Then do any splicing, copying etc in controller:

Simplified example:

<div ng-repeat="movie in movies">
  <button ng-click="edit(movie)">
  <button ng-click="delete(movie)">
</div>

In controller:

  $scope.delete = function(movie){
    var idx = $scope.movies.indexOf(movie);
    if(idx !=-1){
       $scope.movies.splice(idx,1)
    }
  }

  $scope.edit = function(movie){
     $scope.selectedMovie = movie;
  }

Also get rid of all the jQuery and get rid of bootstrap.js and replace with angular-ui-bootstrap


问:
Passing a Class Alias to usort
I have a comparison function in a service class in namespace:

Company\Product\Services\Specific

which I import in to my Controller like:

use Company\Product\Service\Specific as SpecificService;

I have an array that I wish to sort in this Controller class:

usort ($array, 'SpecificService::sortFunction()');

However, this trips up my autoloader, which searches for a class literal SpecificService, which does not exist.  I can, however, get around this:

usort ($array, 'Company\Product\Services\Specific::sortFunction()');

I'm picky and want to use my alias.  How?

答:
Yes, you can do something like this:

```<code>use SomeNamespace\String\Tools as StringTools;
</code>```

and then, inside your method:

```<code>$arr  = ['a', 'c', 'e', 'b'];
$func = function ($a, $b) {
    return StringTools::cmp($a, $b);
    // or
    // $st = new StringTools();
    // return $st->cmp($a, $b);
    // if cmp isn't static
};
usort($arr, $func);
</code>```

Assuming that:

```<code>public static function cmp($a, $b)
{
    // do comparison here
    return strcmp($a, $b);
}
</code>```

and it's in a SomeNamespace\String\Tools as StringTools; namespace.

This way, your autoloader should work properly

If the method isn't static, you're gonna have to instantiate the classs in the anonymus function

Title: Passing a Class Alias to usort

Body:
Yes, you can do something like this:

use SomeNamespace\String\Tools as StringTools;

and then, inside your method:

$arr  = ['a', 'c', 'e', 'b'];
$func = function ($a, $b) {
    return StringTools::cmp($a, $b);
    // or
    // $st = new StringTools();
    // return $st->cmp($a, $b);
    // if cmp isn't static
};
usort($arr, $func);

Assuming that:

public static function cmp($a, $b)
{
    // do comparison here
    return strcmp($a, $b);
}

and it's in a SomeNamespace\String\Tools as StringTools; namespace.

This way, your autoloader should work properly

If the method isn't static, you're gonna have to instantiate the classs in the anonymus function


问:
Search and replace string and also put a counter in replacements
I have a bunch of files containing the exact same log message. One of them happens but as messages are identical I don't known which one. What I want to do is append a number after all these messages to distinguish them.

Now usually when I have a bunch search and replace to perform I just write a quick perl one-liner like:

```<code>perl -pi -e 's/searched/replacement/g' *.c
</code>```

But how can I insert a counter in replacement ?

答:
EDIT: OOPS This may only be helpful if your main project is in perl, too.

This is probably somewhat offtopic, but what about adding automagic location detection to the log messages? Like,

```<code>sub whereami {
    my $shout = shift;
    my @stack = caller(1);
    print LOG "$stack[1]:$stack[2]: $shout\n";
}
</code>```

(see perldoc caller)

Or even better, use Log::Log4perl qw/:easy/; -- it might be an overkill, but it's worth a try.

ContentLicense: CC BY-SA 2.5

Body:
I have a bunch of files containing the exact same log message. One of them happens but as messages are identical I don't known which one. What I want to do is append a number after all these messages to distinguish them.

Now usually when I have a bunch search and replace to perform I just write a quick perl one-liner like:

perl -pi -e 's/searched/replacement/g' *.c

But how can I insert a counter in replacement ?

Body:
EDIT: OOPS This may only be helpful if your main project is in perl, too.

This is probably somewhat offtopic, but what about adding automagic location detection to the log messages? Like,

sub whereami {
    my $shout = shift;
    my @stack = caller(1);
    print LOG "$stack[1]:$stack[2]: $shout\n";
}

(see perldoc caller)

Or even better, use Log::Log4perl qw/:easy/; -- it might be an overkill, but it's worth a try.


问:
One line solution for editing a numpy array of counts? (python)
I want to make a numpy array that contains how many times a value (between 1-3) occurs at a specific location. For example, if I have:

```<code>a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])
</code>```

I want to get back an array like so:

```<code>[[[ 1  0  0]
  [ 0  1  0]
  [ 0  0  1]]

 [[ 0  0  1]
  [ 0  1  0]
  [ 1  0  0]]

 [[ 0  1  0]
  [ 1  0  0]
  [ 0  0  1]]

 [[ 1  0  0]
  [ 1  0  0]
  [ 1  0  0]]]
</code>```

Where the array tells me that 1 occurs once in the first position, 2 occurs once in the second position, 3 occurs once in the third position, 1 occurs once in the fourth position, etc. Later, I'll have more input arrays of the same dimensions, and I would like to add on the totals of the values to this array of counts.

The code I have right now is:

```<code>a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

cumulative = np.zeros((4,3,3))

for r in range(len(cumulative)):
    for c in range(len(cumulative[0])):
        cumulative[r, c, a[r,c]-1] +=1
</code>```

This does give me the output I want. However, I would like to condense the for loops into one line, using a line similar to this:

```<code>cumulative[:, :, a[:, :]-1] +=1
</code>```

This line doesn't work, and I can't find anything online on how to perform this operation. Any suggestions?

Body:
I want to make a numpy array that contains how many times a value (between 1-3) occurs at a specific location. For example, if I have:

a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

I want to get back an array like so:

[[[ 1  0  0]
  [ 0  1  0]
  [ 0  0  1]]

 [[ 0  0  1]
  [ 0  1  0]
  [ 1  0  0]]

 [[ 0  1  0]
  [ 1  0  0]
  [ 0  0  1]]

 [[ 1  0  0]
  [ 1  0  0]
  [ 1  0  0]]]

Where the array tells me that 1 occurs once in the first position, 2 occurs once in the second position, 3 occurs once in the third position, 1 occurs once in the fourth position, etc. Later, I'll have more input arrays of the same dimensions, and I would like to add on the totals of the values to this array of counts.

The code I have right now is:

a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

cumulative = np.zeros((4,3,3))

for r in range(len(cumulative)):
    for c in range(len(cumulative[0])):
        cumulative[r, c, a[r,c]-1] +=1

This does give me the output I want. However, I would like to condense the for loops into one line, using a line similar to this:

cumulative[:, :, a[:, :]-1] +=1

This line doesn't work, and I can't find anything online on how to perform this operation. Any suggestions?

Body:
IIUC, you could take advantage of broadcasting:

In [93]: ((a[:, None] - 1) == np.arange(3)[:, None]).swapaxes(2, 1).astype(int)
Out[93]:
array([[[1, 0, 0],
        [0, 1, 0],
        [0, 0, 1]],

       [[0, 0, 1],
        [0, 1, 0],
        [1, 0, 0]],

       [[0, 1, 0],
        [1, 0, 0],
        [0, 0, 1]],

       [[1, 0, 0],
        [1, 0, 0],
        [1, 0, 0]]])


问:
Should I add a insert_time column for tracking the sequence [sqlite]
I have a table with an auto-increment primary key column; I want to fetch the items of this table order by the time when the record is inserted. I wonder is it necessary to have a dedicated insert_time column for that purpose?</p>

答: If you want to know which records came before others you can just use the primary key. If you want to know the actual time of the record, you will need another column.


问:
Unit testing Room and LiveData
I'm currently developing an app using the newly Android Architecture Components. Specifically, I'm implementing a Room Database that returns a LiveData object on one of its queries. Insertion and querying work as expected, however I have an issue testing the query method using a unit test.

Here is the DAO I'm trying to test:

NotificationDao.kt

```<code>@Dao
interface NotificationDao {

    @Insert
    fun insertNotifications(vararg notifications: Notification): List<Long>

    @Query("SELECT * FROM notifications")
    fun getNotifications(): LiveData<List<Notification>>
}
</code>```

As you can tell, the query function returns a LiveData object, if I change this to be just a List, Cursor, or basically whatever then I get the expected result, which is the data inserted in the Database.

The issue is that the following test will always fail because the value of the LiveData object is always null:

NotificationDaoTest.kt

```<code>lateinit var db: SosafeDatabase
lateinit var notificationDao: NotificationDao

@Before
fun setUp() {
    val context = InstrumentationRegistry.getTargetContext()
    db = Room.inMemoryDatabaseBuilder(context, SosafeDatabase::class.java).build()
    notificationDao = db.notificationDao()
}

@After
@Throws(IOException::class)
fun tearDown() {
    db.close()
}

@Test
fun getNotifications_IfNotificationsInserted_ReturnsAListOfNotifications() {
    val NUMBER_OF_NOTIFICATIONS = 5
    val notifications = Array(NUMBER_OF_NOTIFICATIONS, { i -> createTestNotification(i) })
    notificationDao.insertNotifications(*notifications)

    val liveData = notificationDao.getNotifications()
    val queriedNotifications = liveData.value
    if (queriedNotifications != null) {
        assertEquals(queriedNotifications.size, NUMBER_OF_NOTIFICATIONS)
    } else {
        fail()
    }
}

private fun createTestNotification(id: Int): Notification {
    //method omitted for brevity
}
</code>```

So the question is: Does anyone knows of a better way to perform unit tests that involve LiveData objects?

答:
When you return a LiveData from a Dao in Room it makes the query asynchronously, and as @yigit said Room sets the LiveData#value lazily after you kick off the query by observing the LiveData. This pattern is reactive.

For unit tests you want the behavior to be synchronous, so you must block the test thread and wait for the value to be passed to the observer, then grab it from there and then you can assert on it.

Here's a Kotlin extension function for doing this:

```<code>private fun <T> LiveData<T>.blockingObserve(): T? {
    var value: T? = null
    val latch = CountDownLatch(1)

    val observer = Observer<T> { t ->
        value = t
        latch.countDown()
    }

    observeForever(observer)

    latch.await(2, TimeUnit.SECONDS)
    return value
}
</code>```

You can use it like this:

```<code>val someValue = someDao.getSomeLiveData().blockingObserve()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Unit testing Room and LiveData

Body:
I'm currently developing an app using the newly Android Architecture Components. Specifically, I'm implementing a Room Database that returns a LiveData object on one of its queries. Insertion and querying work as expected, however I have an issue testing the query method using a unit test.

Here is the DAO I'm trying to test:

NotificationDao.kt

@Dao
interface NotificationDao {

    @Insert
    fun insertNotifications(vararg notifications: Notification): List<Long>

    @Query("SELECT * FROM notifications")
    fun getNotifications(): LiveData<List<Notification>>
}

As you can tell, the query function returns a LiveData object, if I change this to be just a List, Cursor, or basically whatever then I get the expected result, which is the data inserted in the Database.

The issue is that the following test will always fail because the value of the LiveData object is always null:

NotificationDaoTest.kt

lateinit var db: SosafeDatabase
lateinit var notificationDao: NotificationDao

@Before
fun setUp() {
    val context = InstrumentationRegistry.getTargetContext()
    db = Room.inMemoryDatabaseBuilder(context, SosafeDatabase::class.java).build()
    notificationDao = db.notificationDao()
}

@After
@Throws(IOException::class)
fun tearDown() {
    db.close()
}

@Test
fun getNotifications_IfNotificationsInserted_ReturnsAListOfNotifications() {
    val NUMBER_OF_NOTIFICATIONS = 5
    val notifications = Array(NUMBER_OF_NOTIFICATIONS, { i -> createTestNotification(i) })
    notificationDao.insertNotifications(*notifications)

    val liveData = notificationDao.getNotifications()
    val queriedNotifications = liveData.value
    if (queriedNotifications != null) {
        assertEquals(queriedNotifications.size, NUMBER_OF_NOTIFICATIONS)
    } else {
        fail()
    }
}

private fun createTestNotification(id: Int): Notification {
    //method omitted for brevity
}

So the question is: Does anyone knows of a better way to perform unit tests that involve LiveData objects?

Body:
When you return a LiveData from a Dao in Room it makes the query asynchronously, and as @yigit said Room sets the LiveData#value lazily after you kick off the query by observing the LiveData. This pattern is reactive.

For unit tests you want the behavior to be synchronous, so you must block the test thread and wait for the value to be passed to the observer, then grab it from there and then you can assert on it.

Here's a Kotlin extension function for doing this:

private fun <T> LiveData<T>.blockingObserve(): T? {
    var value: T? = null
    val latch = CountDownLatch(1)

    val observer = Observer<T> { t ->
        value = t
        latch.countDown()
    }

    observeForever(observer)

    latch.await(2, TimeUnit.SECONDS)
    return value
}

You can use it like this:

val someValue = someDao.getSomeLiveData().blockingObserve()


问:
XSAVE causes Unhandled exception in VS 2017
This code is being run on an Intel 4770K (which supports AVX2 and XSAVE set). The environment is MASM (in VS 2017).

```<code>and  rsp,-40H     ; aligns stack to 64 byte
sub  rsp,2000H    ; creates enough space to write out the XSAVE
mov  qword ptr xsave_space_ptr, rsp
xor  rcx,rcx      ; XCR(0)
xgetbv            ; returns RAX:7,RDX:0
mov  rax,7
mov  rdx,0
xsave  qword ptr xsave_space_ptr ; this is where the VS 2017 crashes.
</code>```

Any suggestion on what is incorrect in this usage is welcome. It also fails if all bits in the EDX:EAX are set to 1.

答:
```<code>xsave  qword ptr xsave_space_ptr
</code>```

It is irrelevant what value is contained in xsave_space_ptr, the location you're xsaveing to here is xsave_space_ptr itself. xsave (like any typical instruction that writes to memory) writes to the address it is given, it doesn't read a pointer from the address it is given and then write to wherever the pointer points, which this code seems to assume. Therefore the address it writes to here may not be 64-aligned (why would it be, except by coincidence) which would cause an exception. It looks like you intended to do this:

```<code>xsave [rsp]
</code>```

Body:
This code is being run on an Intel 4770K (which supports AVX2 and XSAVE set). The environment is MASM (in VS 2017).

and  rsp,-40H     ; aligns stack to 64 byte
sub  rsp,2000H    ; creates enough space to write out the XSAVE
mov  qword ptr xsave_space_ptr, rsp
xor  rcx,rcx      ; XCR(0)
xgetbv            ; returns RAX:7,RDX:0
mov  rax,7
mov  rdx,0
xsave  qword ptr xsave_space_ptr ; this is where the VS 2017 crashes.

Any suggestion on what is incorrect in this usage is welcome. It also fails if all bits in the EDX:EAX are set to 1.

Body:
xsave  qword ptr xsave_space_ptr

It is irrelevant what value is contained in xsave_space_ptr, the location you're xsaveing to here is xsave_space_ptr itself. xsave (like any typical instruction that writes to memory) writes to the address it is given, it doesn't read a pointer from the address it is given and then write to wherever the pointer points, which this code seems to assume. Therefore the address it writes to here may not be 64-aligned (why would it be, except by coincidence) which would cause an exception. It looks like you intended to do this:

xsave [rsp]


问:
Lightweight javascript real-time ticker
I am using ajax to pull from a php file that pulls from a database that gets updated (truncate/insert) every minute. I call the ajax with a setInterval() every 30 seconds. After about 50 people got on the site, it crashed. Is there a better way to set it up to handle more users?</p>

答:
You could try using a cron job to run a single query every 30 seconds, storing the result in a global variable $GLOBALS['results']; and then letting your users pull that back to their browser instead of letting each user hit the database.

And depending on what your're storing (totals perhaps) you could optimize the query by only pulling the records created since the last update.

Title: Lightweight javascript real-time ticker


问:
We just upgraded to VB2017 Community: Can I create a custom toolbox?
I am trying to simplify the toolbox for beginner programmers.  There are too many entries in any of the toolboxes for the few that they will be using

How can I create a custom toolbox that will contain Button, Textbox, listbox, picturebox, for starters.

I saw "Tools/ Choose Toolbox items" and saw that I could select tools from the list but did not seem to be able to proceed from there.

If nothing else, can I arrange these to be at the top of the list of a toolbox?

答:
Yes you can do this:

Right Click on the Toolbox and choose Add Tab. After adding the tab give the item a name.

The do one of the following:

Right click on the new item and choose add items. A dialog will show up and could take some time to build the list of components available. Once completed in the dialog, add the items you would like.

(Faster method) Right on an existing item in another Tool Box and choose copy. After copying the item right click on your custom toolbox and choose paste.

I have created a Custom Toolbox in the following screen shot:


问:
How to design a progress bar logic when inputs are less than 10?
I am parsing strings from an array and showing progress as the strings are parsed. This is my logic but it doesn't scale for inputs less than 10.

Divide by zero is already taken care of during the initial part of the function for 100*i/(lineLen-1)

```<code>progress := 0
for i:= 0; i<lineLen;i++ {
 //.. lineLen = array length
//.....String processing...
if (100*i/(lineLen-1)) >= progress {
     fmt.Printf("--%d%s--", progress, "%")
     progress += 10
}
}
</code>```

答:
I understand that you need to floor all the percentages to a multiple of 10.

You could try something like the following.

```<code>lineLen := 4
progress := 0
for i := 0; i < lineLen; i++ {
    // Rounding down to the nearest multiple of 10.
    actualProgress := (100 * (i+1) / lineLen)
    if actualProgress >= progress {
        roundedProgress := (actualProgress / 10) * 10
        // Condition to make sure the previous progress percentage is not repeated.
        if roundedProgress != progress{
            progress = roundedProgress
            fmt.Printf("--%d%s--", progress, "%")
        }
    }
}
</code>```

Link

Body:
I am parsing strings from an array and showing progress as the strings are parsed. This is my logic but it doesn't scale for inputs less than 10.

Divide by zero is already taken care of during the initial part of the function for 100*i/(lineLen-1)

progress := 0
for i:= 0; i<lineLen;i++ {
 //.. lineLen = array length
//.....String processing...
if (100*i/(lineLen-1)) >= progress {
     fmt.Printf("--%d%s--", progress, "%")
     progress += 10
}
}

Body:
I understand that you need to floor all the percentages to a multiple of 10.

You could try something like the following.

lineLen := 4
progress := 0
for i := 0; i < lineLen; i++ {
    // Rounding down to the nearest multiple of 10.
    actualProgress := (100 * (i+1) / lineLen)
    if actualProgress >= progress {
        roundedProgress := (actualProgress / 10) * 10
        // Condition to make sure the previous progress percentage is not repeated.
        if roundedProgress != progress{
            progress = roundedProgress
            fmt.Printf("--%d%s--", progress, "%")
        }
    }
}

Link


问:
dom is not defined error after transforming jsx to js
I created a jsx file as below

```<code>  /** @jsx dom */
(function(){
'use strict';

define([
        'jquery',
        'react',
        'react-dom'
    ],

    function($, React, ReactDOM){

        var AppView = React.createClass({
            render: function() {
                return <div>Hello World</div>;
            }
        });

        ReactDOM.render(<AppView />, document.getElementById('dsl-application'));

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

And transformed the jsx to js using below command

```<code>babel --watch src --out-dir bundle --preset react
</code>```

And the out put file is like below

```<code>(function () {
'use strict';

define(['jquery', 'react', 'react-dom'], function ($, React, ReactDOM) {

    var AppView = React.createClass({
        displayName: 'AppView',

        render: function () {
            return dom(
                'div',
                null,
                'Hello World'
            );
        }
    });

    ReactDOM.render(dom(AppView, null), document.getElementById('dsl-application'));
});
})();
</code>```

The problem is I got Uncaught ReferenceError: dom is not defined when I run the js file in browser. dom is added after transformation. Any clue how to fix this?

答:
Run into this same issue with a basic React app.

Turned out that the culprit was in my webpack.config.js. I had:

plugins: [
    ["transform-react-jsx", {
        "pragma": "dom"
    }]
]
```

<p>babel's default pragma is React.createElement (https://babeljs.io/docs/plugins/transform-react-jsx/).</p>

<p>The truth is that I had no reason for this option, I had just copy/pasted
from the link above.</p>

<p>From the docs, I should have imported the 'dom' module that I had
specified and made sure I had babel-plugin-jsx-pragmatic installed.</p>

<p>The docs for this plugin are here https://www.npmjs.com/package/babel-plugin-jsx-pragmatic and explain a little bit about pragmas.</p>

<p>I fixed this issue by simply removing the 'pragma' option so I could
just use the default one ( attached a part of my webpack.config.js to provide more context): -- I am using webpack 2.6.1</p>

<pre class="lang-js prettyprint-override"><code>...
module: {
    rules: [{
      //a regexp that tells webpack to use the following loaders on all
      //.js and .jsx files
      test: /\.js$/,
      loader: 'babel-loader',
      options: {
        babelrc: false,
        presets: ["es2016", "react", "stage-0"],
        plugins: [
          ["transform-react-jsx"]
        ]
      },
      //we definitely don't want babel to transpile all the files in
      //node_modules. That would take a long time.
      exclude: /node_modules/
    },

...
</code>```

Body:
I created a jsx file as below

  /** @jsx dom */
(function(){
'use strict';

define([
        'jquery',
        'react',
        'react-dom'
    ],

    function($, React, ReactDOM){

        var AppView = React.createClass({
            render: function() {
                return
Hello World
;
            }
        });

        ReactDOM.render(<AppView />, document.getElementById('dsl-application'));

    });
})();

And transformed the jsx to js using below command

babel --watch src --out-dir bundle --preset react

And the out put file is like below

(function () {
'use strict';

define(['jquery', 'react', 'react-dom'], function ($, React, ReactDOM) {

    var AppView = React.createClass({
        displayName: 'AppView',

        render: function () {
            return dom(
                'div',
                null,
                'Hello World'
            );
        }
    });

    ReactDOM.render(dom(AppView, null), document.getElementById('dsl-application'));
});
})();

The problem is I got Uncaught ReferenceError: dom is not defined when I run the js file in browser. dom is added after transformation. Any clue how to fix this?

Body:
Run into this same issue with a basic React app.

Turned out that the culprit was in my webpack.config.js. I had:

plugins: [
    ["transform-react-jsx", {
        "pragma": "dom"
    }]
]

babel's default pragma is React.createElement (https://babeljs.io/docs/plugins/transform-react-jsx/).

The truth is that I had no reason for this option, I had just copy/pasted
from the link above.

From the docs, I should have imported the 'dom' module that I had
specified and made sure I had babel-plugin-jsx-pragmatic installed.

The docs for this plugin are here https://www.npmjs.com/package/babel-plugin-jsx-pragmatic and explain a little bit about pragmas.

I fixed this issue by simply removing the 'pragma' option so I could
just use the default one ( attached a part of my webpack.config.js to provide more context): -- I am using webpack 2.6.1

...
module: {
    rules: [{
      //a regexp that tells webpack to use the following loaders on all
      //.js and .jsx files
      test: /\.js$/,
      loader: 'babel-loader',
      options: {
        babelrc: false,
        presets: ["es2016", "react", "stage-0"],
        plugins: [
          ["transform-react-jsx"]
        ]
      },
      //we definitely don't want babel to transpile all the files in
      //node_modules. That would take a long time.
      exclude: /node_modules/
    },

...


问:
c# mvc razor view foreach create dynamic table columns
I have a model with 4 properties and each property is a List<T>

Now I want to build a table and the data from each of the 4 propeties will be shown in it's own column. The properties can have different amount of items in them.

How can I loop through the properties of my model and show their items in their own column?

```<code>public class ViewModel
{
   public class List<Custom1> Prop1 {get; set;}
   public class List<Custom2> Prop2 {get; set;}
   public class List<Custom3> Prop3 {get; set;}
   public class List<Custom4> Prop4 {get; set;}
}

Custom1, Custom2, Custom3, Custom4 are all POCO clases and have one common property called Name.
</code>```

答:
Find the max length (M) among the properties. Then use a for loop to iterate M times. Access using the indexer model.Prop1[i]. You'll need to check to make sure you don't go out-of-bounds since each collection is a different size.

```<code>@{
    int rowCount = GetMax(model.Prop1, model.Prop2, model.Prop3);
    int p1Size = model.Prop1.Count();
    int p2Size = model.Prop2.Count();
    int p3Size = model.Prop3.Count();
}

@for (int i = 0; i < rowCount; i++)
{
    var c1 = (i < p1Size) ? model.Prop1[i] : "";
    var c2 = (i < p2Size) ? model.Prop2[i] : "";
    var c3 = (i < p3Size) ? model.Prop3[i] : "";

    <tr><td>@c1</td><td>@c2</td><td>@c3</td></tr>
}
</code>```

Body:
I have a model with 4 properties and each property is a List<T>

Now I want to build a table and the data from each of the 4 propeties will be shown in it's own column. The properties can have different amount of items in them.

How can I loop through the properties of my model and show their items in their own column?

public class ViewModel
{
   public class List<Custom1> Prop1 {get; set;}
   public class List<Custom2> Prop2 {get; set;}
   public class List<Custom3> Prop3 {get; set;}
   public class List<Custom4> Prop4 {get; set;}
}

Custom1, Custom2, Custom3, Custom4 are all POCO clases and have one common property called Name.

Body:
Find the max length (M) among the properties. Then use a for loop to iterate M times. Access using the indexer model.Prop1[i]. You'll need to check to make sure you don't go out-of-bounds since each collection is a different size.

@{
    int rowCount = GetMax(model.Prop1, model.Prop2, model.Prop3);
    int p1Size = model.Prop1.Count();
    int p2Size = model.Prop2.Count();
    int p3Size = model.Prop3.Count();
}

@for (int i = 0; i < rowCount; i++)
{
    var c1 = (i < p1Size) ? model.Prop1[i] : "";
    var c2 = (i < p2Size) ? model.Prop2[i] : "";
    var c3 = (i < p3Size) ? model.Prop3[i] : "";

    <tr><td>@c1</td><td>@c2</td><td>@c3</td></tr>
}


问:
How to uninstall pygame on mac OSX 10.9.4
In fact, I meet the problem that my pygame can not load png image and the method pygame.image.get_extended() returns 0, which means false

```<code>Traceback (most recent call last):
  File "testpygame.py", line 5, in <module>
    myimage = pygame.image.load("diamond.png")
pygame.error: File is not a Windows BMP file
</code>```

I search for solutions and some people suggest that installing the proper version
of pygame might help, so I want to uninstall my current pygame and reinstall

But I dont know how to uninstall pygame on OSX

I installed 2 versions of python on mac (2.7 and 3.3), they are in the list of applications. But as we all know that the default python in mac that runs in terminal is another one given by the operating system itself, the different versions of python in mac totally confused me...

So, how can I uninstall pygame of the proper python version in my mac..?
Thanks a lot

答:
My copy of pygame was installed via the disk image (.dmg) from this download page, which contains a package installer (.mpkg). You can attempt to uninstall the package, but that didn't work for me. Using the Suspicious Package app, I can look at the installer to see what it installs.

For the 1.9.1 version of Pygame, it installs the following:

```<code>/Developer/Python/pygame
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pygame
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame-1.9.1release-py2.7.egg-info
/Library/Frameworks/SDL_image.framework
/Library/Frameworks/SDL_mixer.framework
/Library/Frameworks/SDL_ttf.framework
/Library/Frameworks/SDL.framework
/Library/Frameworks/smpeg.framework
</code>```

You can manually delete all of these files to clear pygame from your system.

Note that Python.framework is where all user-installed versions of Python go to. If you are sure that you do not have a user-installed version of Python, you can delete it entirely. Otherwise, you should surgically remove the pygame parts as shown above.

Body:
In fact, I meet the problem that my pygame can not load png image and the method pygame.image.get_extended() returns 0, which means false

Traceback (most recent call last):
  File "testpygame.py", line 5, in <module>
    myimage = pygame.image.load("diamond.png")
pygame.error: File is not a Windows BMP file

I search for solutions and some people suggest that installing the proper version
of pygame might help, so I want to uninstall my current pygame and reinstall

But I dont know how to uninstall pygame on OSX

I installed 2 versions of python on mac (2.7 and 3.3), they are in the list of applications. But as we all know that the default python in mac that runs in terminal is another one given by the operating system itself, the different versions of python in mac totally confused me...

So, how can I uninstall pygame of the proper python version in my mac..?
Thanks a lot

Body:
My copy of pygame was installed via the disk image (.dmg) from this download page, which contains a package installer (.mpkg). You can attempt to uninstall the package, but that didn't work for me. Using the Suspicious Package app, I can look at the installer to see what it installs.

For the 1.9.1 version of Pygame, it installs the following:

/Developer/Python/pygame
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pygame
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame-1.9.1release-py2.7.egg-info
/Library/Frameworks/SDL_image.framework
/Library/Frameworks/SDL_mixer.framework
/Library/Frameworks/SDL_ttf.framework
/Library/Frameworks/SDL.framework
/Library/Frameworks/smpeg.framework

You can manually delete all of these files to clear pygame from your system.

Note that Python.framework is where all user-installed versions of Python go to. If you are sure that you do not have a user-installed version of Python, you can delete it entirely. Otherwise, you should surgically remove the pygame parts as shown above.


问:
turning string into a number
I am trying to calculate the price total of the below html code and add the result to the dom throuh the JS code further below:

```<code><div class="row">
<div class="col-xs-2 text-center">
<span class="p-name">IronBubble-head</span>
<span id="price-number">$25</span>
<label id="qty" for="qty">QTY</label><input type="number" value="1">
<span id="total">0</span>
<button class="btn btn-delete" type="button">Delete</button>
</div>
</div>
</code>```

and this javascript code:

```<code>function getTotalPrice(e) {
var Price = document.getElementById('price-number').value;
var Quantity = document.getElementById('qty').value;
var Total = document.getElementById('total');
total.innerHTML = Price * Quantity;
}
</code>```

Although the result I get is always NaN.
where is the mistake?

Thanks!

答:
Your code stores "$25" as a string in the variable Price. You need to remove the dollar sign and parse the "25" string as an integer. For example you could add this line to your code anywhere after your initial assignment of the variable Price: </p>

```<code>Price = parseInt(Price.slice(1, Price.length));
</code>```

Title: turning string into a number

Body:
I am trying to calculate the price total of the below html code and add the result to the dom throuh the JS code further below:

IronBubble-head
$25
QTY<input type="number" value="1">
0
<button class="btn btn-delete" type="button">Delete</button>

and this javascript code:

function getTotalPrice(e) {
var Price = document.getElementById('price-number').value;
var Quantity = document.getElementById('qty').value;
var Total = document.getElementById('total');
total.innerHTML = Price * Quantity;
}

Although the result I get is always NaN.
where is the mistake?

Thanks!

Body:
Your code stores "$25" as a string in the variable Price. You need to remove the dollar sign and parse the "25" string as an integer. For example you could add this line to your code anywhere after your initial assignment of the variable Price:

Price = parseInt(Price.slice(1, Price.length));


问:
Tkinter Gui linking button to .py file to open another Gui
Good Evening!  I am trying to figure out how to get a button to, when clicked, open up another Gui in another .py file that is in the same file folder. (I have tried every answer given in other questions that remotely might answer this for me).

```<code>enter code here
#this file is called main.py
from tkinter import *

root1 = Tk()
root1.title("ProQA-ish")

fphoto = PhotoImage(file="../icon/fireorig.png") #change wd to file named icon
fireButton = Button(root1, image=fphoto)
fireButton.config( height=228, width=200)
mphoto = PhotoImage(file="../icon/ems.png")  #change wd to file named icon
emsButton = Button(root1, image=mphoto)
emsButton.config( height=224, width=197)
fireButton.pack(side=LEFT)
emsButton.pack(side=RIGHT)

root1.mainloop()

enter code here
#this is called emdmenu.py
from tkinter import *

root = Tk()
root.title("Emergency Medical Dispatch")
root.iconbitmap(default='../icon/fire.ico')
#----Window------

topframe = Frame(root)
topframe.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

#---Create Buttons for choices----
abdominalPnB = Button(topframe, text="01_Abdominal Pain")
abdominalPnB.config(anchor="w", width=20, height=1)
abdominalPnB.grid(row=0, column=0)

allergyrxB = Button(topframe, text="02_Allergic Reaction")
allergyrxB.config(anchor="w", width=20, height=1)
allergyrxB.grid(row=1, column=0)
#ect..

root.mainloop()
</code>```

Any help would be amazing, thank you!

答:
You need to import that other .py file into your current one

Do this just like any other module.  import myfile.py

create another tkinter function in the external script

link the button to the function in the external script.

The button links with the command key. so it should look like:

```<code>but = Button(bottom, text='click me', command=do_something)
</code>```

In this example do_something is the name of the other function. It is weird here you dont actually put () into the command argument. But do_something() is a normal funciton

EDIT
Looking at your code and reading your comments I think that what your missing is the concept of creating and calling functions. Your code in the external file is executing first because when you import something it is ran. To avoid this put the code inside a funtion.

In your external file you should have something like this:

```<code>def func_name():
    print('hello world')
</code>```

Then in your main file the button should have:

command=func_name

Body:
Good Evening!  I am trying to figure out how to get a button to, when clicked, open up another Gui in another .py file that is in the same file folder. (I have tried every answer given in other questions that remotely might answer this for me).

enter code here
#this file is called main.py
from tkinter import *

root1 = Tk()
root1.title("ProQA-ish")

fphoto = PhotoImage(file="../icon/fireorig.png") #change wd to file named icon
fireButton = Button(root1, image=fphoto)
fireButton.config( height=228, width=200)
mphoto = PhotoImage(file="../icon/ems.png")  #change wd to file named icon
emsButton = Button(root1, image=mphoto)
emsButton.config( height=224, width=197)
fireButton.pack(side=LEFT)
emsButton.pack(side=RIGHT)

root1.mainloop()

enter code here
#this is called emdmenu.py
from tkinter import *

root = Tk()
root.title("Emergency Medical Dispatch")
root.iconbitmap(default='../icon/fire.ico')
#----Window------

topframe = Frame(root)
topframe.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

#---Create Buttons for choices----
abdominalPnB = Button(topframe, text="01_Abdominal Pain")
abdominalPnB.config(anchor="w", width=20, height=1)
abdominalPnB.grid(row=0, column=0)

allergyrxB = Button(topframe, text="02_Allergic Reaction")
allergyrxB.config(anchor="w", width=20, height=1)
allergyrxB.grid(row=1, column=0)
#ect..

root.mainloop()

Any help would be amazing, thank you!

Body:
You need to import that other .py file into your current one

Do this just like any other module.  import myfile.py

create another tkinter function in the external script

link the button to the function in the external script.

The button links with the command key. so it should look like:

but = Button(bottom, text='click me', command=do_something)

In this example do_something is the name of the other function. It is weird here you dont actually put () into the command argument. But do_something() is a normal funciton

EDIT
Looking at your code and reading your comments I think that what your missing is the concept of creating and calling functions. Your code in the external file is executing first because when you import something it is ran. To avoid this put the code inside a funtion.

In your external file you should have something like this:

def func_name():
    print('hello world')

Then in your main file the button should have:

command=func_name


问:
How Am I Changing "this" in Method append(int n)?
I initialized LinkedNode "node" to become keyword "this" and then I append the new node, "last", to the end of the created node, "node". But notice also in the while loop I change "node" to become "node.next". Why does it print the correct result when I run the program? Maybe I don't understand "this" very well.</p>

```<code>public class LinkedNode {

    protected LinkedNode next;
    protected int data;

    LinkedNode(int d) {
        data = d;
    }

    public void append(int n) {
        LinkedNode node = this;
        LinkedNode last  = new LinkedNode(n);
        while (node.next != null) {
            node = node.next;
        }
        node.next = last;
    }

    public static void main(String[] args) {
        LinkedNode Node = new LinkedNode(2);
        Node.append(3);
        Node.append(4);
        Node.append(5);
        for (int i = 0; i < 4; i++) {
            System.out.println("Data: "+Node.data);
            Node = Node.next;
        }
    }
    //Output is correctly "2 3 4 5"
}
</code>```

答:
I don't know whether you understand "this", but what I suspect is that you do not understand java.

In the append() function, node is a pointer to object of type LinkedNode. Initially, the pointer is set to point to the same location as the this pointer, so it points to the current object.

Then, within the loop, the node pointer is set to point to other things, and in the last line a new value ("last") is stored in one of the fields of the object which happens to be pointed by the node pointer after the loop.

If the loop did not loop at all, then node is still pointing at the current object, so the current object is modified.  If the loop looped one or more times, then node is pointing to some other object, so that other object is modified.

No attempt whatsoever is made, at any moment, to change the this pointer, and no such attempt could be made, as that would be illegal in java.

Body:
I initialized LinkedNode "node" to become keyword "this" and then I append the new node, "last", to the end of the created node, "node". But notice also in the while loop I change "node" to become "node.next". Why does it print the correct result when I run the program? Maybe I don't understand "this" very well.

public class LinkedNode {

    protected LinkedNode next;
    protected int data;

    LinkedNode(int d) {
        data = d;
    }

    public void append(int n) {
        LinkedNode node = this;
        LinkedNode last  = new LinkedNode(n);
        while (node.next != null) {
            node = node.next;
        }
        node.next = last;
    }

    public static void main(String[] args) {
        LinkedNode Node = new LinkedNode(2);
        Node.append(3);
        Node.append(4);
        Node.append(5);
        for (int i = 0; i < 4; i++) {
            System.out.println("Data: "+Node.data);
            Node = Node.next;
        }
    }
    //Output is correctly "2 3 4 5"
}


问:
Dockerfile VOLUME not working while -v works
When I pass volume like -v /dir:/dir it works like it should

But when I use VOLUME in my dockerfile it gets mountend empty

My Dockerfile looks like this

```<code>FROM ubuntu:16.04

RUN apt-get update
RUN apt-get install nano
ENV Editor="/usr/bin/nano"

ARG UID=1000
RUN useradd -u "$UID" -G root writer
RUN mkdir -p "/home/writer" && chown -R "$UID":1000 "/home/writer"

RUN mkdir -p "/home/stepik"
RUN chown -R "$UID":1000 "/home/stepik"
VOLUME ["/home/stepik"]

USER writer

WORKDIR /home/stepik
ENTRYPOINT ["bash"]
</code>```

答:
Defining the volume on the Dockerfile only tells docker that the volume needs to exist inside the container, not where to get the volume from. It's the same as passing the option -v /dir instead of -v /dir:/dir. The result is an "anonymous" volume with a guid you can see in docker volume ls. You can't pass the option inside the Dockerfile to identify where to mount the volume from, images you pull from the docker hub can't mount an arbitrary directory from your host and send the contents of that directory to a black hat machine on the internet by design.

Note that I don't recommend defining volumes inside the Dockerfile. See my blog post on the topic for more details.

Body:
When I pass volume like -v /dir:/dir it works like it should

But when I use VOLUME in my dockerfile it gets mountend empty

My Dockerfile looks like this

FROM ubuntu:16.04

RUN apt-get update
RUN apt-get install nano
ENV Editor="/usr/bin/nano"

ARG UID=1000
RUN useradd -u "$UID" -G root writer
RUN mkdir -p "/home/writer" && chown -R "$UID":1000 "/home/writer"

RUN mkdir -p "/home/stepik"
RUN chown -R "$UID":1000 "/home/stepik"
VOLUME ["/home/stepik"]

USER writer

WORKDIR /home/stepik
ENTRYPOINT ["bash"]


问:
How to assign a string variable value to a 2d array
I am trying to populate a 2d array with String values.

int m; n; are used in my loops to assign to rows and columns.

In an inner loop I am pulling out strings from a separate string array and assigning each value to a string variable. Then I am trying to assign that string variable to the 2d array of strings.

String variable = value of string in string array at a specific index;

```<code>String[m][n] example =  variable;
</code>```

It seems to working fine except it doesn't seem to be loading the string in the string variable into the 2d array.

Can anyone help me to understand why this is happening and how I might successfully assign the data to the 2d array?

```<code>for(m = 0; m < people.size(); m++){
        for(n = 0; n < people.get(m).getNames().length; n++){

            for(int i = 0; i < people.size(); i ++){
                for(j = 0; j < people.get(i).getNames().length; j++){
                    String name = people.get(i).getNames()[j];

                }
        NamesGrid [m][n] =  name;

        }
</code>```

答:
Try going through the 2d array using two for loops. Here is some sample code that goes through a for loop and assigns every element with a string.
    String[][] names = new String[14][10];</p>

```<code>    for(int rows = 0; rows < names.length; rows++) {
        for(int cols = 0; cols < names[0].length; cols++) {
            names[rows][cols] = "Strings!";
        }
    }

    for(int rows = 0; rows < names.length; rows++) {
        for(int cols = 0; cols < names[0].length; cols++) {
            System.out.print(names[rows][cols]);
        }
        System.out.println();
    }
</code>```

Body:
I am trying to populate a 2d array with String values.

int m; n; are used in my loops to assign to rows and columns.

In an inner loop I am pulling out strings from a separate string array and assigning each value to a string variable. Then I am trying to assign that string variable to the 2d array of strings.

String variable = value of string in string array at a specific index;

String[m][n] example =  variable;

It seems to working fine except it doesn't seem to be loading the string in the string variable into the 2d array.

Can anyone help me to understand why this is happening and how I might successfully assign the data to the 2d array?

for(m = 0; m < people.size(); m++){
        for(n = 0; n < people.get(m).getNames().length; n++){

            for(int i = 0; i < people.size(); i ++){
                for(j = 0; j < people.get(i).getNames().length; j++){
                    String name = people.get(i).getNames()[j];

                }
        NamesGrid [m][n] =  name;

        }

Body:
Try going through the 2d array using two for loops. Here is some sample code that goes through a for loop and assigns every element with a string.
    String[][] names = new String[14][10];

    for(int rows = 0; rows < names.length; rows++) {
        for(int cols = 0; cols < names[0].length; cols++) {
            names[rows][cols] = "Strings!";
        }
    }

    for(int rows = 0; rows < names.length; rows++) {
        for(int cols = 0; cols < names[0].length; cols++) {
            System.out.print(names[rows][cols]);
        }
        System.out.println();
    }


问:
woocommerce prevent checkout submit on payment method change
Hi I have some problems with the checkout page, when I change the payment method on the page the checkout order is submited automatically, and I want to be manually, using a button. I try this the following code to disable the ajax call but seems that this is not an ajax issue.</p>

```<code>function script_disabled()
{
    wp_dequeue_script( 'wc-checkout' );
}

add_action('wp_enqueue_scripts', 'script_disabled');
</code>```

答:
There is something not quite right about your description of the problem. Changing the payment method using the radio buttons should not automatically submit the order. On my installation this action just shows or hides the appropriate pane for the payment method. The shown pane actually has the button to submit the order. The code below is the jQuery event handler to prevent the submit AJAX call. However, I don't think this is the right solution to your problem. The behavior you are describing is not how the WooCommerce checkout page should work. At least, it doesn't behave that way on my installation, which is pretty much standard with respect to the checkout page.

```<code>jQuery( 'form.checkout' ).on( 'checkout_place_order', function() {
    var $payment_method = jQuery( 'form.checkout input[name="payment_method"]:checked' ).val();
    if ( /* your condition, e.g. "$payment_method == 'paypal'" */ ) {
        // prevent the submit AJAX call
        alert( 'submit cancelled!' );
        return false;
    }
    // allow the submit AJAX call
    return true;
});
</code>```

I would not use this solution as I think something else is wrong.

Body:
Hi I have some problems with the checkout page, when I change the payment method on the page the checkout order is submited automatically, and I want to be manually, using a button. I try this the following code to disable the ajax call but seems that this is not an ajax issue.

function script_disabled()
{
    wp_dequeue_script( 'wc-checkout' );
}

add_action('wp_enqueue_scripts', 'script_disabled');

Body:
There is something not quite right about your description of the problem. Changing the payment method using the radio buttons should not automatically submit the order. On my installation this action just shows or hides the appropriate pane for the payment method. The shown pane actually has the button to submit the order. The code below is the jQuery event handler to prevent the submit AJAX call. However, I don't think this is the right solution to your problem. The behavior you are describing is not how the WooCommerce checkout page should work. At least, it doesn't behave that way on my installation, which is pretty much standard with respect to the checkout page.

jQuery( 'form.checkout' ).on( 'checkout_place_order', function() {
    var $payment_method = jQuery( 'form.checkout input[name="payment_method"]:checked' ).val();
    if ( /* your condition, e.g. "$payment_method == 'paypal'" */ ) {
        // prevent the submit AJAX call
        alert( 'submit cancelled!' );
        return false;
    }
    // allow the submit AJAX call
    return true;
});

I would not use this solution as I think something else is wrong.


问:
Elasticsearch Nest 5 QueryContainer acts differently
Since upgrading from Nest 1.7 to 5 my pattern for creating query classes that I used to use no longer works and I was wondering if someone could point out why or how I can change so that it does.

Firstly I have a base class that my query classes inherit from:

```<code>public abstract class BaseSearchQuery<T> : SearchDescriptor<T>
    where T : class
{
    protected QueryContainer SearchQueryContainer;

    protected void AndQuery(QueryContainer query)
    {
        SearchQueryContainer = SearchQueryContainer == null
                ? query
                : SearchQueryContainer && query;
    }

    protected abstract SearchDescriptor<T> Build();
}
</code>```

Then I'd inherit from this class for each different query I wanted to make:

```<code>public class SomeSearch : BaseSearchQuery<SomeType>
{
    public string SomeValue { get; set; }

    protected override SearchDescriptor<SomeType> Build()
    {
        return AddSomeValue()
            .Query(SearchQueryContainer);
    }

    private SomeSearch AddSomeValue()
    {
        AndQuery(new QueryDescriptor<SomeType>().Term(f => f.SomeField.Suffix("raw"), SomeValue));
        return this;
    }
}
</code>```

Since upgrading NEST this no longer works, if anyone knows how to get this working or a better way of doing this I'd be so grateful.

Thanks

答:
Since upgrading from Nest 1.7 to 5 my pattern for creating query classes that I used to use no longer works

How does it no longer work? There are a few small changes needed to type names, but this works

```<code>public abstract class BaseSearchQuery<T> : SearchDescriptor<T>
    where T : class
{
    protected QueryContainer SearchQueryContainer;

    protected void AndQuery(QueryContainer query)
    {
        SearchQueryContainer = SearchQueryContainer == null
                ? query
                : SearchQueryContainer && query;
    }

    protected abstract SearchDescriptor<T> Build();
}

public class SomeSearch : BaseSearchQuery<SomeType>
{
    public string SomeValue { get; set; }

    protected override SearchDescriptor<SomeType> Build()
    {
        return AddSomeValue()
            .Query(_ => SearchQueryContainer);
    }

    private SomeSearch AddSomeValue()
    {
        AndQuery(new QueryContainerDescriptor<SomeType>().Term(f => f.SomeField.Suffix("raw"), SomeValue));
        return this;
    }
}
</code>```

I'm not really seeing what this query class pattern is really providing you though; I can see it as a way of encapsulating common queries that are called from different places within the solution, but perhaps the Query<T> static class methods can help here, and encapsulate these in a static class for a specific POCO type, to be reused in different places?

```<code>public class SomeType
{
    public string SomeField { get; set; }
}

public static class SomeTypeQueries
{
    public static QueryContainer SomeFieldRawTerm(string value) =>
        Query<SomeType>.Term(f => f.SomeField.Suffix("raw"), value);
}

var client = new ElasticClient(connectionSettings);

client.Search<SomeType>(s => s.Query(_ => SomeTypeQueries.SomeFieldRawTerm("term")));
</code>```

Body:
Since upgrading from Nest 1.7 to 5 my pattern for creating query classes that I used to use no longer works and I was wondering if someone could point out why or how I can change so that it does.

Firstly I have a base class that my query classes inherit from:

public abstract class BaseSearchQuery<T> : SearchDescriptor<T>
    where T : class
{
    protected QueryContainer SearchQueryContainer;

    protected void AndQuery(QueryContainer query)
    {
        SearchQueryContainer = SearchQueryContainer == null
                ? query
                : SearchQueryContainer && query;
    }

    protected abstract SearchDescriptor<T> Build();
}

Then I'd inherit from this class for each different query I wanted to make:

public class SomeSearch : BaseSearchQuery<SomeType>
{
    public string SomeValue { get; set; }

    protected override SearchDescriptor<SomeType> Build()
    {
        return AddSomeValue()
            .Query(SearchQueryContainer);
    }

    private SomeSearch AddSomeValue()
    {
        AndQuery(new QueryDescriptor<SomeType>().Term(f => f.SomeField.Suffix("raw"), SomeValue));
        return this;
    }
}

Since upgrading NEST this no longer works, if anyone knows how to get this working or a better way of doing this I'd be so grateful.

Thanks

Body:
Since upgrading from Nest 1.7 to 5 my pattern for creating query classes that I used to use no longer works

How does it no longer work? There are a few small changes needed to type names, but this works

public abstract class BaseSearchQuery<T> : SearchDescriptor<T>
    where T : class
{
    protected QueryContainer SearchQueryContainer;

    protected void AndQuery(QueryContainer query)
    {
        SearchQueryContainer = SearchQueryContainer == null
                ? query
                : SearchQueryContainer && query;
    }

    protected abstract SearchDescriptor<T> Build();
}

public class SomeSearch : BaseSearchQuery<SomeType>
{
    public string SomeValue { get; set; }

    protected override SearchDescriptor<SomeType> Build()
    {
        return AddSomeValue()
            .Query(_ => SearchQueryContainer);
    }

    private SomeSearch AddSomeValue()
    {
        AndQuery(new QueryContainerDescriptor<SomeType>().Term(f => f.SomeField.Suffix("raw"), SomeValue));
        return this;
    }
}

I'm not really seeing what this query class pattern is really providing you though; I can see it as a way of encapsulating common queries that are called from different places within the solution, but perhaps the Query<T> static class methods can help here, and encapsulate these in a static class for a specific POCO type, to be reused in different places?

public class SomeType
{
    public string SomeField { get; set; }
}

public static class SomeTypeQueries
{
    public static QueryContainer SomeFieldRawTerm(string value) =>
        Query<SomeType>.Term(f => f.SomeField.Suffix("raw"), value);
}

var client = new ElasticClient(connectionSettings);

client.Search<SomeType>(s => s.Query(_ => SomeTypeQueries.SomeFieldRawTerm("term")));


问:
Clion how to add files to a project
This seems really basic. How can i add files to a project without having to manually edit the CMakeLists.txt.

For example source files in another directory

答: No other option. You have to edit the CMakeLists.txt. CLion is completely cmake based IDE. Even if you need to link external libraries, you need to edit the above-mentioned file. It doesn't work like in GUI based code-blocks for example.

Title: Clion how to add files to a project


问:
Communicating with the web through a C# app?
Although i can grasp the concepts of the .Net framework and windows apps, i want to create an app that will involve me simulating website clicks and getting data/response times from that page. I have not had any experience with web yet as im only a junior, could someone explain to me (in english!!) the basic concepts or with examples, the different ways and classes that could help me communicate with a website?</p>

答:
You could use the System.Net.WebClient class of the .NET Framework. See the MSDN documentation here.

Simple example:

```<code>using System;
using System.Net;
using System.IO;

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }

        WebClient client = new WebClient ();

        // Add a user agent header in case the
        // requested URI contains a query.

        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }
}
</code>```

There are other useful methods of the WebClient, which allow developers to download and save resources from a specified URI.

The DownloadFile() method for example will download and save a resource to a local file. The UploadFile() method uploads and saves a resource to a specified URI.

UPDATE:

WebClient is simpler to use than WebRequest. Normally you could stick to using just WebClient unless you need to manipulate requests/responses in an advanced way. See this article where both are used: http://odetocode.com/Articles/162.aspx

OwnerDisplayName: Grace

Body:
You could use the System.Net.WebClient class of the .NET Framework. See the MSDN documentation here.

Simple example:

using System;
using System.Net;
using System.IO;

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }

        WebClient client = new WebClient ();

        // Add a user agent header in case the
        // requested URI contains a query.

        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }
}

There are other useful methods of the WebClient, which allow developers to download and save resources from a specified URI.

The DownloadFile() method for example will download and save a resource to a local file. The UploadFile() method uploads and saves a resource to a specified URI.

UPDATE:

WebClient is simpler to use than WebRequest. Normally you could stick to using just WebClient unless you need to manipulate requests/responses in an advanced way. See this article where both are used: http://odetocode.com/Articles/162.aspx

OwnerDisplayName: splattne

LastEditorDisplayName: splattne


问:
What is RevertToSelf()? - C#.net
I don't understand what RevertToSelf() does in a .net application. Checking MSDN definition it reads the definition as

```<code>The RevertToSelf function terminates the impersonation of a client application.
</code>```

So does the current user context changes to a sysadmin context by stopping client's context? By calling RevertToSelf() will my code run on sys admin mode?

Update

Okay so what happens if I call RevertToSelf() in an ASP.NET application? Let us consider I dont start any impersonation. So if I call RevertToSelf() will it revert to the application pool identity?

答: RevertToSelf will terminate any impersonation that you have actively enabled. You may set an application to impersonate any user account. RevertToSelf has no effect unless you're using impersonation. Calling RevertToSelf will only get your code to run as an administrator, if the application is was up to run as an administrator to begin with, and was from within the application configured to impersonate another account.

Title: What is RevertToSelf()? - C#.net

Body:
I don't understand what RevertToSelf() does in a .net application. Checking MSDN definition it reads the definition as

The RevertToSelf function terminates the impersonation of a client application.

So does the current user context changes to a sysadmin context by stopping client's context? By calling RevertToSelf() will my code run on sys admin mode?

Update

Okay so what happens if I call RevertToSelf() in an ASP.NET application? Let us consider I dont start any impersonation. So if I call RevertToSelf() will it revert to the application pool identity?


问:
How to send messages in mobile as well as email on contact form submission for the client
My client has a website but doesn't check emails often. He has a lot of web enquiries through the online contact form. He carries a mobile phone though.Now he wants to have a message in his mobile as well as email from the contact form submission.How to send contact form details that's submitted through the website to his mobile phone as SMS along with email?The site is in wordpress and using contact form 7</p>

答: You could send an SMS message, but that would get crazy really quick. Why not have your client set up an email app on their mobile device? All email will be accessible from their phone. </p>


问:
Pairing duplicate objects in a very large list
I'm having issues with my program being too slow.
Here is what I need my code to do. (Actual code is below):

Imagine you have a very large (1million+) list of "person" objects. Each person has attributes like "hairColor", "height", "weight"....etc. Each had a isMatched Boolean attribute also.

What the code does is FOR EVERY person object in the list: try to find an exact match to another person by the attributes. When the code finds two person objects that match simply put them into a "pair" object. If there is no match then we simply pair the person object with None. Here is the code

```<code>Deck=collections.deque()
Person=[per1,per2,.....per1000000]
while Person:
    personToBeMatched=Person.pop()
    if not personToBeMatched.isMatched:
        match=next(per for per in Person if  per.hairColor==personToBeMatched.hairColor and per.height==personToBeMatched.height, None)
        if match is not None:
            per.isMatched=True
    Deck.append(Pair(match,personToBeMatched))
</code>```

I ultimately want to do this quickly for a list of size 1million+ but even 100,000 is taking far too long. Does anyone know how I can speed this up??

答:
Since you are only looking for exact matches, the solution is very simple.

For each person, build a tuple of attributes. Here are a few ways to do this:

```<code>person.tup = (person.hairColor, person.height, ...)
</code>```

or

```<code>keys = "hairColor", "height", .....
tup = (person[k] for k in keys)
</code>```

Now, since tuples are hashable, we can just put everything in a dict and use the tuple as a key:

```<code>d = {}
for person in persons:
   tup = gettuple(person) # use previous code snippets
   d.setdefault(tup,[]).append(person)
</code>```

...and in the end, dict d contains lists of all matches. Note that some matches may include more than 2 persons, maybe an odd number, so you'll have to choose how to pair them, that's up to you. But this will handle your matching very quickly, since dict lookups are very fast.

The reason this solution is much faster is that it is O(n), that is only one dict lookup is done for each person, and dict lookups are O(1). Your solution compares every record with every other record, and is thus in O(n^2) which is something you really want to avoid.

Another solution is to sort based on the tuple of keys and the matches will appear next to each other in the sorted results.

EDIT:

Complexity of your solution (ie, number of operations) with a list of size n:

It takes an element out of the list, and compares it to all the others, so we have at most (n-1) comparisons. It stops at the first element it finds, so it will usually be less. So we could add a fudge factor k=0.5 and say on average it finds a match in the first k*(n-1) elements of the list.

Then it does it again on the list which is 1 element shorter (thus n-2) elements.... until the list is exhausted.

So you got k*( (n-1)+(n-2)+ ... +2+1 ) operations.

And this is more or less k/2 * n^2

Point is, the value of k (or the 1/2) doesn't really matter when you have a n^2. This is why we say O(n^2) meaning "n^2 multiplied by whatever constant we don't care about, since when n grows large, it's gonna blow up anyway."

You really want O(n) for speed, like my solution (scan the list once, build a hash, scan the list again looking for matches).

If the list were huge (ie, does not fit in RAM) then stuff based on hashes tends to fail spectacularly as the random access patterns into the hash map are not compatible with virtual memory stored on a slow drive. So you'd want something which has disk-friendly access patterns, like a merge sort in O(n log n). You'd probably use a SQL database for this, as they come with the feature built-in.

Body:
I'm having issues with my program being too slow.
Here is what I need my code to do. (Actual code is below):

Imagine you have a very large (1million+) list of "person" objects. Each person has attributes like "hairColor", "height", "weight"....etc. Each had a isMatched Boolean attribute also.

What the code does is FOR EVERY person object in the list: try to find an exact match to another person by the attributes. When the code finds two person objects that match simply put them into a "pair" object. If there is no match then we simply pair the person object with None. Here is the code

Deck=collections.deque()
Person=[per1,per2,.....per1000000]
while Person:
    personToBeMatched=Person.pop()
    if not personToBeMatched.isMatched:
        match=next(per for per in Person if  per.hairColor==personToBeMatched.hairColor and per.height==personToBeMatched.height, None)
        if match is not None:
            per.isMatched=True
    Deck.append(Pair(match,personToBeMatched))

I ultimately want to do this quickly for a list of size 1million+ but even 100,000 is taking far too long. Does anyone know how I can speed this up??

Body:
Since you are only looking for exact matches, the solution is very simple.

For each person, build a tuple of attributes. Here are a few ways to do this:

person.tup = (person.hairColor, person.height, ...)

or

keys = "hairColor", "height", .....
tup = (person[k] for k in keys)

Now, since tuples are hashable, we can just put everything in a dict and use the tuple as a key:

d = {}
for person in persons:
   tup = gettuple(person) # use previous code snippets
   d.setdefault(tup,[]).append(person)

...and in the end, dict d contains lists of all matches. Note that some matches may include more than 2 persons, maybe an odd number, so you'll have to choose how to pair them, that's up to you. But this will handle your matching very quickly, since dict lookups are very fast.

The reason this solution is much faster is that it is O(n), that is only one dict lookup is done for each person, and dict lookups are O(1). Your solution compares every record with every other record, and is thus in O(n^2) which is something you really want to avoid.

Another solution is to sort based on the tuple of keys and the matches will appear next to each other in the sorted results.

EDIT:

Complexity of your solution (ie, number of operations) with a list of size n:

It takes an element out of the list, and compares it to all the others, so we have at most (n-1) comparisons. It stops at the first element it finds, so it will usually be less. So we could add a fudge factor k=0.5 and say on average it finds a match in the first k*(n-1) elements of the list.

Then it does it again on the list which is 1 element shorter (thus n-2) elements.... until the list is exhausted.

So you got k*( (n-1)+(n-2)+ ... +2+1 ) operations.

And this is more or less k/2 * n^2

Point is, the value of k (or the 1/2) doesn't really matter when you have a n^2. This is why we say O(n^2) meaning "n^2 multiplied by whatever constant we don't care about, since when n grows large, it's gonna blow up anyway."

You really want O(n) for speed, like my solution (scan the list once, build a hash, scan the list again looking for matches).

If the list were huge (ie, does not fit in RAM) then stuff based on hashes tends to fail spectacularly as the random access patterns into the hash map are not compatible with virtual memory stored on a slow drive. So you'd want something which has disk-friendly access patterns, like a merge sort in O(n log n). You'd probably use a SQL database for this, as they come with the feature built-in.


问:
Command line argument in Histogram
I am writing some code which makes a histogram out of imported excel files from a directory and bins the data according to some parameter and exports new excel files accordingly, binned into their respective bins, for ex. if there is a number 5.16 then the bin count for bin (5,10] will go up by one and so on. However, I wanted to write something in which I can input a specific value that would change the bins accordingly, like if I wanted bins of 3, I would choose n=3 and the code would now bin accordingly, such that it makes bin (0,3], (3,6], etc. and the same rules as previously would apply. The original code is:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

datadir = '/Users/user/Desktop/Newfolder/'

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
        data = pd.read_excel(os.path.join(datadir, file))
        counts, bins, patches = plt.hist(data.values, bins=range(0,
        int(max(data.values)+5), 5))
        df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
        plt.title('Data')
        plt.xlabel('Neuron')
        plt.ylabel('# of Spikes')
        plt.show()

        outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
        writer = pd.ExcelWriter(outfile)
        df.to_excel(writer)
        writer.save()
</code>```

My thought was to use argparse as a command line argument which I could us to input the change in the bins, so I wrote:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os
import argparse

datadir = '/Users/user/Desktop/Newfolder/'

parser = argparse.ArgumentParser(description = 'Calculating the bin width')
parser.add_argument('n', type=int, help='Changing of the width')
args = parser.parse_args()

def vary(n):
    wid = n
     return wid

if __name__ == '__main__':
    print(vary(args.n))

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
       data = pd.read_excel(os.path.join(datadir, file))
       counts, bins, patches = plt.hist(data.values, bins=range(0,
       int(max(data.values)+vary(n)), vary(n)))
       df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
       plt.title('Data')
       plt.xlabel('Neuron')
       plt.ylabel('# of Spikes')
       plt.show()

       outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
       writer = pd.ExcelWriter(outfile)
       df.to_excel(writer)
       writer.save()
</code>```

I apologize in advance if this looks idioitic, since I am pretty new to coding and still don't know too much about anything. Anyway, I get an error say that

```<code>Traceback (most recent call last):
File "\Users\user\Desktop\Bins.py", line 25, in <module>
        counts, bins, patches = plt.hist(data.values, bins=range(0, int(max(data.values)+vary(n)), vary(n)))
NameError: name 'n' is not defined
</code>```

Could I get some help with this, how would I go about implementing this command line argument (argparse) into the histogram so I can input the according bins everytime I need to change them. Any help would be greatly appreciated, thank you

答:
Here's how I'd organize your code.  main can be reorganized, but my focus is on the location of the commandline parsing.

```<code>datadir = '/Users/user/Desktop/Newfolder/'
n = 3  # a default if not used with argparse

def main(datadir, n):
    # might split the load and the plot functions
    # or put the action for one file in a separate function

    for file in os.listdir(datadir):
        if file.endswith('.xlsx'):
           data = pd.read_excel(os.path.join(datadir, file))
           counts, bins, patches = plt.hist(data.values, bins=range(0,
           int(max(data.values)+n), n))
           df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
           plt.title('Data')
           plt.xlabel('Neuron')
           plt.ylabel('# of Spikes')
           plt.show()

           outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
           writer = pd.ExcelWriter(outfile)
           df.to_excel(writer)
           writer.save()

if __name__ == '__main__':
    # run only as a script; not on import
    # if more complicated define this parser in a function

    parser = argparse.ArgumentParser(description = 'Calculating the bin width')
    parser.add_argument('n', type=int, help='Changing of the width')
    args = parser.parse_args()

    print(args)  # to see what argparse does
    main(datadir, args.n)
    # main(args.datadir, args.n) # if parser has a datadir  argument
</code>```

(I haven't tested this.)

Title: Command line argument in Histogram

Body:
I am writing some code which makes a histogram out of imported excel files from a directory and bins the data according to some parameter and exports new excel files accordingly, binned into their respective bins, for ex. if there is a number 5.16 then the bin count for bin (5,10] will go up by one and so on. However, I wanted to write something in which I can input a specific value that would change the bins accordingly, like if I wanted bins of 3, I would choose n=3 and the code would now bin accordingly, such that it makes bin (0,3], (3,6], etc. and the same rules as previously would apply. The original code is:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

datadir = '/Users/user/Desktop/Newfolder/'

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
        data = pd.read_excel(os.path.join(datadir, file))
        counts, bins, patches = plt.hist(data.values, bins=range(0,
        int(max(data.values)+5), 5))
        df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
        plt.title('Data')
        plt.xlabel('Neuron')
        plt.ylabel('# of Spikes')
        plt.show()

        outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
        writer = pd.ExcelWriter(outfile)
        df.to_excel(writer)
        writer.save()

My thought was to use argparse as a command line argument which I could us to input the change in the bins, so I wrote:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os
import argparse

datadir = '/Users/user/Desktop/Newfolder/'

parser = argparse.ArgumentParser(description = 'Calculating the bin width')
parser.add_argument('n', type=int, help='Changing of the width')
args = parser.parse_args()

def vary(n):
    wid = n
     return wid

if __name__ == '__main__':
    print(vary(args.n))

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
       data = pd.read_excel(os.path.join(datadir, file))
       counts, bins, patches = plt.hist(data.values, bins=range(0,
       int(max(data.values)+vary(n)), vary(n)))
       df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
       plt.title('Data')
       plt.xlabel('Neuron')
       plt.ylabel('# of Spikes')
       plt.show()

       outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
       writer = pd.ExcelWriter(outfile)
       df.to_excel(writer)
       writer.save()

I apologize in advance if this looks idioitic, since I am pretty new to coding and still don't know too much about anything. Anyway, I get an error say that

Traceback (most recent call last):
File "\Users\user\Desktop\Bins.py", line 25, in <module>
        counts, bins, patches = plt.hist(data.values, bins=range(0, int(max(data.values)+vary(n)), vary(n)))
NameError: name 'n' is not defined

Could I get some help with this, how would I go about implementing this command line argument (argparse) into the histogram so I can input the according bins everytime I need to change them. Any help would be greatly appreciated, thank you

Body:
Here's how I'd organize your code.  main can be reorganized, but my focus is on the location of the commandline parsing.

datadir = '/Users/user/Desktop/Newfolder/'
n = 3  # a default if not used with argparse

def main(datadir, n):
    # might split the load and the plot functions
    # or put the action for one file in a separate function

    for file in os.listdir(datadir):
        if file.endswith('.xlsx'):
           data = pd.read_excel(os.path.join(datadir, file))
           counts, bins, patches = plt.hist(data.values, bins=range(0,
           int(max(data.values)+n), n))
           df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
           plt.title('Data')
           plt.xlabel('Neuron')
           plt.ylabel('# of Spikes')
           plt.show()

           outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
           writer = pd.ExcelWriter(outfile)
           df.to_excel(writer)
           writer.save()

if __name__ == '__main__':
    # run only as a script; not on import
    # if more complicated define this parser in a function

    parser = argparse.ArgumentParser(description = 'Calculating the bin width')
    parser.add_argument('n', type=int, help='Changing of the width')
    args = parser.parse_args()

    print(args)  # to see what argparse does
    main(datadir, args.n)
    # main(args.datadir, args.n) # if parser has a datadir  argument

(I haven't tested this.)


问:
How to Exclude sass files from ng-build?
I use sass-loader in webpack.config to compile scss files to one bundled minified CSS file and I will manually reference this file in my "Index.html" but i need to exclude scss files from "ng build", I excluded it in tsconfig.app
"exclude": ["../**/*.scss"] but it didn't work.

答:
When you use Angular CLI, you are in for it to handle all these sorts of things for you. You are not expected to handle them yourself. The CLI intentionally does not expose a build-tool-specific extension point (although an idea of a CLI plugin system is one of the things on the table for v2).

One thing you can do though is use the ng eject command to extract the Webpack config and customize it yourself. Read more about this option here.

Update:

Based on comments, it looks like this question is motivated by how the CSS is applied via JS in Angular CLI by default.

If this is the case, please note that this is configurable via the ng build flag --extract-css. If set, the build generates a CSS file not JS file for the CSS. The flag is off by default in dev mode (default ng build / ng serve), and on by default in production mode (when you pass the -prod flag).

Learn more from the official ng build docs.


问:
How to achieve security level 3 in FIWARE?
I am deploying FIWARE security GEs (i.e., Wilma, AuthzForce, Keyrock) in my computer. Security level 2 (Basic Authorization) is working well, but now I need security level 3 (Advanced Authorization) using XACML.

Long story short, I want a tutorial of implementation security level 3. However, as far as I know, any tutorial or document about security level 3 does not exist.

For now, I create my policy with PAP's API, and change 'custom_policy' option in config.js from 'undefined' to 'policy.js'. And then I create 'policy.js' file into 'PEP/policies', but don't change anything compared with its template file because I don't know what this code does exactly. I think I should make XACML Request form using 'xml' variable. But in my case, PEP gives me the error when I make the XACML Request using 'xml' variable, and return this variable. Here is my error of PEP:

```<code>Error: Root - Error in AZF communication <?xml version="1.0" encoding="UTF-8" standalone="yes"?><error xmlns="http://authzforce.github.io/rest-api-model/xmlns/authz/S" xmlns:ns2="http://www.w3.org/2005/Atom" xmlns:ns3="http://authzforce.github.io/core/xmlns/pdp/5.0" xmlns:ns4="http://authzforce.github.io/pap-dao-flat-file/xmlns/properties/3.6"><message>Invalid parameters: cvc-elt.1: Cannot find the declaration of element 'Request'.</message></error>
</code>```

And here is my 'getPolicy' code (XACML Request) in policy.js. I just made very simple request whether response is permit or not because I'm not sure what I'm doing at that time.:

```<code>exports.getPolicy = function (roles, req, app_id) {
    var xml = xmlBuilder.create('Request', {
            'xmlns': 'urn:oasis:names:tc:xacml:3.0:core:schema:wd-17',
            'CombinedDecision': 'false',
            'ReturnPolicyIdList': 'false'})
    .ele('Attributes', {
            'Category': 'urn:oasis:names:tc:xacml:1.0:subject-category:access-subject'});
</code>```

So, anyone can give me any information about implementation of security level 3?

答:
Upgrade to Wilma 6.2 (bug fixing).

Reuse the code from lib/azf.js which is known to work, and adapt the Request content to your needs. The variable is wrongly called XACMLPolicy there, but don't be mistaken, this is an actual XACML Request. This is using xml2json package to convert the JSON to XML, whereas in your code you seem to use a different one, xmlbuilder maybe? You didn't paste the full code - where does this xmlBuilder variable come from? - so I'm just guessing.

If you are indeed using xmlbuilder package and want to stick with it, I notice that in the example using namespaces, the xmlns attribute is put in a different way:

```<code>var xmlBuilder = require('xmlbuilder');

var xml = xmlBuilder.create('Request', { encoding: 'utf-8' })
.att('xmlns', 'urn:oasis:names:tc:xacml:3.0:core:schema:wd-17')
.att('CombinedDecision': 'false')
.att('ReturnPolicyIdList': 'false')
.ele('Attributes', {'Category': 'urn:oasis:names:tc:xacml:1.0:subject-category:access-subject'});
</code>```

Maybe this makes a difference, I didn't check.

Also feel free to create an issue with your question on Wilma's github to get help from the dev team. (I am not one of them but we've worked together for AuthzForce integration.)

Body:
I am deploying FIWARE security GEs (i.e., Wilma, AuthzForce, Keyrock) in my computer. Security level 2 (Basic Authorization) is working well, but now I need security level 3 (Advanced Authorization) using XACML.

Long story short, I want a tutorial of implementation security level 3. However, as far as I know, any tutorial or document about security level 3 does not exist.

For now, I create my policy with PAP's API, and change 'custom_policy' option in config.js from 'undefined' to 'policy.js'. And then I create 'policy.js' file into 'PEP/policies', but don't change anything compared with its template file because I don't know what this code does exactly. I think I should make XACML Request form using 'xml' variable. But in my case, PEP gives me the error when I make the XACML Request using 'xml' variable, and return this variable. Here is my error of PEP:

Error: Root - Error in AZF communication <?xml version="1.0" encoding="UTF-8" standalone="yes"?><error xmlns="http://authzforce.github.io/rest-api-model/xmlns/authz/S" xmlns:ns2="http://www.w3.org/2005/Atom" xmlns:ns3="http://authzforce.github.io/core/xmlns/pdp/5.0" xmlns:ns4="http://authzforce.github.io/pap-dao-flat-file/xmlns/properties/3.6"><message>Invalid parameters: cvc-elt.1: Cannot find the declaration of element 'Request'.</message></error>

And here is my 'getPolicy' code (XACML Request) in policy.js. I just made very simple request whether response is permit or not because I'm not sure what I'm doing at that time.:

exports.getPolicy = function (roles, req, app_id) {
    var xml = xmlBuilder.create('Request', {
            'xmlns': 'urn:oasis:names:tc:xacml:3.0:core:schema:wd-17',
            'CombinedDecision': 'false',
            'ReturnPolicyIdList': 'false'})
    .ele('Attributes', {
            'Category': 'urn:oasis:names:tc:xacml:1.0:subject-category:access-subject'});

So, anyone can give me any information about implementation of security level 3?

Body:
Upgrade to Wilma 6.2 (bug fixing).

Reuse the code from lib/azf.js which is known to work, and adapt the Request content to your needs. The variable is wrongly called XACMLPolicy there, but don't be mistaken, this is an actual XACML Request. This is using xml2json package to convert the JSON to XML, whereas in your code you seem to use a different one, xmlbuilder maybe? You didn't paste the full code - where does this xmlBuilder variable come from? - so I'm just guessing.

If you are indeed using xmlbuilder package and want to stick with it, I notice that in the example using namespaces, the xmlns attribute is put in a different way:

var xmlBuilder = require('xmlbuilder');

var xml = xmlBuilder.create('Request', { encoding: 'utf-8' })
.att('xmlns', 'urn:oasis:names:tc:xacml:3.0:core:schema:wd-17')
.att('CombinedDecision': 'false')
.att('ReturnPolicyIdList': 'false')
.ele('Attributes', {'Category': 'urn:oasis:names:tc:xacml:1.0:subject-category:access-subject'});

Maybe this makes a difference, I didn't check.

Also feel free to create an issue with your question on Wilma's github to get help from the dev team. (I am not one of them but we've worked together for AuthzForce integration.)


问:
Proportion distribution of column values by date
I am trying to get the proportion of each category in the data set by day, to be able to plot it eventually.

Sample (daily_usage):

```<code>       type  date        count
0      A     2016-03-01    70
1      A     2016-03-02    64
2      A     2016-03-03    38
3      A     2016-03-04    82
4      A     2016-03-05    37
...
412    G     2016-03-27   149
413    G     2016-03-28   382
414    G     2016-03-29   232
415    G     2016-03-30   312
416    G     2016-03-31   412
</code>```

I plotted the mean and median by type just fine with the following code:

```<code> daily_usage.groupby('type')['count'].agg(['median','mean']).plot(kind='bar')
</code>```

But I wanted a similar plot with the proportion of the daily counts instead. However, for plotting it eventually, I don't need to show the date. It would be just to show the average/median daily proportion for each type.

The proportion interpretation I mean is, for example, for the first line: type A happened 70 times in March 1; considering all other events in March 1, there is a sum of 948 events. The proportion of type A in March 1 is 70/948. This would be computed for all rows. The final plot will have to show each type on the x-axis, and the average daily proportion on the y-axis

I tried getting the proportion in two ways.

First one:

```<code>daily_usage['ratio'] = (daily_usage / daily_usage.groupby('date').transform(sum))['count']
</code>```

The denominator in this first try gives me this sample output, so it looks like it should be very easy to divide the original count column by this new daily count column:

```<code>           count
0    ...   948
1    ...   910
2    ...   588
3    ...   786
4    ...   530
5    ...  1043
</code>```

Error:

```<code>TypeError: unsupported operand type(s) for /: 'str' and 'str'
</code>```

Second one:

```<code>daily_usage.div(day_total,axis='count')
</code>```

where day_total = daily_usage.groupby('date').agg({'count':'sum'}).reset_index()

Error:

```<code> TypeError: ufunc true_divide cannot use operands with types dtype('<M8[ns]') and dtype('<M8[ns]')
</code>```

What's a better way to do this?

答:
if you just want to have your new column in your dataframe you can do the following:

```<code>df['ratio'] = (df.groupby(['type','date'])['count'].transform(sum) / df.groupby('date')['count'].transform(sum))
</code>```

However, it has nearly been 20 mins now that I'm trying to figure out what you're trying to plot exactly and since I still didn't really get your intention I ask from you to leave a detailed comment in case you need help plotting and precise what you want to plot and how ( one plot for the daily usage of each day or some other form ).

PS:

in my code df refers to your daily_usage dataframe.

Hope this was helpful.

Body:
I am trying to get the proportion of each category in the data set by day, to be able to plot it eventually.

Sample (daily_usage):

       type  date        count
0      A     2016-03-01    70
1      A     2016-03-02    64
2      A     2016-03-03    38
3      A     2016-03-04    82
4      A     2016-03-05    37
...
412    G     2016-03-27   149
413    G     2016-03-28   382
414    G     2016-03-29   232
415    G     2016-03-30   312
416    G     2016-03-31   412

I plotted the mean and median by type just fine with the following code:

 daily_usage.groupby('type')['count'].agg(['median','mean']).plot(kind='bar')

But I wanted a similar plot with the proportion of the daily counts instead. However, for plotting it eventually, I don't need to show the date. It would be just to show the average/median daily proportion for each type.

The proportion interpretation I mean is, for example, for the first line: type A happened 70 times in March 1; considering all other events in March 1, there is a sum of 948 events. The proportion of type A in March 1 is 70/948. This would be computed for all rows. The final plot will have to show each type on the x-axis, and the average daily proportion on the y-axis

I tried getting the proportion in two ways.

First one:

daily_usage['ratio'] = (daily_usage / daily_usage.groupby('date').transform(sum))['count']

The denominator in this first try gives me this sample output, so it looks like it should be very easy to divide the original count column by this new daily count column:

           count
0    ...   948
1    ...   910
2    ...   588
3    ...   786
4    ...   530
5    ...  1043

Error:

TypeError: unsupported operand type(s) for /: 'str' and 'str'

Second one:

daily_usage.div(day_total,axis='count')

where day_total = daily_usage.groupby('date').agg({'count':'sum'}).reset_index()

Error:

 TypeError: ufunc true_divide cannot use operands with types dtype('<M8[ns]') and dtype('<M8[ns]')

What's a better way to do this?

Body:
if you just want to have your new column in your dataframe you can do the following:

df['ratio'] = (df.groupby(['type','date'])['count'].transform(sum) / df.groupby('date')['count'].transform(sum))

However, it has nearly been 20 mins now that I'm trying to figure out what you're trying to plot exactly and since I still didn't really get your intention I ask from you to leave a detailed comment in case you need help plotting and precise what you want to plot and how ( one plot for the daily usage of each day or some other form ).

PS:

in my code df refers to your daily_usage dataframe.

Hope this was helpful.