问:
Download Large File Using Web API Returning OutOfMemoryException
I've tried using numerous questions/answers on SO - but can't seem to overcome the OutOfMemoryException I receive when trying to download a 200MB zip file via the web api.

I've drastically simplified my code in order to test:

```<code>    [HttpPost]
    public async Task<HttpResponseMessage> ExportReports(OrderExportFilter filterJson)
    {

        var filename = "C:\\pdftemp\\1128d0ff-a4b7-440d-9e3b-dd152445eb62.zip";

        var fileStream = File.OpenRead(filename);

        var content = new StreamContent(fileStream, 4096);

        resp.Content = content;

        resp.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
        resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "OrdersExport.pdf"
        };

        return resp;
     }
</code>```

This is just one of many way's I've attempted to download the zip file, I've also referenced this link and duplicated the code to no avail.

I'm at a loss as to what I'm doing incorrectly to enable large zip files to be downloaded.

Update: Per request in comments i've tried using "application/octet-stream" instead - still no luck - same error.

Also - one more thing to note - when i download smaller zip files using this code it works fine, it just seems once the file is too large is starts to bomb.

Exception Update:

I was able to pull the exception details:

```<code>    {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Exception of type 'System.OutOfMemoryException' was thrown.",
        "ExceptionType": "System.OutOfMemoryException",
        "StackTrace": "   at System.IO.MemoryStream.set_Capacity(Int32 value)\r\n   at System.IO.MemoryStream.EnsureCapacity(Int32 value)\r\n   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)\r\n   at System.IO.Compression.DeflateStream.WriteDeflaterOutput(Boolean isAsync)\r\n   at System.IO.Compression.DeflateStream.PurgeBuffers(Boolean disposing)\r\n   at System.IO.Compression.DeflateStream.Dispose(Boolean disposing)\r\n   at System.IO.Stream.Close()\r\n   at System.IO.Compression.GZipStream.Dispose(Boolean disposing)\r\n   at System.IO.Stream.Close()\r\n   at System.IO.Stream.Dispose()\r\n   at System.Net.Http.Extensions.Compression.Core.Compressors.BaseCompressor.<Compress>d__4.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Net.Http.Extensions.Compression.Core.Models.CompressedContent.<SerializeToStreamAsync>d__4.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()"
    }
</code>```

答:
Your stack trace indicates that the exception is thrown when a DeflateStream is closed. This stream apparently writes to a MemoryStream and closing the DeflateStream outputs the entire (compressed) response to the MemoryStream. That is, the byte array buffer in the MemoryStream is allocated and it fails with an OutOfMemoryException if the compressed output is too big.

It is somewhat surprising that the compressed response is buffered in memory because a web server at least conceptually is able to stream data from a file through a compressor and to the network without having to read and compress the entire file into memory first.

From the comments I guess that you are using the NuGet package Microsoft.AspNet.WebApi.Extensions.Compression.Server in your Web API application. While I can't claim that I fully understand how it works I did try to decompile it and from what I can see sending a response through this middleware results in the output being buffered not once but actually twice. (The BaseCompressor.Compress() method writes to a MemoryStream created by StreamManager.GetStream() and this MemoryStream is then read into an array of bytes effectively doubling the memory requirement of the compressor.)

Based on this analysis you should turn off compression for big responses and this seems to have fixed your problem by applying the attribute [Compression(Enabled = false)] to your controller action.

It is a bit ironic that you are unable to compress big responses which might benefit the most from being compressed. However, if you run your Web API on top of a web server like IIS that natively supports response compression you can completely remove the middleware and instead turn compression on in the web server (it is called dynamic compression in IIS). Native compression probably also performs better than compression done in managed code.

Body:
I've tried using numerous questions/answers on SO - but can't seem to overcome the OutOfMemoryException I receive when trying to download a 200MB zip file via the web api.

I've drastically simplified my code in order to test:

    [HttpPost]
    public async Task<HttpResponseMessage> ExportReports(OrderExportFilter filterJson)
    {

        var filename = "C:\\pdftemp\\1128d0ff-a4b7-440d-9e3b-dd152445eb62.zip";

        var fileStream = File.OpenRead(filename);

        var content = new StreamContent(fileStream, 4096);

        resp.Content = content;

        resp.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
        resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "OrdersExport.pdf"
        };

        return resp;
     }

This is just one of many way's I've attempted to download the zip file, I've also referenced this link and duplicated the code to no avail.

I'm at a loss as to what I'm doing incorrectly to enable large zip files to be downloaded.

Update: Per request in comments i've tried using "application/octet-stream" instead - still no luck - same error.

Also - one more thing to note - when i download smaller zip files using this code it works fine, it just seems once the file is too large is starts to bomb.

Exception Update:

I was able to pull the exception details:

    {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Exception of type 'System.OutOfMemoryException' was thrown.",
        "ExceptionType": "System.OutOfMemoryException",
        "StackTrace": "   at System.IO.MemoryStream.set_Capacity(Int32 value)\r\n   at System.IO.MemoryStream.EnsureCapacity(Int32 value)\r\n   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)\r\n   at System.IO.Compression.DeflateStream.WriteDeflaterOutput(Boolean isAsync)\r\n   at System.IO.Compression.DeflateStream.PurgeBuffers(Boolean disposing)\r\n   at System.IO.Compression.DeflateStream.Dispose(Boolean disposing)\r\n   at System.IO.Stream.Close()\r\n   at System.IO.Compression.GZipStream.Dispose(Boolean disposing)\r\n   at System.IO.Stream.Close()\r\n   at System.IO.Stream.Dispose()\r\n   at System.Net.Http.Extensions.Compression.Core.Compressors.BaseCompressor.<Compress>d__4.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Net.Http.Extensions.Compression.Core.Models.CompressedContent.<SerializeToStreamAsync>d__4.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()"
    }


来源: stackexchange

问:
Creating a Class Hierarchy with no Public Attributes
I am working on a practice exam question that asks me to build a Battery hierarchy with only private attributes, and no re-declaration of attributes. I have four classes, Battery, BadBattery(an exception class), SingleUse, and Rechargeable. I know that Battery should be an abstract class, which is why I'm confused as to why I can't declare the attributes of this class to be public. I got my hierarchy to give the exact output that my professor wanted, but if I'm to make the attributes private in my abstract class, how can I avoid having to re-declare them in any of the child classes? Would I have to have a bunch of public getters in my abstract class so that I can access those attributes in any child classes?</p>

答:
Using inheritance, the only way to not re-declare variables in common to all subclasses, hiding them to the rest of the context, is declare these as protected in the base class (it doesn't matter if it is abstract or concrete).
 In this way, the attributes can be directly accessed to the class hierarchy, the rest of the world can access only using public getters .

ContentLicense: CC BY-SA 3.0


问:
Recursively check the difference between files in shell
I am trying to recursively check the difference between files in 2 separate directories in shell. NOTE :- both directories are identical only the root name is different

In the diagram shown above I want to "diff ROOT_A/A.md5 ROOT_B/A.md5" recursively in my script file for all files in the root directory.

```<code>for filename in ROOT_A/*.md5; do
    diff ($filename | cut -d '/' -f 2) (ROOT_B/$filename) >> logfile.txt done
</code>```

However, This doesn't work. can someone help me out with this. Thanks

答:
Assuming that your shell is Bash:

ROOT_A='...'
ROOT_B='...'
for file in "$ROOT_A"/*.md5; do
  ! test -r "$file" || ! test -r "$ROOT_B/${file##*/}" && continue
  echo "Comparing $file with $ROOT_B/${file##*/}"
  diff "$file" "$ROOT_B/${file##*/}"
done
```

As @CharlesDuffy observes, if the files are truly MD5 sums (or other such kind of checksums), diff should be replaced with cmp because it doesn't matter how different the files are, only if they are the same or different.

Body:
I am trying to recursively check the difference between files in 2 separate directories in shell. NOTE :- both directories are identical only the root name is different

In the diagram shown above I want to "diff ROOT_A/A.md5 ROOT_B/A.md5" recursively in my script file for all files in the root directory.

for filename in ROOT_A/*.md5; do
    diff ($filename | cut -d '/' -f 2) (ROOT_B/$filename) >> logfile.txt done

However, This doesn't work. can someone help me out with this. Thanks

Body:
Assuming that your shell is Bash:

ROOT_A='...'
ROOT_B='...'
for file in "$ROOT_A"/*.md5; do
  ! test -r "$file" || ! test -r "$ROOT_B/${file##*/}" && continue
  echo "Comparing $file with $ROOT_B/${file##*/}"
  diff "$file" "$ROOT_B/${file##*/}"
done

As @CharlesDuffy observes, if the files are truly MD5 sums (or other such kind of checksums), diff should be replaced with cmp because it doesn't matter how different the files are, only if they are the same or different.


问:
ifelse() and conditionally pasting column names across a data frame
I've got a data frame (df) with nine categorical variables, the first one being called student and then the names of eight school subjects.

I'd like to create a new variable called overall, summing up what subjects the student studied (dfgoal).

The problem's that what I've got doesn't work. Also I'm not sure how to best skip the first column (student). Use a list of the variables I do want to use (the eight subjects)?

Any help would be much appreciated.

starting point (df):

```<code>     df <-
  data.frame(
    student = c(1, 2, 3, 4, 5),
    maths = c("y", "n", "n", "n", "n"),
    English = c("n", "y", "n", "n", "n"),
    geography = c("y", "n", "n", "n", "n"),
    history = c("n", "n", "n", "n", "n"),
    art = c("n", "n", "n", "n", "n"),
    Spanish = c("n", "n", "n", "n", "n"),
    physics = c("n", "n", "n", "n", "y"),
    chemistry = c("n", "n", "n", "n", "y"),
    stringsAsFactors = TRUE
  )
</code>```

desired outcome (dfgoal):

```<code> dfgoal <-
data.frame(
student = c(1, 2, 3, 4, 5),
maths = c("y", "n", "n", "n", "n"),
English = c("n", "y", "n", "n", "n"),
geography = c("y", "n", "n", "n", "n"),
history = c("n", "n", "n", "n", "n"),
art = c("n", "n", "n", "n", "n"),
Spanish = c("n", "n", "n", "n", "n"),
physics = c("n", "n", "n", "n", "y"),
chemistry = c("n", "n", "n", "n", "y"),
overall = c("maths, geography,", "English", "n", "n", "physics,chemistry,"),
stringsAsFactors = TRUE )
</code>```

current code:

```<code>sapply(df, function(x)
  df$overall <- ifelse(df$x == y, paste0(names(df$x), ","), "n"))
</code>```

答:
```<code>library(data.table)
setDT(df)

merge(df,
      melt(df, "student")[value == "y"][, .(overall = paste(variable, collapse = ", ")), by = student],
      by = "student",
      all.x = TRUE)
