问:
Attempting to run parallel tests with py.test and -n option is not working
I am attempting to run parallel tests with pytest in mac terminal, but when I use:

py.test -n NUM

I get the following error:

```<code>Alexs-MacBook-Pro:sauceTests alex$ py.test -n 3
usage: py.test [options] [file_or_dir] [file_or_dir] [...]
py.test: error: unrecognized arguments: -n
  inifile: None
  rootdir: /Users/alex/PycharmProjects/sauceTests
</code>```

Thanks!

答:
You need to install a plugin for that:</p>

```<code>pip install pytest-xdist
</code>```

Body:
I am attempting to run parallel tests with pytest in mac terminal, but when I use:

py.test -n NUM

I get the following error:

Alexs-MacBook-Pro:sauceTests alex$ py.test -n 3
usage: py.test [options] [file_or_dir] [file_or_dir] [...]
py.test: error: unrecognized arguments: -n
  inifile: None
  rootdir: /Users/alex/PycharmProjects/sauceTests

Thanks!

Body:
You need to install a plugin for that:

pip install pytest-xdist


来源: stackexchange

问:
How to use regex to remove the spaces between two rows?
My Input file like this

```<code>Header1,,,,,,,,,,,
c1 , c2 , c3 ,,,,

 22-02-2017,1-2,10,,,,
 22-02-2017,2-3,11,,,,

 22-02-2017,4-6,10,,,,
 22-02-2017,5-8,11,,,,
</code>```

I need to regex to achive below expected output:

```<code>Header1,,,,,,,,,,,
c1 , c2 , c3 ,,,,
22-02-2017,1-2,10,,,,
22-02-2017,2-3,11,,,,
22-02-2017,4-6,10,,,,
22-02-2017,5-8,11,,,,
</code>```

I trying this regex for search \s\n in REplaceTExt and replacement value is \n.

After Replace text output content like below.,

```<code>Header1,,,,,,,,,,,c1 , c2 , c3 ,,,,22-02-2017,1-2,10,,,,22-02-2017,2-3,11,,,,22-02-2017,4-6,10,,,,
</code>```

But my regex worked perfectly in regexr website.

http://regexr.com/3fbse

Is there is any other regex to search empty rows and combine rows before and after of empty rows?

答:
Sahil's solution is not as refined as it could be:

You can match with this pattern: \n+\s and replace with \n.  Demo

This will provide the same result with fewer steps.

The points to keep in mind with this very simple task is that using "alternatives" (pipes |) adds steps to your pattern and should be avoided when possible.

When alternatives are necessary, order the alternatives from shortest to longest -- this will provide greater efficiency.

Lastly, do not repeat characters in your pattern, use quantifiers -- this again improves performance.  When comparing \n\n\s|\n\s versus \n{2}\s|\n\s, the latter will outperform the former simply by using the {2} quantifier.

Probably the best advice would be to read your file with file() (which delivers an array of lines) and set the desired flags.

```<code>$array = file('yourfile.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
</code>```

This prevents needing to perform the extra preparation step with regex or a replacing string function.

fgetcsv() is a great companion for this approach.

ContentLicense: CC BY-SA 3.0

Body:
My Input file like this

Header1,,,,,,,,,,,
c1 , c2 , c3 ,,,,

 22-02-2017,1-2,10,,,,
 22-02-2017,2-3,11,,,,

 22-02-2017,4-6,10,,,,
 22-02-2017,5-8,11,,,,

I need to regex to achive below expected output:

Header1,,,,,,,,,,,
c1 , c2 , c3 ,,,,
22-02-2017,1-2,10,,,,
22-02-2017,2-3,11,,,,
22-02-2017,4-6,10,,,,
22-02-2017,5-8,11,,,,

I trying this regex for search \s\n in REplaceTExt and replacement value is \n.

After Replace text output content like below.,

Header1,,,,,,,,,,,c1 , c2 , c3 ,,,,22-02-2017,1-2,10,,,,22-02-2017,2-3,11,,,,22-02-2017,4-6,10,,,,

But my regex worked perfectly in regexr website.

http://regexr.com/3fbse

Is there is any other regex to search empty rows and combine rows before and after of empty rows?

Body:
Sahil's solution is not as refined as it could be:

You can match with this pattern: \n+\s and replace with \n.  Demo

This will provide the same result with fewer steps.

The points to keep in mind with this very simple task is that using "alternatives" (pipes |) adds steps to your pattern and should be avoided when possible.

When alternatives are necessary, order the alternatives from shortest to longest -- this will provide greater efficiency.

Lastly, do not repeat characters in your pattern, use quantifiers -- this again improves performance.  When comparing \n\n\s|\n\s versus \n{2}\s|\n\s, the latter will outperform the former simply by using the {2} quantifier.

Probably the best advice would be to read your file with file() (which delivers an array of lines) and set the desired flags.

