问:
Most performant way to filter a huge List in C#?
We have an ASP.NET MVC web application that is hooked up to a SQL Server DB via Entity Framework. One of the main tasks of this application is to allow users to quickly search and filter a huge database table that holds archive values.

The table structure is quite simple: Timestamp (DateTime), StationId (int), DatapointId (int), Value (double). This table holds somewhat between 10 to 100 million rows. I optimized the DB table with a covering index etc., but the user experience was still quite laggy when filtering by DatapointId, StationId, Time and Skipping and Taking only the portion I want to show on the page.

So I tried a different approach: as our server has a lot of RAM, I thought that we could simply load the whole archive table into a List<ArchiveRow> when the web app starts up, then simply get the data directly from this List instead of doing a round-trip to the database. This works quite well, it takes about 9 seconds to load the whole archive table (with currently about 10 million entries) into the List. The ArchiveRow is a simple object that looks like this:

```<code>public class ArchiveResponse {
    public  int Length { get; set; }
    public int numShown { get; set; }
    public  int numFound { get; set; }
    public  int numTotal { get; set; }
    public  List<ArchiveRow> Rows { get; set; }
}
</code>```

and accordingly:

```<code>public class ArchiveRow {
    public  int s { get; set; }
    public  int d { get; set; }
    public  DateTime t { get; set; }
    public  double v { get; set; }
}
</code>```

When I now try to get the desired data from the List with a Linq query, it is already faster the querying the DB, but it is still quite slow when filtering by multiple criteria. For example, when I filter by one StationId and 12 DatapointIds, it takes about 5 seconds to retrieve a window of 25 rows. I already switched from filtering with Where to using joins, but I think there is still room for improvement. Are there maybe better ways to implement such a caching mechanism while keeping memory consumption as low as possible? Are there other collection types that are better suited for this purpose?

So here is the code that filters and fetches the relevant data from the ArchiveCache list:

```<code>// Total number of entries in archive cache
var numTotal = ArchiveCache.Count();

// Initial Linq query
ParallelQuery<ArchiveCacheValue> query = ArchiveCache.AsParallel();

// The request may contain StationIds that the user is interested in,
// so here's the filtering by StationIds with a join:
if (request.StationIds.Count > 0)
{
    query = from a in ArchiveCache.AsParallel()
             join b in request.StationIds.AsParallel()
             on a.StationId equals b
             select a;
}

// The request may contain DatapointIds that the user is interested in,
// so here's the filtering by DatapointIds with a join:
if (request.DatapointIds.Count > 0)
{
    query = from a in query.AsParallel()
             join b in request.DatapointIds.AsParallel()
             on a.DataPointId equals b
             select a;
}

// Number of matching entries after filtering and before windowing
int numFound = query.Count();

// Pagination: Select only the current window that needs to be shown on the page
var result = query.Skip(request.Start == 0 ? 0 : request.Start - 1).Take(request.Length);

// Number of entries on the current page that will be shown
int numShown = result.Count();

// Build a response object, serialize it to Json and return to client
// Note: The projection with the Rows is not a bottleneck, it is only done to
// shorten 'StationId' to 's' etc. At this point there are only 25 to 50 rows,
// so that is no problem and happens in way less than 1 ms
ArchiveResponse myResponse = new ArchiveResponse();
myResponse.Length = request.Length;
myResponse.numShown = numShown;
myResponse.numFound = numFound;
myResponse.numTotal = numTotal;
myResponse.Rows = result.Select(x => new archRow() { s = x.StationId, d = x.DataPointId, t = x.DateValue, v = x.Value }).ToList();

return JsonSerializer.ToJsonString(myResponse);
</code>```

Some more details: the number of stations is usually something between 5 to 50, rarely more than 50. The number of datapoints is <7000. The web application is set to 64 bit with <gcAllowVeryLargeObjects enabled="true" /> set in the web.config.

I'm really looking forward for further improvements and recommendations. Maybe there's a completely different approach based on arrays or similar, that performs way better without linq?

答:
The answer of Evk has some good optimizations, I'd just wanted to point out some very unoptimized things in your original code, maybe removing them would speed it up already:

You do your query in-memory three times!

```<code>// execute query first time
int numFound = query.Count();

var result = query.Skip(request.Start == 0 ? 0 : request.Start - 1).Take(request.Length);

// executing query second time!
int numShown = result.Count();

// executing query third time!
// result.Select [...] .ToList()
</code>```

You should really do it once and then do the counting and pagination on that result.

Body:
We have an ASP.NET MVC web application that is hooked up to a SQL Server DB via Entity Framework. One of the main tasks of this application is to allow users to quickly search and filter a huge database table that holds archive values.

The table structure is quite simple: Timestamp (DateTime), StationId (int), DatapointId (int), Value (double). This table holds somewhat between 10 to 100 million rows. I optimized the DB table with a covering index etc., but the user experience was still quite laggy when filtering by DatapointId, StationId, Time and Skipping and Taking only the portion I want to show on the page.

So I tried a different approach: as our server has a lot of RAM, I thought that we could simply load the whole archive table into a List<ArchiveRow> when the web app starts up, then simply get the data directly from this List instead of doing a round-trip to the database. This works quite well, it takes about 9 seconds to load the whole archive table (with currently about 10 million entries) into the List. The ArchiveRow is a simple object that looks like this:

public class ArchiveResponse {
    public  int Length { get; set; }
    public int numShown { get; set; }
    public  int numFound { get; set; }
    public  int numTotal { get; set; }
    public  List<ArchiveRow> Rows { get; set; }
}

and accordingly:

public class ArchiveRow {
    public  int s { get; set; }
    public  int d { get; set; }
    public  DateTime t { get; set; }
    public  double v { get; set; }
}

When I now try to get the desired data from the List with a Linq query, it is already faster the querying the DB, but it is still quite slow when filtering by multiple criteria. For example, when I filter by one StationId and 12 DatapointIds, it takes about 5 seconds to retrieve a window of 25 rows. I already switched from filtering with Where to using joins, but I think there is still room for improvement. Are there maybe better ways to implement such a caching mechanism while keeping memory consumption as low as possible? Are there other collection types that are better suited for this purpose?

So here is the code that filters and fetches the relevant data from the ArchiveCache list:

// Total number of entries in archive cache
var numTotal = ArchiveCache.Count();

// Initial Linq query
ParallelQuery<ArchiveCacheValue> query = ArchiveCache.AsParallel();

// The request may contain StationIds that the user is interested in,
// so here's the filtering by StationIds with a join:
if (request.StationIds.Count > 0)
{
    query = from a in ArchiveCache.AsParallel()
             join b in request.StationIds.AsParallel()
             on a.StationId equals b
             select a;
}

// The request may contain DatapointIds that the user is interested in,
// so here's the filtering by DatapointIds with a join:
if (request.DatapointIds.Count > 0)
{
    query = from a in query.AsParallel()
             join b in request.DatapointIds.AsParallel()
             on a.DataPointId equals b
             select a;
}

// Number of matching entries after filtering and before windowing
int numFound = query.Count();

// Pagination: Select only the current window that needs to be shown on the page
var result = query.Skip(request.Start == 0 ? 0 : request.Start - 1).Take(request.Length);

// Number of entries on the current page that will be shown
int numShown = result.Count();

// Build a response object, serialize it to Json and return to client
// Note: The projection with the Rows is not a bottleneck, it is only done to
// shorten 'StationId' to 's' etc. At this point there are only 25 to 50 rows,
// so that is no problem and happens in way less than 1 ms
ArchiveResponse myResponse = new ArchiveResponse();
myResponse.Length = request.Length;
myResponse.numShown = numShown;
myResponse.numFound = numFound;
myResponse.numTotal = numTotal;
myResponse.Rows = result.Select(x => new archRow() { s = x.StationId, d = x.DataPointId, t = x.DateValue, v = x.Value }).ToList();

return JsonSerializer.ToJsonString(myResponse);

Some more details: the number of stations is usually something between 5 to 50, rarely more than 50. The number of datapoints is <7000. The web application is set to 64 bit with <gcAllowVeryLargeObjects enabled="true" /> set in the web.config.

I'm really looking forward for further improvements and recommendations. Maybe there's a completely different approach based on arrays or similar, that performs way better without linq?

Body:
The answer of Evk has some good optimizations, I'd just wanted to point out some very unoptimized things in your original code, maybe removing them would speed it up already:

You do your query in-memory three times!

// execute query first time
int numFound = query.Count();

var result = query.Skip(request.Start == 0 ? 0 : request.Start - 1).Take(request.Length);

// executing query second time!
int numShown = result.Count();

// executing query third time!
// result.Select [...] .ToList()

You should really do it once and then do the counting and pagination on that result.


来源: stackexchange

问:
Return a value with highlighted color
Requirement: I have a fragment.xml file which I am extending. The form element is currently being processed with a formatter.js where I am validating some values based on some condition:

In Fragment, the formatter function is getting called correctly

```<code><Text text="{
    parts: [
        {path: 'ZName1'},
        {path: 'ZStatus1'}
    ],
    formatter: '.Formatter.delivery'
}" >
</code>```

Formatter:

```<code>delivery: function(iName, iStatus) {
    var sResult = "";
    if(iStatus === "A" ) {
        sResult = iName ;
    } else if(iStatus === "P") {
        sResult = iName ;
    } else {
        sResult = iName ;
    }
    return sResult ;
}
</code>```

In the output, I should get sResult highlighted either in green, yellow, or red based on the condition.

答:
Instead of plain sap.m.Text, take advantage of sap.m.ObjectStatus which works exactly like Text but supports semantic colors (via state) out-of-the-box.

Run the following snippet to see the results:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/m/List",
  "sap/m/CustomListItem",
  "sap/m/ObjectStatus", // instead of Text
  "sap/ui/core/ValueState",
  "sap/ui/model/json/JSONModel",
], (List, Item, ObjectStatus, ValueState, JSONModel) => new List().bindItems({
  path: "/myData",
  template: new Item().addContent(new ObjectStatus({
    text: "{ZName1}",
    state: {
      path: "ZStatus1",
      formatter: status =>
        status === "A" ? ValueState.Success : // Green
        status === "P" ? ValueState.Warning : // Yellow
        status === "Z" ? ValueState.Error : // Red
        ValueState.None
    },
  }).addStyleClass("sapUiSmallMargin")),
}).setModel(new JSONModel({
  myData: [
    {
      ZName1: "Success",
      ZStatus1: "A"
    },
    {
      ZName1: "Warning",
      ZStatus1: "P"
    },
    {
      ZName1: "Error",
      ZStatus1: "Z"
    },
    {
      ZName1: "None",
      ZStatus1: ""
    },
  ],
})).placeAt("content")));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
  window["sap-ui-config"] = {
    libs: "sap.ui.core, sap.m",
    preload: "async",
    theme: "sap_belize",
    compatVersion: "edge",
    "xx-waitForTheme": true,
    "xx-async": true
  }
