问:
Code Gives No Errors but Does Nothing in Command Prompt
I am having trouble getting my code to run on command prompt, I am getting no errors but when I run the code nothing happens. </p>

```<code>#include <iostream>
#include <stdexcept>
using namespace std;
//defines the maximum queue size
#define MAX_QUE_SIZE 10
//creates the "rules" for the queue
class queue {
private:
int A[MAX_QUE_SIZE];
int front;
int rear;

public:
queue() {
    front = -1;
    rear = -1;
}

//checks to see if the queue is empty
bool isEmpty() {
    return (front == -1 && rear == -1);
}

//checks to see if the queue if full
bool isFull() {
    return (rear + 1) % MAX_QUE_SIZE == front ? true : false;
}

//checks to see if the queue is full, if not then it adds to the queue.
//if so it gives an error message.
void enqueue(int element) {
    if (isFull()) {
        throw std::overflow_error("QUEUE FULL");
    }
    if (isEmpty()) {
        front = 0;
        rear = 0;
    }
    else {
        rear = (rear + 1) % MAX_QUE_SIZE;
    }
    A[rear] = element;
}

//checks to see if the queue is empty, if not then it deletes from the queue
//if sos it gives an error message.
void dequeue() {
    if (isEmpty()) {
        throw std::underflow_error("QUEUE EMPTY");
    }
    else if (front == rear) {
        rear = -1;
        front = -1;
    }
    else {
        front = (front + 1) % MAX_QUE_SIZE;
    }
}

//checks to see if the queue is empty, if so it gives a message saying so
//if not then it prints all the items in the queue

void printqueue() {
    if (isEmpty()) {
        cout << "EMPTY QUEUE";
    }
    else {
        int count = (rear + MAX_QUE_SIZE - front) % MAX_QUE_SIZE + 1;
        cout << "Queue       : ";
        for (int i = 0; i < count; i++) {
            int index = (front + i) % MAX_QUE_SIZE;
            cout << A[index] << " ";
        }
        cout << "\n\n";
    }
}
};

int main()
{
queue Q; // creating an instance of Queue.
int i;
int k = 0;
int x;

std::cout << "Please enter some integers (enter 0 to exit):\n";
//a do-while statement that adds to the queue
do {
    std::cin >> i;
    //tries to add to the queue, if the queue is full it gives and overflow error
    try {
        Q.enqueue(i);
    }
    catch (std::overflow_error e) {
        std::cout << e.what() << endl;
    }
} while (i != 0);
std::cout << endl;
Q.printqueue();

std:cout << "How many values do you want to dequeue:\n";
std::cin >> x;
cout << endl;
//a for loop that dequeues the number of items the user wants to delete
//try the foor loop and dequeue function, if the queue is empty then it gives an underflow error
try {
    for (int k = 0; k < x; k++) {

        Q.dequeue();
    }
}
    catch (std::underflow_error e) {
        std::cout << e.what() << endl;
    }

Q.printqueue();

return 0;
 }
</code>```

<p>I am also typing in g++ -o ehQue ehQue.cpp to compile it. I am not sure if this is causing the error or if my code itself is causing the error. Any amount of help will be appreciated. </p>

答:
I suspect you're just not executing your code. It compiles and runs.

You're compiling the program (not executing it) with:

```<code>g++ -o ehQue ehQue.cpp
</code>```

The command can be understood as calling the program "g++" which should be just an alias to "gcc" which is the compiler. It takes sources code and produces object code, which is then linked to produce an executable binary (program.)

```<code>-o ehQue
</code>```

Is the command parameter to specify the output file name. The compiler will take the provided files and (attempt to) produce a working executable called "ehQue".

```<code>ehQue.cpp
</code>```

Is your source code, which you specified to the compiler.

Within your terminal (where you typed the g++ command) you will, also, need to call the program using a command such as:

```<code>./ehQue
</code>```

Or to be specific to the Windows command prompt:

```<code>ehQue
</code>```

Where you should find that your program runs.

(Tangential) Unless you specifically need to re-invent the wheel, one of CPP's defining features is the Standard Template Library (STL) which is part of the core specification... wrapping a std::deque in a class with your print functions would be advisable.

Body:
I am having trouble getting my code to run on command prompt, I am getting no errors but when I run the code nothing happens.

#include <iostream>
#include <stdexcept>
using namespace std;
//defines the maximum queue size
#define MAX_QUE_SIZE 10
//creates the "rules" for the queue
class queue {
private:
int A[MAX_QUE_SIZE];
int front;
int rear;

public:
queue() {
    front = -1;
    rear = -1;
}

//checks to see if the queue is empty
bool isEmpty() {
    return (front == -1 && rear == -1);
}

//checks to see if the queue if full
bool isFull() {
    return (rear + 1) % MAX_QUE_SIZE == front ? true : false;
}

//checks to see if the queue is full, if not then it adds to the queue.
//if so it gives an error message.
void enqueue(int element) {
    if (isFull()) {
        throw std::overflow_error("QUEUE FULL");
    }
    if (isEmpty()) {
        front = 0;
        rear = 0;
    }
    else {
        rear = (rear + 1) % MAX_QUE_SIZE;
    }
    A[rear] = element;
}

//checks to see if the queue is empty, if not then it deletes from the queue
//if sos it gives an error message.
void dequeue() {
    if (isEmpty()) {
        throw std::underflow_error("QUEUE EMPTY");
    }
    else if (front == rear) {
        rear = -1;
        front = -1;
    }
    else {
        front = (front + 1) % MAX_QUE_SIZE;
    }
}

//checks to see if the queue is empty, if so it gives a message saying so
//if not then it prints all the items in the queue

void printqueue() {
    if (isEmpty()) {
        cout << "EMPTY QUEUE";
    }
    else {
        int count = (rear + MAX_QUE_SIZE - front) % MAX_QUE_SIZE + 1;
        cout << "Queue       : ";
        for (int i = 0; i < count; i++) {
            int index = (front + i) % MAX_QUE_SIZE;
            cout << A[index] << " ";
        }
        cout << "\n\n";
    }
}
};

int main()
{
queue Q; // creating an instance of Queue.
int i;
int k = 0;
int x;

std::cout << "Please enter some integers (enter 0 to exit):\n";
//a do-while statement that adds to the queue
do {
    std::cin >> i;
    //tries to add to the queue, if the queue is full it gives and overflow error
    try {
        Q.enqueue(i);
    }
    catch (std::overflow_error e) {
        std::cout << e.what() << endl;
    }
} while (i != 0);
std::cout << endl;
Q.printqueue();

std:cout << "How many values do you want to dequeue:\n";
std::cin >> x;
cout << endl;
//a for loop that dequeues the number of items the user wants to delete
//try the foor loop and dequeue function, if the queue is empty then it gives an underflow error
try {
    for (int k = 0; k < x; k++) {

        Q.dequeue();
    }
}
    catch (std::underflow_error e) {
        std::cout << e.what() << endl;
    }

Q.printqueue();

return 0;
 }

I am also typing in g++ -o ehQue ehQue.cpp to compile it. I am not sure if this is causing the error or if my code itself is causing the error. Any amount of help will be appreciated.

Body:
I suspect you're just not executing your code. It compiles and runs.

You're compiling the program (not executing it) with:

g++ -o ehQue ehQue.cpp

The command can be understood as calling the program "g++" which should be just an alias to "gcc" which is the compiler. It takes sources code and produces object code, which is then linked to produce an executable binary (program.)

-o ehQue

Is the command parameter to specify the output file name. The compiler will take the provided files and (attempt to) produce a working executable called "ehQue".

ehQue.cpp

Is your source code, which you specified to the compiler.

Within your terminal (where you typed the g++ command) you will, also, need to call the program using a command such as:

./ehQue

Or to be specific to the Windows command prompt:

ehQue

Where you should find that your program runs.

(Tangential) Unless you specifically need to re-invent the wheel, one of CPP's defining features is the Standard Template Library (STL) which is part of the core specification... wrapping a std::deque in a class with your print functions would be advisable.


来源: stackexchange