$array = file('yourfile.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

This prevents needing to perform the extra preparation step with regex or a replacing string function.

fgetcsv() is a great companion for this approach.

ContentLicense: CC BY-SA 4.0


问:
How can I make a form appear on top of all other windows?
How can I make a form appear on top of everything on the desktop, not just forms within my application.  I have spent ages Googling but only found snippets for C++ and older versions of Visual Studio which no longer work.  I know the answer is out there, I must be looking for the wrong thing.

Just to be clear - my project is created within Visual Studio 2012 and it is coded in Visual Basic.

Thanks in advance.

答:
```<code>Me.TopMost = True
</code>```

BUT in ACTIVATED  (not in LOAD EVENT)

```<code>Private Sub frm_Activated(sender As Object, e As EventArgs) Handles Me.Activated

    Me.TopMost = True
End Sub
</code>```

Body:
Me.TopMost = True

BUT in ACTIVATED  (not in LOAD EVENT)

Private Sub frm_Activated(sender As Object, e As EventArgs) Handles Me.Activated

    Me.TopMost = True
End Sub


问:
Simplest authentication with flask-restless
I am using Flask-Restless to make a super simple REST API. I would like to add authentication, but just for put/post/delete calls, while I want to leave get calls public.

So far, I put in my views.py file this:

```<code>manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(models.mymodel, methods=['GET', 'POST', 'DELETE'])
</code>```

I had a look on different solutions for authentication, but they all look too "big". I'll have just one user that should be able to make PUT/POST/DELETE calls, and then "public" users will just use GET.

I think that a simple way should be something like this:

Public users making a get call: return the api response, as it is now

Public users making a put/post/delete call: return the "not authorized" response

Registered user making get/put/post/delete calls: check if it is registered and reply the appropriate response.

The "check" shouldn't be something like storing a secret-key in my config.py file and then comparing it to an attribute of the header of the api call? I think that creating an entire table for users, as I saw in some tutorials, and then having usernames+password that generates API tokens is too "big" and not necessary here.. Since I will be the only user that can be authenticated, I know what the key is and I can just put some 'secret-key' : mysecretkey in the header. Am I missing something?

Thanks!

答:
No need to reinvent authentication when HTTP Basic Auth exists:

http://flask.pocoo.org/snippets/8/

Body:
I am using Flask-Restless to make a super simple REST API. I would like to add authentication, but just for put/post/delete calls, while I want to leave get calls public.

So far, I put in my views.py file this:

manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(models.mymodel, methods=['GET', 'POST', 'DELETE'])

I had a look on different solutions for authentication, but they all look too "big". I'll have just one user that should be able to make PUT/POST/DELETE calls, and then "public" users will just use GET.

I think that a simple way should be something like this:

Public users making a get call: return the api response, as it is now

Public users making a put/post/delete call: return the "not authorized" response

Registered user making get/put/post/delete calls: check if it is registered and reply the appropriate response.

The "check" shouldn't be something like storing a secret-key in my config.py file and then comparing it to an attribute of the header of the api call? I think that creating an entire table for users, as I saw in some tutorials, and then having usernames+password that generates API tokens is too "big" and not necessary here.. Since I will be the only user that can be authenticated, I know what the key is and I can just put some 'secret-key' : mysecretkey in the header. Am I missing something?

Thanks!


问:
Graphing Algorithm To Match Nodes
Given a directed graph, what is an algorithm I can use to find a random subset of its edges so that every node has exactly one incoming and exactly one outgoing edge?

For example, this could be the graph I am given:

And this would be a valid output graph:

This is valid because:

It contains all the nodes on the input graph

All its edges are also on the input graph

Every node has exactly one edge leaving it and one edge coming to it (and that can't be the same edge, no loops are allowed, every node has to connect to at least one other node).

If there is no possible solution that should be detected.

Is there an efficient algorithm to solve this?

Thanks!

答:
It's a node cycles coverage problem. It can be solved as Maximum matchings in bipartite graphs.

In short:

Split every node in two, each in one partition of a graph, so that all edges go from partition P1 to partition P2. In your sample, nodes A and D will turn into nodes A1, D1 in partition P1 and A2, D2 in P2. Edge A-D will turn into A1-D2, and D-A - to D1-A2.

Then find a maximum matching, some algorithms exist.

Then merge the nodes back, and you got a cycle coverage.

ContentLicense: CC BY-SA 2.5

Title: Graphing Algorithm To Match Nodes


问:
Typescript return value wrapped in curly braces?
In the following code block heros is wrapped with curly braces:

```<code>  export class InMemoryDataService implements InMemoryDbService {
      createDb() {
        let heroes = [
          {id: 11, name: 'Mr. Nice'},
          {id: 12, name: 'Narco'},
          ...
        ];
        return {heroes};
      }
    }
</code>```

In particular reason for this?

答:
Yes, you return it as an object that looks like this:

```<code>{
    heroes: heroes
}
</code>```

It's a "shortcut" to use this form: { heroes }.

More on this here: Object initializer - New notations in ECMAScript 2015

Body:
In the following code block heros is wrapped with curly braces:

  export class InMemoryDataService implements InMemoryDbService {
      createDb() {
        let heroes = [
          {id: 11, name: 'Mr. Nice'},
          {id: 12, name: 'Narco'},
          ...
        ];
        return {heroes};
      }
    }

In particular reason for this?

Body:
Yes, you return it as an object that looks like this:

{
    heroes: heroes
}

It's a "shortcut" to use this form: { heroes }.

More on this here: Object initializer - New notations in ECMAScript 2015


问:
CSS and images does't work on host
on my computer the website works fine.
when I upload the website the the server the images and css does't work.
I've tried to solve this problem myself but failed.</p>

答:
I had some problem. Do not upload site with file zila or total commander they can loose some files.
Upload site directly using c-panel, zip-it and upload.
If this dont work call administrator</p>

Title: CSS and images does't work on host


问:
Select last unique polymorphic objects ordered by created at in Rails
I'm trying to get unique polymorphic objects by the value of one of the columns. I'm using Postgres.

The object has the following properties: id, available_type, available_id, value, created_at, updated_at.

I'm looking to get the most recent object per available_id (recency determined by created_at) for records with the available_type of "User".

I've been trying ActiveRecord queries like this:

```<code>Service.where(available_type: "User").order(created_at: :desc).distinct(:available_id)
</code>```

But it isn't limiting to one per available_id.

答:
Using a left join is going to be your probably most efficient way

The following sql selects only rows where there are no rows with a larger created_at.

See this post for more info: https://stackoverflow.com/a/27802817/5301717

```<code>query = <<-SQL
    SELECT m.*                    # get the row that contains the max value
    FROM services m                 # "m" from "max"
    LEFT JOIN services b        # "b" from "bigger"
        ON m.available_id = b.available_id    # match "max" row with "bigger" row by `home`
        AND m.available_type = b.available_type
        AND m.created_at < b.created_at    # want "bigger" than "max"
    WHERE b.created_at IS NULL      # keep only if there is no bigger than max
    AND service.available_type = 'User'
SQL

Service.find_by_sql(query)
</code>```

distinct doesn't take a column name as an argument, only true/false.

distinct is for returning only distinct records and has nothing to do with filtering for a specific value.

if you need a specific available_id, you need to use where

e.g.

```<code>Service.distinct.where(available_type: "User").where(available_id: YOUR_ID_HERE).order(created_at: :desc)
</code>```

to only get the most recent add limit

```<code>Service.distinct.where(available_type: "User").where(available_id: YOUR_ID_HERE).order(created_at: :desc).limit(1)
</code>```

if you need to get the most recent of each distinct available_id, that will require a loop

first get the distinct polymorphic values by only selecting the columns that need to be distinct with select:

```<code>available_ids = Service.distinct.select(:available_id).where(available_type: 'User')
</code>```

then get the most recent of each id:

```<code>recents = []
available_ids.each do |id|
  recents << Service.where(available_id: id).where(available_type: 'User').order(created_at: :desc).limit(1)
end
</code>```

Body:
I'm trying to get unique polymorphic objects by the value of one of the columns. I'm using Postgres.

The object has the following properties: id, available_type, available_id, value, created_at, updated_at.

I'm looking to get the most recent object per available_id (recency determined by created_at) for records with the available_type of "User".

I've been trying ActiveRecord queries like this:

Service.where(available_type: "User").order(created_at: :desc).distinct(:available_id)

But it isn't limiting to one per available_id.

Body:
Using a left join is going to be your probably most efficient way

The following sql selects only rows where there are no rows with a larger created_at.

See this post for more info: https://stackoverflow.com/a/27802817/5301717

query = <<-SQL
    SELECT m.*                    # get the row that contains the max value
    FROM services m                 # "m" from "max"
    LEFT JOIN services b        # "b" from "bigger"
        ON m.available_id = b.available_id    # match "max" row with "bigger" row by `home`
        AND m.available_type = b.available_type
        AND m.created_at < b.created_at    # want "bigger" than "max"
    WHERE b.created_at IS NULL      # keep only if there is no bigger than max
    AND service.available_type = 'User'
SQL

Service.find_by_sql(query)

distinct doesn't take a column name as an argument, only true/false.

distinct is for returning only distinct records and has nothing to do with filtering for a specific value.

if you need a specific available_id, you need to use where

e.g.

Service.distinct.where(available_type: "User").where(available_id: YOUR_ID_HERE).order(created_at: :desc)

to only get the most recent add limit

Service.distinct.where(available_type: "User").where(available_id: YOUR_ID_HERE).order(created_at: :desc).limit(1)

if you need to get the most recent of each distinct available_id, that will require a loop

first get the distinct polymorphic values by only selecting the columns that need to be distinct with select:

available_ids = Service.distinct.select(:available_id).where(available_type: 'User')

then get the most recent of each id:

recents = []
available_ids.each do |id|
  recents << Service.where(available_id: id).where(available_type: 'User').order(created_at: :desc).limit(1)
end


问:
How can I find out which test method in a batch of test methods fails to run?
In the Test Explorer window of Visual Studio 2015 for C#, I select all the 360 test methods in my solution, and choose "Run Selected Tests". But not all of them are  executed, as indicated by the Output window:

------ Run test started ------

The active Test Run was aborted because the execution process exited unexpectedly. To investigate further,
enable local crash dumps either at the machine level or for process
te.processhost.managed.exe. Go to more details:
http://go.microsoft.com/fwlink/?linkid=232477

========== Run test finished: 188 run (0:00:12.7254721) ==========

How can I find out which test method fails to run, narrow the culprit test method down? Thanks.

答: Probably not the most subtle way to do it, but you could comment your tests one by one, and see at which point your run stops failing.</p>


问:
Average calculation by eliminating top 10% & bottom 10% values using T-SQL
I need to calculate the average duration of one of our running stored procedures. For example the duration(in seconds) of SP are:
1,30,2,5,2,15,35,7,3,4,2,1,2,40

I have to eliminate top 10% calls (fast calls) & bottom 10% calls (slow calls) & calculate the average on the rest.

Is there a better approach minimizing the performance hit since this has to done on a huge data set in a regular basis?

The approach I'm aware is:

Eliminate top 10% records using following query which results two values (1,1)

```<code>SELECT TOP 10 PERCENT WITH TIES value FROM #t order by value asc
</code>```

bottom 10% gives (35,40),

```<code>SELECT TOP 10 PERCENT WITH TIES value FROM #t order by value desc
</code>```

After eliminating those values(1,1,35 & 40) the average is going to be 7.

答:
Edited to Ensure an Even "Haircut"

```<code>Declare @YourTable table (Seconds int)
Insert Into @YourTable values
(1),(30),(2),(5),(2),(15),(35),(7),(3),(4),(2),(1),(2),(40)

Select AvgSeconds = avg(Seconds)
 From (
        Select *
              ,Dec1 = NTile(10) over (Order By Seconds)
              ,Dec2 = NTile(10) over (Order By Seconds Desc)
          From  @YourTable
      ) A
 Where Dec1 between 2 and 9
   and Dec2 between 2 and 9
</code>```

Returns

```<code>AvgSeconds
7
</code>```

Body:
I need to calculate the average duration of one of our running stored procedures. For example the duration(in seconds) of SP are:
1,30,2,5,2,15,35,7,3,4,2,1,2,40

I have to eliminate top 10% calls (fast calls) & bottom 10% calls (slow calls) & calculate the average on the rest.

Is there a better approach minimizing the performance hit since this has to done on a huge data set in a regular basis?

The approach I'm aware is:

Eliminate top 10% records using following query which results two values (1,1)

SELECT TOP 10 PERCENT WITH TIES value FROM #t order by value asc

bottom 10% gives (35,40),

SELECT TOP 10 PERCENT WITH TIES value FROM #t order by value desc

After eliminating those values(1,1,35 & 40) the average is going to be 7.

Body:
Edited to Ensure an Even "Haircut"

Declare @YourTable table (Seconds int)
Insert Into @YourTable values
(1),(30),(2),(5),(2),(15),(35),(7),(3),(4),(2),(1),(2),(40)

Select AvgSeconds = avg(Seconds)
 From (
        Select *
              ,Dec1 = NTile(10) over (Order By Seconds)
              ,Dec2 = NTile(10) over (Order By Seconds Desc)
          From  @YourTable
      ) A
 Where Dec1 between 2 and 9
   and Dec2 between 2 and 9

Returns

AvgSeconds
7


问:
jQuery: prevent click queue
```<code>$("#right").live("click", function(event) {
    $(".image_scroll").animate({"left": "+=300px"}, "slow");
});
</code>```

I need the click to basically not register until the animation is done.
I've tried using return false but that just seems to kill the link entirely.

Tried also using $(".image_scroll").stop().animate({"left": "+=300px"}, "slow"); but that just makes the animation stutter and look glitchy.

Edit: The id #right is on an image, not an a tag. The HTML is as follows:

```<code><img src="/images/right.png" id="right" alt="" />
<div id="container">
    <div id="image_scroll">
        <img src="1.jpg" />
        <img src="3.jpg" />
        <img src="4.jpg" />
    </div><!-- /#image_scroll -->
</div> <!-- /#container
</code>```

答:
You'll need to store the whether the animation is running or not, you could use the jQuery.data function for that:</p>

```<code>$("#right").live("click", function(event) {
    var el = $(this),
        state = el.data('animation_state');
    if(state == 'busy') {
       //ignore clicks while the animation is running
       return false;
    }
    el.data('animation_state', 'busy');
    $(".image_scroll").animate({"left": "+=300px"}, "slow", function() {
       //finished animating
       //set the state to finished so we can click the element the next time
      el.data('animation_state', 'complete');
    });
});
</code>```

Title: jQuery: prevent click queue

Body:
$("#right").live("click", function(event) {
    $(".image_scroll").animate({"left": "+=300px"}, "slow");
});

I need the click to basically not register until the animation is done.
I've tried using return false but that just seems to kill the link entirely.

Tried also using $(".image_scroll").stop().animate({"left": "+=300px"}, "slow"); but that just makes the animation stutter and look glitchy.

Edit: The id #right is on an image, not an a tag. The HTML is as follows:

Body:
You'll need to store the whether the animation is running or not, you could use the jQuery.data function for that:

$("#right").live("click", function(event) {
    var el = $(this),
        state = el.data('animation_state');
    if(state == 'busy') {
       //ignore clicks while the animation is running
       return false;
    }
    el.data('animation_state', 'busy');
    $(".image_scroll").animate({"left": "+=300px"}, "slow", function() {
       //finished animating
       //set the state to finished so we can click the element the next time
      el.data('animation_state', 'complete');
    });
});


问:
How do I allow my ListView to fill the entire screen in Android?
I'm making a listview in android, and my listview doesn't fill the entire screen. It has some remaining plain space below the listview (probably because i don't have enough items to fill the screen). I've searched for many solutions online, but none seem to be able to solve this problem.

Here is my layout:

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

 <ListView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id = "@+id/customListview">

 </ListView>

</LinearLayout>
</code>```

Here is my item_layout.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id= "@+id/ItemNameSales"
        android:layout_alignParentLeft="true"
        android:text="Item Name"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id= "@+id/ItemNameQty"
        android:layout_alignParentRight="true"
        android:text="Item Quantity"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>
</code>```

答:
You will have to change it dinamically to fit the intire screen!!!</p>

```<code>list.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, CalculateHowYouNeedToFitScreen));
</code>```

Body:
I'm making a listview in android, and my listview doesn't fill the entire screen. It has some remaining plain space below the listview (probably because i don't have enough items to fill the screen). I've searched for many solutions online, but none seem to be able to solve this problem.

Here is my layout:

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

 <ListView
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id = "@+id/customListview">

 </ListView>

</LinearLayout>

Here is my item_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id= "@+id/ItemNameSales"
        android:layout_alignParentLeft="true"
        android:text="Item Name"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id= "@+id/ItemNameQty"
        android:layout_alignParentRight="true"
        android:text="Item Quantity"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

Body:
You will have to change it dinamically to fit the intire screen!!!

list.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, CalculateHowYouNeedToFitScreen));


问:
Why do methods of classes that inherit from numpy arrays return different things?
Let's look at some very simple behaviour of numpy arrays:

```<code>import numpy as np
arr = np.array([1,2,3,4,5])
max_value = arr.max() # returns 5
</code>```

Now I create a class which inherits from np.ndarray:

```<code>class CustomArray(np.ndarray):
    def __new__(cls, *args, **kwargs):
        obj = np.array(*args, **kwargs).view(cls)
        return obj
new_arr = CustomArray([1,2,3,4,5])
</code>```

I haven't actually changed any behaviour - I just made a nominal change in what class the object is.

And yet:

```<code>new_max_value = new_arr.max() # returns CustomArray(5)
</code>```

The return value is an CustomArray instance? Why? arr.max() didn't return a np.ndarray instance, just a plain numpy integer.

Similarly, why do both arr == new_arr and new_arr == arr return CustomArray instances? Shouldn't the former call arr.__eq__(new_arr), which should return a np.ndarray instance?

EDIT:

Note that I override the __new__ method for the sake of easy constructors. E.g. the equivalent of np.array([1,2,3,4,5]) can just be CustomArray([1,2,3,4,5]), whereas if I plainly inherit from np.ndarray I'd have to do something like new_arr = CustomArray((5,)); new_arr[:] = np.array([1,2,3,4,5]).

答:
Following the numpy docs: array_wrap gets called at the end of numpy ufuncs and other numpy functions, to allow a subclass to set the type of the return value and update attributes and metadata.

```<code>class CustomArray(np.ndarray):
    def __new__(cls, a, dtype=None, order=None):
        obj = np.asarray(a, dtype, order).view(cls)
        return obj

    def __array_wrap__(self, out_arr, context=None):
        return np.ndarray.__array_wrap__(self, out_arr, context)

c = CustomArray([1,2,3,4])
c.max() # returns 4
</code>```

Body:
Let's look at some very simple behaviour of numpy arrays:

import numpy as np
arr = np.array([1,2,3,4,5])
max_value = arr.max() # returns 5

Now I create a class which inherits from np.ndarray:

class CustomArray(np.ndarray):
    def __new__(cls, *args, **kwargs):
        obj = np.array(*args, **kwargs).view(cls)
        return obj
new_arr = CustomArray([1,2,3,4,5])

I haven't actually changed any behaviour - I just made a nominal change in what class the object is.

And yet:

new_max_value = new_arr.max() # returns CustomArray(5)

The return value is an CustomArray instance? Why? arr.max() didn't return a np.ndarray instance, just a plain numpy integer.

Similarly, why do both arr == new_arr and new_arr == arr return CustomArray instances? Shouldn't the former call arr.__eq__(new_arr), which should return a np.ndarray instance?

EDIT:

Note that I override the __new__ method for the sake of easy constructors. E.g. the equivalent of np.array([1,2,3,4,5]) can just be CustomArray([1,2,3,4,5]), whereas if I plainly inherit from np.ndarray I'd have to do something like new_arr = CustomArray((5,)); new_arr[:] = np.array([1,2,3,4,5]).

Body:
Following the numpy docs: array_wrap gets called at the end of numpy ufuncs and other numpy functions, to allow a subclass to set the type of the return value and update attributes and metadata.

class CustomArray(np.ndarray):
    def __new__(cls, a, dtype=None, order=None):
        obj = np.asarray(a, dtype, order).view(cls)
        return obj

    def __array_wrap__(self, out_arr, context=None):
        return np.ndarray.__array_wrap__(self, out_arr, context)

c = CustomArray([1,2,3,4])
c.max() # returns 4


问:
How do I read double quotes(") or single quotes(') through command line into my perl program?
I am trying to use use arguments passed as command line arguments into my script, But while doing so the double quotes(") and single quotes(') vanishes.
for example on running the following:

```<code>#!usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument\n";
</code>```

Upon running the above code:

```<code>perl test1.pl name1 "name2 and name3"
</code>```

I am getting the following output:

```<code>name1 name2 and name3
</code>```

Is there any way to include the double quotes along with the command line arguments so that the final argument is "name2 and name3" and not just name2 and name3 ?

I have tried using '\' to escape double quotes perl test1.pl name1 \"name2 and name3\" but it only makes it worse by considering "name2 as a separate argument and as a separate argument and name3" as another argument.

答:
I changed your code a bit to illustrate the points:

```<code>for ($c=0; $c<=$#ARGV; $c++) {print "ARGV[$c] = $ARGV[$c]\n";}
my $argument_list = join(" ",@ARGV);
print "$argument\n"; # you meant argument_list
print "ArgLst = $argument_list\n";

$ perl test.pl 1  two       "3 four" " 5 six"
ARGV[0] = 1
ARGV[1] = two
ARGV[2] = 3 four
ARGV[3] =  5 six

ArgLst = 1 two 3 four  5 six
</code>```

NOTE:

Without the quote, arguments are separated by space(s)

The quote forces the interpreter to treat characters (including spaces) inside the quote as one string

"join" command concatenates the arguments together. Looking at the ArgLst alone, you wont be able to tell which is the 2nd argument.

I dont know 100% about your question. I hope the code indirectly answer your question.

Body:
I am trying to use use arguments passed as command line arguments into my script, But while doing so the double quotes(") and single quotes(') vanishes.
for example on running the following:

#!usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument\n";

Upon running the above code:

perl test1.pl name1 "name2 and name3"

I am getting the following output:

name1 name2 and name3

Is there any way to include the double quotes along with the command line arguments so that the final argument is "name2 and name3" and not just name2 and name3 ?

I have tried using '\' to escape double quotes perl test1.pl name1 \"name2 and name3\" but it only makes it worse by considering "name2 as a separate argument and as a separate argument and name3" as another argument.

Body:
I changed your code a bit to illustrate the points:

for ($c=0; $c<=$#ARGV; $c++) {print "ARGV[$c] = $ARGV[$c]\n";}
my $argument_list = join(" ",@ARGV);
print "$argument\n"; # you meant argument_list
print "ArgLst = $argument_list\n";

$ perl test.pl 1  two       "3 four" " 5 six"
ARGV[0] = 1
ARGV[1] = two
ARGV[2] = 3 four
ARGV[3] =  5 six

ArgLst = 1 two 3 four  5 six

NOTE:

Without the quote, arguments are separated by space(s)

The quote forces the interpreter to treat characters (including spaces) inside the quote as one string

"join" command concatenates the arguments together. Looking at the ArgLst alone, you wont be able to tell which is the 2nd argument.

I dont know 100% about your question. I hope the code indirectly answer your question.


问:
Using '~' (A.K.A. tilde) in input directive does not seem to work?
This is the first time I've tried to use a "~" in my input.
It works when I convert the "~" to an absolute path.

Proof they are the same file:

```<code>(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls ~/share/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls /genesis/extscratch/clc/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /genesis/extscratch/clc/references/rRNA.ensg72.hg19.interval_list

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list
</code>```

Doesn't work:

```<code>rule intervalList:
    input:
       "~/share/references/rRNA.ensg72.hg19.interval_list"
</code>```

Works:

```<code>rule intervalList:
    input:
       "/home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list"
</code>```

I've only tried using it in the input directive at this time. I might spend a moment to see if it works as an output directive (not something I need, just curious).

Thoughts?

EDIT

@alvits Was able to point out that ~ is converted by the shell to ${HOME} before it gets evaluated. It would seem that when providing ~ to snakemake, this conversion does not occurr. Easy alternative is to just always use ${HOME}, which works both on MacOSX and Linux :).

I was able to use the following successfully:

```<code>rule intervalList:
    input:
       "${HOME}/share/references/rRNA.ensg72.hg19.interval_list"
</code>```

Second EDIT

User pointed out what I thought was a solution was in fact not.
Solution is to not use either "~" or "${HOME}" in the input directive.

答:
I'm going to close this question.

I ended up going with @alvits suggestion.

I chose it because that is what tilde represents, so it makes sense to provide it in an non-referenced form.

expanduser wrapping, although a possibility, is overkill for what is required.

Thank you everyone for your help!

2017/06/09 - EDIT: Don't use "~" or "${HOME}" in Snakemake inputs.

After seeing the comment by Johannes Köster, I double checked what I had done, and I was unable to reproduce it.

I'm sorry for the confusion. Thank you so much for catching this error J.K.

I'm not sure what I had setup prior. I ended up changing the way the file is being used, even with git, I cannot reproduce it.

Body:
This is the first time I've tried to use a "~" in my input.
It works when I convert the "~" to an absolute path.

Proof they are the same file:

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls ~/share/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls /genesis/extscratch/clc/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /genesis/extscratch/clc/references/rRNA.ensg72.hg19.interval_list

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list

Doesn't work:

rule intervalList:
    input:
       "~/share/references/rRNA.ensg72.hg19.interval_list"

Works:

rule intervalList:
    input:
       "/home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list"

I've only tried using it in the input directive at this time. I might spend a moment to see if it works as an output directive (not something I need, just curious).

Thoughts?

EDIT

@alvits Was able to point out that ~ is converted by the shell to ${HOME} before it gets evaluated. It would seem that when providing ~ to snakemake, this conversion does not occurr. Easy alternative is to just always use ${HOME}, which works both on MacOSX and Linux :).

I was able to use the following successfully:

rule intervalList:
    input:
       "${HOME}/share/references/rRNA.ensg72.hg19.interval_list"

Second EDIT

User pointed out what I thought was a solution was in fact not.
Solution is to not use either "~" or "${HOME}" in the input directive.


问:
With SQL Server how to get the most recent date while summing on amount and the sum of the amount is greater than 0?
I have a transaction table:

```<code>CREATE TABLE [dbo].[Trans](
[ID] [char](6) NOT NULL,
[PersonID] [char](6) NULL,
[TransCode] [char](2) NULL,
[TransDesc] [char](45) NULL,
[TransDate] [datetime] NULL,
[TransAmount] [numeric](18, 2) NULL)
</code>```

What I want is the date and amount of the most recent payment made by each person.  Payments are defined by the TransCode (see the WHERE clause below).

There can be multiple transactions on any given day, so I want the sum of transactions on the most recent day.  Also there can be "reversal" transactions that could make the sum of the transactions on the most recent day be 0 (zero) -- I don't want these to be in the results (hence the "HAVING   (SUM(TransAmount) > 0)" below).

Here is my most recent attempt, that is not working, but I don't know why!

```<code>SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
GROUP BY PersonID, TotalAmount
ORDER BY PersonID
</code>```

When I run the inner query I get what expect, a list of amounts summed by date, for each person.  The outer query though, for some reason, is returning multiple rows for each person.  It should only return one row for each person :-(

Can someone one tell me what I am doing wrong?

Please let me know if there is any additional information you may need to understand the problem better.

Thank you in advance for any help you can provide,

Ben

答:
```<code>SELECT  LastDate.PersonID, LastDate.TransDate AS LastPaymentDate, TotalAmount.TotalAmount
FROM    (SELECT   PersonID, Max(TransDate) as TransDate
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS LastDate
INNER JOIN (SELECT PersonID, Transdate, SUM(TransAMount) as TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
ON TotalAmount.PersonID = LastDate.PersonID AND TotalAmount.TransDate = LastDate.TransDate
ORDER BY LastDate.PersonID
</code>```

Something like that should work

Body:
I have a transaction table:

CREATE TABLE [dbo].[Trans](
[ID] [char](6) NOT NULL,
[PersonID] [char](6) NULL,
[TransCode] [char](2) NULL,
[TransDesc] [char](45) NULL,
[TransDate] [datetime] NULL,
[TransAmount] [numeric](18, 2) NULL)

What I want is the date and amount of the most recent payment made by each person.  Payments are defined by the TransCode (see the WHERE clause below).

There can be multiple transactions on any given day, so I want the sum of transactions on the most recent day.  Also there can be "reversal" transactions that could make the sum of the transactions on the most recent day be 0 (zero) -- I don't want these to be in the results (hence the "HAVING   (SUM(TransAmount) > 0)" below).

Here is my most recent attempt, that is not working, but I don't know why!

SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
GROUP BY PersonID, TotalAmount
ORDER BY PersonID

When I run the inner query I get what expect, a list of amounts summed by date, for each person.  The outer query though, for some reason, is returning multiple rows for each person.  It should only return one row for each person :-(

Can someone one tell me what I am doing wrong?

Please let me know if there is any additional information you may need to understand the problem better.

Thank you in advance for any help you can provide,

Ben

Body:
SELECT  LastDate.PersonID, LastDate.TransDate AS LastPaymentDate, TotalAmount.TotalAmount
FROM    (SELECT   PersonID, Max(TransDate) as TransDate
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS LastDate
INNER JOIN (SELECT PersonID, Transdate, SUM(TransAMount) as TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
ON TotalAmount.PersonID = LastDate.PersonID AND TotalAmount.TransDate = LastDate.TransDate
ORDER BY LastDate.PersonID

Something like that should work


问:
Twig: Use "Ignore Missing" on Include by default
With Twig I am using {% include %} a lot. I need to attach ignore missing to every include, since I do not want to run into an Exception when a file is not found. This bloats the template code a lot and I am looking for an option to attach ignore default to all includes by default without repeating it with every include call. I am looking for an equivalent of php's include in Twig since Twig's own include behaves like php's require.

How can I include templates in Twig without having Exceptions thrown when a file is not found and without adding ignore missing to every single include?

I was looking for a config in Twig but did not find an option.

答:
by over-riding built-in include</p>

```<code>     class TokenParser_Include extends Twig_TokenParser
        {
            public function parse(Twig_Token $token)
            {
                $expr = $this->parser->getExpressionParser()->parseExpression();

                list($variables, $only, $ignoreMissing) = $this->parseArguments();

                return new Twig_Node_Include($expr, $variables, $only, $ignoreMissing = true, $token->getLine(), $this->getTag());
            }

            protected function parseArguments()
            {
                $stream = $this->parser->getStream();

                $ignoreMissing = false;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'ignore')) {
                    $stream->expect(Twig_Token::NAME_TYPE, 'missing');

                    $ignoreMissing = true;
                }

                $variables = null;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'with')) {
                    $variables = $this->parser->getExpressionParser()->parseExpression();
                }

                $only = false;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'only')) {
                    $only = true;
                }

                $stream->expect(Twig_Token::BLOCK_END_TYPE);

                return array($variables, $only, $ignoreMissing);
            }

            public function getTag()
            {
                return 'include';
            }
        }

   $twig->addTokenParser(new TokenParser_Include());
</code>```

Body:
by over-riding built-in include

     class TokenParser_Include extends Twig_TokenParser
        {
            public function parse(Twig_Token $token)
            {
                $expr = $this->parser->getExpressionParser()->parseExpression();

                list($variables, $only, $ignoreMissing) = $this->parseArguments();

                return new Twig_Node_Include($expr, $variables, $only, $ignoreMissing = true, $token->getLine(), $this->getTag());
            }

            protected function parseArguments()
            {
                $stream = $this->parser->getStream();

                $ignoreMissing = false;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'ignore')) {
                    $stream->expect(Twig_Token::NAME_TYPE, 'missing');

                    $ignoreMissing = true;
                }

                $variables = null;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'with')) {
                    $variables = $this->parser->getExpressionParser()->parseExpression();
                }

                $only = false;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'only')) {
                    $only = true;
                }

                $stream->expect(Twig_Token::BLOCK_END_TYPE);

                return array($variables, $only, $ignoreMissing);
            }

            public function getTag()
            {
                return 'include';
            }
        }

   $twig->addTokenParser(new TokenParser_Include());


问:
ASP.NET MVC2 Reading JSON data with controller
I have problems to receive json values from my javascript/jQuery request to my controller.

MyClass looks like the following:

```<code>function MyClass() {
    this.MyString = null;
    this.MyInt = null;
    this.Subs = null;
}
</code>```

My Request looks like the following:

```<code>var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
var testData2 = new MyClass();
testData2.MyInt = 5678;
testData2.MyString = "GHIjkl";
testData1.Subs.push(testData2);
var jsonData = JSON.stringify(testData1);
var self = this;
$.ajax({
    url: '/Home/Request',
    type: 'POST',
    dataType: 'json',
    data: jsonData,
    contentType: 'application/json; charset=utf-8',
    success: function (x) {
        self.ParseResult(x);
    }
});
</code>```

Now I have a controller:

```<code>public JsonResult Request(MyClass myObj)
{
    var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}
</code>```

With the following class:

```<code>public class  MyClass
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public List<MyClass> Subs { get; set; }
}
</code>```

All names in jsonData are exactly the same like in my class "MyClass". But there are no values in myObj.

Where is the Problem. Is there anything I can do to get this mapping working correctly?

Thank you very much in advance,

Chris

UPDATE:

Thank you for your repley. I have used the JavascriptSerializer. But I have the problem, that myString is null:

```<code>public JsonResult Data(string myString)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var data = serializer.Deserialize<MyClass>(myString);
var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}
</code>```

Where is the value? Should I take the value from the request-data?

@Dave Ward

You second solution is working. But I have a problem with the subs.

```<code>var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
for (var i = 0; i < 10; i++) {
    var testData2 = new MyClass();
    testData2.MyInt = i;
    testData2.MyString = "abcDEF";
    testData1.Subs.push(testData2);
}
</code>```

I get 10 Subs in my controller, but all are empty. What can I do?

@Dave Ward, @ALL

Using the traditional settings my 10 Subs are bot empty, they are not there. Subs count is 0 (not NULL).
I tried to change the Subs Type from List to IEnumerable but that didn't help.
Do you know anything else I can do to get Subs filled in my controller?

Ok, thank you Dave Ward, I will use the JSON method.

For somebody else having the same problem this controller code could be from help:

```<code>MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(myString));
var serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass se = serializer.ReadObject(ms) as MyClass;
ms.Close();
</code>```

答:
In my experience I have to pass in the json as a string and then deserialize it. I use Newtonsoft to do this.</p>

```<code>public ActionResult DoAjax(string jsonRequest)
{
    JsonSerializer serializer = new JsonSerializer();

    StringReader sr = new StringReader(jsonRequest);
    Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);

    MyClass obj = (MyClass)serializer.Deserialize(reader, typeof(MyClass));

    //...do other stuff
}
</code>```

Body:
I have problems to receive json values from my javascript/jQuery request to my controller.

MyClass looks like the following:

function MyClass() {
    this.MyString = null;
    this.MyInt = null;
    this.Subs = null;
}

My Request looks like the following:

var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
var testData2 = new MyClass();
testData2.MyInt = 5678;
testData2.MyString = "GHIjkl";
testData1.Subs.push(testData2);
var jsonData = JSON.stringify(testData1);
var self = this;
$.ajax({
    url: '/Home/Request',
    type: 'POST',
    dataType: 'json',
    data: jsonData,
    contentType: 'application/json; charset=utf-8',
    success: function (x) {
        self.ParseResult(x);
    }
});

Now I have a controller:

public JsonResult Request(MyClass myObj)
{
    var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}

With the following class:

public class  MyClass
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public List<MyClass> Subs { get; set; }
}

All names in jsonData are exactly the same like in my class "MyClass". But there are no values in myObj.

Where is the Problem. Is there anything I can do to get this mapping working correctly?

Thank you very much in advance,

Chris

UPDATE:

Thank you for your repley. I have used the JavascriptSerializer. But I have the problem, that myString is null:

public JsonResult Data(string myString)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var data = serializer.Deserialize<MyClass>(myString);
var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}