#    student maths English geography history art Spanish physics chemistry            overall
# 1:       1     y       n         y       n   n       n       n         n   maths, geography
# 2:       2     n       y         n       n   n       n       n         n            English
# 3:       3     n       n         n       n   n       n       n         n                 NA
# 4:       4     n       n         n       n   n       n       n         n                 NA
# 5:       5     n       n         n       n   n       n       y         y physics, chemistry
</code>```

Body:
I've got a data frame (df) with nine categorical variables, the first one being called student and then the names of eight school subjects.

I'd like to create a new variable called overall, summing up what subjects the student studied (dfgoal).

The problem's that what I've got doesn't work. Also I'm not sure how to best skip the first column (student). Use a list of the variables I do want to use (the eight subjects)?

Any help would be much appreciated.

starting point (df):

     df <-
  data.frame(
    student = c(1, 2, 3, 4, 5),
    maths = c("y", "n", "n", "n", "n"),
    English = c("n", "y", "n", "n", "n"),
    geography = c("y", "n", "n", "n", "n"),
    history = c("n", "n", "n", "n", "n"),
    art = c("n", "n", "n", "n", "n"),
    Spanish = c("n", "n", "n", "n", "n"),
    physics = c("n", "n", "n", "n", "y"),
    chemistry = c("n", "n", "n", "n", "y"),
    stringsAsFactors = TRUE
  )

desired outcome (dfgoal):

 dfgoal <-
data.frame(
student = c(1, 2, 3, 4, 5),
maths = c("y", "n", "n", "n", "n"),
English = c("n", "y", "n", "n", "n"),
geography = c("y", "n", "n", "n", "n"),
history = c("n", "n", "n", "n", "n"),
art = c("n", "n", "n", "n", "n"),
Spanish = c("n", "n", "n", "n", "n"),
physics = c("n", "n", "n", "n", "y"),
chemistry = c("n", "n", "n", "n", "y"),
overall = c("maths, geography,", "English", "n", "n", "physics,chemistry,"),
stringsAsFactors = TRUE )

current code:

sapply(df, function(x)
  df$overall <- ifelse(df$x == y, paste0(names(df$x), ","), "n"))


问:
Projection of mongodb subdocument and get subdocument as class in c#

Hi. I have a Collection named "Level" with this class structure :

```<code>    public class Level
    {
      [BsonId]
      public string Id {get; set;}
      public string Name { get; set; }
      public int Number { get; set; }
      public int TotalScore { get; set; }
      public int QuestionCount { get; set; }
      public IEnumerable<ConnectingQuestion> ConnectingQuestions { get; set; }
    }
    public class ConnectingQuestion
    {
      [BsonId]
      public string Id { get; set; }
      public int QuestionNumber { get; set; }
      public string Description { get; set; }
      public string Type { get; set; }
      public string Title { get; set; }
    }
</code>```

and collection structure like this :

```<code>{
"_id" : "64e850f95322e01e88f131a2",
"Name" : "First Level",
"Number" : NumberInt(1),
"TotalScore" : NumberInt(2690),
"QuestionCount" : NumberInt(40),
"ConnectingQuestions" : [
    {
        "_id" : "5a130570738634297478fb43",
        "QuestionNumber" : NumberInt(1),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title1",
     },
     {
        "_id" : "5a130570738634297478fb76",
        "QuestionNumber" : NumberInt(2),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title2",
     },
     {
        "_id" : "5a130570738634297478fb23",
        "QuestionNumber" : NumberInt(3),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title3",
     }
    ]
}
{
"_id" : "59e850f95322e01e88f131c1",
"Name" : "Second Level",
"Number" : NumberInt(2),
"TotalScore" : NumberInt(8000),
"QuestionCount" : NumberInt(20),
"ConnectingQuestions" : [
    {
        "_id" : "5a130570738634297478fa56",
        "QuestionNumber" : NumberInt(1),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title1",
     },
     {
        "_id" : "5a130570738634297478fb66",
        "QuestionNumber" : NumberInt(2),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title2",
     },
     {
        "_id" : "5a130570738634297478fe32",
        "QuestionNumber" : NumberInt(3),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title3",
     }
    ]
}
</code>```

i need to write Query in c# that first select level with specified id and in selected level, select and return "ConnectingQuestion" subcollection with certain "QuestionNumber" in type of ConnectingQuestion class and not BsonDocument.
A pseudo-query like this:

```<code> ConnectingQuestion cq = MongoDB.Levels.find(level.id == "59e850f95322e01e88f131c1" && level.ConnectingQuestions.QuestionNumber == 2).Projection(level.ConnectingQuestions).SingleOrDefault();
</code>```

答:
Here are two possible solutions - there may be simpler ones...

Version 1: Using find() and project() only plus some BSON magic

```<code>var collection = new MongoClient().GetDatabase("test").GetCollection<Level>("test");

var projection = Builders<Level>.Projection.ElemMatch(level => level.ConnectingQuestions, q => q.QuestionNumber == 2);
var bsonDocument = collection
    // filter out anything that we're not interested in
    .Find(level => level.Id == "59e850f95322e01e88f131c1")
    .Project(projection)
    .First();
// get first (single!) item from "ConnectingQuestions" array
bsonDocument = bsonDocument.GetElement("ConnectingQuestions").Value.AsBsonArray[0].AsBsonDocument;
// deserialize bsonDocument into ConnectingQuestions instance
ConnectingQuestion cq = BsonSerializer.Deserialize<ConnectingQuestion>(bsonDocument);
</code>```

Version 2: Using the aggregation framework ($filter needs MongoDB >= v3.2)

```<code>var collection = new MongoClient().GetDatabase("test").GetCollection<Level>("test");

var cq = collection.Aggregate()
    // filter out anything that we're not interested in
    .Match(level => level.Id == "59e850f95322e01e88f131c1")
    // filter the ConnectingQuestions array to only include the element with QuestionNumber == 2
    .Project<Level>("{ 'ConnectingQuestions': { $filter: { input: '$ConnectingQuestions', cond: { $eq: [ '$$this.QuestionNumber', 2 ] } } } }")
    // move the first (single!) item from "ConnectingQuestions" array to the document root level
    .ReplaceRoot(q => q.ConnectingQuestions.ElementAt(0))
    .FirstOrDefault();
</code>```

Body:
Hi. I have a Collection named "Level" with this class structure :

    public class Level
    {
      [BsonId]
      public string Id {get; set;}
      public string Name { get; set; }
      public int Number { get; set; }
      public int TotalScore { get; set; }
      public int QuestionCount { get; set; }
      public IEnumerable<ConnectingQuestion> ConnectingQuestions { get; set; }
    }
    public class ConnectingQuestion
    {
      [BsonId]
      public string Id { get; set; }
      public int QuestionNumber { get; set; }
      public string Description { get; set; }
      public string Type { get; set; }
      public string Title { get; set; }
    }

and collection structure like this :

{
"_id" : "64e850f95322e01e88f131a2",
"Name" : "First Level",
"Number" : NumberInt(1),
"TotalScore" : NumberInt(2690),
"QuestionCount" : NumberInt(40),
"ConnectingQuestions" : [
    {
        "_id" : "5a130570738634297478fb43",
        "QuestionNumber" : NumberInt(1),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title1",
     },
     {
        "_id" : "5a130570738634297478fb76",
        "QuestionNumber" : NumberInt(2),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title2",
     },
     {
        "_id" : "5a130570738634297478fb23",
        "QuestionNumber" : NumberInt(3),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title3",
     }
    ]
}
{
"_id" : "59e850f95322e01e88f131c1",
"Name" : "Second Level",
"Number" : NumberInt(2),
"TotalScore" : NumberInt(8000),
"QuestionCount" : NumberInt(20),
"ConnectingQuestions" : [
    {
        "_id" : "5a130570738634297478fa56",
        "QuestionNumber" : NumberInt(1),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title1",
     },
     {
        "_id" : "5a130570738634297478fb66",
        "QuestionNumber" : NumberInt(2),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title2",
     },
     {
        "_id" : "5a130570738634297478fe32",
        "QuestionNumber" : NumberInt(3),
        "Description" : "desc",
        "Type" : "sc",
        "Title" : "title3",
     }
    ]
}

i need to write Query in c# that first select level with specified id and in selected level, select and return "ConnectingQuestion" subcollection with certain "QuestionNumber" in type of ConnectingQuestion class and not BsonDocument.
A pseudo-query like this:

 ConnectingQuestion cq = MongoDB.Levels.find(level.id == "59e850f95322e01e88f131c1" && level.ConnectingQuestions.QuestionNumber == 2).Projection(level.ConnectingQuestions).SingleOrDefault();

Body:
Here are two possible solutions - there may be simpler ones...

Version 1: Using find() and project() only plus some BSON magic

var collection = new MongoClient().GetDatabase("test").GetCollection<Level>("test");

var projection = Builders<Level>.Projection.ElemMatch(level => level.ConnectingQuestions, q => q.QuestionNumber == 2);
var bsonDocument = collection
    // filter out anything that we're not interested in
    .Find(level => level.Id == "59e850f95322e01e88f131c1")
    .Project(projection)
    .First();
// get first (single!) item from "ConnectingQuestions" array
bsonDocument = bsonDocument.GetElement("ConnectingQuestions").Value.AsBsonArray[0].AsBsonDocument;
// deserialize bsonDocument into ConnectingQuestions instance
ConnectingQuestion cq = BsonSerializer.Deserialize<ConnectingQuestion>(bsonDocument);

Version 2: Using the aggregation framework ($filter needs MongoDB >= v3.2)

var collection = new MongoClient().GetDatabase("test").GetCollection<Level>("test");

var cq = collection.Aggregate()
    // filter out anything that we're not interested in
    .Match(level => level.Id == "59e850f95322e01e88f131c1")
    // filter the ConnectingQuestions array to only include the element with QuestionNumber == 2
    .Project<Level>("{ 'ConnectingQuestions': { $filter: { input: '$ConnectingQuestions', cond: { $eq: [ '$$this.QuestionNumber', 2 ] } } } }")
    // move the first (single!) item from "ConnectingQuestions" array to the document root level
    .ReplaceRoot(q => q.ConnectingQuestions.ElementAt(0))
    .FirstOrDefault();


问:
Keeping track of UI State in an angularJS app
Intro:
I'm working on a web app using ui-router, and using nested views/controllers. There are several UI elements across the app that need to communicate, and who's actions may be dependent on another one's state.

Example:
For example, I have a "dropdown" element that functions like a typical  dropdown menu. A "dropdown" could exist in any controller, but only one should be open at any given time. That is, if the user opens a dropdown menu, it should also close all other dropdown menus.

Proposed Solution:
My current solution is to $emit an event when a "dropdown" is clicked on, listen for it in the top-most parent controller, and $broadcast an even to close all dropdowns, then catch that event in every other controller.

There are other elements whose state I would like to keep track of, such as the main sidebar (expanded, or collapsed), with a more complicated array of events (size of screen, clicking on an item in the sidebar, clicking on a "menu" button) it seems...messy to have to bounce events around.

tl;dr:
Is the standard way to communicate a UI element's state (visible/invisible, expanded/collapsed) across controllers to $emit and $broadcast events?

Edit:
Another option I thought of is to create a $watch in the children controllers to keep track of a global "ui element state" variable in the top most parent controller. Similar to what I described above, but without the $broadcast.

答:
Experience and new best practices have led me to different solutions:

I eventually solved this many years later with a Service dedicated to broadcasting events. Rather than using $rootScope everywhere, this service gets $injected and used instead.

This service can then send custom events to any controllers listening, which allows you to close menus based on.

I have also solved this with a global click event listener. Each dropdown creates a listener, and will close itself if it notices a click that is outside of its element's $scope.


问:
How to extract paragraphs separated by a comma?
This is a piece of code from which I am trying to obtain data.

```<code><p>ul. Niecała 10</p>
<p>05-800 Pruszków</p>