问:
Importing unquoted strings as factors using read_csv from the readr package in R
I have a .csv datafile with many columns.  Unfortunately, string values do not have quotation marks (i.e., apples i.o. "apples).  When I use read_csv from the readr package, the string values are imported as characters:

```<code>library(readr)

mydat = data.frame(first = letters, numbers = 1:26, second = sample(letters, 26))
write.csv(mydat, "mydat.csv", quote = FALSE, row.names = FALSE)

read_csv("mydat.csv")
</code>```

results in:

```<code>Parsed with column specification:
cols(
  first = col_character(),
  numbers = col_integer(),
  second = col_character()
)
# A tibble: 26 x 3
   first numbers second
   <chr>   <int>  <chr>
1      a       1      r
2      b       2      n
3      c       3      m
4      d       4      z
5      e       5      p
6      f       6      j
7      g       7      u
8      h       8      l
9      i       9      e
    10     j      10      h
    # ... with 16 more rows
</code>```

Is there a way to force read_csv to import the string values as factors i.o. characters?

Importantly, my datafile has so many columns (string and numeric variables) that, AFAIK, there is no way to make this work by providing column specifications with the col_types argument.

Alternative solutions (e.g. using read.csv to import the data, or dplyr code to change all character variables in a dataframe to factors) are appreciated too.

Update: I learned that whether or not the values in the csv file have quotes or not makes no difference for read.csv or read_csv. read.csv will import these values as factors; read_csv will import them as characters.  I prefer to use read_csv because it's considerably faster than read.csv.

答:
I like the alistaire's mutate_if() solution in the comments above, but for completeness, there is another solution which should be mentioned.  You can use unclass() which will force a re-parse.  You'll see this in a lot of code that uses readr.

```<code>df <- data.frame(unclass(fr))
</code>```

or

```<code>df <- df %>% unclass %>% data.frame
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a .csv datafile with many columns.  Unfortunately, string values do not have quotation marks (i.e., apples i.o. "apples).  When I use read_csv from the readr package, the string values are imported as characters:

library(readr)

mydat = data.frame(first = letters, numbers = 1:26, second = sample(letters, 26))
write.csv(mydat, "mydat.csv", quote = FALSE, row.names = FALSE)

read_csv("mydat.csv")

results in:

Parsed with column specification:
cols(
  first = col_character(),
  numbers = col_integer(),
  second = col_character()
)
# A tibble: 26 x 3
   first numbers second
   <chr>   <int>  <chr>
1      a       1      r
2      b       2      n
3      c       3      m
4      d       4      z
5      e       5      p
6      f       6      j
7      g       7      u
8      h       8      l
9      i       9      e
    10     j      10      h
    # ... with 16 more rows

Is there a way to force read_csv to import the string values as factors i.o. characters?

Importantly, my datafile has so many columns (string and numeric variables) that, AFAIK, there is no way to make this work by providing column specifications with the col_types argument.

Alternative solutions (e.g. using read.csv to import the data, or dplyr code to change all character variables in a dataframe to factors) are appreciated too.

Update: I learned that whether or not the values in the csv file have quotes or not makes no difference for read.csv or read_csv. read.csv will import these values as factors; read_csv will import them as characters.  I prefer to use read_csv because it's considerably faster than read.csv.

Body:
I like the alistaire's mutate_if() solution in the comments above, but for completeness, there is another solution which should be mentioned.  You can use unclass() which will force a re-parse.  You'll see this in a lot of code that uses readr.

df <- data.frame(unclass(fr))

or

df <- df %>% unclass %>% data.frame


问:
Dapper Multipmapping collection within collections
In Dapper, what's the best way to map and object that contains a list and each of those list items have their own lists?

```<code>class Object1 {
    int Object1Id;
    List<Object2> object2s;
}

class Object2 {
    int Object2Id;
    List<Object3> object3s;
}

class Object3 {
    int Object3Id;
}
</code>```

Here's the SQL I wanted to use

```<code>SELECT *
  FROM [Object1] o1
  left join [Object2] o2 on o1.Object1Id = o2.Object1Id
  left join [Object3] o3 on o2.Object2Id = o3.Object2Id
</code>```

Using the Left joins because it's possible Object1 has no Object2's and Object2's may not have any Object3's

I thought about using

```<code>connection.Query<Object1, Object2, Object3, Object1>
</code>```

but keeping track of a dictionary within a dictionary to add them to the list seems like a lot of lines of code.

Would I be better off using QueryMultiple?

答:
You're absolutely right : this kind of parent-child handling isn't a scenario that dapper handles very well right now. It would be nice if it did, but it simply hasn't been the top priority to do something about it.

You have a choice of two inelegant solutions. Personally I think the QueryMultiple approach is proabbly cleaner.

Body:
In Dapper, what's the best way to map and object that contains a list and each of those list items have their own lists?

class Object1 {
    int Object1Id;
    List<Object2> object2s;
}

class Object2 {
    int Object2Id;
    List<Object3> object3s;
}

class Object3 {
    int Object3Id;
}

Here's the SQL I wanted to use

SELECT *
  FROM [Object1] o1
  left join [Object2] o2 on o1.Object1Id = o2.Object1Id
  left join [Object3] o3 on o2.Object2Id = o3.Object2Id

Using the Left joins because it's possible Object1 has no Object2's and Object2's may not have any Object3's

I thought about using

connection.Query<Object1, Object2, Object3, Object1>

but keeping track of a dictionary within a dictionary to add them to the list seems like a lot of lines of code.

Would I be better off using QueryMultiple?


问:
How do I use Google Translate Javascript widget with Rails Turbolinks?
Google Translate widget loads fine the first time, but when I navigate to a new page, Turbolinks removes the body and replaces it. This causes the widget to disappear.

```<code>  %head
    / Google Translate
    :javascript
      function googleTranslateElementInit() { // also called from application.coffee
        new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar,en,es,fr,zh-CN', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
      }
    %script{type: "text/javascript", src: "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"}
</code>```

I tried to call the function upon page load

```<code>$(document).on 'turbolinks:load', ->
  googleTranslateElementInit()
</code>```

But it throws an exception in the browser console

```<code>Uncaught TypeError: Cannot read property 'InlineLayout' of undefined
    at googleTranslateElementInit (VM145012 dashboard:101)
    at HTMLDocument.<anonymous> (application.self-fc93480f6ec8a603a6b9a1d0d9d34ab41a68ef8e4e2a52c661eb84e2b92c170c.js?body=1:7)
    at HTMLDocument.dispatch (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:5227)
    at HTMLDocument.elemData.handle (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:4879)
    at Object.t.dispatch (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at r.t.Controller.r.notifyApplicationAfterPageLoad (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at r.t.Controller.r.pageLoaded (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6
</code>```

I tried to mark the element permanent

https://github.com/turbolinks/turbolinks#persisting-elements-across-page-loads

```<code>%body
  ...
    #google_translate_element{'data-turbolinks-permanent'=>true}
</code>```

But it gave this stack trace when I navigate to a new page and click on it

```<code>element_main.js:419 Uncaught TypeError: Cannot read property 'focus' of null
    at ou.u.Ke (element_main.js:419)
    at Lh (element_main.js:78)
    at HTMLDivElement.Gh (element_main.js:80)
    at HTMLDivElement.<anonymous> (element_main.js:76)
</code>```

答:
I found this way, but it's very hackey.

application.coffee
```<code>$(document).on 'turbolinks:load', ->
  $('#google_translate_element').empty()
  # googleTranslateElementInit()
</code>```
application.haml
```<code>  %head
    / Google Translate
    :javascript
      function googleTranslateElementInit() {
        new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar,en,es,fr,zh-CN', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
      }
  %body
    ...
          #google_translate_element
    ...
    = yield
    ...
    %script{type: "text/javascript", src: "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"}
</code>```

Apparently it will not work without being called back from the script tag. You can't call the callback manually and just load the script once. If you don't .empty() the tag, then going back in your history will just keep adding more & more Google Translate widgets.

Body:
Google Translate widget loads fine the first time, but when I navigate to a new page, Turbolinks removes the body and replaces it. This causes the widget to disappear.

  %head
    / Google Translate
    :javascript
      function googleTranslateElementInit() { // also called from application.coffee
        new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar,en,es,fr,zh-CN', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
      }
    %script{type: "text/javascript", src: "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"}

I tried to call the function upon page load

$(document).on 'turbolinks:load', ->
  googleTranslateElementInit()

But it throws an exception in the browser console

Uncaught TypeError: Cannot read property 'InlineLayout' of undefined
    at googleTranslateElementInit (VM145012 dashboard:101)
    at HTMLDocument.<anonymous> (application.self-fc93480f6ec8a603a6b9a1d0d9d34ab41a68ef8e4e2a52c661eb84e2b92c170c.js?body=1:7)
    at HTMLDocument.dispatch (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:5227)
    at HTMLDocument.elemData.handle (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:4879)
    at Object.t.dispatch (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at r.t.Controller.r.notifyApplicationAfterPageLoad (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at r.t.Controller.r.pageLoaded (turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6)
    at turbolinks.self-c5acd7a204f5f25ce7a1d8a0e4d92e28d34c9e2df2c7371cd7af88e147e4ad82.js?body=1:6

I tried to mark the element permanent

https://github.com/turbolinks/turbolinks#persisting-elements-across-page-loads

%body
  ...
    #google_translate_element{'data-turbolinks-permanent'=>true}

But it gave this stack trace when I navigate to a new page and click on it

element_main.js:419 Uncaught TypeError: Cannot read property 'focus' of null
    at ou.u.Ke (element_main.js:419)
    at Lh (element_main.js:78)
    at HTMLDivElement.Gh (element_main.js:80)
    at HTMLDivElement.<anonymous> (element_main.js:76)

Body:
I found this way, but it's very hackey.

application.coffee

$(document).on 'turbolinks:load', ->
  $('#google_translate_element').empty()
  # googleTranslateElementInit()

application.haml

  %head
    / Google Translate
    :javascript
      function googleTranslateElementInit() {
        new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar,en,es,fr,zh-CN', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
      }
  %body
    ...
          #google_translate_element
    ...
    = yield
    ...
    %script{type: "text/javascript", src: "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"}

Apparently it will not work without being called back from the script tag. You can't call the callback manually and just load the script once. If you don't .empty() the tag, then going back in your history will just keep adding more & more Google Translate widgets.


问:
How to move Array up another level by key
I have an array like below and what I want to achieve is basically remove the keys like @attributes and AddressSop and make them all one level so it removes the parent keys and array but keeps the key value pairs:

```<code>[Addresses] => Array
(
    [0] => Array
        (
            [AddrCountry] => US
            [AddrLine1] => Test Street
            [AddrLine2] => Test
            [AddrLine3] => Test
            [AddrName] => Mr John Doe
            [AddrEmail] => test@test.com
            [AddrMasterPriceBook] =>
            [AddrMobile] => 123132142242
        )
    [1] => Array
      (
       ...
      )
)
</code>```

This is how the original array looks. Any help will be awesome thank you.

```<code>[Addresses] => Array
(
    [0] => Array
        (
        [@attributes] => Array
            (
                [AddrCountry] => US
                [AddrLine1] => Test Street
                [AddrLine2] => Test
                [AddrLine3] => Test
                [AddrName] => Mr John Doe
            )

        [AddressSOP] => Array
            (
                [@attributes] => Array
                    (
                        [AddrEmail] => test@test.com
                        [AddrMasterPriceBook] =>
                        [AddrMobile] => 123132142242
                    )

            )
    )

[1] => Array
    (
        [@attributes] => Array
            (
                [AddrCountry] => US
                [AddrLine1] => Test Street
                [AddrLine2] => Test
                [AddrLine3] => Test
                [AddrName] => Mr John Doe
            )

        [AddressSOP] => Array
            (
                [@attributes] => Array
                    (
                        [AddrEmail] => test@test.com
                        [AddrMasterPriceBook] =>
                        [AddrMobile] => 123132142242
                    )

            )
    )
)
</code>```

答:
Try this:

```<code>foreach ($addresses as $key => $address) {
    $addresses[$key] = array_merge($address['@attributes'], $address['AddressSOP']);
}
</code>```

If you want it to be recursive, you can do something like this:

```<code>$filtered = [];

foreach ($addresses as $addressKey => $address) {
    array_walk_recursive($address, function($val, $key) use(&$filtered, $addressKey) {
        $filtered[$addressKey][$key] = $val;
    });
}

print_r($filtered);
</code>```

Body:
I have an array like below and what I want to achieve is basically remove the keys like @attributes and AddressSop and make them all one level so it removes the parent keys and array but keeps the key value pairs:

[Addresses] => Array
(
    [0] => Array
        (
            [AddrCountry] => US
            [AddrLine1] => Test Street
            [AddrLine2] => Test
            [AddrLine3] => Test
            [AddrName] => Mr John Doe
            [AddrEmail] => test@test.com
            [AddrMasterPriceBook] =>
            [AddrMobile] => 123132142242
        )
    [1] => Array
      (
       ...
      )
)

This is how the original array looks. Any help will be awesome thank you.

[Addresses] => Array
(
    [0] => Array
        (
        [@attributes] => Array
            (
                [AddrCountry] => US
                [AddrLine1] => Test Street
                [AddrLine2] => Test
                [AddrLine3] => Test
                [AddrName] => Mr John Doe
            )

        [AddressSOP] => Array
            (
                [@attributes] => Array
                    (
                        [AddrEmail] => test@test.com
                        [AddrMasterPriceBook] =>
                        [AddrMobile] => 123132142242
                    )

            )
    )

[1] => Array
    (
        [@attributes] => Array
            (
                [AddrCountry] => US
                [AddrLine1] => Test Street
                [AddrLine2] => Test
                [AddrLine3] => Test
                [AddrName] => Mr John Doe
            )

        [AddressSOP] => Array
            (
                [@attributes] => Array
                    (
                        [AddrEmail] => test@test.com
                        [AddrMasterPriceBook] =>
                        [AddrMobile] => 123132142242
                    )

            )
    )
)

Body:
Try this:

foreach ($addresses as $key => $address) {
    $addresses[$key] = array_merge($address['@attributes'], $address['AddressSOP']);
}

If you want it to be recursive, you can do something like this:

$filtered = [];

foreach ($addresses as $addressKey => $address) {
    array_walk_recursive($address, function($val, $key) use(&$filtered, $addressKey) {
        $filtered[$addressKey][$key] = $val;
    });
}

print_r($filtered);


问:
OpenCV leaks memory (cvResize, cvCreateImage)
I'm running OpenCV on a RaspberryPi and use OpenCVs C interface.

I need to resize the dimensions of an image from a webcam, therefore I used the cvResize() function.

It works fine but after a few seconds I run out of memory, since I'm executing the code inside a while(1)-Loop and read about other people having this problem, I suspect a memory leak.

Here is my code:

```<code>IplImage *frame;
IplImage *frameRaw;

main() {
    CvCapture *capture = cvCreateCameraCapture(-1);

    while (1) {
        frameRaw = cvQueryFrame(capture);
        frame = cvCreateImage(cvSize(WIDTH, HEIGHT), frameRaw->depth, frameRaw->nChannels);

        cvResize(frameRaw, frame, 0); // 0 = CV_INTER_NEAREST

        // Do something with "frame"
    }

}
</code>```

I already tried to free the reserved memory at the end of each iteration using cvReleaseImage(&frameRaw) (or &frame) but that always caused a segmentation fault. Using cvReleaseImageHeader() caused no segmentation fault but also didn't free any memory.

Also I tried to change the capture-resolution of the frames via cvSetCaptureProperty() but that did nothing.

Can someone help me understand what's going wrong here?

Thanks in advance

答:
Thanks to @DanMašek I found the solution:

After each while-loop iteration the allocated memory for the frame has to be freed. That can be accomplished using cvReleaseImage(&frame).

The complete code now looks like this:

```<code>IplImage *frame;
IplImage *frameRaw;

main() {
    CvCapture *capture = cvCreateCameraCapture(-1);

    while (1) {
        frameRaw = cvQueryFrame(capture);
        frame = cvCreateImage(cvSize(WIDTH, HEIGHT), frameRaw->depth, frameRaw->nChannels);

        cvResize(frameRaw, frame, 0); // 0 = CV_INTER_NEAREST

        // Do something with "frame"

        cvReleaseImage(&frame);
    }

}
</code>```

Body:
I'm running OpenCV on a RaspberryPi and use OpenCVs C interface.

I need to resize the dimensions of an image from a webcam, therefore I used the cvResize() function.

It works fine but after a few seconds I run out of memory, since I'm executing the code inside a while(1)-Loop and read about other people having this problem, I suspect a memory leak.

Here is my code:

IplImage *frame;
IplImage *frameRaw;

main() {
    CvCapture *capture = cvCreateCameraCapture(-1);

    while (1) {
        frameRaw = cvQueryFrame(capture);
        frame = cvCreateImage(cvSize(WIDTH, HEIGHT), frameRaw->depth, frameRaw->nChannels);

        cvResize(frameRaw, frame, 0); // 0 = CV_INTER_NEAREST

        // Do something with "frame"
    }

}

I already tried to free the reserved memory at the end of each iteration using cvReleaseImage(&frameRaw) (or &frame) but that always caused a segmentation fault. Using cvReleaseImageHeader() caused no segmentation fault but also didn't free any memory.

Also I tried to change the capture-resolution of the frames via cvSetCaptureProperty() but that did nothing.

Can someone help me understand what's going wrong here?

Thanks in advance

Body:
Thanks to @DanMašek I found the solution:

After each while-loop iteration the allocated memory for the frame has to be freed. That can be accomplished using cvReleaseImage(&frame).

The complete code now looks like this:

IplImage *frame;
IplImage *frameRaw;

main() {
    CvCapture *capture = cvCreateCameraCapture(-1);

    while (1) {
        frameRaw = cvQueryFrame(capture);
        frame = cvCreateImage(cvSize(WIDTH, HEIGHT), frameRaw->depth, frameRaw->nChannels);

        cvResize(frameRaw, frame, 0); // 0 = CV_INTER_NEAREST

        // Do something with "frame"

        cvReleaseImage(&frame);
    }

}


问:
How to know it is auto reply mail in Microsoft Graph?
I am using Microsoft Graph API to get mails.

```<code>GET /v1.0/me/messages
</code>```

It returns

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('576552d5-3bc0-42a6-a23d-bfceb405db23')/messages",
    "@odata.nextLink": "https://graph.microsoft.com/v1.0/me/messages?$skip=11",
    "value": [
        {
            "@odata.etag": "W/\"HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi2tx\"",
            "id": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI2MgBGAAAAAACUbnk-iwQZRbXMgkfKtmYhBwCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAACpTc-InBsuTYwTUBb_VIb4AACqNTk9AAA=",
            "createdDateTime": "2017-12-06T21:57:09Z",
            "lastModifiedDateTime": "2017-12-06T21:57:19Z",
            "changeKey": "HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi8tx",
            "categories": [],
            "receivedDateTime": "2017-12-06T21:57:09Z",
            "sentDateTime": "2017-12-06T21:56:16Z",
            "hasAttachments": false,
            "internetMessageId": "<e74a536a53d245e49d779d47f774f4a0@CO2PR00MB0214.namprd00.prod.outlook.com>",
            "subject": "Automatic reply: Hi",
            "bodyPreview": "I am OOF.",
            "importance": "normal",
            "parentFolderId": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAuAAAAAACUbnk-iwQZRbXMgkfKtmYhAQCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAAA=",
            "conversationId": "AAQkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAQAPekscpearpHmBFbhG0DKuc=",
            "isDeliveryReceiptRequested": null,
            "isReadReceiptRequested": false,
            "isRead": true,
            "isDraft": false,
            "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI5MgBGAAAAAACUbnk%2FiwQZRbXMgkfKtmYhBwCpTc%2FInBsuTYwTUBb%2BVIb4AAAAAAEMAACpTc%2FInBsuTYwTUBb%2BVIb4AACqNTk2AAA%3D&exvsurl=2&viewmodel=ReadMessageItem",
            "inferenceClassification": "focused",
            "body": {
                "contentType": "html",
                "content": "hi"
            },
            "sender": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "from": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "toRecipients": [
                {
                    "emailAddress": {
                        "name": "Rose",
                        "address": "rose@example.com"
                    }
                }
            ],
            "ccRecipients": [],
            "bccRecipients": [],
            "replyTo": []
        }
    ]
}
</code>```

I didn't find any field related with determine whether it is an auto reply mail.

Right now I am using

```<code>mail.subject.startsWith('Automatic reply:')
</code>```

to determine whether is auto reply mail in code.

However, it is not reliable. Because sometimes I got mails starting with a different language such as Resposta automática:.

So how to know it is auto reply mail correctly?

答: I'm no expert but I don't believe there's any way to determine whether or not an email is an automatic reply unless the email actually contains a string saying "This is an automatic reply" or something.</p>

Body:
I am using Microsoft Graph API to get mails.

GET /v1.0/me/messages

It returns

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('576552d5-3bc0-42a6-a23d-bfceb405db23')/messages",
    "@odata.nextLink": "https://graph.microsoft.com/v1.0/me/messages?$skip=11",
    "value": [
        {
            "@odata.etag": "W/\"HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi2tx\"",
            "id": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI2MgBGAAAAAACUbnk-iwQZRbXMgkfKtmYhBwCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAACpTc-InBsuTYwTUBb_VIb4AACqNTk9AAA=",
            "createdDateTime": "2017-12-06T21:57:09Z",
            "lastModifiedDateTime": "2017-12-06T21:57:19Z",
            "changeKey": "HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi8tx",
            "categories": [],
            "receivedDateTime": "2017-12-06T21:57:09Z",
            "sentDateTime": "2017-12-06T21:56:16Z",
            "hasAttachments": false,
            "internetMessageId": "<e74a536a53d245e49d779d47f774f4a0@CO2PR00MB0214.namprd00.prod.outlook.com>",
            "subject": "Automatic reply: Hi",
            "bodyPreview": "I am OOF.",
            "importance": "normal",
            "parentFolderId": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAuAAAAAACUbnk-iwQZRbXMgkfKtmYhAQCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAAA=",
            "conversationId": "AAQkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAQAPekscpearpHmBFbhG0DKuc=",
            "isDeliveryReceiptRequested": null,
            "isReadReceiptRequested": false,
            "isRead": true,
            "isDraft": false,
            "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI5MgBGAAAAAACUbnk%2FiwQZRbXMgkfKtmYhBwCpTc%2FInBsuTYwTUBb%2BVIb4AAAAAAEMAACpTc%2FInBsuTYwTUBb%2BVIb4AACqNTk2AAA%3D&exvsurl=2&viewmodel=ReadMessageItem",
            "inferenceClassification": "focused",
            "body": {
                "contentType": "html",
                "content": "hi"
            },
            "sender": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "from": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "toRecipients": [
                {
                    "emailAddress": {
                        "name": "Rose",
                        "address": "rose@example.com"
                    }
                }
            ],
            "ccRecipients": [],
            "bccRecipients": [],
            "replyTo": []
        }
    ]
}

I didn't find any field related with determine whether it is an auto reply mail.

Right now I am using

mail.subject.startsWith('Automatic reply:')

to determine whether is auto reply mail in code.

However, it is not reliable. Because sometimes I got mails starting with a different language such as Resposta automática:.

So how to know it is auto reply mail correctly?


问:
How to pass the dropdown and text value to email subject line using Javascript
Need your urgent help

I have one HTML page with 2 text box, 1 dropdown and 1 button, on button click I want to open the email(as currently I am doing with javascript) with subject line as whatever is selected in the drop down and whatever is written in text box.

```<code><body>
<form id='sampleform' method='post' action='' >
   Emp Number: <input type='text' name='empnum' />

   </p>

   <p>
       Unit Name: <input type='text' name='unit' />
   </p>
   <p>
       Type of subscription you want:
   <p>
       <select name="type">
           <option value="standard">Standard - Free</option>
           <option value="prof">Professional - Paid</option>
       </select>
   </p>
   </p>
   <p>
      <input type='submit' name='Submit' value='Submit' onClick="parent.location='mailto:er.saurav1@gmail.com?subject=Thanks for writing &body=Hi,%0A%0CThanks for writing. We will get back to you soon. %0A%0C%0D%0AThanks and Regards,%0A%0CSaurav Kumar%0A%0C%0A%0CFor further assistance call 81111'">
   </p>
</form>

</body>
</code>```

I want when my email will open the subject line output should be:

Emp Num | Unit Name | Selected value
  from the drop down

答:
```<code><script type="text/javascript" charset="utf-8">
    function click_handler(){

            var x = document.forms.sampleform;
            var enum = x.empnum.value;
            var uname = x.unit.value;
            var ddvalue = x.type.options[x.type.selectedIndex].value;
            var subj = enum +'|'+uname+'|'+ddvalue;
            parent.location='mailto:abc@gmail.com?subject=' + encodeURIComponent(subj) +'&body=Thanks for writing. We will get back to you soon';

    }
</script>
<body>
<form id='sampleform' name='sampleform'>
   Emp Number: <input type='text' name='empnum' />

   </p>

   <p>

   Unit Name: <input type='text' name='unit' />

   </p>

    <p>

   Type of subscription you want:

    <p>

    <select name="type">

      <option value="standard">Standard - Free</option>

      <option value="prof">Professional - Paid</option>

    </select>

    </p>

  </p>
  <p>

<input type='button' name='Submit' value='Submit' onClick="javascript:click_handler()">
</p>
</form>
</body>
 </html>
</code>```

Will be fine.. Though didn't check by running it.. Call the click_handler_me() on clicking the button.

Body:
Need your urgent help

I have one HTML page with 2 text box, 1 dropdown and 1 button, on button click I want to open the email(as currently I am doing with javascript) with subject line as whatever is selected in the drop down and whatever is written in text box.

<form id='sampleform' method='post' action='' >
   Emp Number: <input type='text' name='empnum' />

       Unit Name: <input type='text' name='unit' />

       Type of subscription you want:

       <select name="type">
           <option value="standard">Standard - Free</option>
           <option value="prof">Professional - Paid</option>
       </select>

      <input type='submit' name='Submit' value='Submit' onClick="parent.location='mailto:er.saurav1@gmail.com?subject=Thanks for writing &body=Hi,%0A%0CThanks for writing. We will get back to you soon. %0A%0C%0D%0AThanks and Regards,%0A%0CSaurav Kumar%0A%0C%0A%0CFor further assistance call 81111'">

</form>

I want when my email will open the subject line output should be:

Emp Num | Unit Name | Selected value
  from the drop down

Body:
<script type="text/javascript" charset="utf-8">
    function click_handler(){

            var x = document.forms.sampleform;
            var enum = x.empnum.value;
            var uname = x.unit.value;
            var ddvalue = x.type.options[x.type.selectedIndex].value;
            var subj = enum +'|'+uname+'|'+ddvalue;
            parent.location='mailto:abc@gmail.com?subject=' + encodeURIComponent(subj) +'&body=Thanks for writing. We will get back to you soon';

    }
</script>
<body>
<form id='sampleform' name='sampleform'>
   Emp Number: <input type='text' name='empnum' />

   </p>

   <p>

   Unit Name: <input type='text' name='unit' />

   </p>

    <p>

   Type of subscription you want:

    <p>

    <select name="type">

      <option value="standard">Standard - Free</option>

      <option value="prof">Professional - Paid</option>

    </select>

    </p>

  </p>
  <p>

<input type='button' name='Submit' value='Submit' onClick="javascript:click_handler()">
</p>
</form>
</body>
 </html>

Will be fine.. Though didn't check by running it.. Call the click_handler_me() on clicking the button.

ContentLicense: CC BY-SA 2.5


问:
Parent pom usage in build.gradle
I have a need to convert the maven project to gradle project. All is going fine, but there is one problem that I faced, in the current project we are using dependency management throw parent pom of maven and in gradle as long as I researched there is no possibility to do so. I was thinking to convert somehow parent pom to maven bom and use in build.gradle because I know that gradle can use maven boms.

Do anyone have better ideas how to accoplish that ?
Or may be someone also had this kind of problem, can suggest best ways to do it ?

Regards

答:
You could use my gradle-maven-transform plugin to transform your pom.xmls into gradle scripts.

You can use the DependencyAggregator to find versions which are common across all projects and generate a root build.gradle containing the common versions.

Each project script can then reference a version variable from the root project instead of hard coding

You might choose to use nebula dependency recomnender plugin to manage common versions. The maven-transform plugin can generate scripts to support this style of declaration too

Whilst you are evaluating the gradle build you "apply" the generated gradle scripts in your gradle build. During this time both maven and gradle builds will work in parallel. Once your happy with the gradle build you copy paste the generated scripts into your build.gradle files and ditch maven for ever! Yay!

Title: Parent pom usage in build.gradle


问:
Does input dimension/resolution affect the performance of Convolutional Neural Networks?
I am building a image classifier in which I have 66 classes and images around 50000 and my pc's ram is 12 gb my ram is not sufficient for the training of the images my question is does resolution of the images affects the accuracy of the model I am using convolutional neural networks.</p>

答:
If you are using convolutional neural networks with fully connected layer in the end for getting prediction probabilities, the input layer will have fixed size so you will need to preprocess all images to that size to feed to the network.

If you have images with size lesser than this size, you will need to interpolate and increase size upto this so no effect on memory by further reducing image size. So minimum resolution is the input convolutional layer size.

For your ram issue, depending on framework you are using, using queues properly should solve that issue no matter how large size images are. If the OOM error is during preprocessing, try reducing queue size so that only fraction of images are getting resized at a time to fit in memory. If OOM is during training, try reducing the batch size.


问:
How to get previous url in Angular 2 with Observable
I would like to get my previous url

Here is my code

```<code>prev2() {
    Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)).
    then(function(v){
      console.log('Previous ' + v);
    })
}
</code>```

But all I get is [Object object]

How could I solve it?

答:
You can try something like this </p>

```<code>prev2() {
this.router.events
  .filter(event => event instanceof NavigationEnd)
.subscribe(event => {
  this.current = event.url
})
}
</code>```

Body:
I would like to get my previous url

Here is my code

prev2() {
    Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)).
    then(function(v){
      console.log('Previous ' + v);
    })
}

But all I get is [Object object]

How could I solve it?

Body:
You can try something like this

prev2() {
this.router.events
  .filter(event => event instanceof NavigationEnd)
.subscribe(event => {
  this.current = event.url
})
}


问:
What's the de facto practice on ampersand encoding in HTML?
By the HTML specification, an ampersand should be encoded as

```<code>&
</code>```

But of course a lot on the web doesn't do that. Here's an example of an ad widget from Amazon.com:

```<code><iframe
    src="http://rcm.amazon.com/e/cm?t=xyzxyz-20&o=1&p=11&l=ur1&category=textbooks&banner=17P1AE8RQ1T7ZFC62V82&f=ifr"
    width="120"
    height="600"
    scrolling="no"
    border="0"
    marginwidth="0"
    style="border:none;"
    frameborder="0">
</iframe>
</code>```

Note that the ampersand is not encoded.

For those work a lot with commercial sites, work in a company, or work with many widget codes, do most of these sites actually encode the ampersand?

(In other words, what percentage of top 1k sites try to encode ampersand properly when it is in the URL?)

Stress: this is not about whether it should or should not be encoded. I just want to ask those who work in companies: if you have seen a lot CGI based URL that has an ampersand in it, and this URL is inside an HTML page, in your experience, are they encoded?

答:
It should always be encoded - either as & or as &

However, a browser's parser is very forgiving :-)

ContentLicense: CC BY-SA 4.0

Body:
By the HTML specification, an ampersand should be encoded as

&

But of course a lot on the web doesn't do that. Here's an example of an ad widget from Amazon.com:

Note that the ampersand is not encoded.

For those work a lot with commercial sites, work in a company, or work with many widget codes, do most of these sites actually encode the ampersand?

(In other words, what percentage of top 1k sites try to encode ampersand properly when it is in the URL?)

Stress: this is not about whether it should or should not be encoded. I just want to ask those who work in companies: if you have seen a lot CGI based URL that has an ampersand in it, and this URL is inside an HTML page, in your experience, are they encoded?

Body:
It should always be encoded - either as &amp; or as &#38;

However, a browser's parser is very forgiving :-)


问:
can't get nice table with kable / kableExtra with knitr2html
I'm using knit2html to generate html reports from R code.

Been trying to use kable / kableExtra to get table printed out nicely however doesn't seems to work.

I will use this simple program to demonstrate, all attempt to print out the table generate pretty crude print out rather than nice print out as I seen on some of the tutorial (e.g. https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html)

R program:

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

library(data.table)
library(knitr)
library(kableExtra)

test_data=data.table(a=c(1,2,3,4,5),
                     b=rep('a', 5),
                     c=rep(2.0, 5),
                     d=rep('a', 5),
                     e=rep(2.0, 5),
                     f=rep('a', 5),
                     g=rep(2.0, 5))

knit2html('test.Rmd')
</code>```

Rmd file:

```<code>```{r testprint1, echo=FALSE}
test_data
```
```{r testprint2, echo=FALSE}
kable(test_data)
```
```{r testprint3, echo=FALSE}
test_data %>% kable("html")
```
```{r testprint4, echo=FALSE}
test_data %>% kable("html") %>% kable_styling()
```
</code>```

A screen capture of result html:

Am I missing something here?

答:
Maybe knit2html isn't bringing in bootstrap?

If you render from the markdown itself you get the nice table from kable_styling:

```<code>```{r echo=FALSE}
library(data.table)
library(knitr)
library(kableExtra)

test_data=data.table(a=c(1,2,3,4,5),
                     b=rep('a', 5),
                     c=rep(2.0, 5),
                     d=rep('a', 5),
                     e=rep(2.0, 5),
                     f=rep('a', 5),
                     g=rep(2.0, 5))
```

```{r testprint1, echo=FALSE}
test_data
```
```{r testprint2, echo=FALSE}
kable(test_data)
```
```{r testprint3, echo=FALSE}
test_data %>% kable("html")
```
```{r testprint4, echo=FALSE}
test_data %>% kable("html") %>% kable_styling()
```
</code>```

Body:
I'm using knit2html to generate html reports from R code.

Been trying to use kable / kableExtra to get table printed out nicely however doesn't seems to work.

I will use this simple program to demonstrate, all attempt to print out the table generate pretty crude print out rather than nice print out as I seen on some of the tutorial (e.g. https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html)

R program:

#!/usr/bin/Rscript

library(data.table)
library(knitr)
library(kableExtra)

test_data=data.table(a=c(1,2,3,4,5),
                     b=rep('a', 5),
                     c=rep(2.0, 5),
                     d=rep('a', 5),
                     e=rep(2.0, 5),
                     f=rep('a', 5),
                     g=rep(2.0, 5))

knit2html('test.Rmd')

Rmd file:

```{r testprint1, echo=FALSE}
test_data
```
```{r testprint2, echo=FALSE}
kable(test_data)
```
```{r testprint3, echo=FALSE}
test_data %>% kable("html")
```
```{r testprint4, echo=FALSE}
test_data %>% kable("html") %>% kable_styling()
```

A screen capture of result html:

Am I missing something here?

Body:
Maybe knit2html isn't bringing in bootstrap?

If you render from the markdown itself you get the nice table from kable_styling:

```{r echo=FALSE}
library(data.table)
library(knitr)
library(kableExtra)

test_data=data.table(a=c(1,2,3,4,5),
                     b=rep('a', 5),
                     c=rep(2.0, 5),
                     d=rep('a', 5),
                     e=rep(2.0, 5),
                     f=rep('a', 5),
                     g=rep(2.0, 5))
```

```{r testprint1, echo=FALSE}
test_data
```
```{r testprint2, echo=FALSE}
kable(test_data)
```
```{r testprint3, echo=FALSE}
test_data %>% kable("html")
```
```{r testprint4, echo=FALSE}
test_data %>% kable("html") %>% kable_styling()
```


问:
iOS 11 prefersLargeTitles not updating until scroll
I implemented a basic UIViewController with a UITableView that's wrapped in a UINavigationController. I set prefersLargeTitles to true:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.title = "Coffees"
}
</code>```

However, the title stays small until I scroll the view, at which point it enlarges. I tried moving that call to where I create the UINavigationController, but there was no effect. I am sure the navigationController is not nil when I set prefersLargeTitles.

Should I be updating that property elsewhere? Or should I file a Radar?

Update:

This only seems to happen if my view contains a UITableView or is itself a UITableViewController

答: In my case the solution was to set tableView's top align to Safe Area and not Superview</p>

Body:
I implemented a basic UIViewController with a UITableView that's wrapped in a UINavigationController. I set prefersLargeTitles to true:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.title = "Coffees"
}