Where is the value? Should I take the value from the request-data?

@Dave Ward

You second solution is working. But I have a problem with the subs.

var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
for (var i = 0; i < 10; i++) {
    var testData2 = new MyClass();
    testData2.MyInt = i;
    testData2.MyString = "abcDEF";
    testData1.Subs.push(testData2);
}

I get 10 Subs in my controller, but all are empty. What can I do?

@Dave Ward, @ALL

Using the traditional settings my 10 Subs are bot empty, they are not there. Subs count is 0 (not NULL).
I tried to change the Subs Type from List to IEnumerable but that didn't help.
Do you know anything else I can do to get Subs filled in my controller?

Ok, thank you Dave Ward, I will use the JSON method.

For somebody else having the same problem this controller code could be from help:

MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(myString));
var serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass se = serializer.ReadObject(ms) as MyClass;
ms.Close();

Body:
In my experience I have to pass in the json as a string and then deserialize it. I use Newtonsoft to do this.

public ActionResult DoAjax(string jsonRequest)
{
    JsonSerializer serializer = new JsonSerializer();

    StringReader sr = new StringReader(jsonRequest);
    Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);

    MyClass obj = (MyClass)serializer.Deserialize(reader, typeof(MyClass));

    //...do other stuff
}


问:
Why is FileStream not writable?
I'm writing a console program. I got the code to work but I want to change it into a generic function to enable using different Stream sources (such as MemoryStream).