</div>
</code>```

I did it this way:

```<code>address = result.find('div', attrs={'class': 'section address'}).get_text()
</code>```

Unfortunately, the result does not satisfy me. The texts from the paragraphs are stuck together. I would like these paragraphs to be separated by a comma.

Now:

```<code>ul. Niecała 1005-800 Pruszków
</code>```

I would like it to be:

```<code>ul. Niecała 10, 05-800 Pruszków
</code>```

How do I do that? Do you have any suggestions?

答:
Use the stripped_strings generator and join by ', ' (if you want a string), example:

```<code>address = ', '.join(result.find('div', class_='section address').stripped_strings)
</code>```

Body:
This is a piece of code from which I am trying to obtain data.

ul. Niecała 10

05-800 Pruszków

I did it this way:

address = result.find('div', attrs={'class': 'section address'}).get_text()

Unfortunately, the result does not satisfy me. The texts from the paragraphs are stuck together. I would like these paragraphs to be separated by a comma.

Now:

ul. Niecała 1005-800 Pruszków

I would like it to be:

ul. Niecała 10, 05-800 Pruszków

How do I do that? Do you have any suggestions?

Body:
Use the stripped_strings generator and join by ', ' (if you want a string), example:

address = ', '.join(result.find('div', class_='section address').stripped_strings)


问:
No decode delegate for this image format `PDF'

I'm trying to convert some PDFs to jpegs using imagemagick . I'm working on win 10, 64 with python 3.62 - 64 bit and wand 0.4.4. I've been able to get wand working with ImageMagick-6.9.9-Q16-HDRI. I've set the Path and MAGICK_HOME env vars  to

```<code>E:\ImageMagick-6.9.9-Q16-HDR
</code>```

This allow:

```<code>from wand.image import Image
</code>```

to work.

My script:

```<code>import os
magick_home=os.getcwd() + os.sep + "E:\ImageMagick-6.9.9-Q16-HDR"
os.environ["PATH"] += os.pathsep + magick_home + os.sep
os.environ["MAGICK_HOME"] = magick_home
os.environ["MAGICK_CODER_MODULE_PATH"] = magick_home + os.sep + "modules" + os.sep + "coders"

from wand.image import Image

.....

file_path = os.path.dirname(os.path.abspath(__file__))+os.sep+"myfile.pdf"

image_pdf = Image(filename=file_path, resolution=300)
image_jpeg = image_pdf.convert('jpeg')
</code>```

I'm getting:

```<code>  File "ocr_test.py", line 38, in <module>
    image_pdf = Image(filename=file_path, resolution=300)
  File "e:\Myenv\lib\site-packages\wand\image.py", line 2744, in __init__
    self.read(filename=filename, resolution=resolution)
  File "e:\Myenv\lib\site-packages\wand\image.py", line 2822, in read
    self.raise_exception()
  File "e:\Myenv\lib\site-packages\wand\resource.py", line 222, in raise_exception
    raise e
wand.exceptions.MissingDelegateError: no decode delegate for this image format `PDF' @ error/constitute.c/ReadImage/504
</code>```

How can I get this working?

EDIT:

Following your advice, I followed https://glenbambrick.com/2017/01/10/pdf-to-jpg-conversion-with-python-for-windows/ and installed ghostscript 9.22 - 32 bit. (I understand that the 64 bit won't work PythonMagick can't find my pdf files)
I've set both Path and MAGICK_HOME env vars  to contain:

```<code>E:\ImageMagick-6.9.9-Q16-HDR;E:\gs9.22\bin
</code>```

I ran:

```<code>$ E:/ImageMagick-6.9.9-Q16-HDRI/convert --version
Version: ImageMagick 6.9.9-23 Q16 x64 2017-11-12 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2015 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Visual C++: 180040629
Features: Cipher DPC HDRI Modules OpenMP
Delegates (built-in): bzlib cairo flif freetype jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib
</code>```

I don't see gs or gslib. What should I do next?

答:
I don't know if this will help anybody, but for me MAGICK_HOME does not appear to be recognized by windows. I ended up putting :

```<code>E:/gs/bin
</code>```

at the beginning of My PATH env var, and things started working.

Body:
I'm trying to convert some PDFs to jpegs using imagemagick . I'm working on win 10, 64 with python 3.62 - 64 bit and wand 0.4.4. I've been able to get wand working with ImageMagick-6.9.9-Q16-HDRI. I've set the Path and MAGICK_HOME env vars  to

E:\ImageMagick-6.9.9-Q16-HDR

This allow:

from wand.image import Image

to work.

My script:

import os
magick_home=os.getcwd() + os.sep + "E:\ImageMagick-6.9.9-Q16-HDR"
os.environ["PATH"] += os.pathsep + magick_home + os.sep
os.environ["MAGICK_HOME"] = magick_home
os.environ["MAGICK_CODER_MODULE_PATH"] = magick_home + os.sep + "modules" + os.sep + "coders"

from wand.image import Image

.....

file_path = os.path.dirname(os.path.abspath(__file__))+os.sep+"myfile.pdf"

image_pdf = Image(filename=file_path, resolution=300)
image_jpeg = image_pdf.convert('jpeg')

I'm getting:

  File "ocr_test.py", line 38, in <module>
    image_pdf = Image(filename=file_path, resolution=300)
  File "e:\Myenv\lib\site-packages\wand\image.py", line 2744, in __init__
    self.read(filename=filename, resolution=resolution)
  File "e:\Myenv\lib\site-packages\wand\image.py", line 2822, in read
    self.raise_exception()
  File "e:\Myenv\lib\site-packages\wand\resource.py", line 222, in raise_exception
    raise e
wand.exceptions.MissingDelegateError: no decode delegate for this image format `PDF' @ error/constitute.c/ReadImage/504

How can I get this working?

EDIT:

Following your advice, I followed https://glenbambrick.com/2017/01/10/pdf-to-jpg-conversion-with-python-for-windows/ and installed ghostscript 9.22 - 32 bit. (I understand that the 64 bit won't work PythonMagick can't find my pdf files)
I've set both Path and MAGICK_HOME env vars  to contain:

E:\ImageMagick-6.9.9-Q16-HDR;E:\gs9.22\bin

I ran:

$ E:/ImageMagick-6.9.9-Q16-HDRI/convert --version
Version: ImageMagick 6.9.9-23 Q16 x64 2017-11-12 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2015 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Visual C++: 180040629
Features: Cipher DPC HDRI Modules OpenMP
Delegates (built-in): bzlib cairo flif freetype jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib

I don't see gs or gslib. What should I do next?

Body:
I don't know if this will help anybody, but for me MAGICK_HOME does not appear to be recognized by windows. I ended up putting :

E:/gs/bin

at the beginning of My PATH env var, and things started working.


问:
What's the difference between the assignment operator vs equal operator in C
```<code>int main(){

   int x = 5580, y = 55098;

   printf( "%d\n", y = x);

   return 0;

}
</code>```

Why does this print the value of y?  I thought the value of x was being assigned to y but thats not the case.

答: That's expected behavior in C and other languages. Your title of the question also is not worded very well. The assignment operator "is" the equal operator, and that is exactly what you are using. You might be getting confused by the order of operations in C. On your printf line, the expression y = x happens first, and the resulting value (y) is used as a parameter in your printf function, which is why you see the value of y printed. This is one of the fundamentals of C. I would recommend reading up on C syntax.

Body:
int main(){

   int x = 5580, y = 55098;

   printf( "%d\n", y = x);

   return 0;

}

Why does this print the value of y?  I thought the value of x was being assigned to y but thats not the case.


问:
how to set index.html to another page, not homepage
I want to show index.html on special page '/chess', not on home page '/'.

Simple

```<code>app.get('/chess', function(req, res) {
 res.sendFile(__dirname + '/public/index.html');

});
</code>```

doesn't work.

I get the below error

答:
Using the code below i was able to remap

route '/chess' to serve index.html,

And

route '/' to serve select.html.

```<code>const express = require("express");
const app = express();

app
    .get("/", (req, res)=>{
        res.sendFile(__dirname + "/public/select.html");
    })
    .get("/chess", (req, res)=>{
        res.sendFile(__dirname + "/public/index.html");
    });

app.listen(3000, () => console.log("Example app listening on port 3000!"));
</code>```

Can you post more of you application to see if there is another problem?

Body:
I want to show index.html on special page '/chess', not on home page '/'.

Simple

app.get('/chess', function(req, res) {
 res.sendFile(__dirname + '/public/index.html');

});

doesn't work.

I get the below error

Body:
Using the code below i was able to remap

route '/chess' to serve index.html,

And

route '/' to serve select.html.

const express = require("express");
const app = express();

app
    .get("/", (req, res)=>{
        res.sendFile(__dirname + "/public/select.html");
    })
    .get("/chess", (req, res)=>{
        res.sendFile(__dirname + "/public/index.html");
    });

app.listen(3000, () => console.log("Example app listening on port 3000!"));

Can you post more of you application to see if there is another problem?


问:
Difference between rows of different variables, avoiding macro method
I am trying to find the average time between two processes. Each record is a repair process with an part ID, a start date, and an end date. For a given ID, only one repair process can occur at a time. See sample data below:

```<code>ID  START_DATE  END_DATE
123  1/2/2006   2/3/2006
124  1/3/2006   4/2/2006
123  3/5/2006   3/7/2006
123  6/2/2006   6/4/2006
123  6/8/2006   6/9/2006
124  6/2/2006   6/4/2006
124  6/5/2006   6/9/2006
124  6/10/2006   6/12/2006
</code>```

The information I need is the difference between the END_DATE and START_DATE for a given ID. For example, for ID 123, the time between its first process and the second process is 3/5/2006 - 2/3/2006. If the list were longer, I would then take the all those differences and take the average of them.

The output would be something like this:

```<code>ID  AverageTime
123   4.3
124   2.3
</code>```

My approach is to create a macro based on the following steps:

Create list of unique IDs.

For each ID in list, create table
of just that ID.

Calculate the difference between START_DATE and
END_DATE for that ID using the LAG function.

Average the
difference and append to list of unique IDs.

I think this would work, but may take a long time because there are 400k rows. Is there a way to do this without a macro? How might this process be optimized as the server I am running this on is very slow?

答:
Here is the "SAS-y" way of doing it.

First your data:

```<code>data have;
input ID  START_DATE  END_DATE;
informat start_date end_date mmddyy10.;
format start_date end_date mmddyy10.;
datalines;
123  1/2/2006   2/3/2006
124  1/3/2006   4/2/2006
123  3/5/2006   3/7/2006
123  6/2/2006   6/4/2006
123  6/8/2006   6/9/2006
124  6/2/2006   6/4/2006
124  6/5/2006   6/9/2006
124  6/10/2006   6/12/2006
;
</code>```

Sort by the ID and Start_Date:

```<code>proc sort data=have;
by id start_date;
run;
</code>```

Next add a record count for each id and a link to the previous one.

```<code>data tmp;
set have;
by id;
if first.id then
    id_cnt = 0;

id_cnt + 1;
id_last = id_cnt-1;
run;
</code>```

Then join the data to itself taking the mean of the difference between first end and next start:

```<code>proc sql noprint;
create table want as
select a.id
     , mean(b.start_date - a.end_date) as ave
    from tmp as a,
         tmp as b
    where a.id=b.id and
          a.id_cnt=b.id_last
    group by a.id;
quit;
</code>```

Body:
I am trying to find the average time between two processes. Each record is a repair process with an part ID, a start date, and an end date. For a given ID, only one repair process can occur at a time. See sample data below:

ID  START_DATE  END_DATE
123  1/2/2006   2/3/2006
124  1/3/2006   4/2/2006
123  3/5/2006   3/7/2006
123  6/2/2006   6/4/2006
123  6/8/2006   6/9/2006
124  6/2/2006   6/4/2006
124  6/5/2006   6/9/2006
124  6/10/2006   6/12/2006

The information I need is the difference between the END_DATE and START_DATE for a given ID. For example, for ID 123, the time between its first process and the second process is 3/5/2006 - 2/3/2006. If the list were longer, I would then take the all those differences and take the average of them.

The output would be something like this:

ID  AverageTime
123   4.3
124   2.3

My approach is to create a macro based on the following steps:

Create list of unique IDs.

For each ID in list, create table
of just that ID.

Calculate the difference between START_DATE and
END_DATE for that ID using the LAG function.

Average the
difference and append to list of unique IDs.

I think this would work, but may take a long time because there are 400k rows. Is there a way to do this without a macro? How might this process be optimized as the server I am running this on is very slow?

Body:
Here is the "SAS-y" way of doing it.

First your data:

data have;
input ID  START_DATE  END_DATE;
informat start_date end_date mmddyy10.;
format start_date end_date mmddyy10.;
datalines;
123  1/2/2006   2/3/2006
124  1/3/2006   4/2/2006
123  3/5/2006   3/7/2006
123  6/2/2006   6/4/2006
123  6/8/2006   6/9/2006
124  6/2/2006   6/4/2006
124  6/5/2006   6/9/2006
124  6/10/2006   6/12/2006
;

Sort by the ID and Start_Date:

proc sort data=have;
by id start_date;
run;

Next add a record count for each id and a link to the previous one.

data tmp;
set have;
by id;
if first.id then
    id_cnt = 0;

id_cnt + 1;
id_last = id_cnt-1;
run;

Then join the data to itself taking the mean of the difference between first end and next start:

proc sql noprint;
create table want as
select a.id
     , mean(b.start_date - a.end_date) as ave
    from tmp as a,
         tmp as b
    where a.id=b.id and
          a.id_cnt=b.id_last
    group by a.id;
quit;


问:
Calling variables to sub function?
I have a post variable and I want to use it my sub function. How can I do that ? When I tried it says "Undefined Variable".

Controller

```<code>public function getSingle($slug){

    $post = Post::where('slug',$slug)->first();

    $related_categories_posts = Post::whereHas('categories',function ($query){
        $query->where('category_name', $post->categories->category_name);
    })
    ->take(3)
    ->get();

    return view('frontend.single')
            ->with('post',$post)
            ->with('related_categories_posts',$related_categories_posts);
}
</code>```

Any advice ?

答:
You need to pass this variable to the function by using use as described in the docs.

```<code>$related_categories_posts = Post::whereHas('categories', function ($query) use ($post){
    $query->where('category_name', $post->categories->category_name);
})
</code>```

Title: Calling variables to sub function?

Body:
I have a post variable and I want to use it my sub function. How can I do that ? When I tried it says "Undefined Variable".

Controller

public function getSingle($slug){

    $post = Post::where('slug',$slug)->first();

    $related_categories_posts = Post::whereHas('categories',function ($query){
        $query->where('category_name', $post->categories->category_name);
    })
    ->take(3)
    ->get();

    return view('frontend.single')
            ->with('post',$post)
            ->with('related_categories_posts',$related_categories_posts);
}

Any advice ?

Body:
You need to pass this variable to the function by using use as described in the docs.

$related_categories_posts = Post::whereHas('categories', function ($query) use ($post){
    $query->where('category_name', $post->categories->category_name);
})


问:
Online compilers/runtime for Java, C++, Python and ObjC?
Does anyone know of a good online compiler/runtime (for C++, Java, Python, ObjC etc.) that I can access on the web?

What I'm looking for is something that would allow me to type in a program in a web form and to run the program and see the results online.

(Let's not get into the why for now. Suffice it to say for the moment that I don't always have access to a compiler/runtime, and firing up an IDE is just overkill for testing out some code snippets)

I know of codepad.org -- but I'm looking for something better.

答:
I found this online java compiler and runner. It works in realtime and also with threads. Amazing !
http://www.browxy.com</p>

OwnerDisplayName: Debajit

ContentLicense: CC BY-SA 2.5


问:
Check that system passes all the states
A variable state stands for state of a system, for instance state \in {"ready", "prepare", "do", "cleanup", "done"}. How to express condition that state should eventually pass all the five states (in any order)?

Working example (accepted answer):

```<code>EXTENDS Naturals
VARIABLE n
Init == n = 1
Next == IF n < 3 THEN n' = n + 1 ELSE n' = n
Spec == Init /\ [][Next]_<<n>> /\ WF_<<n>>(Next)
Check == \A s \in {1,2,3}: <>(s = n)    \* This goes: Model Overview >
                                        \* > "What to check?" > Properties
</code>```

答:
Given States = {"ready", "prepare", "do", "cleanup", "done"}, you can check that it reaches some given state with

```<code><>(state = "ready")
</code>```

And you can check that it reaches all states with

```<code>\A s \in States: <>(state = s)
</code>```

Title: Check that system passes all the states

Body:
A variable state stands for state of a system, for instance state \in {"ready", "prepare", "do", "cleanup", "done"}. How to express condition that state should eventually pass all the five states (in any order)?

Working example (accepted answer):

EXTENDS Naturals
VARIABLE n
Init == n = 1
Next == IF n < 3 THEN n' = n + 1 ELSE n' = n
Spec == Init /\ [][Next]_<<n>> /\ WF_<<n>>(Next)
Check == \A s \in {1,2,3}: <>(s = n)    \* This goes: Model Overview >
                                        \* > "What to check?" > Properties

Body:
Given States = {"ready", "prepare", "do", "cleanup", "done"}, you can check that it reaches some given state with

<>(state = "ready")

And you can check that it reaches all states with

\A s \in States: <>(state = s)


问:
What version of Docker is my Kubernetes running on?
Kubernetes uses Docker, and kubelet dictates the compatible Docker versions for any given cluster.

My question is, given a Kubernetes cluster that is already configured and running, how would I find out what version of Docker is running in the cluster if I don't have direct access to the nodes?

答:
The following kubectl command will show detail information of the nodes in the cluster:

```<code>kubectl describe nodes
</code>```

One instance of a node is shown below:

```<code>Name:               node3-virtualbox
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/hostname=node3-virtualbox
Annotations:        node.alpha.kubernetes.io/ttl=0
                    volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:             <none>
CreationTimestamp:  Tue, 05 Dec 2017 07:01:42 +0100
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  OutOfDisk        False   Tue, 05 Dec 2017 22:52:05 +0100   Tue, 05 Dec 2017 17:08:13 +0100   KubeletHasSufficientDisk     kubelet has sufficient disk space available
  MemoryPressure   False   Tue, 05 Dec 2017 22:52:05 +0100   Tue, 05 Dec 2017 21:08:21 +0100   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Tue, 05 Dec 2017 22:52:05 +0100   Tue, 05 Dec 2017 21:08:21 +0100   KubeletHasNoDiskPressure     kubelet has no disk pressure
  Ready            False   Tue, 05 Dec 2017 22:52:05 +0100   Tue, 05 Dec 2017 21:08:21 +0100   KubeletNotReady              runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Addresses:
  InternalIP:  10.0.2.15
  Hostname:    node3-virtualbox
Capacity:
 cpu:     1
 memory:  2048268Ki
 pods:    110
Allocatable:
 cpu:     1
 memory:  1945868Ki
 pods:    110
System Info:
 Machine ID:                 9654f9402bfc4042b82b454e323cf46c
 System UUID:                6EBA3E13-624C-4C82-A8EA-24FF86FA6E66
 Boot ID:                    c7217654-8514-482c-9899-f04a3d3ce6d8
 Kernel Version:             4.4.0-101-generic
 OS Image:                   Ubuntu 16.04.1 LTS
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  docker://1.13.1
 Kubelet Version:            v1.8.4
 Kube-Proxy Version:         v1.8.4
ExternalID:                  node3-virtualbox
Non-terminated Pods:         (2 in total)
  Namespace                  Name                CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ---------                  ----                ------------  ----------  ---------------  -------------
  kube-system                kube-proxy-sxp5s    0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                weave-net-6jf98     20m (2%)      0 (0%)      0 (0%)           0 (0%)
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ------------  ----------  ---------------  -------------
  20m (2%)      0 (0%)      0 (0%)           0 (0%)
Events:         <none>
</code>```

The docker version running on the nodes can be found in system info:, for example in above case:

Container Runtime Version:  docker://1.13.1

Body:
The following kubectl command will show detail information of the nodes in the cluster:

kubectl describe nodes

One instance of a node is shown below:

Name:               node3-virtualbox
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/hostname=node3-virtualbox
Annotations:        node.alpha.kubernetes.io/ttl=0
                    volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:             <none>
CreationTimestamp:  Tue, 05 Dec 2017 07:01:42 +0100
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  OutOfDisk        False   Tue, 05 Dec 2017 22:52:05 +0100   Tue, 05 Dec 2017 17:08:13 +0100   KubeletHasSufficientDisk     kubelet has sufficient disk space available
  MemoryPressure   False   Tue, 05 Dec 2017 22:52:05 +0100   Tue, 05 Dec 2017 21:08:21 +0100   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Tue, 05 Dec 2017 22:52:05 +0100   Tue, 05 Dec 2017 21:08:21 +0100   KubeletHasNoDiskPressure     kubelet has no disk pressure
  Ready            False   Tue, 05 Dec 2017 22:52:05 +0100   Tue, 05 Dec 2017 21:08:21 +0100   KubeletNotReady              runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
Addresses:
  InternalIP:  10.0.2.15
  Hostname:    node3-virtualbox
Capacity:
 cpu:     1
 memory:  2048268Ki
 pods:    110
Allocatable:
 cpu:     1
 memory:  1945868Ki
 pods:    110
System Info:
 Machine ID:                 9654f9402bfc4042b82b454e323cf46c
 System UUID:                6EBA3E13-624C-4C82-A8EA-24FF86FA6E66
 Boot ID:                    c7217654-8514-482c-9899-f04a3d3ce6d8
 Kernel Version:             4.4.0-101-generic
 OS Image:                   Ubuntu 16.04.1 LTS
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  docker://1.13.1
 Kubelet Version:            v1.8.4
 Kube-Proxy Version:         v1.8.4