However, the title stays small until I scroll the view, at which point it enlarges. I tried moving that call to where I create the UINavigationController, but there was no effect. I am sure the navigationController is not nil when I set prefersLargeTitles.

Should I be updating that property elsewhere? Or should I file a Radar?

Update:

This only seems to happen if my view contains a UITableView or is itself a UITableViewController


问:
changing the location of the generated mapper classes
I'm using MapStruct with maven as descriped in the documentation (http://mapstruct.org/documentation/stable/reference/html/). Now I'd like to change the location of the generated mapper classes from target to source folder. I've read How to chanage the mapstruct generated classes location and M2E and having maven generated source folders as eclipse source folders and got it working by using the maven-processor-plugin (the apt-maven-plugin might work too). In addition to that I had to remove the annotationProcessorPaths from the maven-compiler-plugin. Otherwise the maven builds failed because the generated code was duplicated under "generated-sources" (the changed output folder) and "target\generated-sources\annotations" (the default output folder).
But now every time I hit "Maven" --> "Update Project" in eclipse I have to re-enable "enable annotation processing" in the project properties. And when I change the "Generated source directory" in eclipse by hand it will also be overridden.

So is it possible to change the output directory in maven and keep "Enable annotation processing" enabled in eclipse ? I'm using eclipse JEE oxygen with the MapStruct and m2e-apt plugin installed. If it helps I'm using also Spring Boot 1.5.9