Here's my program:

```<code>private static void Main(string[] args)
{
    using (var fs = new FileStream("f:\\!temp\\marcXmlRecords.mxml", FileMode.Open))
    {
        var reader = new MarcXmlReader().Read(fs);

        foreach (var record in reader)
        {
            var leader = record.Leader;
            var controlFields = record.GetControlFields();
            var dataFields = record.GetDataFields();
            var allFields = record.GetVariableFields();

            using (var fs2 = new FileStream("f:\\!temp\\marcRecords.mrc",
                FileMode.OpenOrCreate))
            {
                using (var writer = new MarcStreamWriter(fs2, "UTF-8"))
                {
                    var wrecord = MarcFactory.Instance.NewRecord();
                    wrecord.Leader = record.Leader;

                    foreach (var cfield in controlFields)
                    {
                        wrecord.AddVariableField(cfield);
                    }

                    foreach (var dfield in dataFields)
                    {
                        wrecord.AddVariableField(dfield);
                    }

                    foreach (var afield in allFields)
                    {
                        wrecord.AddVariableField(afield);
                    }

                    writer.Write(wrecord);
                }
            }
        }
    }
}
</code>```

Ok, works fine. Now let's make it more generic:

```<code>internal class Program
{
    private static void Main(string[] args)
    {
        using (var fs = new FileStream("f:\\!temp\\marcXmlRecords.mxml", FileMode.Open))
        {
            using (var fs2 = new FileStream("f:\\!temp\\marcRecords.mrc",
                FileMode.OpenOrCreate))
            {
                ConvertXmlMarcToMarc(fs, fs2);
            }
        }
    }

    private static void ConvertXmlMarcToMarc(Stream fin, Stream fout)
    {
        var reader = new MarcXmlReader().Read(fin);

        foreach (var record in reader)
        {
            var leader = record.Leader;
            var controlFields = record.GetControlFields();
            var dataFields = record.GetDataFields();
            var allFields = record.GetVariableFields();

            using (var writer = new MarcStreamWriter(fout, "UTF-8"))
            {
                var wrecord = MarcFactory.Instance.NewRecord();
                wrecord.Leader = record.Leader;

                foreach (var cfield in controlFields)
                {
                    wrecord.AddVariableField(cfield);
                }

                foreach (var dfield in dataFields)
                {
                    wrecord.AddVariableField(dfield);
                }

                foreach (var afield in allFields)
                {
                    wrecord.AddVariableField(afield);
                }

                writer.Write(wrecord);
            }
        }
    }
}
</code>```