ExternalID:                  node3-virtualbox
Non-terminated Pods:         (2 in total)
  Namespace                  Name                CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ---------                  ----                ------------  ----------  ---------------  -------------
  kube-system                kube-proxy-sxp5s    0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                weave-net-6jf98     20m (2%)      0 (0%)      0 (0%)           0 (0%)
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ------------  ----------  ---------------  -------------
  20m (2%)      0 (0%)      0 (0%)           0 (0%)
Events:         <none>

The docker version running on the nodes can be found in system info:, for example in above case:

Container Runtime Version:  docker://1.13.1


问:
Losing data when rotate screen
I have a little funny bug in my application. When the user rotates the screen I lose some of the data in my activity. Anyone that have an idea of why this happens? </p>

答:
In the AndroidManifest.xml add the following code

<activity android:name=".MainActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            >

Title: Losing data when rotate screen


问:
Asp.Net Mvc Url.Action in external js file?
In external js file, I cant use

```<code>url = "@Url.Action("Action", "Controller")"
//url output : @Url.Action("Action", "Controller")
//I get IllegalPath Name error.
</code>```

When I write like this:

```<code>url = "/Controller/Action"
</code>```

And If project is under a sub folder, then scripts do not work. I need something like this as relative Url:

```<code>url = "~/Controller/Action"
</code>```

How can ı do this? Thanks.

答:
Here's a pattern I've been using.  It's a bit more steps, but I like that all of  my urls are in one organized location in the View.

At the bottom of my View I will include a Scripts Section that contains the urls like so:

```<code>@section Scripts
{
    <script type="text/javascript">
        myJavaScriptObject.firstUrl = '@Url.Action("Action1", "Controller", new {id = Model.Id})';
        myJavaScriptObject.secondUrl = '@Url.Action("Action2", "Controller", new {id = Model.Id})';
    </script>
}
</code>```

Inside of my JavaScript Class (which is in an external file)  I will reference the url like so:

```<code>var myJavaScriptObject = {
    firstUrl: '',
    secondUrl: '',
    docReady: function() {
        $.get(myJavaScriptObject.firstUrl, function(data) { do something...  });
    }
}
</code>```

I realize the entries don't need to be referenced inside of the Class, but I like to have them there for my own housekeeping.

Body:
In external js file, I cant use

url = "@Url.Action("Action", "Controller")"
//url output : @Url.Action("Action", "Controller")
//I get IllegalPath Name error.

When I write like this:

url = "/Controller/Action"

And If project is under a sub folder, then scripts do not work. I need something like this as relative Url:

url = "~/Controller/Action"

How can ı do this? Thanks.

Body:
Here's a pattern I've been using.  It's a bit more steps, but I like that all of  my urls are in one organized location in the View.

At the bottom of my View I will include a Scripts Section that contains the urls like so:

@section Scripts
{
    <script type="text/javascript">
        myJavaScriptObject.firstUrl = '@Url.Action("Action1", "Controller", new {id = Model.Id})';
        myJavaScriptObject.secondUrl = '@Url.Action("Action2", "Controller", new {id = Model.Id})';
    </script>
}

Inside of my JavaScript Class (which is in an external file)  I will reference the url like so:

var myJavaScriptObject = {
    firstUrl: '',
    secondUrl: '',
    docReady: function() {
        $.get(myJavaScriptObject.firstUrl, function(data) { do something...  });
    }
}

I realize the entries don't need to be referenced inside of the Class, but I like to have them there for my own housekeeping.


问:
How can I use the hide/show toggle when clicking on text?
I would like to click on the first line of text, which will then expand the rest of the paragraph. But I also want to be able to close the text by clicking on that same first line again. I have written some code for it, but I am very elementary in JS. I would appreciate getting help on this. Thank you.

Here's my JSFiddle: http://jsfiddle.net/JUtcX/868/