</script>
<script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body></code>```

We can see green, yellow, and red depending on the condition.

ContentLicense: CC BY-SA 3.0

Title: Return a value with highlighted color

Body:
Requirement: I have a fragment.xml file which I am extending. The form element is currently being processed with a formatter.js where I am validating some values based on some condition:

In Fragment, the formatter function is getting called correctly

<Text text="{
    parts: [
        {path: 'ZName1'},
        {path: 'ZStatus1'}
    ],
    formatter: '.Formatter.delivery'
}" >

Formatter:

delivery: function(iName, iStatus) {
    var sResult = "";
    if(iStatus === "A" ) {
        sResult = iName ;
    } else if(iStatus === "P") {
        sResult = iName ;
    } else {
        sResult = iName ;
    }
    return sResult ;
}

In the output, I should get sResult highlighted either in green, yellow, or red based on the condition.

Body:
Instead of plain sap.m.Text, take advantage of sap.m.ObjectStatus which works exactly like Text but supports semantic colors (via state) out-of-the-box.

Run the following snippet to see the results:

sap.ui.getCore().attachInit(() => sap.ui.require([
  "sap/m/List",
  "sap/m/CustomListItem",
  "sap/m/ObjectStatus", // instead of Text
  "sap/ui/core/ValueState",
  "sap/ui/model/json/JSONModel",
], (List, Item, ObjectStatus, ValueState, JSONModel) => new List().bindItems({
  path: "/myData",
  template: new Item().addContent(new ObjectStatus({
    text: "{ZName1}",
    state: {
      path: "ZStatus1",
      formatter: status =>
        status === "A" ? ValueState.Success : // Green
        status === "P" ? ValueState.Warning : // Yellow
        status === "Z" ? ValueState.Error : // Red
        ValueState.None
    },
  }).addStyleClass("sapUiSmallMargin")),
}).setModel(new JSONModel({
  myData: [
    {
      ZName1: "Success",
      ZStatus1: "A"
    },
    {
      ZName1: "Warning",
      ZStatus1: "P"
    },
    {
      ZName1: "Error",
      ZStatus1: "Z"
    },
    {
      ZName1: "None",
      ZStatus1: ""
    },
  ],
})).placeAt("content")));

<script>
  window["sap-ui-config"] = {
    libs: "sap.ui.core, sap.m",
    preload: "async",
    theme: "sap_belize",
    compatVersion: "edge",
    "xx-waitForTheme": true,
    "xx-async": true
  }
</script>
<script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>

We can see green, yellow, and red depending on the condition.

ContentLicense: CC BY-SA 4.0


问:
Decompile a C file to Pro*C
I'm currently working in Auditing a software we are supposed to start working on February. As part of the source code, we've recevied what seems to be a C file generated from a Pro*C file.

Pro*C files are compiled using the application "proc" into a C file, then you would use gcc to compile it into an actual executable file.

We are having some troubles with the previous owner of the application, and they refuse to provide us so far with the Pro*C file (pc extension).

I'm not sure if it's possible to revert it back from the C file to the Pro*C, using "proc" or any other tools.

Has anyone been able to do so, and if so, how?

Thanks in advance.

答:
There is no decompiler for C to *Proc  file. A C file containing SQL statement in it is call an embedded  *Proc  file, an utility provided by Oracle. Once you translate this embedded file to  C by using a proc translator provided by Oracle it turn that *Proc file into a C file which modify these SQL statement with oracle provided library APIs.

Now my advice to you is, find out all the methods/functions in that C file (generated from a *Proc file) and check and understand what they are doing in Oracle database, especially all the database transactions. Once you understood that, just try to create your own C or C++ file by using ODBC driver api provided by Oracle.

Title: Decompile a C file to Pro*C


问:
How do I read a file into a matrix in bash?
I have a text file like this

```<code>A;green;3
B;blue;2
A;red;4
C;red;2
C;blue;3
B;green;3
</code>```

I have to write a script that if started with parameter "B" gives me the color of the row with the biggest number (from the rows starting with B). In this case it would be the last line, so the output would be "green".

How do I separate the elements by ";"-s and newlines and store them into a matrix so I can work with it? Do I even need to do that, or is there an easier solution?

Thanks in advance!

答:
A non-awk solution, possibly less elegant and slower than the already proposed solution:

```<code>sort -r -t\; -k1,1 -k3 file | uniq -w1 | grep "B" | cut -f2 -d\;
</code>```

Body:
I have a text file like this

A;green;3
B;blue;2
A;red;4
C;red;2
C;blue;3
B;green;3

I have to write a script that if started with parameter "B" gives me the color of the row with the biggest number (from the rows starting with B). In this case it would be the last line, so the output would be "green".

How do I separate the elements by ";"-s and newlines and store them into a matrix so I can work with it? Do I even need to do that, or is there an easier solution?

Thanks in advance!

Body:
A non-awk solution, possibly less elegant and slower than the already proposed solution:

sort -r -t\; -k1,1 -k3 file | uniq -w1 | grep "B" | cut -f2 -d\;


问:
Sigsegv in malloc
I want to save a struct containing a pointer that I use as a dynamic array but when I load the struct and malloc this pointer, it fails.

I have three structs (Orientation, ShipType, Status and PlayerType are enumerations, you can replace them by Int) :

```<code>struct Map
{
    int width, height;
    int* cases;
};
typedef struct Map Map;

struct Ship
{
    int x, y, length, firstShoot, color;
    int hasBeenDiscovered;
    Orientation orientation;
    ShipType type;
    Status status;
};
typedef struct Ship Ship;

struct Player
{
    int activeShips;
    Map map[2];
    char lastMoves[5][128];
    Ship ships[10];
    PlayerType type;
    int shipcolor[4];
    int color;
};
typedef struct Player Player;
</code>```

I declare an array of 2 Player like this : Player players[2]; and initialize their properties. Then I want to save the struct in a file in order to load it afterwards.
Also, I use the Map struct as a 2d dynamic array using four functions :

```<code>void mallocMap(Map* map, int width, int height)
{
    map->cases = malloc(sizeof(int) * width * height);

    map->width = width;
    map->height = height;

    if (map->cases == NULL)
    {
        printf("Erreur d'allocation de memoire\n");
        exit(0);
    }
}

void freeMap(Map* map)
{
    free(map->cases);
}

int getMapValue(Map map, int x, int y)
{
    return *(map.cases + y*map.width + x);
}