But I get an exception on the line: using (var writer = new MarcStreamWriter(fs2, "UTF-8")):

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

  Additional information: Stream was not writable.

Stack Trace

at System.IO.BinaryWriter..ctor(Stream output, Encoding encoding, Boolean leaveOpen)

at MARC4J.Net.MarcStreamWriter..ctor(Stream output, String encoding, Boolean allowOversizeRecord)

at MARC4J.Net.MarcStreamWriter..ctor(Stream output, String encoding)

at SummonImport.Program.ConvertXmlMarcToMarc(Stream fin, Stream fout) in F:!!LocalRepository\Libraries_Apps\SummonImport\trunk\release\SummonImport\SummonImport\Program.cs:line 35

at SummonImport.Program.Main(String[] args) in F:!!LocalRepository\Libraries_Apps\SummonImport\trunk\release\SummonImport\SummonImport\Program.cs:line 20

at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)

at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

at System.Threading.ThreadHelper.ThreadStart()

答:
You need the FileStream constructor that takes a FileAccess parameter:

```<code>using (var fs2 = new FileStream("f:\\!temp\\marcRecords.mrc", FileMode.OpenOrCreate, FileAccess.Write))
</code>```

FileMode.OpenOrCreate on its own isn't enough to make it writable:

Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess.Read, FileIOPermissionAccess.Read permission is required. If the file access is FileAccess.Write, FileIOPermissionAccess.Write permission is required. If the file is opened with FileAccess.ReadWrite, both FileIOPermissionAccess.Read and FileIOPermissionAccess.Write permissions are required.

Title: Why is FileStream not writable?

Body:
I'm writing a console program. I got the code to work but I want to change it into a generic function to enable using different Stream sources (such as MemoryStream).

Here's my program:

private static void Main(string[] args)
{
    using (var fs = new FileStream("f:\\!temp\\marcXmlRecords.mxml", FileMode.Open))
    {
        var reader = new MarcXmlReader().Read(fs);

        foreach (var record in reader)
        {
            var leader = record.Leader;
            var controlFields = record.GetControlFields();
            var dataFields = record.GetDataFields();
            var allFields = record.GetVariableFields();

            using (var fs2 = new FileStream("f:\\!temp\\marcRecords.mrc",
                FileMode.OpenOrCreate))
            {
                using (var writer = new MarcStreamWriter(fs2, "UTF-8"))
                {
                    var wrecord = MarcFactory.Instance.NewRecord();
                    wrecord.Leader = record.Leader;

                    foreach (var cfield in controlFields)
                    {
                        wrecord.AddVariableField(cfield);
                    }

                    foreach (var dfield in dataFields)
                    {
                        wrecord.AddVariableField(dfield);
                    }

                    foreach (var afield in allFields)
                    {
                        wrecord.AddVariableField(afield);
                    }

                    writer.Write(wrecord);
                }
            }
        }
    }
}

Ok, works fine. Now let's make it more generic:

internal class Program
{
    private static void Main(string[] args)
    {
        using (var fs = new FileStream("f:\\!temp\\marcXmlRecords.mxml", FileMode.Open))
        {
            using (var fs2 = new FileStream("f:\\!temp\\marcRecords.mrc",
                FileMode.OpenOrCreate))
            {
                ConvertXmlMarcToMarc(fs, fs2);
            }
        }
    }

    private static void ConvertXmlMarcToMarc(Stream fin, Stream fout)
    {
        var reader = new MarcXmlReader().Read(fin);

        foreach (var record in reader)
        {
            var leader = record.Leader;
            var controlFields = record.GetControlFields();
            var dataFields = record.GetDataFields();
            var allFields = record.GetVariableFields();

            using (var writer = new MarcStreamWriter(fout, "UTF-8"))
            {
                var wrecord = MarcFactory.Instance.NewRecord();
                wrecord.Leader = record.Leader;

                foreach (var cfield in controlFields)
                {
                    wrecord.AddVariableField(cfield);
                }

                foreach (var dfield in dataFields)
                {
                    wrecord.AddVariableField(dfield);
                }

                foreach (var afield in allFields)
                {
                    wrecord.AddVariableField(afield);
                }

                writer.Write(wrecord);
            }
        }
    }
}

But I get an exception on the line: using (var writer = new MarcStreamWriter(fs2, "UTF-8")):

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

  Additional information: Stream was not writable.

Stack Trace

at System.IO.BinaryWriter..ctor(Stream output, Encoding encoding, Boolean leaveOpen)

at MARC4J.Net.MarcStreamWriter..ctor(Stream output, String encoding, Boolean allowOversizeRecord)

at MARC4J.Net.MarcStreamWriter..ctor(Stream output, String encoding)