$('.expand').each(function() {
  var reducedHeight = $(this).height();
  $(this).css('height', 'auto');
  var fullHeight = $(this).height();
  $(this).height(reducedHeight);

  $(this).data('reducedHeight', reducedHeight);
  $(this).data('fullHeight', fullHeight);
}).click(function() {
  $(this).animate({
    height: $(this).height() ==
      $(this).data('reducedHeight') ? $(this).data('fullHeight') : $(this).data('reducedHeight')
  }, 500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.expand {
  height: 14pt;
  padding: 2px;
  overflow: hidden
}</code>```

  The day after his forty-eighth birthday was the same day Theo Bitner’s seventy-five-year-old mother Friended him on Facebook. It was also the same day his wife told him he needed to see a doctor. Or a therapist. “It’s your mood,” she said. “It sucks.”

```

答:
check this way:

```<code>$('.expand').click(function(){
    if($(this).hasClass( "open" )){
    $(this).removeClass("open");
  }else{
    $(this).addClass("open");
  }
});
</code>```

I just checked if the paragraph were open, and after that I add or remove the class .open to the content.

the css:

```<code>.expand {
    max-height: 14pt;
    padding: 2px;
    overflow: hidden;
    transition: max-height 0.5s;
}

.expand.open{
   max-height: 15em;
}
</code>```

here the fiddle

hope it helps you.

Body:
I would like to click on the first line of text, which will then expand the rest of the paragraph. But I also want to be able to close the text by clicking on that same first line again. I have written some code for it, but I am very elementary in JS. I would appreciate getting help on this. Thank you.

Here's my JSFiddle: http://jsfiddle.net/JUtcX/868/

$('.expand').each(function() {
  var reducedHeight = $(this).height();
  $(this).css('height', 'auto');
  var fullHeight = $(this).height();
  $(this).height(reducedHeight);

  $(this).data('reducedHeight', reducedHeight);
  $(this).data('fullHeight', fullHeight);
}).click(function() {
  $(this).animate({
    height: $(this).height() ==
      $(this).data('reducedHeight') ? $(this).data('fullHeight') : $(this).data('reducedHeight')
  }, 500);
});

.expand {
  height: 14pt;
  padding: 2px;
  overflow: hidden
}

  The day after his forty-eighth birthday was the same day Theo Bitner’s seventy-five-year-old mother Friended him on Facebook. It was also the same day his wife told him he needed to see a doctor. Or a therapist. “It’s your mood,” she said. “It sucks.”

Body:
check this way:

$('.expand').click(function(){
    if($(this).hasClass( "open" )){
    $(this).removeClass("open");
  }else{
    $(this).addClass("open");
  }
});

I just checked if the paragraph were open, and after that I add or remove the class .open to the content.

the css:

.expand {
    max-height: 14pt;
    padding: 2px;
    overflow: hidden;
    transition: max-height 0.5s;
}

.expand.open{
   max-height: 15em;
}

here the fiddle

hope it helps you.


问:
Asymptotic notation properties proofs?
I am trying to prove that if f(n) and g(n) are asymptotically positive functions, then:

f(n) = O((f(n))^2)

f(n) = O(g(n)) implies 2^(f(n)) = O(2^(g(n)))

f(n) = O(g(n)) implies g(n) = O(f(n))

答:
f(n) = O((f(n))2)

Any function is by default big-O of itself, i.e. we can use a bigger constant cbig such that f(n) <= cbig.f(n).

Thus,

if f(n) is less than or equal to cbig.f(n),

then f(n) will definitely be less than or equal to cbig.f(n).f(n), for asymptotically positive f(n).

Mathematically, f(n) = O(f(n).f(n)) = O(f(n)2) is true.

f(n) = O(g(n)) implies 2f(n) = O(2g(n))

f(n) = O(g(n)) implies that f(n) <= g(n)

Also, if some positive number n is less than m, then 2n will be less than 2m

Using 1. and 2. above, we can conclude that if f(n) = O(g(n)), then 2f(n) = O(2g(n))

f(n) = O(g(n)) implies g(n) = O(f(n))

This one is wrong.

f(n) = O(g(n)) implies g(n) = Ω(f(n)).

If f(n) = O(g(n)), then f(n) is upper bound by g(n) which means that g(n) is lower bound by f(n), therefore g(n) = Ω(f(n)).

Title: Asymptotic notation properties proofs?


问:
SmartyStreets Jquery thingie not binding to address fields in a modal?
situation is not limited to SmartyStreet's Website Plugin, but its the latest symptom:

A page opens a modal with the following form:

<form id="frmCreateDonorPerson" action="/donor/createPerson" method="post">
   <input type="text" id="txtLine1" name="txtLine1">
   etc.
   etc.
</form>

And the following javascript, which without the modal situation (i.e. when I navigate straight to the page), had no issue creating a SmartyStreets address validator Jquery experience:

var ss = jQuery.LiveAddress({
    key: "30340983409834098",
    target: "US",
    addresses: [{
            address1: '#txtLine1',
            etc.
            etc.
    }]
});

I'm expecting real-time options to be populated by SmartyStreet's website plug while anything is being entered into the "Line1" box.

But...nada.

I've noticed symptoms of this weirdness in other similar situations ("Jquery in a modal"), and I've researched solutions to that problem phrase, but no solutions seem to answer this one..

Thx super much in advance!!!

答: I think by default SmartyStreets object attaches itself to the address field and finds the parent form element within that page.  Does your modal use an iframe or is it inline?  If its an iframe, I think it will have trouble locating the form.</p>


问:
Can't submit apps to AppStore: ERROR ITMS-90534: "Invalid Toolchain

ERROR ITMS-90534: "Invalid Toolchain.

New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds." ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

I found this error during upload IPA to account.

答:
For XCode 9.2
Problem mostly in Command Line Tools version.

Best solution:

Reinstall XCode or Command Line Tools

Set Project Format in your project to Xcode 8.3-compatible

Possible solution:

Open XCode.app (Show Package Contents)

Find and open version.plist

Change ProductBuildVersion from 9C40b to 9C40

Set Project Format in your project to Xcode 8.3-compatible

Enjoy!

ContentLicense: CC BY-SA 4.0


问:
Comparing Two Folders and its Subfolder batch file
I have two folders that contain all the same files and subfolders, but the conents inside each file may have changed. I want  to write a batch file that will search through each file and look for any differences. What's the best tool for what I want to do?</p>

答:
I modified a batch file I wrote for a CD process that should meet your need.  It

takes 2 directory trees and compares each file in each tree

creates a list of the file differences (named File_differences.txt in the output folder)

and creates a folder with a diff file for each non-matching object

If both directory structures are under the same parent, then all you need to do is update the first 8 variables in the script.  If the directory trees have different parents, then read through the scripts comments.  Particularly lines 14, 38 and 46.

```<code>:: This script compares the contents of 2 trees
:: set a workspace location for the script outside of the trees being reviewed
set home=D:\path\to\batch_file_home
set Input=D:\path\to\batch_file_home\Input_Files
set Resource=D:\path\to\batch_file_home\Resource_Files
set Output=D:\path\to\where your want to view your\Output_Files

set environment=D:\path\to\parent directory containing the different tree structures (if they do not share a parent, then make this the drive)
:: the next 3 lines are only needed if you want to predefine multiple directories for comparison
set Prod=production
set QA=test
set Dev=branches\dev
:: If you remove the 3 lines above, then you need to replace the 2 below variables with values
:: If the trees are not under the same parent, then include the full path for Tree A and B below
set Tree_A=%Prod%
set Tree_B=%QA%
:: if you already have an object list, place it in the Input folder and remove lines 24 through 35 of this script
set Object_List=Object_List_minus_Direcotries.txt
set Output_File=File_differences.txt

if exist %Output%\%Output_File% del %Output%\%Output_File%
if exist %Output%\Differences\*.txt del %Output%\Differences\*.txt
if exist %Resource%\* del /q %Resource%\*

:: since you state the objects in both trees are always the same, I have not included a comparison to verify the 2 trees match
:: this section identifies the contents of Tree A
cd %environment%\%Tree_A%
dir /b /s > %Resource%\Complete_Tree_A_Object_List.txt

:: Next, remove the objects that are directories
setlocal enabledelayedexpansion
for /f "tokens=*" %%p in (%Resource%\Complete_Tree_A_Object_List.txt) do (
  dir /a:d /b %%p 2>nul >nul && (set object_type=folder) || (set object_type=file)
  echo !object_type!
  if !object_type!==file echo %%p >> %Resource%\%Object_List%
  )

:: in the object list, remove the parent tree from the path
:: if the Trees are not under the same parent, then comment out the below 6 lines
powershell -command "(Get-Content %Resource%\%Object_List%) -replace '\\','/' | set-content %Resource%\%Object_List%"
powershell -command "(get-content %Resource%\%Object_List%) | Foreach {$_.TrimEnd()} | Set-Content %Resource%\%Object_List%"
set remove_parent_prefix=%environment%\%Tree_A%
set remove_parent_prefix=%remove_parent_prefix:\=/%
powershell -command "(Get-Content %Resource%\%Object_List%) -replace '%remove_parent_prefix%/','' | set-content %Resource%\%Object_List%"
powershell -command "(Get-Content %Resource%\%Object_List%) -replace '/','\' | set-content %Resource%\%Object_List%"

:: the below loop assumes both Trees are under the same parent.  If this is not the case, replace the cd %environment% line with cd %home%
:: when the Trees are not under the same parent, set home to the root location, example cd D:\
setlocal enabledelayedexpansion
for /f "tokens=*" %%x in (%Resource%\%Object_List%) do (
  set Diff_File=%%x
  set Diff_File=!Diff_File:\=-!
  cd %environment%
  fc %Tree_A%\%%x %Tree_B%\%%x > "%Output%\Differences\!Diff_File!-%Output_File%"
  for %%a in ("%Output%\Differences\!Diff_File!-%Output_File%") do for /f %%b in ('find /c /v "" ^< "%%a" ') do if %%b LSS 3 del "%%a"
  for %%R in ("%Output%\Differences\!Diff_File!-%Output_File%") do if not %%~zR lss 1 (
   echo %%x >> %Output%\%Output_File%
  )
  for %%R in ("%Output%\Differences\!Diff_File!-%Output_File%") do if %%~zR lss 1 (
     del "%Output%\Differences\!Diff_File!-%Output_File%"
  )
)
endlocal

:: Clean up Resources.  If you want to review the temp files used to create the report, comment out the below line
if exist %Resource%\* del /q %Resource%\*
</code>```

Body:
I modified a batch file I wrote for a CD process that should meet your need.  It

takes 2 directory trees and compares each file in each tree

creates a list of the file differences (named File_differences.txt in the output folder)

and creates a folder with a diff file for each non-matching object

If both directory structures are under the same parent, then all you need to do is update the first 8 variables in the script.  If the directory trees have different parents, then read through the scripts comments.  Particularly lines 14, 38 and 46.

:: This script compares the contents of 2 trees
:: set a workspace location for the script outside of the trees being reviewed
set home=D:\path\to\batch_file_home
set Input=D:\path\to\batch_file_home\Input_Files
set Resource=D:\path\to\batch_file_home\Resource_Files
set Output=D:\path\to\where your want to view your\Output_Files

set environment=D:\path\to\parent directory containing the different tree structures (if they do not share a parent, then make this the drive)
:: the next 3 lines are only needed if you want to predefine multiple directories for comparison
set Prod=production
set QA=test
set Dev=branches\dev
:: If you remove the 3 lines above, then you need to replace the 2 below variables with values
:: If the trees are not under the same parent, then include the full path for Tree A and B below
set Tree_A=%Prod%
set Tree_B=%QA%
:: if you already have an object list, place it in the Input folder and remove lines 24 through 35 of this script
set Object_List=Object_List_minus_Direcotries.txt
set Output_File=File_differences.txt

if exist %Output%\%Output_File% del %Output%\%Output_File%
if exist %Output%\Differences\*.txt del %Output%\Differences\*.txt
if exist %Resource%\* del /q %Resource%\*

:: since you state the objects in both trees are always the same, I have not included a comparison to verify the 2 trees match
:: this section identifies the contents of Tree A
cd %environment%\%Tree_A%
dir /b /s > %Resource%\Complete_Tree_A_Object_List.txt

:: Next, remove the objects that are directories
setlocal enabledelayedexpansion
for /f "tokens=*" %%p in (%Resource%\Complete_Tree_A_Object_List.txt) do (
  dir /a:d /b %%p 2>nul >nul && (set object_type=folder) || (set object_type=file)
  echo !object_type!
  if !object_type!==file echo %%p >> %Resource%\%Object_List%
  )

:: in the object list, remove the parent tree from the path
:: if the Trees are not under the same parent, then comment out the below 6 lines
powershell -command "(Get-Content %Resource%\%Object_List%) -replace '\\','/' | set-content %Resource%\%Object_List%"
powershell -command "(get-content %Resource%\%Object_List%) | Foreach {$_.TrimEnd()} | Set-Content %Resource%\%Object_List%"
set remove_parent_prefix=%environment%\%Tree_A%
set remove_parent_prefix=%remove_parent_prefix:\=/%
powershell -command "(Get-Content %Resource%\%Object_List%) -replace '%remove_parent_prefix%/','' | set-content %Resource%\%Object_List%"
powershell -command "(Get-Content %Resource%\%Object_List%) -replace '/','\' | set-content %Resource%\%Object_List%"

:: the below loop assumes both Trees are under the same parent.  If this is not the case, replace the cd %environment% line with cd %home%
:: when the Trees are not under the same parent, set home to the root location, example cd D:\
setlocal enabledelayedexpansion
for /f "tokens=*" %%x in (%Resource%\%Object_List%) do (
  set Diff_File=%%x
  set Diff_File=!Diff_File:\=-!
  cd %environment%
  fc %Tree_A%\%%x %Tree_B%\%%x > "%Output%\Differences\!Diff_File!-%Output_File%"
  for %%a in ("%Output%\Differences\!Diff_File!-%Output_File%") do for /f %%b in ('find /c /v "" ^< "%%a" ') do if %%b LSS 3 del "%%a"
  for %%R in ("%Output%\Differences\!Diff_File!-%Output_File%") do if not %%~zR lss 1 (
   echo %%x >> %Output%\%Output_File%
  )
  for %%R in ("%Output%\Differences\!Diff_File!-%Output_File%") do if %%~zR lss 1 (
     del "%Output%\Differences\!Diff_File!-%Output_File%"
  )
)
endlocal

:: Clean up Resources.  If you want to review the temp files used to create the report, comment out the below line
if exist %Resource%\* del /q %Resource%\*


问:
Mailer send nil records
I am running tasks to scrap a website to get some concert dates.

My tasks are finding/updating the concerts (date and city), and record them in the data base. I can find them in my rails console and also they can be displayed in my index and show views.
BTW it seems it doesn't go through the create method in the ConcertController (I tried with binding.pry)

After the task is run, I want to get an email alert if a new record was found. When I receive the email it's not complete:

concert_mailer/new_dates.html.erb

```<code><p>The boys are playing at <%= @concert.city %> on <%= @concert.date %></p>
#returns The boys are playing at on

<p>The boys are playing at <%= @concert.inspect %> </p>

#returns: The boys are playing at <Concert id: 1, date: nil, city: nil, created_at: "2017-12-05 20:32:09", updated_at: "2017-12-05 20:32:09">
</code>```

In rails console I have the record:

```<code><Concert id: 1, date: "2017-12-08 00:00:00", city: "ECHANGE CULTUREL CAMEROUN (0)  | au 18 décembre 20...", created_at: "2017-12-05 20:32:09", updated_at: "2017-12-05 20:32:10">
</code>```

Btw here are my tasks:

```<code> namespace :scrap do
  desc "This get MM concerts"

    url = "http://mountain-men.fr/concerts/"
    doc = Nokogiri::HTML(open(url))
    data = doc.search('#dateconcert table')
    data = data.css('.jaunec' ).map { |tr| tr.css('td').map(&:text) } + doc.css('.jaunef' ).map { |tr| tr.css('td').map(&:text) }

  task :find_concerts  => :environment do

    data.each do |concert|
      c = Concert.create!
      c.date = concert[0]
      c.city = concert[1]
      c.save
    end

  end

  task :update_concerts  => :environment do

    existing_date = Concert.all.map { |c| [c.date, c.city] }

    data.each do |concert|
      c = Concert.create!
      c.date = concert[0]
      c.city = concert[1]
      c.save unless existing_date.include?([concert[0], concert[1]])
    end
      Concert.where(city: nil, date:nil).destroy_all

  end
end
</code>```

concert.rb

```<code>class Concert < ApplicationRecord
   after_create :send_notification

   def send_notification
    ConcertMailer.new_dates(self).deliver_now
   end
end
</code>```

concert_mailer.rb

```<code>class ConcertMailer < ApplicationMailer

  default from: "concert@mountain-men.fr"

  def new_dates(concert)
    @concert = concert

    mail( to:   "email@exemple.com",
         subject:  "The boys are back in town"
        )
  end
end
</code>```

答:
Your after_create callback to trigger the email is being called before you update your Concert object with data. Instead of creating a empty object, try adding values to your fields before you save the Concert object.

Something like this:

```<code>data.each do |concert|
  c = Concert.new
  c.date = concert[0]
  c.city = concert[1]
  c.save
end
</code>```

Or this :

```<code>data.each do |concert|
  Concert.create(date: concert[0], city: concert[1])
end
</code>```

This way you will have values saved before the after_create callback is triggered.

Title: Mailer send nil records

Body:
I am running tasks to scrap a website to get some concert dates.

My tasks are finding/updating the concerts (date and city), and record them in the data base. I can find them in my rails console and also they can be displayed in my index and show views.
BTW it seems it doesn't go through the create method in the ConcertController (I tried with binding.pry)

After the task is run, I want to get an email alert if a new record was found. When I receive the email it's not complete:

concert_mailer/new_dates.html.erb

The boys are playing at <%= @concert.city %> on <%= @concert.date %>

#returns The boys are playing at on

The boys are playing at <%= @concert.inspect %>

#returns: The boys are playing at <Concert id: 1, date: nil, city: nil, created_at: "2017-12-05 20:32:09", updated_at: "2017-12-05 20:32:09">

In rails console I have the record:

<Concert id: 1, date: "2017-12-08 00:00:00", city: "ECHANGE CULTUREL CAMEROUN (0)  | au 18 décembre 20...", created_at: "2017-12-05 20:32:09", updated_at: "2017-12-05 20:32:10">

Btw here are my tasks:

 namespace :scrap do
  desc "This get MM concerts"

    url = "http://mountain-men.fr/concerts/"
    doc = Nokogiri::HTML(open(url))
    data = doc.search('#dateconcert table')
    data = data.css('.jaunec' ).map { |tr| tr.css('td').map(&:text) } + doc.css('.jaunef' ).map { |tr| tr.css('td').map(&:text) }

  task :find_concerts  => :environment do

    data.each do |concert|
      c = Concert.create!
      c.date = concert[0]
      c.city = concert[1]
      c.save
    end

  end

  task :update_concerts  => :environment do

    existing_date = Concert.all.map { |c| [c.date, c.city] }

    data.each do |concert|
      c = Concert.create!
      c.date = concert[0]
      c.city = concert[1]
      c.save unless existing_date.include?([concert[0], concert[1]])
    end
      Concert.where(city: nil, date:nil).destroy_all

  end
end

concert.rb

class Concert < ApplicationRecord
   after_create :send_notification

   def send_notification
    ConcertMailer.new_dates(self).deliver_now
   end
end

concert_mailer.rb

class ConcertMailer < ApplicationMailer

  default from: "concert@mountain-men.fr"

  def new_dates(concert)
    @concert = concert

    mail( to:   "email@exemple.com",
         subject:  "The boys are back in town"
        )
  end
end

Body:
Your after_create callback to trigger the email is being called before you update your Concert object with data. Instead of creating a empty object, try adding values to your fields before you save the Concert object.

Something like this:

data.each do |concert|
  c = Concert.new
  c.date = concert[0]
  c.city = concert[1]
  c.save
end

Or this :

data.each do |concert|
  Concert.create(date: concert[0], city: concert[1])
end

This way you will have values saved before the after_create callback is triggered.


问:
R read.csv data from inline string with a csv file content
this is supposed to be a trivial thing, but I have not found anything googling it.

I have the following data in a csv file

test.csv

```<code>var1,var2
'a',1
'b',2
</code>```

which I read into R with

```<code>d <- read.csv('test.csv')
</code>```

This there a way for me to insert the content of the csv file in my R code? Something like:

```<code>d <- read.csv(
    'var1,var2\n
    'a',1\n
    'b',2')
</code>```

(above syntax does not work)

how can I tell R that the input string should be treated as the data itself instead of a file name containing it?

This would be for adding small tables to Rmarkdown without having to create a bunch of auxiliary files

of course I could add the same info with

```<code>d <- data.frame(
  var1=c('a','b'),
  var2=1,2
)
</code>```

but listing the data vector by vector slow the process down. The row by row structure of the csv is easyer

答:
The tibble package's tribble() method, is another great option for writing short bits of tabular data in an R file, in a way that is human-readable, machine-readable, and easy to maintain/edit. And as a bonus, it makes it easy to use R expressions as values in the table.

```<code># Column names are prefaced with "~"
my_tibble1 <- tribble(
  ~colA, ~colB, ~colC,
  "a",   1,     10.1,
  "b",   2,     3.4,
  "c",   3,     5.6
)
#> # A tibble: 3 x 3
#>    colA  colB  colC
#>   <chr> <dbl> <dbl>
#> 1     a     1  10.1
#> 2     b     2   3.4
#> 3     c     3   5.6

# tribble will create a list column if the value in any cell is
# not a scalar
my_tibble2 <- tribble(
  ~x,  ~y,
  "a", 1:3,
  "b", 4:6
)
#> # A tibble: 2 x 2
#>       x         y
#>   <chr>    <list>
#> 1     a <int [3]>
#> 2     b <int [3]>
</code>```

If you haven't encountered tibbles before, they're a (mostly) drop-in replacement for data.frame. If you need to really make sure that your data is a data.frame and not a tibble, you can convert it to one with as.data.frame(...).

Body:
this is supposed to be a trivial thing, but I have not found anything googling it.

I have the following data in a csv file

test.csv

var1,var2
'a',1
'b',2

which I read into R with

d <- read.csv('test.csv')

This there a way for me to insert the content of the csv file in my R code? Something like:

d <- read.csv(
    'var1,var2\n
    'a',1\n
    'b',2')

(above syntax does not work)

how can I tell R that the input string should be treated as the data itself instead of a file name containing it?

This would be for adding small tables to Rmarkdown without having to create a bunch of auxiliary files

of course I could add the same info with

d <- data.frame(
  var1=c('a','b'),
  var2=1,2
)

but listing the data vector by vector slow the process down. The row by row structure of the csv is easyer

Body:
The tibble package's tribble() method, is another great option for writing short bits of tabular data in an R file, in a way that is human-readable, machine-readable, and easy to maintain/edit. And as a bonus, it makes it easy to use R expressions as values in the table.

# Column names are prefaced with "~"
my_tibble1 <- tribble(
  ~colA, ~colB, ~colC,
  "a",   1,     10.1,
  "b",   2,     3.4,
  "c",   3,     5.6
)
#> # A tibble: 3 x 3
#>    colA  colB  colC
#>   <chr> <dbl> <dbl>
#> 1     a     1  10.1
#> 2     b     2   3.4
#> 3     c     3   5.6

# tribble will create a list column if the value in any cell is
# not a scalar
my_tibble2 <- tribble(
  ~x,  ~y,
  "a", 1:3,
  "b", 4:6
)
#> # A tibble: 2 x 2
#>       x         y
#>   <chr>    <list>
#> 1     a <int [3]>
#> 2     b <int [3]>

If you haven't encountered tibbles before, they're a (mostly) drop-in replacement for data.frame. If you need to really make sure that your data is a data.frame and not a tibble, you can convert it to one with as.data.frame(...).


问:
Framework7 router does not work after converting project to apk
I have tried out this tutorial to develop an android application via Cordova and Framework7. It works in the browser and also Android Emulator (ADK). I converted the project to the apk with Cordova build command and transferred the apk file to my device.

The application works, however, the list which is the application based Framework7 (indeed on Vue) does not show anything. It looks like Vue not initialized.

Here is the HTML code:

```<code><template  id="page-alt-sayfa">
<f7-page>
  <f7-navbar title="Alt Sayfa" back-link="Geri" sliding></f7-navbar>
  <f7-block-title>
  <!-- sayfa id'sini data obj iÃ§inde ara-->
  {{this.$root.$data['icerik'][$route.params['sayfaId']].baslik}}</p>
  </f7-block-title>
  <f7-block-title>Dondurucuya Konur mu?</f7-block-title>
  <f7-block inner>
    <img style="width:95%;overflow:hidden" :src="'./img/sembolik/'+$route.params['sayfaId']+'.png'"/>
    <br>
    <div v-if="this.$root.$data['icerik'][$route.params['sayfaId']].dondurucu">
      <div class="chip">
          <div class="chip-media bg-green"><i class="material-icons">dns</i></div>
          <div class="chip-label">Dondurucuya Konulur</div>
        </div>
    </div>
</code>```

Here is initializing Framework7 and Vue:

```<code>...
<script src="cordova.js"></script>
          <script src="js/framework7.min.js"></script>
          <script src="js/vue.min.js"></script>
          <script src="js/framework7-vue.min.js"></script>
          <script type="text/javascript" src="js/data.json"></script>
          <script src="js/app.js"></script>
        </body>

    </html>
</code>```

Here a screenshoot from my phone.

(source: ultraimg.com)

How can the problem be solved?

Edit:
Here is my router code:

```<code>// Init F7 Vue Plugin
Vue.use(Framework7Vue)
// Init Page Components
Vue.component('page-about', {
  template: '#page-about'
})
Vue.component('page-form', {
  template: '#page-form'
})
Vue.component('page-dynamic-routing', {
  template: '#page-dynamic-routing'
})
Vue.component('page-alt-sayfa', {
  template: '#page-alt-sayfa'
})
// Handle device ready event
// Note: You may want to check out the vue-cordova package on npm for cordova specific handling with vue - https://www.npmjs.com/package/vue-cordova
document.addEventListener('deviceready', () => {
  console.log("DEVICE IS READY!");
}, false)

// Init App
new Vue({
  el: '#app',
  // Init Framework7 by passing parameters here
  framework7: {
    root: '#app',
    /* Uncomment to enable Material theme: */
    // material: true,
    routes: [
      {
        path: '/about/',
        component: 'page-about'
      },
      {
        path: '/alt-sayfa/:sayfaId/',
        component: 'page-alt-sayfa'
      }
    ]
  },
  data: {
    mesaj: 'Merhaba',
    icerik: icerik
  }
});
</code>```

答:
I do not find the where is the problem stems from. However, I find a npm template and reorganized my code according to this template and it worked

Template is:

https://framework7.io/vue/templates.html

I installed it with this command:

```<code>cordova create <project_create_dir> [com.example.projectname] [ProjectClassName] --template cordova-template-framework7-vue-webpack
</code>```

Body:
I have tried out this tutorial to develop an android application via Cordova and Framework7. It works in the browser and also Android Emulator (ADK). I converted the project to the apk with Cordova build command and transferred the apk file to my device.

The application works, however, the list which is the application based Framework7 (indeed on Vue) does not show anything. It looks like Vue not initialized.

Here is the HTML code:

<template  id="page-alt-sayfa">
<f7-page>
  <f7-navbar title="Alt Sayfa" back-link="Geri" sliding></f7-navbar>
  <f7-block-title>

  {{this.$root.$data['icerik'][$route.params['sayfaId']].baslik}}

  </f7-block-title>
  <f7-block-title>Dondurucuya Konur mu?</f7-block-title>
  <f7-block inner>

dns

Dondurucuya Konulur

Here is initializing Framework7 and Vue:

...

Here a screenshoot from my phone.

(source: ultraimg.com)

How can the problem be solved?

Edit:
Here is my router code:

// Init F7 Vue Plugin
Vue.use(Framework7Vue)
// Init Page Components
Vue.component('page-about', {
  template: '#page-about'
})
Vue.component('page-form', {
  template: '#page-form'
})
Vue.component('page-dynamic-routing', {
  template: '#page-dynamic-routing'
})
Vue.component('page-alt-sayfa', {
  template: '#page-alt-sayfa'
})
// Handle device ready event
// Note: You may want to check out the vue-cordova package on npm for cordova specific handling with vue - https://www.npmjs.com/package/vue-cordova
document.addEventListener('deviceready', () => {
  console.log("DEVICE IS READY!");
}, false)

// Init App
new Vue({
  el: '#app',
  // Init Framework7 by passing parameters here
  framework7: {
    root: '#app',
    /* Uncomment to enable Material theme: */
    // material: true,
    routes: [
      {
        path: '/about/',
        component: 'page-about'
      },
      {
        path: '/alt-sayfa/:sayfaId/',
        component: 'page-alt-sayfa'
      }
    ]
  },
  data: {
    mesaj: 'Merhaba',
    icerik: icerik
  }
});

Body:
I do not find the where is the problem stems from. However, I find a npm template and reorganized my code according to this template and it worked

Template is:

https://framework7.io/vue/templates.html

I installed it with this command:

cordova create <project_create_dir> [com.example.projectname] [ProjectClassName] --template cordova-template-framework7-vue-webpack


问:
SQL Sum Case that includes an is not statement
I am trying to create a table that will give a count of entries with a given age range. I am trying to sort between AAAAAA, BBBBBB, and other; where other is a count of entries that is neither A nor B within the database. I am looking for a way to write in syntax an "is not" statement. is this possible? </p>

```<code>SELECT AgeRange
,SUM(CASE WHEN OP ='A' THEN 1 ELSE 0 END) AS 'AAAAAA'
,SUM(CASE WHEN OP ='B' THEN 1 ELSE 0 END) AS 'BBBBBB'
,Sum(Case WHEN OP <> ('A','B') THEN 1 ELSE 0 END) AS 'OTHER'
FROM ;ALKSDJF.A;LKSDFJ.A;SLDKFJ (NOLOCK)
</code>```

答:
Try:

```<code>SELECT AgeRange,
SUM(CASE WHEN OP ='A' THEN 1 ELSE 0 END) AS 'AAAAAA',
SUM(CASE WHEN OP ='B' THEN 1 ELSE 0 END) AS 'BBBBBB',
SUM(Case WHEN OP NOT IN ('A','B') THEN 1 ELSE 0 END) AS 'OTHER'
FROM YOUR_TABLE
GROUP BY AgeRange;
</code>```

Not sure what you have in your FROM clause. I also used NOT IN ('A','B') as I wasn't sure what R and D were.

Body:
I am trying to create a table that will give a count of entries with a given age range. I am trying to sort between AAAAAA, BBBBBB, and other; where other is a count of entries that is neither A nor B within the database. I am looking for a way to write in syntax an "is not" statement. is this possible?

SELECT AgeRange
,SUM(CASE WHEN OP ='A' THEN 1 ELSE 0 END) AS 'AAAAAA'
,SUM(CASE WHEN OP ='B' THEN 1 ELSE 0 END) AS 'BBBBBB'
,Sum(Case WHEN OP <> ('A','B') THEN 1 ELSE 0 END) AS 'OTHER'
FROM ;ALKSDJF.A;LKSDFJ.A;SLDKFJ (NOLOCK)

Body:
Try:

SELECT AgeRange,
SUM(CASE WHEN OP ='A' THEN 1 ELSE 0 END) AS 'AAAAAA',
SUM(CASE WHEN OP ='B' THEN 1 ELSE 0 END) AS 'BBBBBB',
SUM(Case WHEN OP NOT IN ('A','B') THEN 1 ELSE 0 END) AS 'OTHER'
FROM YOUR_TABLE
GROUP BY AgeRange;

Not sure what you have in your FROM clause. I also used NOT IN ('A','B') as I wasn't sure what R and D were.


答:
Logical negation should almost always (can't think of any where it is not) be possible.

A=B negated is A<>B, or NOT (A=B)

A OR B negated is NOT (A OR B) or NOT A AND NOT B

A IN (B, C, D) negated is A NOT IN (B, C, D)

...and even if NOT IN was not an operator NOT (A IN (B,C,D)) could be used.

Title: SQL Sum Case that includes an is not statement


问:
Overloading operator= in a singly linked list
I'm currently having a problem copying the contents from one list to another. The values all appear as 0 when compiled. I thought that there might be something wrong when overloading the assignment operator as the copy constructor is using its code.

Copy Constructor

```<code>ListOfDoubles::ListOfDoubles(const ListOfDoubles&e):head(NULL) {
if (this != &e) {
    *this = e;
}
}
</code>```

Overloaded operator=

```<code>const ListOfDoubles& ListOfDoubles::operator=(const ListOfDoubles
&doubleslist)
{
DoubleListNode *cpyPtr = NULL;
DoubleListNode* orgPtr = doubleslist.head;

if (this != &doubleslist)
{
    while (head != NULL)
    {
        ListOfDoubles::~ListOfDoubles();
    }

    while (orgPtr != NULL)
    {
        if (head == NULL)
        {
            head = cpyPtr = new DoubleListNode(orgPtr->data);

        }
        else
        {
            cpyPtr->next = new DoubleListNode(orgPtr->data);
            cpyPtr = cpyPtr->next;
        }
        orgPtr = orgPtr->next;
    }
}
return *this;
}
</code>```

答:
General-purpose copy logic looks something like:

```<code>DoubleListNode * from = source.head; // copying from
DoubleListNode ** to = &head; // pointer to where we want to copy to
while (from != nullptr) // keep going until end of list. You did mark
                        // the end of the list, didn't you?
{
    *to = new node(*from); //copy construct a new node around from and store it at to
    to = &(*to)->next; // advance to
    from = from.next; // advance from
}
*to = nullptr; // all done. Terminate list.
</code>```

The real magic is going on up here at the double pointer: DoubleListNode ** to By having a pointer to a pointer, we don't care whether we're pointing at head, another node's next or what have you. It's just another node, so there are no special cases to cover.

You can do the above in both the copy constructor and assignment operator, though you are better off not repeating yourself and putting it in a function called by the copy constructor and assignment operator. Note that there are different assumptions about pre-existing data in the copy constructor (eg, list will be empty) and the assignment operator (eg, list may not be empty, so clear it and free all of the nodes before you begin) that need to be taken into account.

The primary alternative, as discussed in the comments above, is to use the Copy and Swap Idiom. For this, the above copy loop only exists in the copy constructor.

Body:
I'm currently having a problem copying the contents from one list to another. The values all appear as 0 when compiled. I thought that there might be something wrong when overloading the assignment operator as the copy constructor is using its code.

Copy Constructor

ListOfDoubles::ListOfDoubles(const ListOfDoubles&e):head(NULL) {
if (this != &e) {
    *this = e;
}
}

Overloaded operator=

const ListOfDoubles& ListOfDoubles::operator=(const ListOfDoubles
&doubleslist)
{
DoubleListNode *cpyPtr = NULL;
DoubleListNode* orgPtr = doubleslist.head;

if (this != &doubleslist)
{
    while (head != NULL)
    {
        ListOfDoubles::~ListOfDoubles();
    }

    while (orgPtr != NULL)
    {
        if (head == NULL)
        {
            head = cpyPtr = new DoubleListNode(orgPtr->data);

        }
        else
        {
            cpyPtr->next = new DoubleListNode(orgPtr->data);
            cpyPtr = cpyPtr->next;
        }
        orgPtr = orgPtr->next;
    }
}
return *this;
}

Body:
General-purpose copy logic looks something like:

DoubleListNode * from = source.head; // copying from
DoubleListNode ** to = &head; // pointer to where we want to copy to
while (from != nullptr) // keep going until end of list. You did mark
                        // the end of the list, didn't you?
{
    *to = new node(*from); //copy construct a new node around from and store it at to
    to = &(*to)->next; // advance to
    from = from.next; // advance from
}
*to = nullptr; // all done. Terminate list.

The real magic is going on up here at the double pointer: DoubleListNode ** to By having a pointer to a pointer, we don't care whether we're pointing at head, another node's next or what have you. It's just another node, so there are no special cases to cover.

You can do the above in both the copy constructor and assignment operator, though you are better off not repeating yourself and putting it in a function called by the copy constructor and assignment operator. Note that there are different assumptions about pre-existing data in the copy constructor (eg, list will be empty) and the assignment operator (eg, list may not be empty, so clear it and free all of the nodes before you begin) that need to be taken into account.

The primary alternative, as discussed in the comments above, is to use the Copy and Swap Idiom. For this, the above copy loop only exists in the copy constructor.


问:
How to save data from a new object in a nested resource in rails?
I am looking to create a new record within a nested resource in rails as according to http://guides.rubyonrails.org/routing.html.

My model is:

```<code>class Entry < ApplicationRecord
  belongs_to :user
  belongs_to :event

class User < ApplicationRecord
  has_many :entries, dependent: :destroy

class Event < ApplicationRecord
   has_many :entries, dependent: :destroy
</code>```

And I have declared my route as

```<code>Rails.application.routes.draw do
    resources :users
    resources :events do
        resources :entries
   end
</code>```

What is the syntax for the entries controller for me to be able to create an entry on a link like events/2/entries/new. This is what I was trying:

```<code>class EntriesController < ApplicationController

 def new
    @entry = Entry.new
 end

def create
    @entry = Entry.new(params[:entry])
    if @entry.save
        redirect_to @user
        flash.now[:info] = "Event Created"
    else
        render '/create'
        flash.now[:danger] = "Somthing went wrong"
    end
end

  def entry_params
        params.require(:event_id).permit(:siCard, :course)
    end

 end
</code>```

On by new.html.erb I am using

```<code><%= form_for(new_event_entry_path) do |f| %>.
</code>```

But I cant get it to work as No route matches [POST] "/events/1/entries/new"
Many thanks

答:
The route you've provided in form_for does not accept POSTs. You've provided the route that renders the new page, not the route that accepts new records, which is the create route. For that, you'll want to use event_entries_path(@event) route helper.

With nested resources, the form_for's first argument should be an array: <%= form_for([@event, @entry], .... Rails will intelligently choose the route you need based on whether the @entry is persisted or not.

Body:
I am looking to create a new record within a nested resource in rails as according to http://guides.rubyonrails.org/routing.html.

My model is:

class Entry < ApplicationRecord
  belongs_to :user
  belongs_to :event

class User < ApplicationRecord
  has_many :entries, dependent: :destroy

class Event < ApplicationRecord
   has_many :entries, dependent: :destroy

And I have declared my route as

Rails.application.routes.draw do
    resources :users
    resources :events do
        resources :entries
   end

What is the syntax for the entries controller for me to be able to create an entry on a link like events/2/entries/new. This is what I was trying:

class EntriesController < ApplicationController

 def new
    @entry = Entry.new
 end

def create
    @entry = Entry.new(params[:entry])
    if @entry.save
        redirect_to @user
        flash.now[:info] = "Event Created"
    else
        render '/create'
        flash.now[:danger] = "Somthing went wrong"
    end
end

  def entry_params
        params.require(:event_id).permit(:siCard, :course)
    end

 end

On by new.html.erb I am using

<%= form_for(new_event_entry_path) do |f| %>.

But I cant get it to work as No route matches [POST] "/events/1/entries/new"
Many thanks


问:
What's the difference between the assignment operator vs equal operator in C
```<code>int main(){

   int x = 5580, y = 55098;

   printf( "%d\n", y = x);

   return 0;

}
</code>```

Why does this print the value of y?  I thought the value of x was being assigned to y but thats not the case.

答:
According to the standard, an assignment expression evaluates to the valueof the left operand after assignment:

6.5.16 Assignment operators

(3) An assignment operator stores a value in the object designated by
  the left operand. An assignment expression has the value of the left
  operand after the assignment

So y=x in printf( "%d\n", y = x) first lets y take on the value of x, and then evaluates to the (newly assigned) value of y. So the output of the printf-statement will be 5580, i.e. the value of x, which is the new value of y.

Body:
int main(){

   int x = 5580, y = 55098;

   printf( "%d\n", y = x);

   return 0;

}

Why does this print the value of y?  I thought the value of x was being assigned to y but thats not the case.