void setMapValue(Map* map, int value, int x, int y)
{
    *(map->cases + y*map->width + x) = value;
}
</code>```

So when I store the struct, map.cases is only a pointer and I need to store the values at its address separately like so :

```<code>int save(Player players[2])
{
    int* i;
    FILE* file = NULL;

    file = fopen("save.txt","w+");

    if (file != NULL)
    {
        fwrite(players, sizeof(Player), 2, file);

        fwrite(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
        fwrite(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
        fwrite(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
        fwrite(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);
    }
    else
    {
        // error
    }

    fclose(file);

    return 1;
}
</code>```

Each player has 2 maps so there are 4 maps to store at the end.
The problem is in my load() function :

```<code>int load(Player players[2])
{
    FILE* file = NULL;

    file = fopen("save.txt","r");

    if (file != NULL)
    {
        int *i;

        fread(players, sizeof(Player), 2, file);

        mallocMap(&players[0].map[0], players[0].map[0].width, players[0].map[0].height);
        mallocMap(&players[0].map[1], players[0].map[1].width, players[0].map[1].height);
        mallocMap(&players[1].map[0], players[1].map[0].width, players[1].map[0].height);
        mallocMap(&players[1].map[1], players[1].map[1].width, players[1].map[1].height);

        fread(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
        fread(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
        fread(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
        fread(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);

    }
    else
    {
        // error
    }

    fclose(file);

    return 1;
}
</code>```

When I call mapAlloc(), it fails to allocate the memory and exit(0); my program stops.

答:
The way you've declared your load function doesn't look right:

```<code>int load(Player* players[2])
</code>```

This takes an array of pointers to Player, while your save routine takes an array of Player (i.e. Player players[2]).  You probably need to change it to:

```<code>int load(Player players[2])
</code>```

You're also reading the values back in to the wrong address:

```<code>    for(i = players[0]->map[0].cases; i < players[0]->map[0].cases + players[0]->map[0].width * players[0]->map[0].height; i++)
        fread(&i, sizeof(int), 1, file);
</code>```

You're passing to fread the address of i.  That means you're reading in an int and storing it in i, which is a local int * and not the dynamically allocated array you want to write to.

Remove the address-of operator here and pass in i directly, just like you do when you use fwrite

```<code>        fread(i, sizeof(int), 1, file);
</code>```

This will write the int that you read in into your array.

Also, there is no need to use loops to read / write individual ints here.  Just do a single read / write passing in the number of values to read/write.

So saving would be:

```<code>fwrite(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
fwrite(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
fwrite(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
fwrite(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);
</code>```

And loading would be:

```<code>fread(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
fread(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
fread(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
fread(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);
</code>```

When compiling your code, there shouldn't be any warnings.  If there are any, you're probably doing something wrong that you need to fix.

Title: Sigsegv in malloc

Body:
I want to save a struct containing a pointer that I use as a dynamic array but when I load the struct and malloc this pointer, it fails.

I have three structs (Orientation, ShipType, Status and PlayerType are enumerations, you can replace them by Int) :

struct Map
{
    int width, height;
    int* cases;
};
typedef struct Map Map;

struct Ship
{
    int x, y, length, firstShoot, color;
    int hasBeenDiscovered;
    Orientation orientation;
    ShipType type;
    Status status;
};
typedef struct Ship Ship;

struct Player
{
    int activeShips;
    Map map[2];
    char lastMoves[5][128];
    Ship ships[10];
    PlayerType type;
    int shipcolor[4];
    int color;
};
typedef struct Player Player;

I declare an array of 2 Player like this : Player players[2]; and initialize their properties. Then I want to save the struct in a file in order to load it afterwards.
Also, I use the Map struct as a 2d dynamic array using four functions :

void mallocMap(Map* map, int width, int height)
{
    map->cases = malloc(sizeof(int) * width * height);

    map->width = width;
    map->height = height;

    if (map->cases == NULL)
    {
        printf("Erreur d'allocation de memoire\n");
        exit(0);
    }
}

void freeMap(Map* map)
{
    free(map->cases);
}

int getMapValue(Map map, int x, int y)
{
    return *(map.cases + y*map.width + x);
}

void setMapValue(Map* map, int value, int x, int y)
{
    *(map->cases + y*map->width + x) = value;
}

So when I store the struct, map.cases is only a pointer and I need to store the values at its address separately like so :

int save(Player players[2])
{
    int* i;
    FILE* file = NULL;

    file = fopen("save.txt","w+");

    if (file != NULL)
    {
        fwrite(players, sizeof(Player), 2, file);

        fwrite(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
        fwrite(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
        fwrite(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
        fwrite(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);
    }
    else
    {
        // error
    }

    fclose(file);

    return 1;
}

Each player has 2 maps so there are 4 maps to store at the end.
The problem is in my load() function :

int load(Player players[2])
{
    FILE* file = NULL;

    file = fopen("save.txt","r");

    if (file != NULL)
    {
        int *i;

        fread(players, sizeof(Player), 2, file);

        mallocMap(&players[0].map[0], players[0].map[0].width, players[0].map[0].height);
        mallocMap(&players[0].map[1], players[0].map[1].width, players[0].map[1].height);
        mallocMap(&players[1].map[0], players[1].map[0].width, players[1].map[0].height);
        mallocMap(&players[1].map[1], players[1].map[1].width, players[1].map[1].height);

        fread(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
        fread(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
        fread(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
        fread(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);

    }
    else
    {
        // error
    }

    fclose(file);

    return 1;
}

When I call mapAlloc(), it fails to allocate the memory and exit(0); my program stops.

Body:
The way you've declared your load function doesn't look right:

int load(Player* players[2])

This takes an array of pointers to Player, while your save routine takes an array of Player (i.e. Player players[2]).  You probably need to change it to:

int load(Player players[2])

You're also reading the values back in to the wrong address:

    for(i = players[0]->map[0].cases; i < players[0]->map[0].cases + players[0]->map[0].width * players[0]->map[0].height; i++)
        fread(&i, sizeof(int), 1, file);

You're passing to fread the address of i.  That means you're reading in an int and storing it in i, which is a local int * and not the dynamically allocated array you want to write to.

Remove the address-of operator here and pass in i directly, just like you do when you use fwrite

        fread(i, sizeof(int), 1, file);

This will write the int that you read in into your array.

Also, there is no need to use loops to read / write individual ints here.  Just do a single read / write passing in the number of values to read/write.

So saving would be:

fwrite(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
fwrite(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
fwrite(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
fwrite(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);

And loading would be:

fread(players[0].map[0].cases, sizeof(int), players[0].map[0].width * players[0].map[0].height, file);
fread(players[0].map[1].cases, sizeof(int), players[0].map[1].width * players[0].map[1].height, file);
fread(players[1].map[0].cases, sizeof(int), players[1].map[0].width * players[1].map[0].height, file);
fread(players[1].map[1].cases, sizeof(int), players[1].map[1].width * players[1].map[1].height, file);

When compiling your code, there shouldn't be any warnings.  If there are any, you're probably doing something wrong that you need to fix.


问:
Wait for page redirect Selenium WebDriver (Python)
I have a page which loads dynamic content with ajax and then redirects after a certain amount of time (not fixed). How can I force Selenium Webdriver to wait for the page to redirect then go to a different link immediately after?</p>

```<code>import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome();
driver.get("http://www.website.com/wait.php")
</code>```

答:
There are several ExpectedConditions that can be used along with ExplicitWait to handle page redirection:

```<code>from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
</code>```

Wait for new page title with title_is(title_name):

```<code>wait.until(EC.title_is('New page Title'))
</code>```

Wait for current URL to be changed to any other URL with url_changes(exact_url):

```<code>wait.until(EC.url_changes('https://current_page.com'))
</code>```

Wait for navigating to exact URL with url_to_be(exact_url):

```<code>wait.until(EC.url_to_be('https://new_page.com'))
</code>```

Also

url_contains(partial_url) could be used to wait for URL that contains specified substring or url_matches(pattern) - to wait for URL matched by passed regex pattern or title_contains(substring) - to wait for new title that contains specified substring

Body:
I have a page which loads dynamic content with ajax and then redirects after a certain amount of time (not fixed). How can I force Selenium Webdriver to wait for the page to redirect then go to a different link immediately after?

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome();
driver.get("http://www.website.com/wait.php")

Body:
There are several ExpectedConditions that can be used along with ExplicitWait to handle page redirection:

from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

Wait for new page title with title_is(title_name):

wait.until(EC.title_is('New page Title'))

Wait for current URL to be changed to any other URL with url_changes(exact_url):

wait.until(EC.url_changes('https://current_page.com'))

Wait for navigating to exact URL with url_to_be(exact_url):

wait.until(EC.url_to_be('https://new_page.com'))

Also

url_contains(partial_url) could be used to wait for URL that contains specified substring or url_matches(pattern) - to wait for URL matched by passed regex pattern or title_contains(substring) - to wait for new title that contains specified substring


问:
OkHttp networkInterceptors does not catch client connect timeouts?
I've been testing the out Application vs Network Interceptors for OkHttp clients. I created an simple interceptor that simply logs latency and errors if errors occur.

I found that if I purposely set:

```<code>client.setConnectTimeout(0, TimeUnit.MILLISECONDS);
</code>```

Only Application Interceptors will intercept and chain the request. If I add the interceptor as a Network Interceptor, my intercept() method is never hit on the connect timeout.

Why is this the case?

The distinction made on the doc here https://github.com/square/okhttp/wiki/Interceptors is not super obvious to me.

I'm adding the interceptor by calling:

```<code>client.interceptors().addAll(interceptors);
</code>```

or:

```<code>client.networkInterceptors().addAll(interceptors);
</code>```

答:
A timeout of 0 means no timeout at all: the call will be allowed to run indefinitely.

Note that interceptors typically return before the response body has been streamed. If your timeout occurs while reading the response body a network interceptor won't observe it.

Finally the connection is established after all application interceptors but before any network interceptors. If the timeout occurs on connect the network interceptors won't be executed.

Body:
I've been testing the out Application vs Network Interceptors for OkHttp clients. I created an simple interceptor that simply logs latency and errors if errors occur.

I found that if I purposely set:

client.setConnectTimeout(0, TimeUnit.MILLISECONDS);

Only Application Interceptors will intercept and chain the request. If I add the interceptor as a Network Interceptor, my intercept() method is never hit on the connect timeout.

Why is this the case?

The distinction made on the doc here https://github.com/square/okhttp/wiki/Interceptors is not super obvious to me.

I'm adding the interceptor by calling:

client.interceptors().addAll(interceptors);

or:

client.networkInterceptors().addAll(interceptors);


问:
Catching input events
I have a form with TextBox, ComboBox and CheckBox that are filled from a function (with textbox.text = "newValue"; for example).

```<code>private void updateIdentite(Contact c, Dal dal)
{
    Identite id = dal.GetIdentite(c);
    if (id != null)
    {
        idCivilite.SelectedValue = id.type_civilite;//example of a ComboBox
        ...
        idNom.Text = id.pers_nom;//example of a TextBox
        ...
        idAi.IsChecked = (id.cont_drap_ai == "1");//example of a CheckBox
        ...
    }
}
</code>```

I need to catch an event when an item is edited manually by the user, but with TextChanged, SelectionChanged or Checked, these events are also fired when the form is filled with the previous function.

```<code>foreach (object item in identiteGrid.Children)
{
    TextBox tb = item as TextBox;
    if (tb != null)
    {
        tb.TextChanged += new TextChangedEventHandler(idTextBox_TextChanged);
        continue;
    }
    ComboBox droplist = item as ComboBox;
    if (droplist != null)
    {
        droplist.SelectionChanged += new SelectionChangedEventHandler(idCombobox_SelectionChanged);
        continue;
    }
    CheckBox cb = item as CheckBox;
    if (cb != null)
    {
        cb.Checked += new RoutedEventHandler(idCheckbox_Checked);
        continue;
    }
}
</code>```

Is there any way to catch an "onInput" event for those controls ?

Thanks

答:
You could either hook up your event handlers, i.e. execute the foreach loop, after you have set initial values.

Or you could temporarily unhook the event handlers just before you programmatically set the values:

```<code>private void updateIdentite(Contact c, Dal dal)
{
    Identite id = dal.GetIdentite(c);
    if (id != null)
    {
        idCivilite.SelectionChanged -= idCombobox_SelectionChanged;
        idCivilite.SelectedValue = id.type_civilite;//example of a ComboBox
        idCivilite.SelectionChanged += idCombobox_SelectionChanged;

        tb.TextChanged -= idTextBox_TextChanged;
        idNom.Text = id.pers_nom;//example of a TextBox
        tb.TextChanged += idTextBox_TextChanged;

        idAi.Checked -= idCheckbox_Checked;
        idAi.IsChecked = (id.cont_drap_ai == "1");//example of a CheckBox
        idAi.Checked += idCheckbox_Checked;
    }
}
</code>```

Or you could use a boolean flag to prevent the code inside the event handler from being run in specific cases:

```<code>private bool handleSelectionChanged = true;
private void updateIdentite(Contact c, Dal dal)
{
    ...
    handleSelectionChanged = false;
    idCivilite.SelectedValue = id.type_civilite;//example of a ComboBox
    handleSelectionChanged = true;
    ...
}

private void idCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (!handleSelectionChanged)
        return;

    //your code...
}
</code>```

Title: Catching input events

Body:
I have a form with TextBox, ComboBox and CheckBox that are filled from a function (with textbox.text = "newValue"; for example).

private void updateIdentite(Contact c, Dal dal)
{
    Identite id = dal.GetIdentite(c);
    if (id != null)
    {
        idCivilite.SelectedValue = id.type_civilite;//example of a ComboBox
        ...
        idNom.Text = id.pers_nom;//example of a TextBox
        ...
        idAi.IsChecked = (id.cont_drap_ai == "1");//example of a CheckBox
        ...
    }
}

I need to catch an event when an item is edited manually by the user, but with TextChanged, SelectionChanged or Checked, these events are also fired when the form is filled with the previous function.

foreach (object item in identiteGrid.Children)
{
    TextBox tb = item as TextBox;
    if (tb != null)
    {
        tb.TextChanged += new TextChangedEventHandler(idTextBox_TextChanged);
        continue;
    }
    ComboBox droplist = item as ComboBox;
    if (droplist != null)
    {
        droplist.SelectionChanged += new SelectionChangedEventHandler(idCombobox_SelectionChanged);
        continue;
    }
    CheckBox cb = item as CheckBox;
    if (cb != null)
    {
        cb.Checked += new RoutedEventHandler(idCheckbox_Checked);
        continue;
    }
}

Is there any way to catch an "onInput" event for those controls ?

Thanks

Body:
You could either hook up your event handlers, i.e. execute the foreach loop, after you have set initial values.

Or you could temporarily unhook the event handlers just before you programmatically set the values:

private void updateIdentite(Contact c, Dal dal)
{
    Identite id = dal.GetIdentite(c);
    if (id != null)
    {
        idCivilite.SelectionChanged -= idCombobox_SelectionChanged;
        idCivilite.SelectedValue = id.type_civilite;//example of a ComboBox
        idCivilite.SelectionChanged += idCombobox_SelectionChanged;

        tb.TextChanged -= idTextBox_TextChanged;
        idNom.Text = id.pers_nom;//example of a TextBox
        tb.TextChanged += idTextBox_TextChanged;

        idAi.Checked -= idCheckbox_Checked;
        idAi.IsChecked = (id.cont_drap_ai == "1");//example of a CheckBox
        idAi.Checked += idCheckbox_Checked;
    }
}

Or you could use a boolean flag to prevent the code inside the event handler from being run in specific cases:

private bool handleSelectionChanged = true;
private void updateIdentite(Contact c, Dal dal)
{
    ...
    handleSelectionChanged = false;
    idCivilite.SelectedValue = id.type_civilite;//example of a ComboBox
    handleSelectionChanged = true;
    ...
}

private void idCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (!handleSelectionChanged)
        return;

    //your code...
}


问:
How do I run a modulo conditional using one list on another list in python
I've only been using python for about 2 weeks and need some help. I am trying to use the mod (%) function between two lists of varying sizes.

```<code>n = 23 #user input, starting point for the code
listp = [2, 3, 5, 7, 11, 13]
listr = list(range((n-1)**2, n**2+1, 2))
listb = list(listr)  #I need to remove items from listr but if i do, it
                     #crashes so I decided to copy it to listb in order to manipulate it

for k in listr:
    for i in listp[1:]:
        if k%i == 0:
            if k in listb:
                listb.remove(k)
</code>```

This works but it's slow, I'd like to manipulate listr directly and I can individually:

```<code>listr = [k for k in listr if i%listp[1] !=0]
listr = [k for k in listr if i%listp[2] !=0]
</code>```

Bottom line is that I'd like to use the % function on each k element in listr using every i element in listp and only keep those elements in listr that are !=0; I've tried using numpy and an array but that's not helping either

答:
For faster operations you can try using pandas, it uses numpy under the hood and "pushes the work down to C level". Look at arange

Then create a function to do the work you want and apply it to all entries of your panda data structure and capture it: something like

final _list = pandas_struct.apply(function)

Some sample you could play with follow:
How fast is acceptable?

```<code>import numpy as np
import pandas as pd

n=23
first = np.array([2, 3, 5, 7, 11, 13])
second = np.arange((n-1)**2, n**2+1, 2)
pand_second=pd.Series(second)

def modme(num,div):
    if num % div  == 0:
        return num,'mod ok by',div

[9]: pand_second.apply(modme, args=(3,))
Out[9]:
0                    None
1     (486, mod ok by, 3)
2                    None
3                    None
4     (492, mod ok by, 3)
5                    None
6                    None
7     (498, mod ok by, 3)
8                    None
9                    None
10    (504, mod ok by, 3)
11                   None
12                   None
13    (510, mod ok by, 3)
14                   None
15                   None
16    (516, mod ok by, 3)
17                   None
18                   None
19    (522, mod ok by, 3)
20                   None
21                   None
22    (528, mod ok by, 3)
dtype: object

%timeit pand_second.apply(modme, args=(3,))
81.3 µs ± 201 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Or not use pandas at all :):

```<code>import numpy as np

n=23
first = np.array([2, 3, 5, 7, 11, 13])
second = np.arange((n-1)**2, n**2+1, 2)

In [11]: [ second[ second % x == 0 ] for x in first ]
Out[11]:
[array([484, 486, 488, 490, 492, 494, 496, 498, 500, 502, 504, 506, 508,
        510, 512, 514, 516, 518, 520, 522, 524, 526, 528]),
 array([486, 492, 498, 504, 510, 516, 522, 528]),
 array([490, 500, 510, 520]),
 array([490, 504, 518]),
 array([484, 506, 528]),
 array([494, 520])]

%timeit [ second[ second % x == 0 ] for x in first ]
15.6 µs ± 25.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Body:
I've only been using python for about 2 weeks and need some help. I am trying to use the mod (%) function between two lists of varying sizes.

n = 23 #user input, starting point for the code
listp = [2, 3, 5, 7, 11, 13]
listr = list(range((n-1)**2, n**2+1, 2))
listb = list(listr)  #I need to remove items from listr but if i do, it
                     #crashes so I decided to copy it to listb in order to manipulate it

for k in listr:
    for i in listp[1:]:
        if k%i == 0:
            if k in listb:
                listb.remove(k)

This works but it's slow, I'd like to manipulate listr directly and I can individually:

listr = [k for k in listr if i%listp[1] !=0]
listr = [k for k in listr if i%listp[2] !=0]

Bottom line is that I'd like to use the % function on each k element in listr using every i element in listp and only keep those elements in listr that are !=0; I've tried using numpy and an array but that's not helping either

Body:
For faster operations you can try using pandas, it uses numpy under the hood and "pushes the work down to C level". Look at arange

Then create a function to do the work you want and apply it to all entries of your panda data structure and capture it: something like

final _list = pandas_struct.apply(function)

Some sample you could play with follow:
How fast is acceptable?

import numpy as np
import pandas as pd

n=23
first = np.array([2, 3, 5, 7, 11, 13])
second = np.arange((n-1)**2, n**2+1, 2)
pand_second=pd.Series(second)

def modme(num,div):
    if num % div  == 0:
        return num,'mod ok by',div

[9]: pand_second.apply(modme, args=(3,))
Out[9]:
0                    None
1     (486, mod ok by, 3)
2                    None
3                    None
4     (492, mod ok by, 3)
5                    None
6                    None
7     (498, mod ok by, 3)
8                    None
9                    None
10    (504, mod ok by, 3)
11                   None
12                   None
13    (510, mod ok by, 3)
14                   None
15                   None
16    (516, mod ok by, 3)
17                   None
18                   None
19    (522, mod ok by, 3)
20                   None
21                   None
22    (528, mod ok by, 3)
dtype: object

%timeit pand_second.apply(modme, args=(3,))
81.3 µs ± 201 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Or not use pandas at all :):

import numpy as np

n=23
first = np.array([2, 3, 5, 7, 11, 13])
second = np.arange((n-1)**2, n**2+1, 2)

In [11]: [ second[ second % x == 0 ] for x in first ]
Out[11]:
[array([484, 486, 488, 490, 492, 494, 496, 498, 500, 502, 504, 506, 508,
        510, 512, 514, 516, 518, 520, 522, 524, 526, 528]),
 array([486, 492, 498, 504, 510, 516, 522, 528]),
 array([490, 500, 510, 520]),
 array([490, 504, 518]),
 array([484, 506, 528]),
 array([494, 520])]

%timeit [ second[ second % x == 0 ] for x in first ]
15.6 µs ± 25.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


问:
ASP.NET MVC 4 - razor empty post in for loop
I have the following code in razor:

```<code>  @for (int i = 0; i < Model.Count; i++)
  {
      using (Html.BeginForm("Bonnen", "Bon"))
      {
          <tr>
              <td> @Html.TextBoxFor(model => Model[i].Id)</td>
              <td>@Html.DisplayFor(model => Model[i].Date)</td>
              <td>@Html.DisplayFor(model => Model[i].Description)</td>
              <td><button type="submit" value="Details" class="btn btn-info">Details</button></td>
          </tr>
      }
  }
</code>```

When i post the data to the controller it becomes empty.
I've already seen a question where it said you can't use a foreach loop here.
On the website itself it does show all the data, but it won't give it to the controller.

Controller:

```<code>  [HttpPost]
  public ActionResult Bonnen(Bon bon)
  {
   return RedirectToAction("Details", "Bon", bon);
  }
</code>```

Model:

```<code>  public int Id { get; set; }
  public string Description { get; set; }
  public DateTime Date { get; set; }
</code>```

答:
Try the following code

```<code>@for (int i = 0; i < Model.Count; i++)
{
  using (Html.BeginForm("Bonnen", "Bon"))
  {
      <tr>
          <td> @Html.TextBox("Id", Model[i].Id)</td>
          <td>@Html.Display("Date", Model[i].Date)</td>
          <td>@Html.Display("Description", Model[i].Description)</td>
          <td><button type="submit" value="Details" class="btn btn-info">Details</button></td>
      </tr>
  }
}
</code>```

If you want the values of Date and Description too in controller then change them from Display to Editor.

Body:
I have the following code in razor:

  @for (int i = 0; i < Model.Count; i++)
  {
      using (Html.BeginForm("Bonnen", "Bon"))
      {

               @Html.TextBoxFor(model => Model[i].Id)
              @Html.DisplayFor(model => Model[i].Date)
              @Html.DisplayFor(model => Model[i].Description)
              <button type="submit" value="Details" class="btn btn-info">Details</button>

      }
  }

When i post the data to the controller it becomes empty.
I've already seen a question where it said you can't use a foreach loop here.
On the website itself it does show all the data, but it won't give it to the controller.

Controller:

  [HttpPost]
  public ActionResult Bonnen(Bon bon)
  {
   return RedirectToAction("Details", "Bon", bon);
  }

Model:

  public int Id { get; set; }
  public string Description { get; set; }
  public DateTime Date { get; set; }

Body:
Try the following code

@for (int i = 0; i < Model.Count; i++)
{
  using (Html.BeginForm("Bonnen", "Bon"))
  {
      <tr>
          <td> @Html.TextBox("Id", Model[i].Id)</td>
          <td>@Html.Display("Date", Model[i].Date)</td>
          <td>@Html.Display("Description", Model[i].Description)</td>
          <td><button type="submit" value="Details" class="btn btn-info">Details</button></td>
      </tr>
  }
}

If you want the values of Date and Description too in controller then change them from Display to Editor.


问:
Parent / Child component communication angular 2
I am failing to implement action button in child_1 component but the event handler is in sub child component child_2 as shown in the following code:

app.component.html (Parent Html)

```<code><div style="text-align:center">
  <h1>
    Welcome to {{title}}!
  </h1>
  <app-navigation></app-navigation> <!-- Child1-->
</div>
</code>```

app.component.html (Parent Component)

```<code>import { Component } from '@angular/core';
import { ProductService } from './productservice';
import {Product} from './product';

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      title = 'MobileShirtShoeApp';
    }
</code>```

app.module.ts (Main Module)

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Product } from './product';
import { ProductService } from './productservice';
import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { DataTemplateComponent } from './data-template/data-template.component';

@NgModule({
  declarations: [AppComponent,NavigationComponent,DataTemplateComponent],
  imports: [BrowserModule,HttpModule],
  providers: [ProductService],
  bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

navigation.component.html (Child 1 HTML)

```<code><fieldset>
  <legend>Navigate</legend>
  <div>
     <button  (click)="loadMobiles()">Mobiles</button> <!--Child_1 Action-->
  </div>
  <app-data-template></app-data-template>
</fieldset>
</code>```

navigation.component.ts (Child 1 Component.ts)

```<code>import { Component, OnInit } from '@angular/core';
import { ProductService } from '../productservice';
import {Product} from '../product';
import {DataTemplateComponent} from '../data-template/data-template.component';

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {
  error: string;
  productArray: Product[];

  constructor(private myService: ProductService){
    this.myService = myService;
  }

  dataTemplateComponent: DataTemplateComponent = new DataTemplateComponent(this.myService);

  ngOnInit() {
  }

  loadMobiles() {
   return this.dataTemplateComponent.loadMobiles();
  }
}
</code>```

data-template.component.html (Child 2 HTML) (NOT DISPLAYING DATA)

```<code><fieldset>
    <legend>Requested Data</legend>
    Welcome
    <div>
      <ul>
            <li *ngFor="let product of productArray">
                {{product.id}} {{product.name}} {{product.price}}
                <img src="{{product.url}}">
            </li>
        </ul>
    </div>
</fieldset>
</code>```

data-template.component.ts (Child 2 Component) (Contains Product service calling code)

```<code>import { Component} from '@angular/core';
import {Product} from '../product';
import {ProductService} from '../productservice';

@Component({
  selector: 'app-data-template',
  templateUrl: './data-template.component.html',
  styleUrls: ['./data-template.component.css']
})

export class DataTemplateComponent  {
  error: string;
  productArray: Product[];
  constructor(private productService: ProductService) {
    this.productService = productService;
  }

  loadMobiles(){
    let promise  = this.productService.fetchMobiles();
    promise.then(productArr => {
        return this.productArray = productArr;
      }).catch((err) => {
       this.error = err;
      });
  }
}
</code>```

ProductService.ts

```<code>import 'rxjs/add/operator/toPromise';
import {Http, HttpModule} from '@angular/http';
import {Injectable} from '@angular/core';
import {Product} from './product';

@Injectable()
export class ProductService{
  http: Http;
  constructor(http: Http){
  this.http = http;
  console.log(http);
 }

fetchMobiles(): Promise<Product[]>{
  let url = "https://raw.githubusercontent.com/xxxxx/Other/master/JsonData/MobileData.json";
  return this.http.get(url).toPromise().then((response) => {
        return response.json().mobiles as Product[];
    }).catch(this.handleError);
}

private handleError(error: any): Promise<any> {
  console.error('An error occurred', error);
  return Promise.reject(error.message || error);
}
}
</code>```

Sorry if the code bothers you. So basically i am failing to display service data in child_2.html when an action made in child_1.html.The service working fine and name is ProductService which uses Product.ts as an object to get the data in JSON format. Any kind of help is appreciated.

答:
This doesn't work because the DataTemplateComponent you're instantiating in app-navigation isn't the same instance of DataTemplateComponent as the one on the page.  It's a brand new one that you instantiated and that isn't bound to the page at all.  What you're trying to achieve is component communication.  Specifically, parent / child component communication.  There are a number of ways to do this, the cleanest and most flexible / extensible way is with a shared service pattern. Basically, you declare a service with an observable in it that you inject into both services and one updates the observable while the other is subscribed to it, like this:

```<code>@Inject()
export class MyComponentCommunicationService {
    private commSubject: Subject<any> = new Subject();
    comm$: Observable<any> = this.commSubject.asObservable();
    notify() {
        this.commSubject.next();
    }
}
</code>```

Then provide this service, either at the app module or possibly at the parent component depending on needs then in app navigation:

```<code>constructor(private commService: MyComponentCommunicationService) {}
loadMobiles() {
   this.commservice.notify();
}
</code>```

and in data template:

```<code>constructor(private commService: MyComponentCommunicationService, private productService: ProductService) {}
ngOnInit() {
    this.commSub = this.commService.comm$.subscribe(e => this.loadMobiles());
}
ngOnDestroy() { this.commSub.unsubscribe(); } // always clean subscriptions
</code>```

This is probably a little unneccessary since you already have the product service there.  You could probably just move the load mobiles logic into the product service and have that trigger an observable that the data template service is subscribed to, and have the nav component call the load mobile method on the product service, but this is just meant to illustrate the concept.

I'd probably do it like this:

```<code>@Inject()
export class ProductService {
    private productSubject: Subject<Product[]> = new Subject<Product[]>();
    products$: Observable<Product[]> = this.productSubject.asObservable();
    loadMobiles() {
        this.fetchMobiles().then(productArr => {
            this.productSubject.next(productArr);
          }).catch((err) => {
            this.productSubject.error(err);
          });
    }
}
</code>```

then nav component:

```<code>loadMobiles() {
   this.myService.loadMobiles();
}
</code>```

then data template:

```<code>ngOnInit() {
    this.productSub = this.productService.products$.subscribe(
        products => this.productArray = products,
        err => this.error = err
    );
}
ngOnDestroy() { this.productSub.unsubscribe(); } // always clean subscriptions
</code>```

Body:
I am failing to implement action button in child_1 component but the event handler is in sub child component child_2 as shown in the following code:

app.component.html (Parent Html)

    Welcome to {{title}}!

  <app-navigation></app-navigation>

app.component.html (Parent Component)

import { Component } from '@angular/core';
import { ProductService } from './productservice';
import {Product} from './product';

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      title = 'MobileShirtShoeApp';
    }

app.module.ts (Main Module)

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Product } from './product';
import { ProductService } from './productservice';
import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { DataTemplateComponent } from './data-template/data-template.component';

@NgModule({
  declarations: [AppComponent,NavigationComponent,DataTemplateComponent],
  imports: [BrowserModule,HttpModule],
  providers: [ProductService],
  bootstrap: [AppComponent]
})

export class AppModule { }

navigation.component.html (Child 1 HTML)

<fieldset>
  <legend>Navigate</legend>

     <button  (click)="loadMobiles()">Mobiles</button>

  <app-data-template></app-data-template>
</fieldset>

navigation.component.ts (Child 1 Component.ts)

import { Component, OnInit } from '@angular/core';
import { ProductService } from '../productservice';
import {Product} from '../product';
import {DataTemplateComponent} from '../data-template/data-template.component';

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {
  error: string;
  productArray: Product[];

  constructor(private myService: ProductService){
    this.myService = myService;
  }

  dataTemplateComponent: DataTemplateComponent = new DataTemplateComponent(this.myService);

  ngOnInit() {
  }

  loadMobiles() {
   return this.dataTemplateComponent.loadMobiles();
  }
}

data-template.component.html (Child 2 HTML) (NOT DISPLAYING DATA)

<fieldset>
    <legend>Requested Data</legend>
    Welcome

                {{product.id}} {{product.name}} {{product.price}}

</fieldset>

data-template.component.ts (Child 2 Component) (Contains Product service calling code)

import { Component} from '@angular/core';
import {Product} from '../product';
import {ProductService} from '../productservice';

@Component({
  selector: 'app-data-template',
  templateUrl: './data-template.component.html',
  styleUrls: ['./data-template.component.css']
})

export class DataTemplateComponent  {
  error: string;
  productArray: Product[];
  constructor(private productService: ProductService) {
    this.productService = productService;
  }

  loadMobiles(){
    let promise  = this.productService.fetchMobiles();
    promise.then(productArr => {
        return this.productArray = productArr;
      }).catch((err) => {
       this.error = err;
      });
  }
}

ProductService.ts

import 'rxjs/add/operator/toPromise';
import {Http, HttpModule} from '@angular/http';
import {Injectable} from '@angular/core';
import {Product} from './product';

@Injectable()
export class ProductService{
  http: Http;
  constructor(http: Http){
  this.http = http;
  console.log(http);
 }

fetchMobiles(): Promise<Product[]>{
  let url = "https://raw.githubusercontent.com/xxxxx/Other/master/JsonData/MobileData.json";
  return this.http.get(url).toPromise().then((response) => {
        return response.json().mobiles as Product[];
    }).catch(this.handleError);
}

private handleError(error: any): Promise<any> {
  console.error('An error occurred', error);
  return Promise.reject(error.message || error);
}
}

Sorry if the code bothers you. So basically i am failing to display service data in child_2.html when an action made in child_1.html.The service working fine and name is ProductService which uses Product.ts as an object to get the data in JSON format. Any kind of help is appreciated.

Body:
This doesn't work because the DataTemplateComponent you're instantiating in app-navigation isn't the same instance of DataTemplateComponent as the one on the page.  It's a brand new one that you instantiated and that isn't bound to the page at all.  What you're trying to achieve is component communication.  Specifically, parent / child component communication.  There are a number of ways to do this, the cleanest and most flexible / extensible way is with a shared service pattern. Basically, you declare a service with an observable in it that you inject into both services and one updates the observable while the other is subscribed to it, like this:

@Inject()
export class MyComponentCommunicationService {
    private commSubject: Subject<any> = new Subject();
    comm$: Observable<any> = this.commSubject.asObservable();
    notify() {
        this.commSubject.next();
    }
}

Then provide this service, either at the app module or possibly at the parent component depending on needs then in app navigation:

constructor(private commService: MyComponentCommunicationService) {}
loadMobiles() {
   this.commservice.notify();
}

and in data template:

constructor(private commService: MyComponentCommunicationService, private productService: ProductService) {}
ngOnInit() {
    this.commSub = this.commService.comm$.subscribe(e => this.loadMobiles());
}
ngOnDestroy() { this.commSub.unsubscribe(); } // always clean subscriptions

This is probably a little unneccessary since you already have the product service there.  You could probably just move the load mobiles logic into the product service and have that trigger an observable that the data template service is subscribed to, and have the nav component call the load mobile method on the product service, but this is just meant to illustrate the concept.

I'd probably do it like this:

@Inject()
export class ProductService {
    private productSubject: Subject<Product[]> = new Subject<Product[]>();
    products$: Observable<Product[]> = this.productSubject.asObservable();
    loadMobiles() {
        this.fetchMobiles().then(productArr => {
            this.productSubject.next(productArr);
          }).catch((err) => {
            this.productSubject.error(err);
          });
    }
}

then nav component:

loadMobiles() {
   this.myService.loadMobiles();
}

then data template:

ngOnInit() {
    this.productSub = this.productService.products$.subscribe(
        products => this.productArray = products,
        err => this.error = err
    );
}
ngOnDestroy() { this.productSub.unsubscribe(); } // always clean subscriptions


问:
Is it possible to escape a space in a word list sigil?
I'm trying to create an atom list with all the provinces of Argentina. Since some of the are composed of multiple words, I need to escape the whitespace.

```<code>~w[
  Buenos\sAires
  Capital\sfederal Catamarca Chaco Chubut Corrientes Córdoba
  Entre\sRíos Formosa Jujuy La\sPampa La\sRioja Mendoza Misiones Neuquén
  Río\sNegro Salta San\sJuan San\ Luis Santa\sCruz Santa\sFe
  Santiago\sdel\sEstero Tierra\sdel\sFuego Tucumán
]a
</code>```

I've tried using sigil_w and sigil_W, with the classic escaping sequences \ and \s, but it does not work.

(26 provinces - 1) * (2 quotes (") + 1 comma (,) + 1 space for readability(" ")) - 25 spaces I would use with the sigil form = 75 characters I could save

I know I can achieve this using a custom sigil:

```<code>defmodule MySigil do
  def sigil_X(string, [])  do
   string
   |> String.split(~r/\s/)
   |> Enum.map(&String.replace(&1, "\\s", " "))
  end
end

import MySigil
~X[Buenos\sAires La\sPlata]
["Buenos Aires", "La Plata"]
</code>```

... but is there less "homemade" approach?

答: No, this is not possible. sigil_w and sigil_W both call the private split_words method in the Kernel module, which uses String.split to split the string which will always split on any whitespace.

Body:
I'm trying to create an atom list with all the provinces of Argentina. Since some of the are composed of multiple words, I need to escape the whitespace.

~w[
  Buenos\sAires
  Capital\sfederal Catamarca Chaco Chubut Corrientes Córdoba
  Entre\sRíos Formosa Jujuy La\sPampa La\sRioja Mendoza Misiones Neuquén
  Río\sNegro Salta San\sJuan San\ Luis Santa\sCruz Santa\sFe
  Santiago\sdel\sEstero Tierra\sdel\sFuego Tucumán
]a

I've tried using sigil_w and sigil_W, with the classic escaping sequences \ and \s, but it does not work.

(26 provinces - 1) * (2 quotes (") + 1 comma (,) + 1 space for readability(" ")) - 25 spaces I would use with the sigil form = 75 characters I could save

I know I can achieve this using a custom sigil:

defmodule MySigil do
  def sigil_X(string, [])  do
   string
   |> String.split(~r/\s/)
   |> Enum.map(&String.replace(&1, "\\s", " "))
  end
end

import MySigil
~X[Buenos\sAires La\sPlata]
["Buenos Aires", "La Plata"]

... but is there less "homemade" approach?


问:
Multiple modules and routing in angular 5
can somebody tell me how correct to set up routing when using multiple modules in my project? I have app.module and courses.module with some components declared in. I want to know how to connect modules and edit properly routing in courses.module, thats share routes: "/courses/list" and "/courses/detail"

app.routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

//import { CoursesRoutingModule } from './components/courses/courses-routing.module';

const routes: Routes = [
  {
    path: 'courses',
    loadChildren: './components/courses/courses-routing.module#CoursesRoutingModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

app.component.html

```<code><h1>App.component</h1>
<p>
    <button routerLink="/">HOME</button>
    <button routerLink="/courses">KURSY</button>
</p>
<router-outlet></router-outlet>
</code>```

And here's courses component:

courses.routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CoursesComponent } from './courses.component';
import { CoursesDetailComponent } from './components/courses-detail/courses-detail.component';
import { CoursesListComponent } from './components/courses-list/courses-list.component';

const routes: Routes = [
//  {
//    path: 'courses',
//    loadChildren: '/src/app/components/courses/courses.module'
//  }
//  ,
//  {
//    path: 'courses/list',
//    component: CoursesListComponent,
//    outlet: 'courseslist'
//  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CoursesRoutingModule { }
</code>```

courses.component.html:

```<code><p>
    <button routerLink="/">HOME</button>
    <button routerLink="/courses/list">list</button>
    <button routerLink="/courses/detail">detail</button>
</p>
</code>```

答:
app.routing.module.ts

```<code>const routes: Routes = [
  {
    path: '',
    children: [
      { path: 'courses', loadChildren: './components/courses/courses-routing.module#CoursesRoutingModule' }
    ]
  }
];
</code>```

courses.routing.module.ts

```<code>const routes: Routes = [
  {
    path: '',
    children: [
      { path: 'list', component: CoursesListComponent}
    }
  }
];
</code>```

I would do it this way. Give it a try yourself and see how it goes.

Body:
can somebody tell me how correct to set up routing when using multiple modules in my project? I have app.module and courses.module with some components declared in. I want to know how to connect modules and edit properly routing in courses.module, thats share routes: "/courses/list" and "/courses/detail"

app.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

//import { CoursesRoutingModule } from './components/courses/courses-routing.module';

const routes: Routes = [
  {
    path: 'courses',
    loadChildren: './components/courses/courses-routing.module#CoursesRoutingModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

App.component

    <button routerLink="/">HOME</button>
    <button routerLink="/courses">KURSY</button>

<router-outlet></router-outlet>

And here's courses component:

courses.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CoursesComponent } from './courses.component';
import { CoursesDetailComponent } from './components/courses-detail/courses-detail.component';
import { CoursesListComponent } from './components/courses-list/courses-list.component';

const routes: Routes = [
//  {
//    path: 'courses',
//    loadChildren: '/src/app/components/courses/courses.module'
//  }
//  ,
//  {
//    path: 'courses/list',
//    component: CoursesListComponent,
//    outlet: 'courseslist'
//  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CoursesRoutingModule { }

courses.component.html:

    <button routerLink="/">HOME</button>
    <button routerLink="/courses/list">list</button>
    <button routerLink="/courses/detail">detail</button>

Body:
app.routing.module.ts

const routes: Routes = [
  {
    path: '',
    children: [
      { path: 'courses', loadChildren: './components/courses/courses-routing.module#CoursesRoutingModule' }
    ]
  }
];

courses.routing.module.ts

const routes: Routes = [
  {
    path: '',
    children: [
      { path: 'list', component: CoursesListComponent}
    }
  }
];

I would do it this way. Give it a try yourself and see how it goes.


问:
Rollback on elasticsearch bulk insert failure
Use case: Right now I am using Python elasticsearch API form bulk insert.
I have try except wrapped around my bulk insert code but whenever any exception comes elastisearch doesn't rollback inserted document.
And also doesn't try to insert the remaining documents other than the corrupted document which throws an exception.</p>

答:
There is no such thing, a bulk queries contains a list of queries to insert / update or delete documents.

elasticsearch is not a database (no ACID / no transaction etc..), so you must create a rollback feature yourself.


问:
How can I set $build['#cache']['max-age'] in the following code?
In my drupal 8 custom module I use block to show the next and previous links of current article page. However, links do not change when switching nodes due to the caching. How can I limit the caching for this block?
I can't wrap my head around this.</p>

```<code>  public function build() {
        /**
          * {@inheritdoc}
          */

          $node = \Drupal::request()->attributes->get('node');
          $created_time = $node->getCreatedTime();
          $nextprevlinks ="";
          $nextprevlinks .= $this->generateNext($created_time);
          $nextprevlinks .= $this->generatePrevious($created_time);

          return array('#markup' => $nextprevlinks);
        }
</code>```

答:
Just in case someone else brain farts like I just did.

This is how my return now looks:

```<code>  return array('#markup' => $nextprevlinks,
              '#cache' => array("max-age" => 0),
          );
</code>```

Body:
In my drupal 8 custom module I use block to show the next and previous links of current article page. However, links do not change when switching nodes due to the caching. How can I limit the caching for this block?
I can't wrap my head around this.

  public function build() {
        /**
          * {@inheritdoc}
          */

          $node = \Drupal::request()->attributes->get('node');
          $created_time = $node->getCreatedTime();
          $nextprevlinks ="";
          $nextprevlinks .= $this->generateNext($created_time);
          $nextprevlinks .= $this->generatePrevious($created_time);

          return array('#markup' => $nextprevlinks);
        }

Body:
Just in case someone else brain farts like I just did.

This is how my return now looks:

  return array('#markup' => $nextprevlinks,
              '#cache' => array("max-age" => 0),
          );


问:
How to create a facetted plot with title and subtitle specific to each facet?
Generating a plot combined with separate plots for each column with title and subtitles, along with a vertical line for each plot:

I have created using the histogram plot for a column with a vertical line.

```<code>library(ggplot2)
library(gridExtra)
library(tidyr)

actualIris <- data.frame(Sepal.Length=6.1, Sepal.Width=3.1, Petal.Length=5.0, Petal.Width=1.7)

# Sepal Length
oneTailed <- sum(actualIris$Sepal.Length < iris$Sepal.Length)/nrow(iris)

plot1SL <- ggplot(iris, aes(x=Sepal.Length)) + geom_histogram() +
  geom_vline(xintercept = actualIris$Sepal.Length, col = "blue", lwd = 2) +
  labs(title='Distribution of Sepal Length', x='Sepal Length', y='Frequency',
       subtitle=paste('one-tailed test=', oneTailed, sep='')) + theme_bw()
</code>```

The below code is just repetition of three other columns. (You can ignore it).

```<code># Sepal Width
oneTailed <- sum(actualIris$Sepal.Width < iris$Sepal.Width)/nrow(iris)

plot1SW <- ggplot(iris, aes(x=Sepal.Width)) + geom_histogram() +
  geom_vline(xintercept = actualIris$Sepal.Width, col = "blue", lwd = 2) +
  labs(title='Distribution of Sepal Width', x='Sepal Width', y='Frequency',
       subtitle=paste('one-tailed test=', oneTailed, sep='')) + theme_bw()

# Petal Length
oneTailed <- sum(actualIris$Petal.Length < iris$Petal.Length)/nrow(iris)

plot1PL <- ggplot(iris, aes(x=Petal.Length)) + geom_histogram() +
  geom_vline(xintercept = actualIris$Petal.Length, col = "blue", lwd = 2) +
  labs(title='Distribution of Petal Length', x='Petal Length', y='Frequency',
       subtitle=paste('one-tailed test=', oneTailed, sep='')) + theme_bw()

# Petal Width
oneTailed <- sum(actualIris$Petal.Width < iris$Petal.Width)/nrow(iris)

plot1PW <- ggplot(iris, aes(x=Petal.Width)) + geom_histogram() +
  geom_vline(xintercept = actualIris$Petal.Width, col = "blue", lwd = 2) +
  labs(title='Distribution of Petal Width', x='Petal Width', y='Frequency',
       subtitle=paste('one-tailed test=', oneTailed, sep='')) + theme_bw()

# Combine the plots
grid.arrange(plot1SL, plot1SW, plot1PL, plot1PW, nrow=1)
</code>```

It results in the below plot:

I have tried to create the single plot using facet_wrap instead of combining multiple single plots, after creating the long data.

```<code>tmp <- iris[,-5] %>% gather(Type, value)
#actualIris <- data.frame(Sepal.Length=6.1, Sepal.Width=3.1, Petal.Length=5.0, Petal.Width=1.7)
actuals <- data.frame(col1=colnames(actualIris), col2=as.numeric(actualIris[1,]))
tmp$Actual <- actuals$col2[match(tmp$Type, actuals$col1)]
tmp$Type <- factor(tmp$Type, levels = c('Petal.Length', 'Petal.Width', 'Sepal.Length', 'Sepal.Width'),
                   labels = c('Petal Length', 'Petal Width', 'Sepal Length', 'Sepal Width'))
ggplot(tmp, aes(value)) + facet_wrap(~Type, scales="free", nrow = 1) + geom_histogram() +
  geom_vline(aes(xintercept=Actual), colour="blue", lwd=2)
</code>```

I have tried to change the facet labels using the labeller option but it did not work. (However, this is not the main question.)

```<code>ggplot(tmp, aes(value)) + geom_histogram() +
  facet_wrap(~Type, scales="free", nrow = 1,
             labeller = as_labeller(paste('Distribution of ', levels(~Type), sep=''))) +
  geom_vline(aes(xintercept=Actual), colour="blue", lwd=2)
</code>```

How to create the plot similar to the first plot using the long data tmp created?

答:
You can make tailored two lines labels:

labels <- c(paste('Petal Length\none-tailed test=', round(sum(actualIris$Sepal.Length < iris$Sepal.Length)/nrow(iris), 2)),
            paste('Petal Width\none-tailed test=', round(sum(actualIris$Sepal.Width < iris$Sepal.Width)/nrow(iris), 2)),
            paste('Sepal Length\none-tailed test=', round(sum(actualIris$Petal.Length < iris$Petal.Length)/nrow(iris), 2)),
            paste('Sepal Width\none-tailed test=', round(sum(actualIris$Petal.Width < iris$Petal.Width)/nrow(iris), 2)))

tmp <- iris[,-5] %>% gather(Type, value)
actuals <- data.frame(col1=colnames(actualIris), col2=as.numeric(actualIris[1,]))
tmp$Actual <- actuals$col2[match(tmp$Type, actuals$col1)]
tmp$Type <- factor(tmp$Type, levels = c('Petal.Length', 'Petal.Width', 'Sepal.Length', 'Sepal.Width'),
                   labels = labels)
ggplot(tmp, aes(value)) + facet_wrap(~Type, scales="free", nrow = 1) + geom_histogram() +
  geom_vline(aes(xintercept=Actual), colour="blue", lwd=2)
```

And get this:

Body:
Generating a plot combined with separate plots for each column with title and subtitles, along with a vertical line for each plot:

I have created using the histogram plot for a column with a vertical line.

library(ggplot2)
library(gridExtra)
library(tidyr)

actualIris <- data.frame(Sepal.Length=6.1, Sepal.Width=3.1, Petal.Length=5.0, Petal.Width=1.7)

# Sepal Length
oneTailed <- sum(actualIris$Sepal.Length < iris$Sepal.Length)/nrow(iris)

plot1SL <- ggplot(iris, aes(x=Sepal.Length)) + geom_histogram() +
  geom_vline(xintercept = actualIris$Sepal.Length, col = "blue", lwd = 2) +
  labs(title='Distribution of Sepal Length', x='Sepal Length', y='Frequency',
       subtitle=paste('one-tailed test=', oneTailed, sep='')) + theme_bw()

The below code is just repetition of three other columns. (You can ignore it).

# Sepal Width
oneTailed <- sum(actualIris$Sepal.Width < iris$Sepal.Width)/nrow(iris)

plot1SW <- ggplot(iris, aes(x=Sepal.Width)) + geom_histogram() +
  geom_vline(xintercept = actualIris$Sepal.Width, col = "blue", lwd = 2) +
  labs(title='Distribution of Sepal Width', x='Sepal Width', y='Frequency',
       subtitle=paste('one-tailed test=', oneTailed, sep='')) + theme_bw()

# Petal Length
oneTailed <- sum(actualIris$Petal.Length < iris$Petal.Length)/nrow(iris)

plot1PL <- ggplot(iris, aes(x=Petal.Length)) + geom_histogram() +
  geom_vline(xintercept = actualIris$Petal.Length, col = "blue", lwd = 2) +
  labs(title='Distribution of Petal Length', x='Petal Length', y='Frequency',
       subtitle=paste('one-tailed test=', oneTailed, sep='')) + theme_bw()

# Petal Width
oneTailed <- sum(actualIris$Petal.Width < iris$Petal.Width)/nrow(iris)

plot1PW <- ggplot(iris, aes(x=Petal.Width)) + geom_histogram() +
  geom_vline(xintercept = actualIris$Petal.Width, col = "blue", lwd = 2) +
  labs(title='Distribution of Petal Width', x='Petal Width', y='Frequency',
       subtitle=paste('one-tailed test=', oneTailed, sep='')) + theme_bw()

# Combine the plots
grid.arrange(plot1SL, plot1SW, plot1PL, plot1PW, nrow=1)

It results in the below plot:

I have tried to create the single plot using facet_wrap instead of combining multiple single plots, after creating the long data.

tmp <- iris[,-5] %>% gather(Type, value)
#actualIris <- data.frame(Sepal.Length=6.1, Sepal.Width=3.1, Petal.Length=5.0, Petal.Width=1.7)
actuals <- data.frame(col1=colnames(actualIris), col2=as.numeric(actualIris[1,]))
tmp$Actual <- actuals$col2[match(tmp$Type, actuals$col1)]
tmp$Type <- factor(tmp$Type, levels = c('Petal.Length', 'Petal.Width', 'Sepal.Length', 'Sepal.Width'),
                   labels = c('Petal Length', 'Petal Width', 'Sepal Length', 'Sepal Width'))
ggplot(tmp, aes(value)) + facet_wrap(~Type, scales="free", nrow = 1) + geom_histogram() +
  geom_vline(aes(xintercept=Actual), colour="blue", lwd=2)

I have tried to change the facet labels using the labeller option but it did not work. (However, this is not the main question.)

ggplot(tmp, aes(value)) + geom_histogram() +
  facet_wrap(~Type, scales="free", nrow = 1,
             labeller = as_labeller(paste('Distribution of ', levels(~Type), sep=''))) +
  geom_vline(aes(xintercept=Actual), colour="blue", lwd=2)

How to create the plot similar to the first plot using the long data tmp created?

Body:
You can make tailored two lines labels:

labels <- c(paste('Petal Length\none-tailed test=', round(sum(actualIris$Sepal.Length < iris$Sepal.Length)/nrow(iris), 2)),
            paste('Petal Width\none-tailed test=', round(sum(actualIris$Sepal.Width < iris$Sepal.Width)/nrow(iris), 2)),
            paste('Sepal Length\none-tailed test=', round(sum(actualIris$Petal.Length < iris$Petal.Length)/nrow(iris), 2)),
            paste('Sepal Width\none-tailed test=', round(sum(actualIris$Petal.Width < iris$Petal.Width)/nrow(iris), 2)))

tmp <- iris[,-5] %>% gather(Type, value)
actuals <- data.frame(col1=colnames(actualIris), col2=as.numeric(actualIris[1,]))
tmp$Actual <- actuals$col2[match(tmp$Type, actuals$col1)]
tmp$Type <- factor(tmp$Type, levels = c('Petal.Length', 'Petal.Width', 'Sepal.Length', 'Sepal.Width'),
                   labels = labels)
ggplot(tmp, aes(value)) + facet_wrap(~Type, scales="free", nrow = 1) + geom_histogram() +
  geom_vline(aes(xintercept=Actual), colour="blue", lwd=2)

And get this:


问:
Yii2 $model->load(Yii::$app->request->post()) does not load data from form
When I take out condition to load data it saves it to db, the $_POST gets values but doesnt send them to controller , this way works in my other projects but not here. If I use if(isset($_POST['money']) && isset($_POST['username'])){ to save data it works but not the load() function.

Controller

```<code>public function actionSend() {
    $model = new User();
    $model->getErrors();
    if ($model->load(Yii::$app->request->post())) {
        $model->money = 'something';
        $model->username = 'something';
        $model->save();
    }
    return $this->render('send', [
        'model' => $model
    ]);
}
</code>```

Model

```<code><?php

namespace app\models;
use yii\db\ActiveRecord;

use Yii;

class User extends \yii\db\ActiveRecord {
    public static function tableName() {
        return 'user';
    }

    public function rules() {
        return [
            [['username', 'money'], 'safe'],
            [['username', 'password'], 'string', 'max' => 15],
            [['auth_key', 'access_token'], 'string', 'max' => 32],
            [['money'], 'string', 'max' => 8],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'auth_key' => 'Auth Key',
            'access_token' => 'Access Token',
            'money' => 'Money',
        ];
    }
}
</code>```

view

```<code><?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>

<h2>Send</h2>

<?php $form = ActiveForm::begin([
    'layout' => 'horizontal',
    'fieldConfig' => [
        'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
        'labelOptions' => ['class' => 'col-lg-1 control-label'],
    ],
]); ?>
    <?= $form->field($model, 'username')->textInput(['name' => 'username']) ?>

    <?= $form->field($model, 'money')->textInput(['name' => 'money'])?>

    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('Send', ['class' => 'btn btn-success']) ?>
        </div>
    </div>

<?php ActiveForm::end(); ?>
</code>```

答:
Change your controller to this

```<code>public function actionSend() {
    $model = new User();
    $model->getErrors();

    /* set the second parameters of load to empty string */
    if ($model->load(Yii::$app->request->post(), '')) {
        $model->money = 'something';
        $model->username = 'something';
        $model->save();
    }
    return $this->render('send', [
        'model' => $model
    ]);
}
</code>```

If you review the implementation of load method, you would find that
load takes two parameters, the first is the data you want to assign, the second is the data's prefix name.

Let's look at an example to illustrate the usage of the second parameter. (We assume that your formname is User)

```<code>$data1 = [
    'username' => 'sam',
    'money' => 100
];

$data2 = [
    'User' => [
        'username' => 'sam',
        'money' => 100
    ],
],

// if you want to load $data1, you have to do like this
$model->load($data1, '');

// if you want to load $data2, you have to do like this
$model->load($data2);

// either one of the two ways, the result is the same.
echo $model->username;    // sam
echo $model->money;       // 100
</code>```

Hope it would be helpful.

Body:
When I take out condition to load data it saves it to db, the $_POST gets values but doesnt send them to controller , this way works in my other projects but not here. If I use if(isset($_POST['money']) && isset($_POST['username'])){ to save data it works but not the load() function.

Controller

public function actionSend() {
    $model = new User();
    $model->getErrors();
    if ($model->load(Yii::$app->request->post())) {
        $model->money = 'something';
        $model->username = 'something';
        $model->save();
    }
    return $this->render('send', [
        'model' => $model
    ]);
}

Model

<?php

namespace app\models;
use yii\db\ActiveRecord;

use Yii;

class User extends \yii\db\ActiveRecord {
    public static function tableName() {
        return 'user';
    }

    public function rules() {
        return [
            [['username', 'money'], 'safe'],
            [['username', 'password'], 'string', 'max' => 15],
            [['auth_key', 'access_token'], 'string', 'max' => 32],
            [['money'], 'string', 'max' => 8],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'auth_key' => 'Auth Key',
            'access_token' => 'Access Token',
            'money' => 'Money',
        ];
    }
}

view

<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>

Send

<?php $form = ActiveForm::begin([
    'layout' => 'horizontal',
    'fieldConfig' => [
        'template' => "{label}\n
{input}
\n
{error}
",
        'labelOptions' => ['class' => 'col-lg-1 control-label'],
    ],
]); ?>
    <?= $form->field($model, 'username')->textInput(['name' => 'username']) ?>

    <?= $form->field($model, 'money')->textInput(['name' => 'money'])?>

            <?= Html::submitButton('Send', ['class' => 'btn btn-success']) ?>

<?php ActiveForm::end(); ?>

Body:
Change your controller to this

public function actionSend() {
    $model = new User();
    $model->getErrors();

    /* set the second parameters of load to empty string */
    if ($model->load(Yii::$app->request->post(), '')) {
        $model->money = 'something';
        $model->username = 'something';
        $model->save();
    }
    return $this->render('send', [
        'model' => $model
    ]);
}

If you review the implementation of load method, you would find that
load takes two parameters, the first is the data you want to assign, the second is the data's prefix name.

Let's look at an example to illustrate the usage of the second parameter. (We assume that your formname is User)

$data1 = [
    'username' => 'sam',
    'money' => 100
];

$data2 = [
    'User' => [
        'username' => 'sam',
        'money' => 100
    ],
],

// if you want to load $data1, you have to do like this
$model->load($data1, '');

// if you want to load $data2, you have to do like this
$model->load($data2);

// either one of the two ways, the result is the same.
echo $model->username;    // sam
echo $model->money;       // 100

Hope it would be helpful.


问:
What may be the difficulties, if any, with the web applications developed in Java EE?
I have a few questions to understand better Java's usage in context of web applications:-

Is Java EE web development suitable for small start-up (with less human resource) looking to develop an web application ?

What kind of difficulties may arise in Java EE web development, deployment & maintenance ?

What kind of things should be kept in mind/ considerations to be made when moving from PHP background to Java ?

Why Java web applications are not so popular today?  ( or in case I perceived it wrongly, please list any major deployments beside linkedIn and ebay)

and Finally, What are some of the most important things to learn before starting web development in Java EE ?

Thank you

答:
Generally the answer to the question of "what technology to use" is "the one which you have most experience with". However, Java EE is huge and clunky, and definitely not good for rapid prototyping, which you will be doing if you're doing a startup.

Personally I would recommend a more modern and dynamic environment. If you're coming from PHP, you should be able to pick up Ruby on Rails or Django (Python) easily. These two choices are in my opinion orders of magnitude better than Java EE.  If you want to stick with Java, at least go with the Play framework then.

ContentLicense: CC BY-SA 2.5


问:
Unable to exclude files using FindBugs
I have a gradle project and I want to exclude some files from analysis with Findbugs
There is some generated code in my project and I want to exclude those classes

Here is the findbugs setup in my build.gradle

```<code>apply plugin: 'findbugs'
findbugs {
    toolVersion "3.0.1"
}

tasks.withType(FindBugs) {
    excludeFilter = rootProject.file('projectConfig/findbugs/excludeFilter.xml')

    reports {
        xml.enabled false
        html.enabled true
        html.stylesheet resources.text.fromFile('../projectConfig/findbugs/findbugs-style.xsl')
    }
}
</code>```

The contentes of excludeFilter.xml are as follows

<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
  <Match>
     <Class name="~.*\.Immutable*\.java" />
  </Match>
  <Match>
     <Class name="~.*\.GsonAdapters*\.java" />
  </Match>
</FindBugsFilter>
```

<p>Sample files I want to exclude have the following package and class names</p>

```com.tools.vo.event.GsonAdaptersGetEventDataBalancesVO
com.tools.vo.event.ImmutableGetEventDataVO
```

Any help on what I can do to exclude these patterns would be appreciated

Thank you
Damien

答:
This seems to be a problem with your exclude patterns (docs, regex). Try:

<Match>
  <Or>
    <Class name="~.*?\.Immutable.*" />
    <Class name="~.*?\.GsonAdapters.*" />
  </Or>
</Match>
```

In detail, I changed the beginning of the expression to not be "greedy", and removed the .java part, as this expression is applied to the class name. Also, the asterisk operator always applies to the previous element, so you were missing some dots.

Title: Unable to exclude files using FindBugs

Body:
I have a gradle project and I want to exclude some files from analysis with Findbugs
There is some generated code in my project and I want to exclude those classes

Here is the findbugs setup in my build.gradle

apply plugin: 'findbugs'
findbugs {
    toolVersion "3.0.1"
}

tasks.withType(FindBugs) {
    excludeFilter = rootProject.file('projectConfig/findbugs/excludeFilter.xml')

    reports {
        xml.enabled false
        html.enabled true
        html.stylesheet resources.text.fromFile('../projectConfig/findbugs/findbugs-style.xsl')
    }
}

The contentes of excludeFilter.xml are as follows

<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
  <Match>
     <Class name="~.*\.Immutable*\.java" />
  </Match>
  <Match>
     <Class name="~.*\.GsonAdapters*\.java" />
  </Match>
</FindBugsFilter>

Sample files I want to exclude have the following package and class names

com.tools.vo.event.GsonAdaptersGetEventDataBalancesVO
com.tools.vo.event.ImmutableGetEventDataVO

Any help on what I can do to exclude these patterns would be appreciated

Thank you
Damien

Body:
This seems to be a problem with your exclude patterns (docs, regex). Try:

<Match>
  <Or>
    <Class name="~.*?\.Immutable.*" />
    <Class name="~.*?\.GsonAdapters.*" />
  </Or>
</Match>

In detail, I changed the beginning of the expression to not be "greedy", and removed the .java part, as this expression is applied to the class name. Also, the asterisk operator always applies to the previous element, so you were missing some dots.


问:
How to pass user_name based on the user_ID from login page to home page using mvc
When i login my login page it goes to home page with my user name it working fine and i want userID based on my user_namefrom login to home page

```<code><section id="login">
                                @if (Request.IsAuthenticated)
                                {
                                    <text>
                                        <button class="dropdown-toggle" id="dd-user-menu" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                             <img src="~/img/avatar-2-64.png" alt="">
                                        </button>
                                        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dd-user-menu">
                                            <a class="dropdown-item"><span class="font-icon glyphicon glyphicon-user"></span>Hello, @User.Identity.Name</a>
                                            <a class="dropdown-item" href="#"><span class="font-icon glyphicon glyphicon-cog"></span>Settings</a>
                                            <a class="dropdown-item" href="#"><span class="font-icon glyphicon glyphicon-question-sign"></span>Help</a>
                                            <div class="dropdown-divider"></div>
                                            @using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
                                            {
                                                @Html.AntiForgeryToken()
                                                <a class="dropdown-item" href="javascript:document.getElementById('logoutForm').submit()"><span class="font-icon glyphicon glyphicon-log-out"></span>Logout</a>
                                            }
                                        </div>
                                    </text>
                                }
                            </section>
</code>```

but in my above code i get user_name so i want to get user_id as well

```<code>[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Login login)
        {
            if (ModelState.IsValid)
            {
                bool success = WebSecurity.Login(login.UserName, login.Password, false);
                var UserID = GetUserID_By_UserName(login.UserName);
                var DocID = GetDocID_By_UserName(login.UserName);

                if (success == true)
                {
                    Session["Name"] = login.UserName;
                    Session["UserID"] = UserID;
                    Session["RefID"] = DocID;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("Error", "Please enter valid Username and Password");
                    return View(login);
                }

            }
            return View(login);
        }
        #endregion
</code>```

答:
in my above code i get user_name so i want to get user_id as well

You cannot call User.Identity.XXX. You cannot add custom property to Principle class.

However, you could just call Session["UserID"] inside View, since you already store UserID in session state.

For example,

```<code><div>@Convert.ToInt32(Session["UserID"] ?? 0)</div>
</code>```

Body:
When i login my login page it goes to home page with my user name it working fine and i want userID based on my user_namefrom login to home page

                                @if (Request.IsAuthenticated)
                                {
                                    <text>
                                        <button class="dropdown-toggle" id="dd-user-menu" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                                        </button>

                                            Hello, @User.Identity.Name
                                            Settings
                                            Help

                                            @using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
                                            {
                                                @Html.AntiForgeryToken()
                                                Logout
                                            }

                                    </text>
                                }

but in my above code i get user_name so i want to get user_id as well

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Login login)
        {
            if (ModelState.IsValid)
            {
                bool success = WebSecurity.Login(login.UserName, login.Password, false);
                var UserID = GetUserID_By_UserName(login.UserName);
                var DocID = GetDocID_By_UserName(login.UserName);

                if (success == true)
                {
                    Session["Name"] = login.UserName;
                    Session["UserID"] = UserID;
                    Session["RefID"] = DocID;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("Error", "Please enter valid Username and Password");
                    return View(login);
                }

            }
            return View(login);
        }
        #endregion

Body:
in my above code i get user_name so i want to get user_id as well

You cannot call User.Identity.XXX. You cannot add custom property to Principle class.

However, you could just call Session["UserID"] inside View, since you already store UserID in session state.

For example,

<div>@Convert.ToInt32(Session["UserID"] ?? 0)</div>