at SummonImport.Program.ConvertXmlMarcToMarc(Stream fin, Stream fout) in F:!!LocalRepository\Libraries_Apps\SummonImport\trunk\release\SummonImport\SummonImport\Program.cs:line 35

at SummonImport.Program.Main(String[] args) in F:!!LocalRepository\Libraries_Apps\SummonImport\trunk\release\SummonImport\SummonImport\Program.cs:line 20

at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)

at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

at System.Threading.ThreadHelper.ThreadStart()

Body:
You need the FileStream constructor that takes a FileAccess parameter:

using (var fs2 = new FileStream("f:\\!temp\\marcRecords.mrc", FileMode.OpenOrCreate, FileAccess.Write))

FileMode.OpenOrCreate on its own isn't enough to make it writable:

Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess.Read, FileIOPermissionAccess.Read permission is required. If the file access is FileAccess.Write, FileIOPermissionAccess.Write permission is required. If the file is opened with FileAccess.ReadWrite, both FileIOPermissionAccess.Read and FileIOPermissionAccess.Write permissions are required.


问:
custom map does not display
i have published suitability map on arc server. but my map does not display, i have followed arcgis java script api example. i want to display suitability map of the desired area. when user click on the map pop window display the analysis result here is my code

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Create web map from id</title>

    <link rel="stylesheet" href="https://js.arcgis.com/3.20/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="https://js.arcgis.com/3.20/esri/css/esri.css">
    <link rel="stylesheet" href="css/layout.css">

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  </head>

  <body class="claro">
    <div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline'" style="width:100%; height:100%;">
      <div id="header" class="shadow roundedCorners" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top'">
        <div id="title"></div>
        <div id="subtitle"></div>
      </div>
      <div id="map" class="roundedCorners shadow" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'"></div>
      <div id="rightPane" class="roundedCorners shadow" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'right'" >
        <div id="legend"></div>
      </div>
    </div>
  </body>
</html></code>```

答:
Well, you apparently adapted this sample:
https://developers.arcgis.com/javascript/3/jssamples/ags_createwebmapid.html
I am not sure if this is what you want, as using webmaps needs some licensing, I guess. In any case, you need to change few lines in your example. Instead of

```<code><link rel="stylesheet" href="css/layout.css">
</code>```

you should have

```<code><link rel="stylesheet" href="https://developers.arcgis.com/javascript/3/samples/ags_createwebmapid/css/layout.css">
</code>```

to load the original CSS file. You should make your own copy and load it from your server.
More important is to change this line:

```<code>arcgisUtils.arcgisUrl = "http://localhost:6080/arcgis/rest/services/Soil_Maps/changa_manga_soil_map/MapServer/0";
</code>```

which should be:

```<code>arcgisUtils.arcgisUrl = "https://www.arcgis.com/sharing/rest/content/items/";
</code>```

or, as the sample suggests, path with YOUR portal URL.
And, last but not least, the next line must be something like:

```<code>arcgisUtils.createMap("ef9c7fbda731474d98647bebb4b33c20","map").then(
</code>```

Title: custom map does not display

Body:
Well, you apparently adapted this sample:
https://developers.arcgis.com/javascript/3/jssamples/ags_createwebmapid.html
I am not sure if this is what you want, as using webmaps needs some licensing, I guess. In any case, you need to change few lines in your example. Instead of

<link rel="stylesheet" href="css/layout.css">

you should have

<link rel="stylesheet" href="https://developers.arcgis.com/javascript/3/samples/ags_createwebmapid/css/layout.css">

to load the original CSS file. You should make your own copy and load it from your server.
More important is to change this line:

arcgisUtils.arcgisUrl = "http://localhost:6080/arcgis/rest/services/Soil_Maps/changa_manga_soil_map/MapServer/0";

which should be:

arcgisUtils.arcgisUrl = "https://www.arcgis.com/sharing/rest/content/items/";

or, as the sample suggests, path with YOUR portal URL.
And, last but not least, the next line must be something like:

arcgisUtils.createMap("ef9c7fbda731474d98647bebb4b33c20","map").then(


问:
Convert into a For Comprehension in Scala
Testing this I can see that it works:

```<code>def twoHtmlFutures = Action { request =>

  val async1 = as1.index(embed = true)(request) // Future[Result]
  val async2 = as2.index(embed = true)(request) // Future[Result]

  val async1Html = async1.flatMap(x => Pagelet.readBody(x)) // Future[Html]
  val async2Html = async2.flatMap(x => Pagelet.readBody(x)) // Future[Html]

  val source1 = Source.fromFuture(async1Html) // Source[Html, NotUsed]
  val source2 = Source.fromFuture(async2Html) // Source[Html, NotUsed]

  val merged = source1.merge(source2) // Source[Html, NotUsed]
  Ok.chunked(merged)
}
</code>```

But trying to put it into a For Comprehension is not working for me. This is what I tried:

```<code>def twoHtmlFutures2 = Action.async { request =>

  val async1 = as1.index(embed = true)(request)
  val async2 = as2.index(embed = true)(request)

  for {
    async1Res <- async1 // from Future[Result] to Result
    async2Res <- async2 // from Future[Result] to Result

    async1Html <- Pagelet.readBody(async1Res) // from Result to Html
    async2Html <- Pagelet.readBody(async2Res) // from Result to Html

  } yield {
    val source1 = single(async1Html) // from Html to Source[Html, NotUsed]
    val source2 = single(async2Html) // from Html to Source[Html, NotUsed]

    val merged = source1.merge(source2) // Source[Html, NotUsed]
    Ok.chunked(merged)
  }

}
</code>```

But this just jumps on-screen at the same time rather than at different times (streamed) as the first example does. Any helpers out there to widen my eyelids?Thanks

答:
For comprehension and flatMap (which is its desugared version) are used to sequence things.

In the context of Future, this means that in a for comprehension, each of the statement is started only once the previous one has successfully ended.

In your case, you want two Futures run in parallel. This is not what flatMap (or for comprehension) is.

What your code do is the following:

do the first index call

when that's over, do the second index call

when that's over, do the first readBody

when that's over, do the second readBody

when that's over create two (synchronous) sources with the values from the two previous steps, merge them, and start returning the merged source as chunked response.

What your previous code did was

do the first index call

when that's over, do the first readBody

in the meantime, do the same for the second index and readBody

in the meantime, create a source that will output an element when the first readBody yields a result

in the meantime, do the same for the second

merge these two sources, and start all at once to give the merged output as a chunked response.

So, in this case, you start your chunked response just after receiving the request (but with nothing inside yet, waiting for the Futures to be resolved), while in the former case, you wait at each computation for the previous one to be over, even if you don't need its result to go on.

What you should remember, is that you should use flatMap on Future, only if you need the result from a previous computation or if you wish for another computation to be over before doing something else. The same goes for for comprehension, which is just a nice-looking way of chaining flatMaps.

Body:
Testing this I can see that it works:

def twoHtmlFutures = Action { request =>

  val async1 = as1.index(embed = true)(request) // Future[Result]
  val async2 = as2.index(embed = true)(request) // Future[Result]

  val async1Html = async1.flatMap(x => Pagelet.readBody(x)) // Future[Html]
  val async2Html = async2.flatMap(x => Pagelet.readBody(x)) // Future[Html]

  val source1 = Source.fromFuture(async1Html) // Source[Html, NotUsed]
  val source2 = Source.fromFuture(async2Html) // Source[Html, NotUsed]

  val merged = source1.merge(source2) // Source[Html, NotUsed]
  Ok.chunked(merged)
}

But trying to put it into a For Comprehension is not working for me. This is what I tried:

def twoHtmlFutures2 = Action.async { request =>

  val async1 = as1.index(embed = true)(request)
  val async2 = as2.index(embed = true)(request)

  for {
    async1Res <- async1 // from Future[Result] to Result
    async2Res <- async2 // from Future[Result] to Result

    async1Html <- Pagelet.readBody(async1Res) // from Result to Html
    async2Html <- Pagelet.readBody(async2Res) // from Result to Html

  } yield {
    val source1 = single(async1Html) // from Html to Source[Html, NotUsed]
    val source2 = single(async2Html) // from Html to Source[Html, NotUsed]

    val merged = source1.merge(source2) // Source[Html, NotUsed]
    Ok.chunked(merged)
  }

}

But this just jumps on-screen at the same time rather than at different times (streamed) as the first example does. Any helpers out there to widen my eyelids?Thanks


问:
Redirecting System.out to JTextPane
I have a class (shown below) that extends JPanel and contains a JTextPane. I want to redirect System.out and System.err to my JTextPane. My class does not seem to work. When I run it, it does redirect the system prints, but they do not print to my JTextPane. Please help!

Note: The calls are only redirected when the application launches. But any time after launch, the System.out calls are not redirected to the JTextPane. (ie, if I place a System.out.prinln(); in the class, it will be called, but if it is placed in a actionListener for later use, it does not redirect).

```<code>public class OSXConsole extends JPanel {
    public static final long serialVersionUID = 21362469L;

    private JTextPane textPane;
    private PipedOutputStream pipeOut;
    private PipedInputStream pipeIn;

    public OSXConsole() {
        super(new BorderLayout());
        textPane = new JTextPane();
        this.add(textPane, BorderLayout.CENTER);

        redirectSystemStreams();

        textPane.setBackground(Color.GRAY);
        textPane.setBorder(new EmptyBorder(5, 5, 5, 5));

    }

    private void updateTextPane(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Document doc = textPane.getDocument();
                try {
                    doc.insertString(doc.getLength(), text, null);
                } catch (BadLocationException e) {
                    throw new RuntimeException(e);
                }
                textPane.setCaretPosition(doc.getLength() - 1);
            }
        });
    }

    private void redirectSystemStreams() {
      OutputStream out = new OutputStream() {
        @Override
        public void write(final int b) throws IOException {
          updateTextPane(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
          updateTextPane(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
          write(b, 0, b.length);
        }
      };

      System.setOut(new PrintStream(out, true));
      System.setErr(new PrintStream(out, true));
    }

}
</code>```

答:
Piped streams always confuse me, which is why my Message Console solution doesn't use them. Anyway here is my attempt at a console using piped streams. A couple of differences:

a) it uses a JTextArea because a JTextArea is more efficient than a JTextPane for just displaying text. Of course if you intend to add attributes to the text then you need a text pane.

b) this solution uses Threads. I'm sure I read somewhere that this was necessary to prevent blocking of the output. Anyway it works in my simple test case.

```<code>import java.io.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class Console implements Runnable
{
    JTextArea displayPane;
    BufferedReader reader;

    private Console(JTextArea displayPane, PipedOutputStream pos)
    {
        this.displayPane = displayPane;

        try
        {
            PipedInputStream pis = new PipedInputStream( pos );
            reader = new BufferedReader( new InputStreamReader(pis) );
        }
        catch(IOException e) {}
    }

    public void run()
    {
        String line = null;

        try
        {
            while ((line = reader.readLine()) != null)
            {
//              displayPane.replaceSelection( line + "\n" );
                displayPane.append( line + "\n" );
                displayPane.setCaretPosition( displayPane.getDocument().getLength() );
            }

            System.err.println("im here");
        }
        catch (IOException ioe)
        {
            JOptionPane.showMessageDialog(null,
                "Error redirecting output : "+ioe.getMessage());
        }
    }

    public static void redirectOutput(JTextArea displayPane)
    {
        Console.redirectOut(displayPane);
        Console.redirectErr(displayPane);
    }

    public static void redirectOut(JTextArea displayPane)
    {
        PipedOutputStream pos = new PipedOutputStream();
        System.setOut( new PrintStream(pos, true) );

        Console console = new Console(displayPane, pos);
        new Thread(console).start();
    }

    public static void redirectErr(JTextArea displayPane)
    {
        PipedOutputStream pos = new PipedOutputStream();
        System.setErr( new PrintStream(pos, true) );

        Console console = new Console(displayPane, pos);
        new Thread(console).start();
    }

    public static void main(String[] args)
    {
        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane( textArea );

        JFrame frame = new JFrame("Redirect Output");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().add( scrollPane );
        frame.setSize(200, 100);
        frame.setVisible(true);

        Console.redirectOutput( textArea );
        final int i = 0;

        Timer timer = new Timer(1000, new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println( new java.util.Date().toString() );
                System.err.println( System.currentTimeMillis() );
            }
        });
        timer.start();
    }
}
</code>```

Title: Redirecting System.out to JTextPane

Body:
I have a class (shown below) that extends JPanel and contains a JTextPane. I want to redirect System.out and System.err to my JTextPane. My class does not seem to work. When I run it, it does redirect the system prints, but they do not print to my JTextPane. Please help!

Note: The calls are only redirected when the application launches. But any time after launch, the System.out calls are not redirected to the JTextPane. (ie, if I place a System.out.prinln(); in the class, it will be called, but if it is placed in a actionListener for later use, it does not redirect).

public class OSXConsole extends JPanel {
    public static final long serialVersionUID = 21362469L;

    private JTextPane textPane;
    private PipedOutputStream pipeOut;
    private PipedInputStream pipeIn;

    public OSXConsole() {
        super(new BorderLayout());
        textPane = new JTextPane();
        this.add(textPane, BorderLayout.CENTER);

        redirectSystemStreams();

        textPane.setBackground(Color.GRAY);
        textPane.setBorder(new EmptyBorder(5, 5, 5, 5));

    }

    private void updateTextPane(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Document doc = textPane.getDocument();
                try {
                    doc.insertString(doc.getLength(), text, null);
                } catch (BadLocationException e) {
                    throw new RuntimeException(e);
                }
                textPane.setCaretPosition(doc.getLength() - 1);
            }
        });
    }

    private void redirectSystemStreams() {
      OutputStream out = new OutputStream() {
        @Override
        public void write(final int b) throws IOException {
          updateTextPane(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
          updateTextPane(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
          write(b, 0, b.length);
        }
      };

      System.setOut(new PrintStream(out, true));
      System.setErr(new PrintStream(out, true));
    }

}

Body:
Piped streams always confuse me, which is why my Message Console solution doesn't use them. Anyway here is my attempt at a console using piped streams. A couple of differences:

a) it uses a JTextArea because a JTextArea is more efficient than a JTextPane for just displaying text. Of course if you intend to add attributes to the text then you need a text pane.

b) this solution uses Threads. I'm sure I read somewhere that this was necessary to prevent blocking of the output. Anyway it works in my simple test case.

import java.io.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class Console implements Runnable
{
    JTextArea displayPane;
    BufferedReader reader;

    private Console(JTextArea displayPane, PipedOutputStream pos)
    {
        this.displayPane = displayPane;

        try
        {
            PipedInputStream pis = new PipedInputStream( pos );
            reader = new BufferedReader( new InputStreamReader(pis) );
        }
        catch(IOException e) {}
    }

    public void run()
    {
        String line = null;

        try
        {
            while ((line = reader.readLine()) != null)
            {
//              displayPane.replaceSelection( line + "\n" );
                displayPane.append( line + "\n" );
                displayPane.setCaretPosition( displayPane.getDocument().getLength() );
            }

            System.err.println("im here");
        }
        catch (IOException ioe)
        {
            JOptionPane.showMessageDialog(null,
                "Error redirecting output : "+ioe.getMessage());
        }
    }

    public static void redirectOutput(JTextArea displayPane)
    {
        Console.redirectOut(displayPane);
        Console.redirectErr(displayPane);
    }

    public static void redirectOut(JTextArea displayPane)
    {
        PipedOutputStream pos = new PipedOutputStream();
        System.setOut( new PrintStream(pos, true) );

        Console console = new Console(displayPane, pos);
        new Thread(console).start();
    }

    public static void redirectErr(JTextArea displayPane)
    {
        PipedOutputStream pos = new PipedOutputStream();
        System.setErr( new PrintStream(pos, true) );

        Console console = new Console(displayPane, pos);
        new Thread(console).start();
    }

    public static void main(String[] args)
    {
        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane( textArea );

        JFrame frame = new JFrame("Redirect Output");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().add( scrollPane );
        frame.setSize(200, 100);
        frame.setVisible(true);

        Console.redirectOutput( textArea );
        final int i = 0;

        Timer timer = new Timer(1000, new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println( new java.util.Date().toString() );
                System.err.println( System.currentTimeMillis() );
            }
        });
        timer.start();
    }
}


问:
String with emoticon appears to be valid UTF-8 but iconv cannot handle it
I've got the following code that tries to encode a UTF-8 string to UCS-2LE. The string appears to be valid, as can be checked with mb_check_encoding, however when I run iconv on it, I get the following notice:

Notice: iconv(): Detected an illegal character in input string

Any idea what the issue is?

```<code><?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$string = 'Voiture ';
$isValidUTF8 = mb_check_encoding($string, 'UTF-8');
echo 'Is valid UTF-8: ' . ($isValidUTF8 ? 'Yes' : 'No') . "\n";