答:
What you are looking for is the generatedSourcesDirectory option of the maven-compiler. That property controls where the Java Annotation Processor will output the generated sources.

I think that if you set that, the integration between Eclipse and Maven should work correctly and you should get everything without the need of the build-helper-maven-plugin


问:
Struggling with while loop with two conditions and a for loop
I'm trying to learn how to use arrays in bash. I'm writing a script that asks the user for three numbers and figures out what the biggest number is. I want the script to force the user to enter only numeric values. Furthermore, I want the three numbers should be different. I'm using an array to store user input. This is what I have so far:

```<code>## declare variables
order=("first" "second" "third")
answers=()
RED='\033[0;31m'
NC='\033[0m' # No Color

numbersonly() {
        if [[ ! $1 =~ ^[0-9]+$ ]]; then
        echo "${RED}$1 is not a valid number.${NC}"
        else
            answers+=("$input")
            break
        fi
}

inarray(){
    for e in ${answers[@]}; do
    if [[ $1 == $e ]]; then
    echo "${RED}Warning.${NC}"
    fi
    done
}

readnumber(){
for i in {1..3}; do
j=$(awk "BEGIN { print $i-1 }")
    while read -p "Enter the ${order[$j]} number: " input ; do
    inarray $input
    numbersonly $input
    done
done
}

displayanswers(){
echo "Your numbers are: ${answers[@]}"
}

biggestnumber(){

if (( ${answers[0]} >= ${answers[1]} )); then
        biggest=${answers[0]}
        else
        biggest=${answers[1]}
        fi
if (( $biggest <= ${answers[2]} )); then
        biggest=${answers[2]}
        fi
echo "The biggest number is: $biggest"
}

main(){
readnumber
displayanswers
biggestnumber
}

main
</code>```