$text1 = iconv('UTF-8', 'UCS-2LE', $string);
var_dump($text1);
</code>```

Output:

Is valid UTF-8: Yes

Notice: iconv(): Detected an illegal character in input string

bool(false)

答:
The problem is, that  isn't a valid UCS-2LE character. You could try to append \TRANSLIT or \IGNORE to the output encoding.

Using TRANSLIT should replace non existing characters with similar ones and IGNORE removes them from the output string.

You could do this like that, but thats not tested, and I'm not sure, if this works with UCS-2LE

```<code>$text1 = iconv('UTF-8', 'UCS-2LE\\IGNORE', $string);
// or
$text1 = iconv('UTF-8', 'UCS-2LE\\TRANSLIT', $string);
</code>```

If you need emoji support, you should think about stay at the UTF-8 encoding.

Body:
I've got the following code that tries to encode a UTF-8 string to UCS-2LE. The string appears to be valid, as can be checked with mb_check_encoding, however when I run iconv on it, I get the following notice:

Notice: iconv(): Detected an illegal character in input string

Any idea what the issue is?

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$string = 'Voiture ';
$isValidUTF8 = mb_check_encoding($string, 'UTF-8');
echo 'Is valid UTF-8: ' . ($isValidUTF8 ? 'Yes' : 'No') . "\n";

$text1 = iconv('UTF-8', 'UCS-2LE', $string);
var_dump($text1);

Output:

Is valid UTF-8: Yes

Notice: iconv(): Detected an illegal character in input string

bool(false)

Body:
The problem is, that  isn't a valid UCS-2LE character. You could try to append \TRANSLIT or \IGNORE to the output encoding.

Using TRANSLIT should replace non existing characters with similar ones and IGNORE removes them from the output string.

You could do this like that, but thats not tested, and I'm not sure, if this works with UCS-2LE

$text1 = iconv('UTF-8', 'UCS-2LE\\IGNORE', $string);
// or
$text1 = iconv('UTF-8', 'UCS-2LE\\TRANSLIT', $string);

If you need emoji support, you should think about stay at the UTF-8 encoding.


问:
Where does the default datasource url for h2 come from on Spring Boot?
I started a new spring-boot 1.5.3 project. Added some starters:

data-jpa

starter-web

data-rest

And then added

devtools

h2

I can see the datasource is automatically set to jdbc:h2:mem:testdb. Everything is working fine but just out of curiosity I tried to determine from where the jdbc:h2:mem:testdb value comes from. I searched spring-boot, spring-data, spring jdbc and devtools projects' source code but I was unable to find out. As far as I can tell, the value does not come as default suggestion from h2 either.

So where does this value exactly come from?

答:
That would be coming from this class, which also contains the defaults for other flavours of in-mem DBs.

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java

   H2(EmbeddedDatabaseType.H2, "org.h2.Driver", "jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"),

Which get's loaded via, the DataSourceAutoConfiguration if it meets the criteria,

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java

The default for the database name, testdb, comes from a default set in the Datasourceproperties,

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java

  private String name = "testdb";


问:
How can I expand all lists in a row of lists at the same time?
I would like to expand all of the lists in this table at once without having to explicitly name (hard-code) each column. I do want to assume that all columns have a list in the row. I also want to be able to apply the solution to a table with less or more columns than are in the example. The table might decrease or increase its number of columns and the columns' names might change, which is why I don't want to use explicit column names.

I've found a few threads about expanding multiple lists at once, at various forum sites, but they all address more than just doing what I describe above and have all confused me to one degree or another as I've tried to fit them to my need.

@MarcelBeug provides a detailed solution at this site (as do other folks too). I'm using @MarcelBeug's function, and it works great; but I'd like to tailor it to just what I'm seeking, as mentioned above, and I'm having trouble doing that.

So how do I do this?

答:
You want to aggregate the Table.ExpandListColumn function across each column:

```<code>let
    Source = #table({"A", "B"}, {{ {1,2}, {3,4}} }),
    Expanded = List.Accumulate(
        Table.ColumnNames(Source),
        Source,
        (state, column) => Table.ExpandListColumn(state, column))