Right now, I can get the script to display a warning when the user enters a number that was previously entered, but I can't seem to find the proper syntax to stay in the while loop if the user input has already been entered. Thoughts?

答:
Without much study here is what leapt off the screen to me follows. Beware I haven't actually tested it... debugging is an exercise left to the student.

Recommend using newer "function" definitions as you can declare local variables. () definitions do not allow localized variables.

```function inarray
{
    local e;   #don't muck up any variable e in caller
 ...
}```

To calculate values avoid extra awk and use j=$(( i - 1 ));

biggestnumber should likely use a loop.

Overall comment:

```nummax=3;  #maximum value defined in just one place

# loop this way... showing optional {} trick for marking larger loops
for (( n = 0; n < nummax; ++n )); do
{
     nx=$(( 1 + n ));   #1 based index
} done;
```

Hint: should stop input loop once all input present. Could also add:

```    if [ "" == "${input:-}" ]; then break;```

```for (( a = 0; a < ${#answer[*]}; ++a )); do```

Note the extensive use of double quotes to avoid syntax errors if the variable value is empty or contains many shell metacharacters, like spaces. I can't tell you how many bug reports I've fixed by adding the quotes to existing code.

[[ ... ]] expressions use file name tests, not regular expressions.  The closest you can get to [[ ! $1 =~ ^[0-9]+$ ]]; is using [[ "$1" != [0-9]* ]] && [[ "$1" != *[^0-9]* ]].
But I suspect ! expr >/dev/null "$i" : '[0-9][0-9]*$'; is more what you want as "expr" does use regular expressions. Don't enclose in []s. Used [0-9][0-9]* rather than [0-9]+ as "+" has given me mixed successes across all dialects of UNIX regular expressions.

Body:
I'm trying to learn how to use arrays in bash. I'm writing a script that asks the user for three numbers and figures out what the biggest number is. I want the script to force the user to enter only numeric values. Furthermore, I want the three numbers should be different. I'm using an array to store user input. This is what I have so far:

## declare variables
order=("first" "second" "third")
answers=()
RED='\033[0;31m'
NC='\033[0m' # No Color

numbersonly() {
        if [[ ! $1 =~ ^[0-9]+$ ]]; then
        echo "${RED}$1 is not a valid number.${NC}"
        else
            answers+=("$input")
            break
        fi
}

inarray(){
    for e in ${answers[@]}; do
    if [[ $1 == $e ]]; then
    echo "${RED}Warning.${NC}"
    fi
    done
}

readnumber(){
for i in {1..3}; do
j=$(awk "BEGIN { print $i-1 }")
    while read -p "Enter the ${order[$j]} number: " input ; do
    inarray $input
    numbersonly $input
    done
done
}

displayanswers(){
echo "Your numbers are: ${answers[@]}"
}

biggestnumber(){

if (( ${answers[0]} >= ${answers[1]} )); then
        biggest=${answers[0]}
        else
        biggest=${answers[1]}
        fi
if (( $biggest <= ${answers[2]} )); then
        biggest=${answers[2]}
        fi
echo "The biggest number is: $biggest"
}

main(){
readnumber
displayanswers
biggestnumber
}

main

Right now, I can get the script to display a warning when the user enters a number that was previously entered, but I can't seem to find the proper syntax to stay in the while loop if the user input has already been entered. Thoughts?

Body:
Without much study here is what leapt off the screen to me follows. Beware I haven't actually tested it... debugging is an exercise left to the student.

Recommend using newer "function" definitions as you can declare local variables. () definitions do not allow localized variables.

function inarray
{
    local e;   #don't muck up any variable e in caller
 ...
}

To calculate values avoid extra awk and use j=$(( i - 1 ));

biggestnumber should likely use a loop.

Overall comment:

nummax=3;  #maximum value defined in just one place

# loop this way... showing optional {} trick for marking larger loops
for (( n = 0; n < nummax; ++n )); do
{
     nx=$(( 1 + n ));   #1 based index
} done;

Hint: should stop input loop once all input present. Could also add:

    if [ "" == "${input:-}" ]; then break;