in
    Expanded
</code>```

Body:
You want to aggregate the Table.ExpandListColumn function across each column:

let
    Source = #table({"A", "B"}, {{ {1,2}, {3,4}} }),
    Expanded = List.Accumulate(
        Table.ColumnNames(Source),
        Source,
        (state, column) => Table.ExpandListColumn(state, column))
in
    Expanded


问:
Django messages formatting
does anyone understand this code and how it would be changed to show "sender wrote : message" on the same line instead of having it split on different lines. As you see in the image below. I really dont understand why they've gone for this formatting.

Code in utils.py

```<code>def format_quote(sender, body):
    """
    Wraps text at 55 chars and prepends each
    line with `> `.
    Used for quoting messages in replies.
    """
    lines = wrap(body, 55).split('\n')
    for i, line in enumerate(lines):
        lines[i] = "> %s" % line
    quote = '\n'.join(lines)
    return ugettext(u"%(sender)s wrote:\n%(body)s") % {
        'sender': sender,
        'body': quote
    }
</code>```

this is the messaging app im using: https://github.com/arneb/django-messages

It just look horrendous as it is and i can figure out how to make it look nicer, any help would be hugely appreciated!

Title: Django messages formatting

Body:
does anyone understand this code and how it would be changed to show "sender wrote : message" on the same line instead of having it split on different lines. As you see in the image below. I really dont understand why they've gone for this formatting.

Code in utils.py

def format_quote(sender, body):
    """
    Wraps text at 55 chars and prepends each
    line with `> `.
    Used for quoting messages in replies.
    """
    lines = wrap(body, 55).split('\n')
    for i, line in enumerate(lines):
        lines[i] = "> %s" % line
    quote = '\n'.join(lines)
    return ugettext(u"%(sender)s wrote:\n%(body)s") % {
        'sender': sender,
        'body': quote
    }

this is the messaging app im using: https://github.com/arneb/django-messages

It just look horrendous as it is and i can figure out how to make it look nicer, any help would be hugely appreciated!

Body:
This piece of code just takes some text, and name of sender:

wraps it (it tries to add some '\n to make rather column of text than line)

makes list of lines

prepend '> ' to every line

makes text from list

prepends 'someone wrote:\n' to this text

some copypaste from python:

>>> message = '1234567890 ' * 7
>>> message
'1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 '
>>> sender = 'john'
>>> sender
'john'
>>> wrap(message, 55)
'1234567890 1234567890 1234567890 1234567890 1234567890\n1234567890 1234567890 '

notice \n

>>> lines = wrap(message, 55).split('\n')
>>> lines
['1234567890 1234567890 1234567890 1234567890 1234567890', '1234567890 1234567890 ']
>>> for i, line in enumerate(lines):
...         lines[i] = "> %s" % line
...
>>> lines
['> 1234567890 1234567890 1234567890 1234567890 1234567890', '> 1234567890 1234567890 ']
>>> quote = '\n'.join(lines)
>>> quote
'> 1234567890 1234567890 1234567890 1234567890 1234567890\n> 1234567890 1234567890 '
>>> ret = u"%(sender)s wrote:\n%(body)s" % {
...         'sender': sender,
...         'body': quote
...         }
>>> print(ret)
john wrote:
> 1234567890 1234567890 1234567890 1234567890 1234567890
> 1234567890 1234567890

I think this code isn't problem itself. Probably function is called bunch of times producing such ugly output.


问:
How to call the original JavaScript function which has been overridden by an extension first?
There's a Firefox extension which modifies the native preventDefault function via

Object.defineProperty(Event.prototype, 'preventDefault', ...
```

before my JavaScript script executed. So, when I call preventDefault function, the modified function would be called instead of the original one. The behavior of the function is changed by the extension.

For me, there's two way to bypass the extension:

Get the native preventDefault function before the extension executed, but my script always executed after the extension even I put my script in head tag.

Implement the preventDefault function by myself, but I don't know how to.

Or this's some alternative ways?

答:
Get the native preventDefault function before the extension executed, but my script always executed after the extension even I put my script in head tag.

This is not possible. The extension has chosen to run prior to your HTML being loaded (i.e. the extension is running at document_start). Extensions get to run code first, if they want to. This is as the browser is designed/intended. If the extension changes the prototype, you will not have direct access to the function which has been overridden.

Implement the preventDefault function by myself, but I don't know how to.

Basically, you can't. The .preventDefault() method is the way that you can affect the browser-internal data structure that represents the event in a way that will cause the browser to not call the default action. Even removing the element from the DOM will not prevent the default action. There's no way for you to affect if the default action will be taken, or not, other than calling .preventDefault().

All you can do is detect that the .preventDefault() method has been overridden and alert the user that your website does not function properly with that extension installed/active. In this case, you could, probably, detect that the .preventDefault() method has been changed by comparing what is returned by Event.prototype.preventDefault.toString() to what you expect it to return when the method has not been overridden.

Body:
There's a Firefox extension which modifies the native preventDefault function via

Object.defineProperty(Event.prototype, 'preventDefault', ...

before my JavaScript script executed. So, when I call preventDefault function, the modified function would be called instead of the original one. The behavior of the function is changed by the extension.

For me, there's two way to bypass the extension:

Get the native preventDefault function before the extension executed, but my script always executed after the extension even I put my script in head tag.

Implement the preventDefault function by myself, but I don't know how to.

Or this's some alternative ways?


问:
How does asm("nop"); works?
I red the definition from http://en.wikipedia.org/wiki/NOP but I still need a simpler definition.

I stumbled across a code and I don't know exactly what it does:

```<code>switch (Something)
    {

        case this_one:
            asm ("nop");
            break;
        case other_one:
            asm ("nop");
            break;
        default:
            asm ("nop");
            break;
    }
</code>```

答:
On Intel x86 atleast, nop is a mnemonic for xchg eax,eax, so it exchanges the eax register with itself.
There's other forms which do the same thing but take more space (for eg. lea esi,[esi + eiz] - adds 0 to esi), but these are not the "official" nop instruction.

Title: How does asm("nop"); works?

Body:
I red the definition from http://en.wikipedia.org/wiki/NOP but I still need a simpler definition.

I stumbled across a code and I don't know exactly what it does:

switch (Something)
    {

        case this_one:
            asm ("nop");
            break;
        case other_one:
            asm ("nop");
            break;
        default:
            asm ("nop");
            break;
    }


问:
Variable name from template argument?
Is there any way to generate the name of a variable inside a class based on a template argument?

```<code>template<class T, (someconstruct) t>

class Item {
    public:
        T t;
};

Item<float, "Position"> myItem;

myItem.Position = 0.123f;
</code>```

Such that what I have instantiated is a variable of type T, with the identifier t (where t is passed in by the programmer, i.e. Position, so we have a T called Position? Or is this stretching the template meta-programming concept a little too far? :p

答:
No, not with that syntax, but you CAN create a setup similar to what you're trying to do:

```<code>template < typename Field >
struct field_value
{
  typename Field::type value;
};

template < typename Seq >
struct funky_struct : boost::mpl::inherit_linearly
  <
    Seq
  , boost::mpl::inherit
    <
      field_value< boost::mpl::placeholders::_2>
    , boost::mpl::placeholders::_1
    >
  >::type
{};

template < typename Field, typename Struct >
typename Field::type & get(Struct & s) { return static_cast< field_value<Field>& >(s).value; }

struct first_field { typedef int type; };
struct second_field { typedef char type; };

struct my_funky : funky_struct< boost::mpl::vector<first_field,second_field> > {};

...
my_funky f;
get<first_field>(f) = 23;
</code>```

I leave allowing non-default construction to you.  Also, with a minor amount of work this can be reflected and you can stick any amount of useful information about fields within.

Title: Variable name from template argument?

Body:
Is there any way to generate the name of a variable inside a class based on a template argument?

template<class T, (someconstruct) t>

class Item {
    public:
        T t;
};

Item<float, "Position"> myItem;

myItem.Position = 0.123f;

Such that what I have instantiated is a variable of type T, with the identifier t (where t is passed in by the programmer, i.e. Position, so we have a T called Position? Or is this stretching the template meta-programming concept a little too far? :p

Body:
No, not with that syntax, but you CAN create a setup similar to what you're trying to do:

template < typename Field >
struct field_value
{
  typename Field::type value;
};

template < typename Seq >
struct funky_struct : boost::mpl::inherit_linearly
  <
    Seq
  , boost::mpl::inherit
    <
      field_value< boost::mpl::placeholders::_2>
    , boost::mpl::placeholders::_1
    >
  >::type
{};

template < typename Field, typename Struct >
typename Field::type & get(Struct & s) { return static_cast< field_value<Field>& >(s).value; }

struct first_field { typedef int type; };
struct second_field { typedef char type; };

struct my_funky : funky_struct< boost::mpl::vector<first_field,second_field> > {};

...
my_funky f;
get<first_field>(f) = 23;

I leave allowing non-default construction to you.  Also, with a minor amount of work this can be reflected and you can stick any amount of useful information about fields within.