for (( a = 0; a < ${#answer[*]}; ++a )); do

Note the extensive use of double quotes to avoid syntax errors if the variable value is empty or contains many shell metacharacters, like spaces. I can't tell you how many bug reports I've fixed by adding the quotes to existing code.

[[ ... ]] expressions use file name tests, not regular expressions.  The closest you can get to [[ ! $1 =~ ^[0-9]+$ ]]; is using [[ "$1" != [0-9]* ]] && [[ "$1" != *[^0-9]* ]].
But I suspect ! expr >/dev/null "$i" : '[0-9][0-9]*$'; is more what you want as "expr" does use regular expressions. Don't enclose in []s. Used [0-9][0-9]* rather than [0-9]+ as "+" has given me mixed successes across all dialects of UNIX regular expressions.


问:
HUBOT Coffescript - JSON obejct
Wondering if anyone can help me with this - pretty much novice in scripting and not sure if I'm doing it right. I need to get an object from this JSON string and it keeps giving me "undefined" error.

Here's the JSON:

```<code>    `
    { data:
    [ { type: 'gif',
        id: 'Cmr1OMJ2FN0B2',
        slug: 'hello-Cmr1OMJ2FN0B2',
        url: 'https://giphy.com/gifs/hello-Cmr1OMJ2FN0B2',
        bitly_gif_url: 'https://gph.is/2bZufS7',
        bitly_url: 'https://gph.is/2bZufS7',
        embed_url: 'https://giphy.com/embed/Cmr1OMJ2FN0B2',
        username: '',
        source: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo',
        rating: 'g',
        content_url: '',
        source_tld: 'www.fanpop.com',
        source_post_url: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo',
        is_indexable: 0,
        import_datetime: '2016-09-05 13:48:36',
        trending_datetime: '2017-09-19 14:26:18',
        images: [Object],
        title: 'bom dia hello GIF' } ],
    pagination: { total_count: 2516, count: 1, offset: 0 },
    meta:
    { status: 200,
        msg: 'OK',
        response_id: '5a28576867382f644dc7d33b' } }
    `
</code>```

And here's my HUBOT script:

```<code>    `
    robot.hear /^(no)$|^.*(\sno\s).*$/i, (res) ->
            api_url = 'https://api.giphy.com'
            path = '/v1/gifs/search'
            url = "#{api_url}#{path}"
            robot.http(url)
                .query
                    q: "nono+penguin"
                    rating: 'g'
                    limit: 1
                    fmt: 'json'
                .header('api_key', giphyAuthToken)
                .header('Content-Type', 'application/json')
                .get() (err, res, body) ->
                    # error checking code here
                    if err
                        console.log err
                    else
                        data = JSON.parse(body)
                        console.log data #this prints above data
                        console.log "success....got giphy response"
                        console.log data.images.original.url #This is giving error that original is undefined
                        process.exit(1)
    `
</code>```

Wondering how can I access this "images" object from Giphy's response.

Thanks

答:
The data field in your object is an Array so you need to put the index in order to access the content, i.e. </p>

```<code>data = JSON.parse(body)
console.log data[0].images
</code>```

Title: HUBOT Coffescript - JSON obejct

Body:
Wondering if anyone can help me with this - pretty much novice in scripting and not sure if I'm doing it right. I need to get an object from this JSON string and it keeps giving me "undefined" error.

Here's the JSON:

    `
    { data:
    [ { type: 'gif',
        id: 'Cmr1OMJ2FN0B2',
        slug: 'hello-Cmr1OMJ2FN0B2',
        url: 'https://giphy.com/gifs/hello-Cmr1OMJ2FN0B2',
        bitly_gif_url: 'https://gph.is/2bZufS7',
        bitly_url: 'https://gph.is/2bZufS7',
        embed_url: 'https://giphy.com/embed/Cmr1OMJ2FN0B2',
        username: '',
        source: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo',
        rating: 'g',
        content_url: '',
        source_tld: 'www.fanpop.com',
        source_post_url: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo',
        is_indexable: 0,
        import_datetime: '2016-09-05 13:48:36',
        trending_datetime: '2017-09-19 14:26:18',
        images: [Object],
        title: 'bom dia hello GIF' } ],
    pagination: { total_count: 2516, count: 1, offset: 0 },
    meta:
    { status: 200,
        msg: 'OK',
        response_id: '5a28576867382f644dc7d33b' } }
    `

And here's my HUBOT script:

    `
    robot.hear /^(no)$|^.*(\sno\s).*$/i, (res) ->
            api_url = 'https://api.giphy.com'
            path = '/v1/gifs/search'
            url = "#{api_url}#{path}"
            robot.http(url)
                .query
                    q: "nono+penguin"
                    rating: 'g'
                    limit: 1
                    fmt: 'json'
                .header('api_key', giphyAuthToken)
                .header('Content-Type', 'application/json')
                .get() (err, res, body) ->
                    # error checking code here
                    if err
                        console.log err
                    else
                        data = JSON.parse(body)
                        console.log data #this prints above data
                        console.log "success....got giphy response"
                        console.log data.images.original.url #This is giving error that original is undefined
                        process.exit(1)
    `

Wondering how can I access this "images" object from Giphy's response.

Thanks

Body:
The data field in your object is an Array so you need to put the index in order to access the content, i.e.

data = JSON.parse(body)
console.log data[0].images


问:
Core Data tutorials
Is there any good Core Data tutorials out there for mac/cocoa(not iphone)? </p>

答:
What about the Core Data Programming Guide?

And, except for XML Storage and support for Cocoa Bindings, Core Data is (exactly?) the same in both Mac OS X and iOS.

Title: Core Data tutorials


问:
Optimise T-sql query
The query I need to develop is to list out sites which have no records (retail transactions) for a given date.  I've been able to accomplish this for a specific site, but I know the query can be written more efficiently using joins but my foray into inners and outers hasn't been much fun.

Here's what I have so far:

```<code>DECLARE @StartDate DATE = '2017-11-01',
    @EndDate DATE = '2017-11-30';

SELECT tx.Txndate, count(*) as txCount
FROM [Report].[dbo].[FactTransactions] tx
where tx.Site = 2
and tx.TxnDate between @StartDate and @EndDate
group by tx.TxnDate
union all
select db.daybookdate, 0 as txCount
from DimDaybook db
where db.daybookdate between @StartDate and @EndDate
and NOT EXISTS (SELECT 1 FROM [Report].[dbo].[FactTransactions] AS t WHERE t.TxnDate = db.daybookdate and t.txndate between @StartDate and @EndDate and t.site = 2)
order by tx.Txndate
</code>```

This returns me the result set for site 2

```<code>Txndate txCount
2017-11-01  1691
2017-11-02  1657
2017-11-03  1835
2017-11-04  1587
2017-11-05  1489
2017-11-06  1544
2017-11-07  1525
2017-11-08  1782
2017-11-09  1848
2017-11-10  1990
2017-11-11  0
2017-11-12  0
</code>```

What I'd really like to have is a result set that looks like this and runs much much quicker than my hack (currently around 2mins - for context the transactions table has 83,486,412 records)

```<code>Site    Date    Transactions
2   11/11/17    0
2   12/11/27    0
3   12/11/17    0
22  1/11/17     0
</code>```

答:
As you already have a list of all days available (DimDaybook) all you need to do is "left join" your counts to those days and then replace any NULLs with zero.

Do be careful with date ranges, using "between" might sound like a good way to do it but it isn't the best way. Instead of trying to specify the last day of November, just specify the first of December instead, then use a combination of >= and < with your date parameters and then your date range will work for every date/time data type (datetime2, datetime, smalldatime, date)

```<code>DECLARE @StartDate date = '2017-11-01'
      , @EndDate date = '2017-12-01'; -- this has changed!

SELECT
      db.daybookdate
    , COALESCE(txCount, 0)
FROM DimDaybook db
LEFT JOIN (
                  SELECT
                        tx.Txndate
                      , COUNT(*) AS txcount
                  FROM [Report].[dbo].[FactTransactions] tx
                  WHERE tx.Site = 2
                  AND tx.TxnDate >= @StartDate AND tx.TxnDate < @EndDate
                  GROUP BY
                        tx.TxnDate
      ) c ON db.daybookdate = c.Txndate
WHERE db.daybookdate >= @StartDate AND db.daybookdate < @EndDate
AND tx.Txndate IS NULL
</code>```

When you establish a date reference like '2017-11-30' the time of day is automatically set at 00:00:00+0000000. So, for any data you might encounter that has a date of '2017-11-30' but a time > 00:00:00 that data would be excluded. In short: the duration of that day is ignored. This is easily overcome by simply moving the end date "up" to the next day and using less than that date, and to do that you must avoid using "between".

Title: Optimise T-sql query

Body:
The query I need to develop is to list out sites which have no records (retail transactions) for a given date.  I've been able to accomplish this for a specific site, but I know the query can be written more efficiently using joins but my foray into inners and outers hasn't been much fun.

Here's what I have so far:

DECLARE @StartDate DATE = '2017-11-01',
    @EndDate DATE = '2017-11-30';

SELECT tx.Txndate, count(*) as txCount
FROM [Report].[dbo].[FactTransactions] tx
where tx.Site = 2
and tx.TxnDate between @StartDate and @EndDate
group by tx.TxnDate
union all
select db.daybookdate, 0 as txCount
from DimDaybook db
where db.daybookdate between @StartDate and @EndDate
and NOT EXISTS (SELECT 1 FROM [Report].[dbo].[FactTransactions] AS t WHERE t.TxnDate = db.daybookdate and t.txndate between @StartDate and @EndDate and t.site = 2)
order by tx.Txndate

This returns me the result set for site 2

Txndate txCount
2017-11-01  1691
2017-11-02  1657
2017-11-03  1835
2017-11-04  1587
2017-11-05  1489
2017-11-06  1544
2017-11-07  1525
2017-11-08  1782
2017-11-09  1848
2017-11-10  1990
2017-11-11  0
2017-11-12  0

What I'd really like to have is a result set that looks like this and runs much much quicker than my hack (currently around 2mins - for context the transactions table has 83,486,412 records)

Site    Date    Transactions
2   11/11/17    0
2   12/11/27    0
3   12/11/17    0
22  1/11/17     0

Body:
As you already have a list of all days available (DimDaybook) all you need to do is "left join" your counts to those days and then replace any NULLs with zero.

Do be careful with date ranges, using "between" might sound like a good way to do it but it isn't the best way. Instead of trying to specify the last day of November, just specify the first of December instead, then use a combination of >= and < with your date parameters and then your date range will work for every date/time data type (datetime2, datetime, smalldatime, date)

DECLARE @StartDate date = '2017-11-01'
      , @EndDate date = '2017-12-01'; -- this has changed!

SELECT
      db.daybookdate
    , COALESCE(txCount, 0)
FROM DimDaybook db
LEFT JOIN (
                  SELECT
                        tx.Txndate
                      , COUNT(*) AS txcount
                  FROM [Report].[dbo].[FactTransactions] tx
                  WHERE tx.Site = 2
                  AND tx.TxnDate >= @StartDate AND tx.TxnDate < @EndDate
                  GROUP BY
                        tx.TxnDate
      ) c ON db.daybookdate = c.Txndate
WHERE db.daybookdate >= @StartDate AND db.daybookdate < @EndDate
AND tx.Txndate IS NULL

When you establish a date reference like '2017-11-30' the time of day is automatically set at 00:00:00+0000000. So, for any data you might encounter that has a date of '2017-11-30' but a time > 00:00:00 that data would be excluded. In short: the duration of that day is ignored. This is easily overcome by simply moving the end date "up" to the next day and using less than that date, and to do that you must avoid using "between".


问:
Not able to print very large strings in java (neither in Eclipse nor in cmd)
I am working with very large strings whose length range from 0 to 2*10^5.
When I try to print the strings on the console or using command line via System.out.println, nothing shows up. Only strings/substrings with 4096 characters show up. Also, I get no errors.

I also tried to print the characters one at a time using System.out.print(chararray[i]) but to no avail.

I even tried tried to use the below but it did not work.

```<code>StringWriter stringWriter = new StringWriter();
BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
bufferedWriter.write(str);   //does not display
StringBuilder sb = new StringBuilder(str);
System.out.println(sb);   //does not display
</code>```

Displaying is important here since I am submitting my program on HackerRank and my program does not pass the test case due to this issue.

Can anyone please help?

Note: I know the strings are being stored properly since I was able to verify their lengths using str.length();

答:
Try dividing the string into multiple chunks and then write to a text file.
You can refer below link to divide the string : How to split a string into equal parts and store it in a string array</p>

Body:
I am working with very large strings whose length range from 0 to 2*10^5.
When I try to print the strings on the console or using command line via System.out.println, nothing shows up. Only strings/substrings with 4096 characters show up. Also, I get no errors.

I also tried to print the characters one at a time using System.out.print(chararray[i]) but to no avail.

I even tried tried to use the below but it did not work.

StringWriter stringWriter = new StringWriter();
BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
bufferedWriter.write(str);   //does not display
StringBuilder sb = new StringBuilder(str);
System.out.println(sb);   //does not display

Displaying is important here since I am submitting my program on HackerRank and my program does not pass the test case due to this issue.

Can anyone please help?

Note: I know the strings are being stored properly since I was able to verify their lengths using str.length();


问:
best way to concatenate scope results
I have two scopes. One that checks if db column is null or empty string and another that checks for the opposite (not null, and not empty string)

```<code>scope :has_something, where('something IS NOT NULL AND something != ""')
scope :has_no_something, where('something IS NULL OR something = ""')
</code>```

I would like to end up with the two results concatenated. ie results that have something followed by results that do not have something

My first attempt was something like this:

```<code>def self.with_something_data_first
  has_something + has_no_something
end
</code>```

This results in:

NoMethodError: undefined method `order' for #

because this method is combined with an order

```<code>Model.with_something_data_first.order(:created_at).reverse_order.limit(20)
</code>```

It would be great if I could could do this in one scope where it returned all records with data then all records with null or empty string. Obviously you can't order by nil but maybe you know of a tricky way to get around this?

答:
I ended up coming up with a solution that better served my needs. Instead of checking for empty strings and null values in the db. I'm going to just switch empty strings into nulls when they entered and use an order like this that puts nulls at the end of the result set.</p>

```<code>scope :with_post_comments_first, order('-comment DESC')
</code>```

Title: best way to concatenate scope results

Body:
I have two scopes. One that checks if db column is null or empty string and another that checks for the opposite (not null, and not empty string)

scope :has_something, where('something IS NOT NULL AND something != ""')
scope :has_no_something, where('something IS NULL OR something = ""')

I would like to end up with the two results concatenated. ie results that have something followed by results that do not have something

My first attempt was something like this:

def self.with_something_data_first
  has_something + has_no_something
end

This results in:

NoMethodError: undefined method `order' for #

because this method is combined with an order

Model.with_something_data_first.order(:created_at).reverse_order.limit(20)

It would be great if I could could do this in one scope where it returned all records with data then all records with null or empty string. Obviously you can't order by nil but maybe you know of a tricky way to get around this?

Body:
I ended up coming up with a solution that better served my needs. Instead of checking for empty strings and null values in the db. I'm going to just switch empty strings into nulls when they entered and use an order like this that puts nulls at the end of the result set.

scope :with_post_comments_first, order('-comment DESC')


问:
Excel Function checking street name in full addresses
I have two sheets in excel, on containing full addresses and one containing street names. I need to create a lookup function that checks each full address to see if it contains one of the street names in the other sheet.

Normally i would use this =VLOOKUP or =Countif function to return a value if the cell exist in the lookup matrix, but they both check the whole content of the cell. while i only need to see if it contains a specific part.

Example cells would be.

Full Adresse Sheet1 A1:

Alpha street 34, fictional city Zip230

Lookup Sheet2 columns A:

Alpha Street

Beta Street

...

trying to create a function that check if any string in Column A Sheet2 exisit inside the string in Sheet1 A1. Even better if the function is not case sensitive.

答:
This formula should do the trick:

```<code>=SUMPRODUCT(--ISNUMBER(SEARCH(search_range,lookup_cell)))>0
</code>```

where search_range is the column where you have your street names, and lookup_cell is the cell that you are searching in that instance.

As far as I've tested it, this is not case-sensitive.

Body:
This formula should do the trick:

=SUMPRODUCT(--ISNUMBER(SEARCH(search_range,lookup_cell)))>0

where search_range is the column where you have your street names, and lookup_cell is the cell that you are searching in that instance.

As far as I've tested it, this is not case-sensitive.


问:
Powershell - Send CSV data to email in a table
Right now my goal is to download a CSV containing threat data from a url, capture two columns, File Name and the DeviceName, both of which are headers in the CSV. I then want to export that data to a single line in an email, which will then go to two members on our security team to review in a plaintext format. The goal is to make it unnecessary for them to download and copy paste directly from the CSV, as there's a lot of extraneous data in the CSV.

It's a pretty simple script, so everything works fine. My question is: how do I pull two columns of data from the csv and write it to the email body? Ideally in some sort of table, so the two columns are aligned.

I've found some resources online, most notably a script that takes any Object from the PowerShell interface, convert the object (table) into HTML and then sends it by email: https://gallery.technet.microsoft.com/scriptcenter/bd0c8d87-466f-4488-92a2-0f726cb6f4cd

Which is perfect, since this is exactly what I want to do. I'm just not really sure how to properly pass the data from the CSV to the powershell function.

Note this is also my first project in powershell, and it's mostly cobbled together from technet documentation and scraps of code examples I've found online. I'm a junior sysadmin, so not a ton of programming background.

Thanks bunches!

Update 1

So managed to get a bit more success this time around, but unfortunately the emailed output is a garbled list of numbers that don't correspond to any data found within the CSV.

I'm pretty sure my error is somewhere in here, but I'm not quite sure where I'm failing:

```<code>$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html
</code>```

The rest of my code is below:

```<code><#
.SYNOPSIS
Send an email with an object in a pretty table
.DESCRIPTION
Send email
.PARAMETER InputObject
Any PSOBJECT or other Table
.PARAMETER Subject
The Subject of the email
.PARAMETER To
The To field is who receives the email
.PARAMETER From
The From address of the email
.PARAMETER CSS
This is the Cascading Style Sheet that will be used to Style the table
.PARAMETER SmtpServer
The SMTP relay server
.EXAMPLE
PS C:\> Send-HtmlEmail -InputObject (Get-process *vmware* | select CPU, WS) -Subject "This is a process report"
An example to send some process information to email recipient
.NOTES
NAME        :  Send-HtmlEmail
VERSION     :  1.1.0
LAST UPDATED:  01/03/2013
AUTHOR      :  Milo
.INPUTS
None
.OUTPUTS
None
#>

function Send-HTMLEmail {
#Requires -Version 2.0
[CmdletBinding()]
 Param
   ([Parameter(Mandatory=$True,
               Position = 0,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Inputobject")]
    $InputObject,
    [Parameter(Mandatory=$True,
               Position = 1,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Subject")]
    [String]$Subject,
    [Parameter(Mandatory=$False,
               Position = 2,
               HelpMessage="Please enter the To address")]
    [String[]]$To = "smurphy@klick.com",
    [String]$From = "cylancereporting@klick.com",
    [String]$CSS,
    [String]$SmtpServer ="smtp.klick.com"
   )#End Param

if (!$CSS)
{
    $CSS = @"
        <style type="text/css">
            table {
            font-family: Verdana;
            border-style: dashed;
            border-width: 1px;
            border-color: #FF6600;
            padding: 5px;
            background-color: #FFFFCC;
            table-layout: auto;
            text-align: center;
            font-size: 8pt;
            }

            table th {
            border-bottom-style: solid;
            border-bottom-width: 1px;
            font: bold
            }
            table td {
            border-top-style: solid;
            border-top-width: 1px;
            }
            .style1 {
            font-family: Courier New, Courier, monospace;
            font-weight:bold;
            font-size:small;
            }
            </style>
"@
}#End if

$HTMLDetails = @{
    Title = $Subject
    Head = $CSS
    }

$Splat = @{
    To         =$To
    Body       ="$($InputObject | ConvertTo-Html @HTMLDetails)"
    Subject    =$Subject
    SmtpServer =$SmtpServer
    From       =$From
    BodyAsHtml =$True
    }
    Send-MailMessage @Splat

}#Send-HTMLEmail

#Defines variables
$url = "https://protect.cylance.com/Reports/ThreatDataReportV1/threats/BE5ABB1717DB46978BED0AF14A308557"
$output = "$PWD\ThreatsDataReport.csv"

(New-Object System.Net.WebClient).DownloadFile($url, $output)
#Downloads the CSV from $url and saves it to $output

$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html

Send-HTMLEmail -InputObject ($csv) -Subject "Cylance: Weekly Summary"
</code>```

Original Code

```<code>$url = "foo.com/directlinktocsv"
$output = "$PSScriptRoot\ThreatsDataReport.csv"
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "myemail@mydomain.com"
$emailRecipients = @("Foo <foo@mydomain.com>", "Bar <bar@mydomain.com>")
$emailSubject = "Cylance Detected Threats"
$emailBody = "This is where I want my output to go"

(New-Object System.Net.WebClient).DownloadFile($url, $output)

$csv = Import-Csv $output

    $csv."File Name" | ForEach-Object {
    $_

    }

    $csv.DeviceName | ForEach-Object {

    $_

    }

Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody
</code>```

答:
Managed to come up with an answer to this!

First things first I threw out the Send-HTMLEmail in the link, as it was neither necessary nor particularly helpful.

My fixed, working code is

```<code>#Defines variables
$url = "mysite.com/ThreatsDataReport.csv"
$output = "$PWD\ThreatsDataReport.csv"
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "reportingemail@domain.com"
$emailRecipients = @("Foo <foo@domain.com>"), "Bar <bar@domain.com>")
$emailSubject = "Cylance Reporting"

(New-Object System.Net.WebClient).DownloadFile($url, $output)
#Downloads the CSV from $url and saves it to $output

#Sets HTML Head Information
$a = "<style>"
$a = $a + "BODY{background-color:peachpuff;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}"
$a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:palegoldenrod}"
$a = $a + "</style>"

$csv = Import-Csv $output | Select "File Name",DeviceName,"File Path" | ConvertTo-Html -head $a -Body "<H2>Cylance Weekly Report</H2>"
#Imports the CSV saved to $output.
#Selects File Name, Device Name, and File Path columns, then converts to HTML using the Head +Body Information
$emailBody = "$csv"

#defines the body text of the email. Note that this has to be a string, $emailBody = $csv will not work on its own.

Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody -BodyAsHtml
#Sends the actual email
</code>```

Body:
Right now my goal is to download a CSV containing threat data from a url, capture two columns, File Name and the DeviceName, both of which are headers in the CSV. I then want to export that data to a single line in an email, which will then go to two members on our security team to review in a plaintext format. The goal is to make it unnecessary for them to download and copy paste directly from the CSV, as there's a lot of extraneous data in the CSV.

It's a pretty simple script, so everything works fine. My question is: how do I pull two columns of data from the csv and write it to the email body? Ideally in some sort of table, so the two columns are aligned.

I've found some resources online, most notably a script that takes any Object from the PowerShell interface, convert the object (table) into HTML and then sends it by email: https://gallery.technet.microsoft.com/scriptcenter/bd0c8d87-466f-4488-92a2-0f726cb6f4cd

Which is perfect, since this is exactly what I want to do. I'm just not really sure how to properly pass the data from the CSV to the powershell function.

Note this is also my first project in powershell, and it's mostly cobbled together from technet documentation and scraps of code examples I've found online. I'm a junior sysadmin, so not a ton of programming background.

Thanks bunches!

Update 1

So managed to get a bit more success this time around, but unfortunately the emailed output is a garbled list of numbers that don't correspond to any data found within the CSV.

I'm pretty sure my error is somewhere in here, but I'm not quite sure where I'm failing:

$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html

The rest of my code is below:

<#
.SYNOPSIS
Send an email with an object in a pretty table
.DESCRIPTION
Send email
.PARAMETER InputObject
Any PSOBJECT or other Table
.PARAMETER Subject
The Subject of the email
.PARAMETER To
The To field is who receives the email
.PARAMETER From
The From address of the email
.PARAMETER CSS
This is the Cascading Style Sheet that will be used to Style the table
.PARAMETER SmtpServer
The SMTP relay server
.EXAMPLE
PS C:\> Send-HtmlEmail -InputObject (Get-process *vmware* | select CPU, WS) -Subject "This is a process report"
An example to send some process information to email recipient
.NOTES
NAME        :  Send-HtmlEmail
VERSION     :  1.1.0
LAST UPDATED:  01/03/2013
AUTHOR      :  Milo
.INPUTS
None
.OUTPUTS
None
#>

function Send-HTMLEmail {
#Requires -Version 2.0
[CmdletBinding()]
 Param
   ([Parameter(Mandatory=$True,
               Position = 0,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Inputobject")]
    $InputObject,
    [Parameter(Mandatory=$True,
               Position = 1,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Subject")]
    [String]$Subject,
    [Parameter(Mandatory=$False,
               Position = 2,
               HelpMessage="Please enter the To address")]
    [String[]]$To = "smurphy@klick.com",
    [String]$From = "cylancereporting@klick.com",
    [String]$CSS,
    [String]$SmtpServer ="smtp.klick.com"
   )#End Param

if (!$CSS)
{
    $CSS = @"

"@
}#End if

$HTMLDetails = @{
    Title = $Subject
    Head = $CSS
    }

$Splat = @{
    To         =$To
    Body       ="$($InputObject | ConvertTo-Html @HTMLDetails)"
    Subject    =$Subject
    SmtpServer =$SmtpServer
    From       =$From
    BodyAsHtml =$True
    }
    Send-MailMessage @Splat

}#Send-HTMLEmail

#Defines variables
$url = "https://protect.cylance.com/Reports/ThreatDataReportV1/threats/BE5ABB1717DB46978BED0AF14A308557"
$output = "$PWD\ThreatsDataReport.csv"

(New-Object System.Net.WebClient).DownloadFile($url, $output)
#Downloads the CSV from $url and saves it to $output

$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html

Send-HTMLEmail -InputObject ($csv) -Subject "Cylance: Weekly Summary"

Original Code

$url = "foo.com/directlinktocsv"
$output = "$PSScriptRoot\ThreatsDataReport.csv"
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "myemail@mydomain.com"
$emailRecipients = @("Foo <foo@mydomain.com>", "Bar <bar@mydomain.com>")
$emailSubject = "Cylance Detected Threats"
$emailBody = "This is where I want my output to go"

(New-Object System.Net.WebClient).DownloadFile($url, $output)

$csv = Import-Csv $output

    $csv."File Name" | ForEach-Object {
    $_

    }

    $csv.DeviceName | ForEach-Object {

    $_

    }

Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody

Body:
Managed to come up with an answer to this!

First things first I threw out the Send-HTMLEmail in the link, as it was neither necessary nor particularly helpful.

My fixed, working code is

#Defines variables
$url = "mysite.com/ThreatsDataReport.csv"
$output = "$PWD\ThreatsDataReport.csv"
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "reportingemail@domain.com"
$emailRecipients = @("Foo <foo@domain.com>"), "Bar <bar@domain.com>")
$emailSubject = "Cylance Reporting"

(New-Object System.Net.WebClient).DownloadFile($url, $output)
#Downloads the CSV from $url and saves it to $output

#Sets HTML Head Information
$a = "<style>"
$a = $a + "BODY{background-color:peachpuff;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}"
$a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:palegoldenrod}"
$a = $a + "</style>"

$csv = Import-Csv $output | Select "File Name",DeviceName,"File Path" | ConvertTo-Html -head $a -Body "<H2>Cylance Weekly Report</H2>"
#Imports the CSV saved to $output.
#Selects File Name, Device Name, and File Path columns, then converts to HTML using the Head +Body Information
$emailBody = "$csv"

#defines the body text of the email. Note that this has to be a string, $emailBody = $csv will not work on its own.

Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody -BodyAsHtml
#Sends the actual email