问:
how to pass multiple params in exec in node js
I'm using exec library to call R-script from node js express. Below is my code :

```<code>var exec = require("child_process").exec;

var param1 = some url;
var param2 = "hello";
var param3 = "world"
exec('Rscript pathtoscript/myScript.R"+" "+param1+" "+param2 , function(error, stdout, stderr) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        else if (stderr) {
            console.log(stderr);
            res.send(stderr);
        }
        else if (stdout) {
            console.log("RAN SUCCESSFULLY");
            res.json(stdout);
        }
    });
</code>```

In the above code, if I pass only param2 and param3 the r script is able to identify it. But when I pass url, only some part of url is is getting identified as URL and rest is not (may be its long). Please suggest. Thanks

答:
This is not an exact answer, but I hope it helps debug the issue;

What I tried to do here is double quote param1, and separate the command from the exec to make it a little easier to read.

Best of luck.

```<code>var exec = require("child_process").exec;

var param1 = "\"http:\\something\"";
var param2 = "hello";
var param3 = "world"
var command = "Rscript pathtoscript/myScript.R "+ param1 + " " + param2 + " " + param3;

exec(command, function(error, stdout, stderr) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        else if (stderr) {
            console.log(stderr);
            res.send(stderr);
        }
        else if (stdout) {
            console.log("RAN SUCCESSFULLY");
            res.json(stdout);
        }
    });
</code>```

Body:
I'm using exec library to call R-script from node js express. Below is my code :

var exec = require("child_process").exec;

var param1 = some url;
var param2 = "hello";
var param3 = "world"
exec('Rscript pathtoscript/myScript.R"+" "+param1+" "+param2 , function(error, stdout, stderr) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        else if (stderr) {
            console.log(stderr);
            res.send(stderr);
        }
        else if (stdout) {
            console.log("RAN SUCCESSFULLY");
            res.json(stdout);
        }
    });

In the above code, if I pass only param2 and param3 the r script is able to identify it. But when I pass url, only some part of url is is getting identified as URL and rest is not (may be its long). Please suggest. Thanks

Body:
This is not an exact answer, but I hope it helps debug the issue;

What I tried to do here is double quote param1, and separate the command from the exec to make it a little easier to read.

Best of luck.

var exec = require("child_process").exec;

var param1 = "\"http:\\something\"";
var param2 = "hello";
var param3 = "world"
var command = "Rscript pathtoscript/myScript.R "+ param1 + " " + param2 + " " + param3;

exec(command, function(error, stdout, stderr) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        else if (stderr) {
            console.log(stderr);
            res.send(stderr);
        }
        else if (stdout) {
            console.log("RAN SUCCESSFULLY");
            res.json(stdout);
        }
    });


来源: stackexchange

ContentLicense: CC BY-SA 3.0

Title: Splitting a pandas Dataframe into separate groups

Body:
Given the following dataset DF:

uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:49,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:54:27,P,5.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:16,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:18,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:55,P,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:15,P,1.0,01:59:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:31,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:51,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:22,P,4.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:51,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:22,S,98.0,00:04:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:27,S,98.0,00:03:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:30:27,S,99.0,00:02:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:31:27,S,100.0,00:01:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00

I would like to split into two:

df1:

uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:49,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:54:27,P,5.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00

df2:

uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:16,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:18,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:55,P,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:15,P,1.0,01:59:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:31,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:51,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:22,P,4.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:51,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:22,S,98.0,00:04:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:27,S,98.0,00:03:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:30:27,S,99.0,00:02:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:31:27,S,100.0,00:01:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00

The split should be based on the Op.progressPercentage attribute which can assume value from 1 to 100.

When I try to apply the solution provided at splitting a pandas Dataframe as shown below, I do not get the right and expected result.

df_dataset = pd.read_csv(filepath) #your input data saved here
wash_list = []
shifted = df_dataset['Op.progressPercentage'].shift()
m = shifted.diff(-1).ne(0) & shifted.eq(100)
a = m.cumsum()
aa = df_dataset.groupby([df_dataset.uuid,a])
for k, gp in aa:
    wash_list.append(gp.sort_values(['uuid', 'eventTime'], ascending=[1, 1]))

for wash in wash_list :
    print("")
    print(wash.to_string())
    print("")

Please, any help would be very appreciated.
Thank you very much in advance,
Best Regards,
Carlo

Body:
Use np.diff to calculate differences between next value relative to current value.

d < 0 show where value drops

np.flatnonzero finds locations of non zero values.  In our case, True values

Sind np.diff shaved off one element from the source array, I add 1 to get the positions correct.

np.split separates df into all parts where there was a negative diff

I used some fanciness to print it out.

d = np.diff(df['Op.progressPercentage'].values)
results = np.split(df, np.flatnonzero(d < 0) + 1)

print(*results, sep='\n' * 2)

                                   uuid            eventTime Op.progress  Op.progressPercentage  AnotherAttribute
0  C0972765-8436-0000-0000-000000000000  2017-08-19T12:52:39           P                    3.0          01:57:00
1  C0972765-8436-0000-0000-000000000000  2017-08-19T12:52:49           P                    3.0          01:56:00
2  C0972765-8436-0000-0000-000000000000  2017-08-19T12:53:18           P                    4.0          01:55:00
3  C0972765-8436-0000-0000-000000000000  2017-08-19T12:53:49           P                    5.0          01:55:00
4  C0972765-8436-0000-0000-000000000000  2017-08-19T12:54:27           P                    5.0          01:54:00
5  C0972765-8436-0000-0000-000000000000  2017-08-19T12:55:07           P                    6.0          01:54:00
6  C0972765-8436-0000-0000-000000000000  2017-08-19T12:55:27           P                    6.0          01:53:00
7  C0972765-8436-0000-0000-000000000000  2017-08-19T13:33:46           W                   40.0          01:13:00

                                    uuid            eventTime Op.progress  Op.progressPercentage  AnotherAttribute
8   C0972765-8436-0000-0000-000000000000  2017-08-19T13:40:10           N                    1.0          02:00:00
9   C0972765-8436-0000-0000-000000000000  2017-08-19T13:40:16           N                    1.0          02:00:00
10  C0972765-8436-0000-0000-000000000000  2017-08-19T13:40:18           N                    1.0          02:00:00
11  C0972765-8436-0000-0000-000000000000  2017-08-19T13:40:55           P                    1.0          02:00:00
12  C0972765-8436-0000-0000-000000000000  2017-08-19T13:41:15           P                    1.0          01:59:00
13  C0972765-8436-0000-0000-000000000000  2017-08-19T13:41:31           P                    3.0          01:57:00
14  C0972765-8436-0000-0000-000000000000  2017-08-19T13:41:51           P                    3.0          01:56:00
15  C0972765-8436-0000-0000-000000000000  2017-08-19T13:42:22           P                    4.0          01:56:00
16  C0972765-8436-0000-0000-000000000000  2017-08-19T13:42:51           P                    4.0          01:55:00
17  C0972765-8436-0000-0000-000000000000  2017-08-19T15:29:22           S                   98.0          00:04:00
18  C0972765-8436-0000-0000-000000000000  2017-08-19T15:29:27           S                   98.0          00:03:00
19  C0972765-8436-0000-0000-000000000000  2017-08-19T15:30:27           S                   99.0          00:02:00
20  C0972765-8436-0000-0000-000000000000  2017-08-19T15:31:27           S                  100.0          00:01:00
21  C0972765-8436-0000-0000-000000000000  2017-08-19T15:33:01           F                  100.0          00:01:00
22  C0972765-8436-0000-0000-000000000000  2017-08-19T15:33:01           F                  100.0          00:01:00


问:
403 when using spring boot, but works well with postman
Im making api call with postman on url:

```<code>https://cex.io/api/order_book/BTC/USD
</code>```

plain GET no headers no params no nothing. But the same with java:

```<code>RestTemplate rt = new RestTemplate();
rt.getForObject("https://cex.io/api/order_book/BTC/USD", String.class);
</code>```

gets me 403. where is the problem?

答:
RestTemplate sets "User-Agent: Java_version" header, and it seems the site you are trying to query denies access with that user-agent.

You can explicitly set a user-agent instead of the default one like:

```<code>    HttpHeaders headers = new HttpHeaders();
    headers.set("User-agent", "SomeUserAgent");
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    RestTemplate rt = new RestTemplate();
    String result = rt.exchange("https://cex.io/api/order_book/BTC/USD", HttpMethod.GET, entity, String.class).getBody();
</code>```

Body:
Im making api call with postman on url:

https://cex.io/api/order_book/BTC/USD

plain GET no headers no params no nothing. But the same with java:

RestTemplate rt = new RestTemplate();
rt.getForObject("https://cex.io/api/order_book/BTC/USD", String.class);

gets me 403. where is the problem?

Body:
RestTemplate sets "User-Agent: Java_version" header, and it seems the site you are trying to query denies access with that user-agent.

You can explicitly set a user-agent instead of the default one like:

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-agent", "SomeUserAgent");
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    RestTemplate rt = new RestTemplate();
    String result = rt.exchange("https://cex.io/api/order_book/BTC/USD", HttpMethod.GET, entity, String.class).getBody();


问:
Two NSArrayControllers and a relationship (CoreData)
Is it okay to do it like i did … ?

Created nsarraycontroller in entity mode controlling 'Accounts'

Created nsarraycontroller in entity mode controlling 'Transactions' and bound to the 'Accounts' nsarraycontroller with key 'selection' and model key path 'transactions' (to-many relationship from accounts to transactions)

I'm askin cause i think something is kinda messed up. Because when i create a button, and try to connect it with the add:(id)sender of the transactionsArrayController, it doesn't seem to add it ... Where can be the problem ? addObject works as expected. But I want to use add:(id)sender and also be sure the code is working as it has to ...

答:
Yes, it's quite normal to base the contents of one array controller on some property of another (including selection.someCollection).

Do you receive any errors in the console when you add? (Hint: include them in your question) Are both array controllers' Managed Object Contexts bound to a valid MOC? What are all your other settings for both array controllers set to? (Another hint: you need to be a lot more specific about describing your setup.)

ContentLicense: CC BY-SA 2.5


问:
Transforming a string to list of integer then sum them up in haskell?
I have a function checkIfTrue where I want to computes a string and check if the sum of the string is true. Like for example, I have a String "ABC" where A= 1, B=2, C=3.Let say

input:

checkIfTrue "ABC" 2

output:

False

as the sum of A+B+C = 6.

```<code>checkIfTrue :: String -> Int -> Bool
checkIfTrue = sum x + xs .words
    | x <- A = 1
    |x <- B = 2
    |x <- C = 3
</code>```

This is what I had in mind but I don't know how to compare if the sum of the input is the same. Sorry if what I had in mind is ridiculous.

答:
You'll need a function with signature

```<code>:: Char -> Int
</code>```

Or more likely

```<code>:: Char -> Maybe Int
</code>```

since only 3 values in the domain Char will have valid outputs. You can write this as:

```<code>charVal :: Char -> Maybe Int
charVal 'A' = Just 1
charVal 'B' = Just 2
charVal 'C' = Just 3
charVal _   = Nothing
</code>```

Then you can sum over the map of the string, using Data.Maybe's catMaybes to ignore the Nothing values. This can be generalized with Data.Maybe's mapMaybe :: (a -> Maybe b) -> [a] -> [b]

```<code>import Data.Maybe (catMaybes)

charVal :: Char -> Maybe Int
charVal 'A' = Just 1
charVal 'B' = Just 2
charVal 'C' = Just 3
charVal _   = Nothing

checkIfTrue :: String -> Int -> Bool
checkIfTrue s k = k == stringSum where
  stringSum = sum . (mapMaybe charVal) $ s
</code>```

Body:
I have a function checkIfTrue where I want to computes a string and check if the sum of the string is true. Like for example, I have a String "ABC" where A= 1, B=2, C=3.Let say

input:

checkIfTrue "ABC" 2

output:

False

as the sum of A+B+C = 6.

checkIfTrue :: String -> Int -> Bool
checkIfTrue = sum x + xs .words
    | x <- A = 1
    |x <- B = 2
    |x <- C = 3

This is what I had in mind but I don't know how to compare if the sum of the input is the same. Sorry if what I had in mind is ridiculous.

Body:
You'll need a function with signature

:: Char -> Int

Or more likely

:: Char -> Maybe Int

since only 3 values in the domain Char will have valid outputs. You can write this as:

charVal :: Char -> Maybe Int
charVal 'A' = Just 1
charVal 'B' = Just 2
charVal 'C' = Just 3
charVal _   = Nothing

Then you can sum over the map of the string, using Data.Maybe's catMaybes to ignore the Nothing values. This can be generalized with Data.Maybe's mapMaybe :: (a -> Maybe b) -> [a] -> [b]

import Data.Maybe (catMaybes)

charVal :: Char -> Maybe Int
charVal 'A' = Just 1
charVal 'B' = Just 2
charVal 'C' = Just 3
charVal _   = Nothing

checkIfTrue :: String -> Int -> Bool
checkIfTrue s k = k == stringSum where
  stringSum = sum . (mapMaybe charVal) $ s


问:
Postgres Crosstab allocating values to wrong columns
I have a sample table named antest as shown below to test the crosstab function.

```<code>create table antest(student text, subject text, result numeric);
insert into antest(student, subject, result) values
('peter','music',2.0),
('peter','language',2.0),
('gabriel','history',8.0),
('john','history',9.0),
('john','maths',4.0),
('john','music',7.0);

student|subject|result
-------+-------+------
peter  |music  |2.0
peter  |lanuage|2.0
gabriel|history|8.0
john   |history|9.0
john   |maths  |4.0
john   |music  |7.0
</code>```

Result wanted:

```<code>student|music|language|history|maths
-------+-----+--------+-------+-----
peter  |2.0  |2.0     |       |
gabriel|     |        |8.0    |
john   |7.0  |        |9.0    |4.0
</code>```

I have executed the follwoin query for that:

```<code>select *
from public.crosstab (
    'select student, subject, result from antest',
    'select distinct subject from antest'
) as final_result(student text, music numeric, maths numeric, history numeric, language numeric);
</code>```

I got the following result:

```<code>student|music|maths|history|language
-------+-----+-----+-------+--------
peter  |2.0  |     |       |2.0
gabriel|     |8.0  |       |
john   |7.0  |9.0  |4.0    |
</code>```

Kindly let me know the mistake I am doing.

I have to repeat this query for anyother database which is 30gb large later with about 75 attributes. Is there any possibility to automate it?

答:
You have to take care that the order of categories is exactly the same in the category query and in the column definition. Because you want an arbitrary chosen (not alphabetical) order, you should use values in the category query.

```<code>select *
from crosstab (
    $q$ select student, subject, result from antest $q$,
    $q$ values ('music'), ('language'), ('history'), ('maths') $q$
) as final_result(student text, music numeric, language numeric, history numeric, maths numeric);

 student | music | language | history | maths
---------+-------+----------+---------+-------
 peter   |   2.0 |      2.0 |         |
 gabriel |       |          |     8.0 |
 john    |   7.0 |          |     9.0 |   4.0
(3 rows)
</code>```

Of course, you can use order by in the query but then you have to change the order in the column definition:

```<code>select *
from crosstab (
    $q$ select student, subject, result from antest $q$,
    $q$ select distinct subject from antest order by 1 $q$
) as final_result(student text, history numeric, language numeric, math numeric, music numeric);

 student | history | language | math | music
---------+---------+----------+------+-------
 peter   |         |      2.0 |      |   2.0
 gabriel |     8.0 |          |      |
 john    |     9.0 |          |  4.0 |   7.0
(3 rows)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a sample table named antest as shown below to test the crosstab function.

create table antest(student text, subject text, result numeric);
insert into antest(student, subject, result) values
('peter','music',2.0),
('peter','language',2.0),
('gabriel','history',8.0),
('john','history',9.0),
('john','maths',4.0),
('john','music',7.0);

student|subject|result
-------+-------+------
peter  |music  |2.0
peter  |lanuage|2.0
gabriel|history|8.0
john   |history|9.0
john   |maths  |4.0
john   |music  |7.0

Result wanted:

student|music|language|history|maths
-------+-----+--------+-------+-----
peter  |2.0  |2.0     |       |
gabriel|     |        |8.0    |
john   |7.0  |        |9.0    |4.0

I have executed the follwoin query for that:

select *
from public.crosstab (
    'select student, subject, result from antest',
    'select distinct subject from antest'
) as final_result(student text, music numeric, maths numeric, history numeric, language numeric);

I got the following result:

student|music|maths|history|language
-------+-----+-----+-------+--------
peter  |2.0  |     |       |2.0
gabriel|     |8.0  |       |
john   |7.0  |9.0  |4.0    |

Kindly let me know the mistake I am doing.

I have to repeat this query for anyother database which is 30gb large later with about 75 attributes. Is there any possibility to automate it?

Body:
You have to take care that the order of categories is exactly the same in the category query and in the column definition. Because you want an arbitrary chosen (not alphabetical) order, you should use values in the category query.

select *
from crosstab (
    $q$ select student, subject, result from antest $q$,
    $q$ values ('music'), ('language'), ('history'), ('maths') $q$
) as final_result(student text, music numeric, language numeric, history numeric, maths numeric);

 student | music | language | history | maths
---------+-------+----------+---------+-------
 peter   |   2.0 |      2.0 |         |
 gabriel |       |          |     8.0 |
 john    |   7.0 |          |     9.0 |   4.0
(3 rows)

Of course, you can use order by in the query but then you have to change the order in the column definition:

select *
from crosstab (
    $q$ select student, subject, result from antest $q$,
    $q$ select distinct subject from antest order by 1 $q$
) as final_result(student text, history numeric, language numeric, math numeric, music numeric);

 student | history | language | math | music
---------+---------+----------+------+-------
 peter   |         |      2.0 |      |   2.0
 gabriel |     8.0 |          |      |
 john    |     9.0 |          |  4.0 |   7.0
(3 rows)


问:
Azure AD App Registration - Exchange API - Read Calendar
I have the following permissions granted in my Azure AD App:

App:

```<code>Read calendars in all mailboxes
Read and write calendars in all mailboxes
Read calendars in all mailboxes
</code>```

Delegated:

```<code>Read user and shared calendars
Read and write user and shared calendars
Read and write user calendars
Read user calendars
Read and write user and shared calendars
Read user and shared calendars
</code>```

Registration Screen Shot

I am successfully generating an Access Token like the following:

const string clientId = "my-client-id";
const string clientSecret = "my-secret"; // C
var tenant = "mytenant.onmicrosoft.com";

var authContext = new AuthenticationContext($"https://login.windows.net/{tenant}/oauth2/token");
var credentials = new ClientCredential(clientId, clientSecret);

AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);
```

<p>With that Access Token, I am trying to make  a basic request to <code>/CalendarView</code> passing the Bearer token header:</p>

```https://outlook.office.com/api/v2.0/users/my@email.com/calendarview?startDateTime=2017-11-12&endDateTime=2017-11-13
```

However, I keep receiving Access Denied. Are there additional permissions I need to set? Am I calling into the correct endpoint?

答:
I actually was able to figure this out. Instead of using the Exchange API, I just applied the permissions in the Graph API.

Hit the following endpoint:

```<code>https://graph.microsoft.com/v1.0/users/{email}/calendarview?startDateTime={startDate}&endDateTime={endDate}
</code>```

It's not very clear the difference between which API to use... but I'm moving forward now.

Body:
I have the following permissions granted in my Azure AD App:

App:

Read calendars in all mailboxes
Read and write calendars in all mailboxes
Read calendars in all mailboxes

Delegated:

Read user and shared calendars
Read and write user and shared calendars
Read and write user calendars
Read user calendars
Read and write user and shared calendars
Read user and shared calendars

Registration Screen Shot

I am successfully generating an Access Token like the following:

const string clientId = "my-client-id";
const string clientSecret = "my-secret"; // C
var tenant = "mytenant.onmicrosoft.com";

var authContext = new AuthenticationContext($"https://login.windows.net/{tenant}/oauth2/token");
var credentials = new ClientCredential(clientId, clientSecret);

AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);

With that Access Token, I am trying to make  a basic request to /CalendarView passing the Bearer token header:

https://outlook.office.com/api/v2.0/users/my@email.com/calendarview?startDateTime=2017-11-12&endDateTime=2017-11-13

However, I keep receiving Access Denied. Are there additional permissions I need to set? Am I calling into the correct endpoint?

Body:
I actually was able to figure this out. Instead of using the Exchange API, I just applied the permissions in the Graph API.

Hit the following endpoint:

https://graph.microsoft.com/v1.0/users/{email}/calendarview?startDateTime={startDate}&endDateTime={endDate}

It's not very clear the difference between which API to use... but I'm moving forward now.


问:
Android Gradle Group Common Properties
Is there a way to group gradle properties to be reused? I can accomplish the following by having duplicate properties but I am trying to avoid this by grouping them in a common place. I have the following build types

```<code>buildTypes {
    debug {}
    qa {
        applicationIdSuffix = ".qa" //Duplicate
    }
    qa2 {
        applicationIdSuffix = ".qa" //Duplicate
    }
    release {}
}

flavors {
    flagship {}
    other1 {}
    other2 {}
}
</code>```

I already have different flavors defined so I don't think I can place the common properties in different flavors. I was hoping I'd be able to do something like

```<code>def commonQaProps {
   applicationIdSuffix = ".qa"
   //Other properties
}
</code>```

and then have

```<code>qa { commonQaProps }
qa2 { commonQaProps }
</code>```

Is something like this possible?

答:
After reading the documentation if you're building one buildType off of another you can use initWith.

```<code>buildTypes {
    debug {}
    qa {
        applicationIdSuffix = ".qa" //Duplicate
    }
    qa2 {
        initWith qa
        //Customize other properties here
    }
    release {}
}
</code>```

I still would like to know if grouping properties is possible to use in many variants that don't inherit from each other.

Title: Android Gradle Group Common Properties

Body:
Is there a way to group gradle properties to be reused? I can accomplish the following by having duplicate properties but I am trying to avoid this by grouping them in a common place. I have the following build types

buildTypes {
    debug {}
    qa {
        applicationIdSuffix = ".qa" //Duplicate
    }
    qa2 {
        applicationIdSuffix = ".qa" //Duplicate
    }
    release {}
}

flavors {
    flagship {}
    other1 {}
    other2 {}
}

I already have different flavors defined so I don't think I can place the common properties in different flavors. I was hoping I'd be able to do something like

def commonQaProps {
   applicationIdSuffix = ".qa"
   //Other properties
}

and then have

qa { commonQaProps }
qa2 { commonQaProps }

Is something like this possible?

Body:
After reading the documentation if you're building one buildType off of another you can use initWith.

buildTypes {
    debug {}
    qa {
        applicationIdSuffix = ".qa" //Duplicate
    }
    qa2 {
        initWith qa
        //Customize other properties here
    }
    release {}
}

I still would like to know if grouping properties is possible to use in many variants that don't inherit from each other.


问:
Correctly parsing through a JSON array with multiple objects using Alamofire and SwiftyJSON
I am able to print out the response. However I am unable to loop through the array and initialise it. This is how I am requesting the data:

```<code>Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { (response) in

    print(response.value!)

    guard let data = response.data else { return }
    let json = JSON(data: data)

    for r in json.arrayValue {
        let person = Person(json: r)
    }
}
</code>```

I have added breakpoints but I am unable to understand as to why the loop does not happen?

Update:

response.value! example:

```<code>{
  "pagination": {
    "object_count": 1,
    "page_number": 1
  },
  "attendees": [
    {
      "id": "818060297",
      "quantity": 1,
      "profile": {
        "first_name": "John",
        "last_name": "Doe",
        "company": "Apple",
        "name": "John Doe",
        "email": "john_doe@testmail.com",
        "job_title": "CEO"
      },
      "status": "Attending"
    }
  ]
}
</code>```

Update 2

Here is my AttendeesProfile class:

```<code>class AttendeesProfile {

    var name: String?

    init(json: JSON) {
        self.name = json["name"].stringValue
    }

}
</code>```

Now I am not sure how to get the Attendee class to work properly:

```<code>class Attendees {

    var attendees = [String]()
    var attendeesProfile: AttendeesProfile!

    init(json: JSON) {
        // Something here
    }
}
</code>```

答:
You could implement a couple of structs conforming to Decodable, which among other things would give you the benefit of not relying on SwiftyJSON for your code to work.

Going off from the JSON data that you have provided, consider the following three simple structs:

```<code>struct AttendeeArray: Decodable {
   let attendees: [Attendee]
}

struct Attendee: Decodable {
   let status: String
   let profile: AttendeeProfile
}

struct AttendeeProfile: Decodable {
   let name: String
   let age: Int
}
</code>```

Each struct simply contains the variables that you have defined in your JSON object.

Using the JSONDecoder you will now be able to decode your JSON data as simple as calling:

```<code>do {
   let array = try JSONDecoder().decode(AttendeeArray.self, from: data)
   // do whatever with your attendees array
} catch {
   // handle error if parsing fails
   print(error)
}
</code>```

I created a simple Playground where you can test this by adding the code bolow along with the Decodable structs above:

```<code>import Foundation

func decodeAttendees(json: String) -> AttendeeArray? {
   guard let data = json.data(using: .utf8) else { return nil }
   do {
       return try JSONDecoder().decode(AttendeeArray.self, from: data)
   } catch {
       print("Error: \(error)")
       return nil
   }
}

let json = """
{
   "attendees": [
       {
           "status": "attending",
           "profile": {
               "name": "Joe",
               "age": 22
           }
       },
       {
           "status": "not attending",
           "profile": {
               "name": "Bob",
               "age": 44
           }
       }
   ],
   "servlet": {
       "servlet-name": "cofaxCDS",
       "servlet-class": "org.cofax.cds.CDSServlet"
   }
}
"""

let arr = decodeAttendees(json: json)
arr?.attendees[0].profile.name //"Joe"
arr?.attendees[1].status //"not attending"
</code>```

Now, for your current Alamofire completion handler, I'm guessing that it would be as simple to modify it to be something along the lines of:

```<code>Alamofire.request(url, method: .get, parameters: nil, encoding:   URLEncoding.default).responseJSON { (response) in
   guard let data = response.data else { return //remember to error if data is nil }
   do {
      let array = JSONDecoder().decode(AttendeesArray.self, from: data)
      //update your UI to show the array, or pass it on to a completion hanldler
   } catch {
      //handle errors
   }
}
</code>```

Body:
I am able to print out the response. However I am unable to loop through the array and initialise it. This is how I am requesting the data:

Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { (response) in

    print(response.value!)

    guard let data = response.data else { return }
    let json = JSON(data: data)

    for r in json.arrayValue {
        let person = Person(json: r)
    }
}

I have added breakpoints but I am unable to understand as to why the loop does not happen?

Update:

response.value! example:

{
  "pagination": {
    "object_count": 1,
    "page_number": 1
  },
  "attendees": [
    {
      "id": "818060297",
      "quantity": 1,
      "profile": {
        "first_name": "John",
        "last_name": "Doe",
        "company": "Apple",
        "name": "John Doe",
        "email": "john_doe@testmail.com",
        "job_title": "CEO"
      },
      "status": "Attending"
    }
  ]
}

Update 2

Here is my AttendeesProfile class:

class AttendeesProfile {

    var name: String?

    init(json: JSON) {
        self.name = json["name"].stringValue
    }

}

Now I am not sure how to get the Attendee class to work properly:

class Attendees {

    var attendees = [String]()
    var attendeesProfile: AttendeesProfile!

    init(json: JSON) {
        // Something here
    }
}

Body:
You could implement a couple of structs conforming to Decodable, which among other things would give you the benefit of not relying on SwiftyJSON for your code to work.

Going off from the JSON data that you have provided, consider the following three simple structs:

struct AttendeeArray: Decodable {
   let attendees: [Attendee]
}

struct Attendee: Decodable {
   let status: String
   let profile: AttendeeProfile
}

struct AttendeeProfile: Decodable {
   let name: String
   let age: Int
}

Each struct simply contains the variables that you have defined in your JSON object.

Using the JSONDecoder you will now be able to decode your JSON data as simple as calling:

do {
   let array = try JSONDecoder().decode(AttendeeArray.self, from: data)
   // do whatever with your attendees array
} catch {
   // handle error if parsing fails
   print(error)
}

I created a simple Playground where you can test this by adding the code bolow along with the Decodable structs above:

import Foundation

func decodeAttendees(json: String) -> AttendeeArray? {
   guard let data = json.data(using: .utf8) else { return nil }
   do {
       return try JSONDecoder().decode(AttendeeArray.self, from: data)
   } catch {
       print("Error: \(error)")
       return nil
   }
}

let json = """
{
   "attendees": [
       {
           "status": "attending",
           "profile": {
               "name": "Joe",
               "age": 22
           }
       },
       {
           "status": "not attending",
           "profile": {
               "name": "Bob",
               "age": 44
           }
       }
   ],
   "servlet": {
       "servlet-name": "cofaxCDS",
       "servlet-class": "org.cofax.cds.CDSServlet"
   }
}
"""

let arr = decodeAttendees(json: json)
arr?.attendees[0].profile.name //"Joe"
arr?.attendees[1].status //"not attending"

Now, for your current Alamofire completion handler, I'm guessing that it would be as simple to modify it to be something along the lines of:

Alamofire.request(url, method: .get, parameters: nil, encoding:   URLEncoding.default).responseJSON { (response) in
   guard let data = response.data else { return //remember to error if data is nil }
   do {
      let array = JSONDecoder().decode(AttendeesArray.self, from: data)
      //update your UI to show the array, or pass it on to a completion hanldler
   } catch {
      //handle errors
   }
}


问:
FP alternative to polymorphism in JavaScript/ReactJS
I'm currently working on a ReactJS project where I need to create "re-usable" components in which some of the methods would need to be "overridden". In OOP I would use polymorphism. I've done some reading and it seems the consensus is to use HoC/composition but I can't quite figure out how to achieve this. I figure if I could just get a ES6 sample using composition it would maybe be easier to adapt the idea to ReactJS afterwards.

Below is a ES6 OOP example (ignore the event handling it's just for testing) of pretty much what I would like to achieve in ReactJS. Does anyone have some guidance on how to break up a ReactJS component into a HoC or even just demonstrate how I would go about using composition in ES6 based on the example?

class TransferComponent {
    constructor(){
        let timeout = null;

        this.render();
        this.events();
    }

    events(){
        let scope = this;

        document.getElementById('button').addEventListener('click', function(){
            scope.validate.apply(scope);
        });
    }

    validate(){
        if(this.isValid()){
            this.ajax();
        }
    }

    isValid(){
        if(document.getElementById('username').value !== ''){
            return true;
        }

        return false;
    }

    ajax(){
        clearTimeout(this.timeout);

        document.getElementById('message').textContent = 'Loading...';

        this.timeout = setTimeout(function(){
            document.getElementById('message').textContent = 'Success';
        }, 500);
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

class OverrideTransferComponent extends TransferComponent{
    isValid(){
        if(document.getElementById('username').value !== '' && document.getElementById('password').value !== ''){
            return true;
        }

        return false;
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <input type="text" id="password" value="password"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

const overrideTransferComponent = new OverrideTransferComponent();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content"></div>
<div id="message"></div></code>```

UPDATE:
Even though my original question was around FP I think render props is a really good solution to my issue and avoids the HoC issues.

答:
The non-React FP example

For starters, in Functional Programming, the function is a first class citizen. This means you can treat functions as you would data in OOP (i.e. pass as parameters, assign to variables, etc.).

Your example comingles data with behavior in the objects. In order to write a purely functional solution, we'll want to separate these.

Functional Programming is fundamentally about separating data from behavior.

So, let's start with isValid.

Functional isValid

There are a few ways to order the logic here, but we'll go with this:

Given a list of ids

All ids are valid if there does not exist an invalid id

Which, in JS, translates to:

```<code>const areAllElementsValid = (...ids) => !ids.some(isElementInvalid)
</code>```

We need a couple helper functions to make this work:

```<code>const isElementInvalid = (id) => getValueByElementId(id) === ''
const getValueByElementId = (id) => document.getElementById(id).value
</code>```

We could write all of that on one line, but breaking it up makes it a bit more readable. With that, we now have a generic function that we can use to determine isValid for our components!

```<code>areAllElementsValid('username') // TransferComponent.isValid
areAllElementsValid('username', 'password') // TransferOverrideComponent.isValid
</code>```

Functional render

I cheated a little on isValid by using document. In true functional programming, functions should be pure. Or, in other words, the result of a function call must only be determined from its inputs (a.k.a. it is idempotent) and it cannot have side effects.

So, how do we render to the DOM without side effects? Well, React uses a virtual DOM (a fancy data structure that lives in memory and is passed into and returned from functions to maintain functional purity) for the core library. React's side effects live in the react-dom library.

For our case, we'll use a super simple virtual DOM (of type string).

```<code>const USERNAME_INPUT = '<input type="text" id="username" value="username"/>'
const PASSWORD_INPUT = '<input type="text" id="password" value="password"/>'
const VALIDATE_BUTTON = '<button id="button" type="button">Validate</button>'
</code>```

These are our components--to use the React terminology--which we can compose into UIs:

```<code>USERNAME_INPUT + VALIDATE_BUTTON // TransferComponent.render
USERNAME_INPUT + PASSWORD_INPUT + VALIDATE_BUTTON // TransferOverrideComponent.render
</code>```

This probably seems like an oversimplification and not functional at all. But the + operator is in fact functional! Think about it:

it takes two inputs (the left operand and the right operand)

it returns a result (for strings, the concatenation of the operands)

it has no side effects

it doesn't mutate its inputs (the result is a new string--the operands are unchanged)

So, with that, render is now functional!

What about ajax?

Unfortunately, we can't perform an ajax call, mutate the DOM, set up event listeners, or set timeouts without side effects. We could go the complex route of creating monads for these actions, but for our purposes, suffice it to say that we'll just keep using the non-functional methods.

Applying it in React

Here's a rewrite of your example using common React patterns. I'm using controlled components for the form inputs. The majority of the functional concepts we've talked about really live under the hood in React, so this is a pretty simple implementation that doesn't use anything fancy.

```<code>class Form extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            success: false
        };
    }

    handleSubmit() {
        if (this.props.isValid()) {
            this.setState({
                loading: true
            });

            setTimeout(
                () => this.setState({
                    loading: false,
                    success: true
                }),
                500
            );
        }
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    {this.props.children}
                    <input type="submit" value="Submit" />
                </form>

                { this.state.loading && 'Loading...' }
                { this.state.success && 'Success' }
            </div>
        );
    }
}
</code>```

The use of state probably seems like a side effect, doesn't it? In some ways it is, but digging into the React internals may reveal a more functional implementation than can be seen from our single component.

Here's the Form for your example. Note that we could handle submission in a couple different ways here. One way is to pass the username and password as props into Form (probably as a generic data prop). Another option is to pass a handleSubmit callback specific to that form (just like we're doing for validate).

```<code>class LoginForm extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            username: '',
            password: ''
        };
    }

    isValid() {
        return this.state.username !== '' && this.state.password !== '';
    }

    handleUsernameChange(event) {
        this.setState({ username: event.target.value });
    }

    handlePasswordChange(event) {
        this.setState({ password: event.target.value });
    }

    render() {
        return (
            <Form
                validate={this.isValid}
            >
                <input value={this.state.username} onChange={this.handleUsernameChange} />
                <input value={this.state.password} onChange={this.handlePasswordChange} />
            </Form>
        );
    }
}
</code>```

You could also write another Form but with different inputs

```<code>class CommentForm extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            comment: ''
        };
    }

    isValid() {
        return this.state.comment !== '';
    }

    handleCommentChange(event) {
        this.setState({ comment: event.target.value });
    }

    render() {
        return (
            <Form
                validate={this.isValid}
            >
                <input value={this.state.comment} onChange={this.handleCommentChange} />
            </Form>
        );
    }
}
</code>```

For sake of example, your app can render both Form implementations:

```<code>class App extends React.Component {
    render() {
        return (
            <div>
                <LoginForm />
                <CommentForm />
            </div>
        );
    }
}
</code>```

Finally, we use ReactDOM instead of innerHTML

```<code>ReactDOM.render(
    <App />,
    document.getElementById('content')
);
</code>```

The functional nature of React is often hidden by using JSX. I encourage you to read up on how what we're doing is really just a bunch of functions composed together. The official docs cover this pretty well.

For further reading, James K. Nelson has put together some stellar resources on React that should help with your functional understanding: https://reactarmory.com/guides/learn-react-by-itself/react-basics

Body:
I'm currently working on a ReactJS project where I need to create "re-usable" components in which some of the methods would need to be "overridden". In OOP I would use polymorphism. I've done some reading and it seems the consensus is to use HoC/composition but I can't quite figure out how to achieve this. I figure if I could just get a ES6 sample using composition it would maybe be easier to adapt the idea to ReactJS afterwards.

Below is a ES6 OOP example (ignore the event handling it's just for testing) of pretty much what I would like to achieve in ReactJS. Does anyone have some guidance on how to break up a ReactJS component into a HoC or even just demonstrate how I would go about using composition in ES6 based on the example?

class TransferComponent {
    constructor(){
        let timeout = null;

        this.render();
        this.events();
    }

    events(){
        let scope = this;

        document.getElementById('button').addEventListener('click', function(){
            scope.validate.apply(scope);
        });
    }

    validate(){
        if(this.isValid()){
            this.ajax();
        }
    }

    isValid(){
        if(document.getElementById('username').value !== ''){
            return true;
        }

        return false;
    }

    ajax(){
        clearTimeout(this.timeout);

        document.getElementById('message').textContent = 'Loading...';

        this.timeout = setTimeout(function(){
            document.getElementById('message').textContent = 'Success';
        }, 500);
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

class OverrideTransferComponent extends TransferComponent{
    isValid(){
        if(document.getElementById('username').value !== '' && document.getElementById('password').value !== ''){
            return true;
        }

        return false;
    }

    render(){
        document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
            <input type="text" id="password" value="password"/>\n\
            <button id="button" type="button">Validate</button>';
    }
}

const overrideTransferComponent = new OverrideTransferComponent();

UPDATE:
Even though my original question was around FP I think render props is a really good solution to my issue and avoids the HoC issues.

Body:
The non-React FP example

For starters, in Functional Programming, the function is a first class citizen. This means you can treat functions as you would data in OOP (i.e. pass as parameters, assign to variables, etc.).

Your example comingles data with behavior in the objects. In order to write a purely functional solution, we'll want to separate these.

Functional Programming is fundamentally about separating data from behavior.

So, let's start with isValid.

Functional isValid

There are a few ways to order the logic here, but we'll go with this:

Given a list of ids

All ids are valid if there does not exist an invalid id

Which, in JS, translates to:

const areAllElementsValid = (...ids) => !ids.some(isElementInvalid)

We need a couple helper functions to make this work:

const isElementInvalid = (id) => getValueByElementId(id) === ''
const getValueByElementId = (id) => document.getElementById(id).value

We could write all of that on one line, but breaking it up makes it a bit more readable. With that, we now have a generic function that we can use to determine isValid for our components!

areAllElementsValid('username') // TransferComponent.isValid
areAllElementsValid('username', 'password') // TransferOverrideComponent.isValid

Functional render

I cheated a little on isValid by using document. In true functional programming, functions should be pure. Or, in other words, the result of a function call must only be determined from its inputs (a.k.a. it is idempotent) and it cannot have side effects.

So, how do we render to the DOM without side effects? Well, React uses a virtual DOM (a fancy data structure that lives in memory and is passed into and returned from functions to maintain functional purity) for the core library. React's side effects live in the react-dom library.

For our case, we'll use a super simple virtual DOM (of type string).

const USERNAME_INPUT = '<input type="text" id="username" value="username"/>'
const PASSWORD_INPUT = '<input type="text" id="password" value="password"/>'
const VALIDATE_BUTTON = '<button id="button" type="button">Validate</button>'

These are our components--to use the React terminology--which we can compose into UIs:

USERNAME_INPUT + VALIDATE_BUTTON // TransferComponent.render
USERNAME_INPUT + PASSWORD_INPUT + VALIDATE_BUTTON // TransferOverrideComponent.render

This probably seems like an oversimplification and not functional at all. But the + operator is in fact functional! Think about it:

it takes two inputs (the left operand and the right operand)

it returns a result (for strings, the concatenation of the operands)

it has no side effects

it doesn't mutate its inputs (the result is a new string--the operands are unchanged)

So, with that, render is now functional!

What about ajax?

Unfortunately, we can't perform an ajax call, mutate the DOM, set up event listeners, or set timeouts without side effects. We could go the complex route of creating monads for these actions, but for our purposes, suffice it to say that we'll just keep using the non-functional methods.

Applying it in React

Here's a rewrite of your example using common React patterns. I'm using controlled components for the form inputs. The majority of the functional concepts we've talked about really live under the hood in React, so this is a pretty simple implementation that doesn't use anything fancy.

class Form extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            success: false
        };
    }

    handleSubmit() {
        if (this.props.isValid()) {
            this.setState({
                loading: true
            });

            setTimeout(
                () => this.setState({
                    loading: false,
                    success: true
                }),
                500
            );
        }
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    {this.props.children}
                    <input type="submit" value="Submit" />
                </form>

                { this.state.loading && 'Loading...' }
                { this.state.success && 'Success' }
            </div>
        );
    }
}

The use of state probably seems like a side effect, doesn't it? In some ways it is, but digging into the React internals may reveal a more functional implementation than can be seen from our single component.

Here's the Form for your example. Note that we could handle submission in a couple different ways here. One way is to pass the username and password as props into Form (probably as a generic data prop). Another option is to pass a handleSubmit callback specific to that form (just like we're doing for validate).

class LoginForm extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            username: '',
            password: ''
        };
    }

    isValid() {
        return this.state.username !== '' && this.state.password !== '';
    }

    handleUsernameChange(event) {
        this.setState({ username: event.target.value });
    }

    handlePasswordChange(event) {
        this.setState({ password: event.target.value });
    }

    render() {
        return (
            <Form
                validate={this.isValid}
            >
                <input value={this.state.username} onChange={this.handleUsernameChange} />
                <input value={this.state.password} onChange={this.handlePasswordChange} />
            </Form>
        );
    }
}

You could also write another Form but with different inputs

class CommentForm extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            comment: ''
        };
    }

    isValid() {
        return this.state.comment !== '';
    }

    handleCommentChange(event) {
        this.setState({ comment: event.target.value });
    }

    render() {
        return (
            <Form
                validate={this.isValid}
            >
                <input value={this.state.comment} onChange={this.handleCommentChange} />
            </Form>
        );
    }
}

For sake of example, your app can render both Form implementations:

class App extends React.Component {
    render() {
        return (
            <div>
                <LoginForm />
                <CommentForm />
            </div>
        );
    }
}

Finally, we use ReactDOM instead of innerHTML

ReactDOM.render(
    <App />,
    document.getElementById('content')
);

The functional nature of React is often hidden by using JSX. I encourage you to read up on how what we're doing is really just a bunch of functions composed together. The official docs cover this pretty well.

For further reading, James K. Nelson has put together some stellar resources on React that should help with your functional understanding: https://reactarmory.com/guides/learn-react-by-itself/react-basics


问:
How to insert/store a string value in influxdb measurement?
I am trying to insert some string value in influx db but keep getting 400 error. I am iusing python requests module to connect to influxdb. Here is my code:

```<code>description = '"' + some_str + '"'
payload = "%s, name=%s, description=%s, count=%d %d" %(measurement, name, description,count,timestamp)
requests.post(influx_uri, data=payload, headers= headers)
</code>```

I keep getting this error:

```<code>400 {"error":"unable to parse 'sample,name=sample, description=\"some_str\", count=1 15106068120000000' : missing tag key"}
</code>```

I don't know how this is getting generated description=\"some_str\"

答:
I have never used influxdb, to be honest it's the first time I hear of it, but...

By looking in the docs they seem to post a JSON content to the url using POST method, e.g.:

```<code>curl -X POST -d '[{"name":"foo","columns":["val"],"points":[[23]]}]' 'http://localhost:8086/db/mydb/series?u=root&p=root'
</code>```

Your line doesn't look like a JSON document. And you better make it. Not sure what is your structure, but maybe this could do the job?

```<code>payload = """{"name":"%s", "description":"%s", "count":"%d %d"}""" %(name, description, count, timestamp)
</code>```

Body:
I am trying to insert some string value in influx db but keep getting 400 error. I am iusing python requests module to connect to influxdb. Here is my code:

description = '"' + some_str + '"'
payload = "%s, name=%s, description=%s, count=%d %d" %(measurement, name, description,count,timestamp)
requests.post(influx_uri, data=payload, headers= headers)

I keep getting this error:

400 {"error":"unable to parse 'sample,name=sample, description=\"some_str\", count=1 15106068120000000' : missing tag key"}

I don't know how this is getting generated description=\"some_str\"

Body:
I have never used influxdb, to be honest it's the first time I hear of it, but...

By looking in the docs they seem to post a JSON content to the url using POST method, e.g.:

curl -X POST -d '[{"name":"foo","columns":["val"],"points":[[23]]}]' 'http://localhost:8086/db/mydb/series?u=root&p=root'

Your line doesn't look like a JSON document. And you better make it. Not sure what is your structure, but maybe this could do the job?

payload = """{"name":"%s", "description":"%s", "count":"%d %d"}""" %(name, description, count, timestamp)


问:
PHP, SMTP - Subject in email shows International Characters as HTML_Entities
I've spent over half a day on this - just trying to get the email Subject to appear normal. But international characters appear as HTML_Entities when the email lands in the inbox.

For example: Tydzień o Jedność

Shows up as: Tydzień o Jedność

I already encode the email Subject for UTF-8:

$this->subject = "=?UTF-8?B?" . base64_encode($this->subject) . "?=";

When I get the email (Gmail), the header appears as:

Subject: =?UTF-8?B?VHlkemllJiMzMjQ7IG8gSmVkbm8mIzM0NzsmIzI2Mzs=?=

So it seems to encode properly. But for some reason, Gmail still displays the Subject with HTML_Entities.

Any ideas?

See code: SMTP mail class

答: If you have iconv available, you could try using the iconv_mime_encode() function instead of "=?UTF-8?B?" . base64_encode($this->subject) . "?=";


问:
How To Increment Numbers in Calculated field of TQuery?
I Have TQuery With Calculated Field N.

How To Increment Numbers in the example (N starts with 5):

I tried this but Nothing:

```<code>procedure TForm1.Query1CalcFields(DataSet: TDataSet);
var i:integer;
begin
  i := strtoint(edit2.Text);
  Query1['N'] := inttostr(i+1);
end;
</code>```

result:

```<code>N
2
2
2
2
.
.
</code>```

Note: Foxpro database ,i use BDE to connect with ,It does not have to be a calculated field ,i want the Incremented value to use it in print of quickreport like a single reference for each Page (not pagenumber).

答:
This is a simple way that I test it:

1- declare a global variable for saving auto number

2- Set it in FormShow to 5

3- In OnCalcFields assign global variable to the new field

4- increment global variable

Notes: Do not use TEdit or any thing for show the result of calculate field, because it will  just show the first result. but all the result will save in table or query correctly.

Codes

Global Variable:

```<code>var
  Form1: TForm1;
  i : Integer;
</code>```

Form Show:

```<code>procedure TForm1.FormShow(Sender: TObject);
begin
    i := 5;
end;
</code>```

Calc Filed:

```<code>procedure TForm1.adoqry1CalcFields(DataSet: TDataSet);
begin
   adoqry1['n'] := i;
   //OR adoqry1N.AsInteger := i;
   //OR adoqry1.FieldByName('n').AsInteger := i;

   i := i + 1;
end;
</code>```

At the end, I test it with ADOQuery.

Body:
I Have TQuery With Calculated Field N.

How To Increment Numbers in the example (N starts with 5):

I tried this but Nothing:

procedure TForm1.Query1CalcFields(DataSet: TDataSet);
var i:integer;
begin
  i := strtoint(edit2.Text);
  Query1['N'] := inttostr(i+1);
end;

result:

N
2
2
2
2
.
.

Note: Foxpro database ,i use BDE to connect with ,It does not have to be a calculated field ,i want the Incremented value to use it in print of quickreport like a single reference for each Page (not pagenumber).

Body:
This is a simple way that I test it:

1- declare a global variable for saving auto number

2- Set it in FormShow to 5

3- In OnCalcFields assign global variable to the new field

4- increment global variable

Notes: Do not use TEdit or any thing for show the result of calculate field, because it will  just show the first result. but all the result will save in table or query correctly.

Codes

Global Variable:

var
  Form1: TForm1;
  i : Integer;

Form Show:

procedure TForm1.FormShow(Sender: TObject);
begin
    i := 5;
end;

Calc Filed:

procedure TForm1.adoqry1CalcFields(DataSet: TDataSet);
begin
   adoqry1['n'] := i;
   //OR adoqry1N.AsInteger := i;
   //OR adoqry1.FieldByName('n').AsInteger := i;

   i := i + 1;
end;

At the end, I test it with ADOQuery.


问:
How to write an average equation in c# for any amount of numbers
My goal is to produce the average of the numbers a person types into the box (which I have already set up).  The equation needs to be after the f.Close(); and the data type needs to be float.

```<code>public partial class frmMain : Form
{
    public frmMain()
    {
        InitializeComponent();
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        int total = 0, count = 0;
        DialogResult result;
        result = ofd.ShowDialog();
        if (result == System.Windows.Forms.DialogResult.OK)
        {
            string fileName = ofd.FileName;
            StreamReader f = new StreamReader(fileName);

            while (!f.EndOfStream)
            {
                string textScore = f.ReadLine();
                firstScores.Items.Add(textScore);
                int score = int.Parse(textScore);
                total = total + score;
                count = count + 1;
            }

            f.Close();

            //This is what I have currently
            float sum, length, average;
            string textLine;

            sum = float.Parse(textLine);
            length = float.Parse(textLine);
            average = sum / length;
</code>```

I thought this might work, but it states that the textLine in the sum = float.Parse is unassigned.

答:
The average is the total divided by the count.  You are already getting the total and the count as you go.

You already have a hint - they need to be floats, not integers, so cast them like this:

```<code>float floatTotal = (float)total;
float floatCount = (float)count;
</code>```

then do your math:

```<code>float average = floatTotal / floatCount;
</code>```

You will also want to check that you are not dividing by zero (ie: that count > 0).  This will keep your program from crashing if you don't read any scores in.

Body:
My goal is to produce the average of the numbers a person types into the box (which I have already set up).  The equation needs to be after the f.Close(); and the data type needs to be float.

public partial class frmMain : Form
{
    public frmMain()
    {
        InitializeComponent();
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        int total = 0, count = 0;
        DialogResult result;
        result = ofd.ShowDialog();
        if (result == System.Windows.Forms.DialogResult.OK)
        {
            string fileName = ofd.FileName;
            StreamReader f = new StreamReader(fileName);

            while (!f.EndOfStream)
            {
                string textScore = f.ReadLine();
                firstScores.Items.Add(textScore);
                int score = int.Parse(textScore);
                total = total + score;
                count = count + 1;
            }

            f.Close();

            //This is what I have currently
            float sum, length, average;
            string textLine;

            sum = float.Parse(textLine);
            length = float.Parse(textLine);
            average = sum / length;

I thought this might work, but it states that the textLine in the sum = float.Parse is unassigned.

Body:
The average is the total divided by the count.  You are already getting the total and the count as you go.

You already have a hint - they need to be floats, not integers, so cast them like this:

float floatTotal = (float)total;
float floatCount = (float)count;

then do your math:

float average = floatTotal / floatCount;

You will also want to check that you are not dividing by zero (ie: that count > 0).  This will keep your program from crashing if you don't read any scores in.


问:
Configuration prooph in Symfony DI Container
I configured all prooph service buses with event source and event store.

But it's one thing what make me confused. I must call:
$eventPublisher = $this->container->get('event_publisher'); in my CommandBusFactory  to glue event emitter and event bus together for dispatching domain event (from Aggregate Root) throught bus to projector. Without this my projections are not called.

My services: link

Can someone with experience in Symfony DI (Extension and CompilerPass) help me with it?

答:
The event publisher is not part of your dependency chain. That's the reason why it is not initialized by symfony DI. The event publisher is an event store plugin and you have correctly configured symfony DI to call the method attachToEventStore but this is not done automatically but only when you request the service from the DI.

To solve the problem you need a factory for the event store that takes a list of plugins and calls the attachToEventStore method on each plugin.
The prooph/event-store-symfony-bundle contains such a factory


问:
Extension Methods vs. Regular Methods - Best Practice Ideas
I'm having a bit of a difficult time determining when to implement a method as an extension method and when to implement a method as a stand-alone method. What are some best practices people follow in determining this?</p>

答:
Try this Stackoverflow post for a discussion about extension method best practices.

From my perspective I use extension methods when I have a lot of utility functions for a particular type.

I find that...

```<code>string.ExtensionMethod();
</code>```

looks cleaner than...

```<code>StringHelper.ExtensionMethod("string to do something with");
</code>```

Body:
Try this Stackoverflow post for a discussion about extension method best practices.

From my perspective I use extension methods when I have a lot of utility functions for a particular type.

I find that...

string.ExtensionMethod();

looks cleaner than...

StringHelper.ExtensionMethod("string to do something with");


问:
Spring with IntelliJ attribute p:prefix is not allowed here
Please help I need to surpass this problem:

I have no idea of how to solve this problem.

Snippet of code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/p ">

    <mvc:annotation-driven/>

    <context:component-scan base-package="basic" />

    <bean class="org.springframework.web.servlet.view.InternalResourceView" p:prefix="/WEB-INF/jsp/"/>

</beans>
</code>```

Now for the second try:

答:
It should be like this :

dispatcher-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/p ">

    <mvc:annotation-driven/>

    <context:component-scan base-package="basic" />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceView" >
        <property name="prefix">
           <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>
</code>```

Body:
Please help I need to surpass this problem:

I have no idea of how to solve this problem.

Snippet of code:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/p ">

    <mvc:annotation-driven/>

    <context:component-scan base-package="basic" />

    <bean class="org.springframework.web.servlet.view.InternalResourceView" p:prefix="/WEB-INF/jsp/"/>

</beans>

Now for the second try:

Body:
It should be like this :

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/p ">

    <mvc:annotation-driven/>

    <context:component-scan base-package="basic" />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceView" >
        <property name="prefix">
           <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>


问:
CardView selector?
I'm creating a notes app and I'm using a contextual action bar to delete notes. I have my notes displayed in a card view. I have the action bar working to the point where I can select notes and delete them. But when I select notes I want to use a checkmark as a selector if possible (otherwise any selector) which I have been unsuccessful in achieving.

contextual action bar

```<code>mListViewNotes = (ListView) findViewById(R.id.listview_notes);
    mListViewNotes.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    mListViewNotes.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

        CardView cardView = (CardView) findViewById(R.id.cardView);

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            if (list_items.contains(notes.get(position))) {
                count = count-1;
                list_items.remove(notes.get(position));
                mode.setTitle(count + " Notes Selected");
            } else {
                count = count+1;
                list_items.add(notes.get(position));
                mode.setTitle(count + " Notes Selected");
            }

            if (count == 0) {
                mode.setTitle("No Notes Selected");
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {

            app_bar.setVisibility(View.GONE);
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);
            actionMode = mode;
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            deleteNote();
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            count = 0;
            app_bar.setVisibility(View.VISIBLE);
            list_items.clear();
        }
    });
}
</code>```

item_note.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/light_sand"
android:orientation="vertical"
android:id="@+id/item_note">

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    android:layout_marginBottom="6dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="6dp"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="6dp">

    <ImageView
        android:layout_width="1000dp"
        android:layout_height="150dp"
        android:layout_gravity="start"
        android:layout_marginLeft="-80dp"
        android:layout_marginTop="-12dp"
        android:background="@drawable/texture_tile_old"
        android:scaleType="fitStart" />

    <ImageView
        android:id="@+id/clef_note"
        android:layout_width="70dp"
        android:layout_height="120dp"
        android:layout_gravity="start"
        android:layout_marginTop="10dp"
        android:background="@drawable/treble_clef" />

    <View
        android:layout_width="780dp"
        android:layout_height="1dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="43dp"
        android:background="@color/black" />

    <View
        android:layout_width="780dp"
        android:layout_height="1dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="70dp"
        android:background="@color/black" />

    <View
        android:layout_width="780dp"
        android:layout_height="1dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="97dp"
        android:background="@color/black" />

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:scaleType="center">

        <TextView
            android:id="@+id/list_note_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="65dp"
            android:layout_marginTop="8dp"
            android:textColor="@color/black"
            android:textSize="28sp" />

        <TextView
            android:id="@+id/list_note_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="46dp"
            android:layout_marginLeft="65dp"
            android:layout_marginTop="0dp"
            android:maxLines="2"
            android:textColor="@color/gunmetal"
            android:textSize="20sp"
            android:lineSpacingExtra="4dp"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@color/brown"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4dp"
            android:text="Last Updated:"
            android:textColor="@color/white" />

        <TextView
            android:id="@+id/list_note_date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="4dp"
            android:gravity="end"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="@color/white" />
    </LinearLayout>
</android.support.v7.widget.CardView>
</code>```

答:
You can add a CheckBox to your item layout, and/or change the background of the layout itself to display a selected state.

With the first option, you can change the layout to the selected state just by setting the isChecked to true.

```<code>checkBox.setChecked(true);
</code>```

To change the background of the layout, you can simply set the background to a new color resource.

```<code>itemLayout.setBackgroundResource(R.color.color_selected);
</code>```

Or you can use a ColorStateList to do some more advanced state changes (such as a ripple effect to a solid color).

ripple_selector.xml

```<code><ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/color_highlight">
    <item android:drawable="@drawable/color_highlight"/>
</ripple>
</code>```

item_selector_background.xml

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
            android:drawable="@color/color_selected"/>
    <item android:drawable="@drawable/ripple_effect"/>
</selector>
</code>```

To use this, you can set the background attribute in your layout xml to item_selector_background then changed the selected state in your code.

```<code>itemLayout.setSelected(true);
</code>```

Title: CardView selector?

Body:
I'm creating a notes app and I'm using a contextual action bar to delete notes. I have my notes displayed in a card view. I have the action bar working to the point where I can select notes and delete them. But when I select notes I want to use a checkmark as a selector if possible (otherwise any selector) which I have been unsuccessful in achieving.

contextual action bar

mListViewNotes = (ListView) findViewById(R.id.listview_notes);
    mListViewNotes.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    mListViewNotes.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

        CardView cardView = (CardView) findViewById(R.id.cardView);

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            if (list_items.contains(notes.get(position))) {
                count = count-1;
                list_items.remove(notes.get(position));
                mode.setTitle(count + " Notes Selected");
            } else {
                count = count+1;
                list_items.add(notes.get(position));
                mode.setTitle(count + " Notes Selected");
            }

            if (count == 0) {
                mode.setTitle("No Notes Selected");
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {

            app_bar.setVisibility(View.GONE);
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);
            actionMode = mode;
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            deleteNote();
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            count = 0;
            app_bar.setVisibility(View.VISIBLE);
            list_items.clear();
        }
    });
}

item_note.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/light_sand"
android:orientation="vertical"
android:id="@+id/item_note">

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    android:layout_marginBottom="6dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="6dp"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="6dp">

    <ImageView
        android:layout_width="1000dp"
        android:layout_height="150dp"
        android:layout_gravity="start"
        android:layout_marginLeft="-80dp"
        android:layout_marginTop="-12dp"
        android:background="@drawable/texture_tile_old"
        android:scaleType="fitStart" />

    <ImageView
        android:id="@+id/clef_note"
        android:layout_width="70dp"
        android:layout_height="120dp"
        android:layout_gravity="start"
        android:layout_marginTop="10dp"
        android:background="@drawable/treble_clef" />

    <View
        android:layout_width="780dp"
        android:layout_height="1dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="43dp"
        android:background="@color/black" />

    <View
        android:layout_width="780dp"
        android:layout_height="1dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="70dp"
        android:background="@color/black" />

    <View
        android:layout_width="780dp"
        android:layout_height="1dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="97dp"
        android:background="@color/black" />

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:scaleType="center">

        <TextView
            android:id="@+id/list_note_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="65dp"
            android:layout_marginTop="8dp"
            android:textColor="@color/black"
            android:textSize="28sp" />

        <TextView
            android:id="@+id/list_note_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="46dp"
            android:layout_marginLeft="65dp"
            android:layout_marginTop="0dp"
            android:maxLines="2"
            android:textColor="@color/gunmetal"
            android:textSize="20sp"
            android:lineSpacingExtra="4dp"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@color/brown"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4dp"
            android:text="Last Updated:"
            android:textColor="@color/white" />

        <TextView
            android:id="@+id/list_note_date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="4dp"
            android:gravity="end"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="@color/white" />
    </LinearLayout>
</android.support.v7.widget.CardView>

Body:
You can add a CheckBox to your item layout, and/or change the background of the layout itself to display a selected state.

With the first option, you can change the layout to the selected state just by setting the isChecked to true.

checkBox.setChecked(true);

To change the background of the layout, you can simply set the background to a new color resource.

itemLayout.setBackgroundResource(R.color.color_selected);

Or you can use a ColorStateList to do some more advanced state changes (such as a ripple effect to a solid color).

ripple_selector.xml

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/color_highlight">
    <item android:drawable="@drawable/color_highlight"/>
</ripple>

item_selector_background.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
            android:drawable="@color/color_selected"/>
    <item android:drawable="@drawable/ripple_effect"/>
</selector>

To use this, you can set the background attribute in your layout xml to item_selector_background then changed the selected state in your code.

itemLayout.setSelected(true);


问:
Add Original Date to Pivot Table DataFeed
Is there a way to add a data to an Excel datafeed pivot table the first time that a unique item appears and retain that date following future updates to the data?

I am monitoring a data feed to see when new items appear on it.  I would like to be able to filter on blocks of time and see what new data was added in that period but if I add a column with the function Now(), for example, it will reset every single time that I refresh the data.

答:
Put your Item in the Rows area, and also add it to the Values field as a Count. Then add your Date field to the values area as a Min. That will show you the first time any item appears.

If you are only interested in items where multiple of the same item have been sold, then additionally set a Values filter on your Item in the Rows filter so that only counts above one show:


问:
Any SQL Server multiple-recordset stored procedure gotchas?

Context

My current project is a large-ish public site (2 million pageviews per day) site running a mixture of asp classic and asp.net with a SQL Server 2005 back-end. We're heavy on reads, with occasional writes and virtually no updates/deletes. Our pages typically concern a single 'master' object with a stack of dependent (detail) objects.

I like the idea of returning all the data required for a page in a single proc (and absolutely no unnecesary data). True, this requires a dedicated proc for such pages, but some pages receive double-digit percentages of our overall site traffic so it's worth the time/maintenance hit. We typically only consume multiple-recordsets from our .net code, using System.Data.SqlClient.SqlDataReader and it's NextResult method. Oh, yeah, I'm not doing any updates/inserts in these procs either (except to table variables).

The question

SQL Server (2005) procs which return multiple recordsets are working well (in prod) for us so far but I am a little worried that multi-recordset procs are my new favourite hammer that i'm hitting every problem (nail) with. Are there any multi-recordset sql server proc gotchas I should know about? Anything that's going to make me wish I hadn't used them? Specifically anything about it affecting connection pooling, memory utilization etc.

答:
I think multi recordset stored procedures are great in some cases, and it sounds like yours maybe one of them.

The bigger (more traffic), you site gets, the more important that 'extra' bit of performance is going to matter. If you can combine 2-3-4 calls (and possibly a new connections), to the database in one, you could be cutting down your database hits by 4-6-8 million per day, which is substantial.

I use them sparingly, but when I have, I have never had a problem.

OwnerDisplayName: Jaysen Marais

LastEditorDisplayName: Jaysen Marais

OwnerDisplayName: E.J. Brennan


问:
add subtitle in navigation bar
I want to add subtitle in navigation bar. How can i do this?

Here is image of what i want =>

http://img189.imageshack.us/img189/6373/80160929.jpg

Let say this is my navigation bar . so how can add sub title which is smaller than title in size?
thanks in advance

答:
You may want to set the prompt ivar of the UINavigationItem object of your UINavigationBar.

But afair this is not really a subtitle but a smaller title above the title, so I'm not sure if this helps you in this case.

Title: add subtitle in navigation bar


问:
Display custom content based on shipping method in Woocommerce email notification
After Woocommerce update to 3.2, This code below does not work anymore.

```<code>add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for "Customer Completed Order" email notification
    if( 'customer_completed_order' != $email->id ) return;

    // Comptibility With WC 3.0+
    if ( method_exists( $order, 'get_id' ) ) {
        $order_id = $order->get_id();
    } else {
        $order_id = $order->id;
    }
    //$order->has_shipping_method('')
    $shipping_method_arr = get_post_meta($order_id, '_shipping_method', false); // an array
    $rate_id = $shipping_method_arr[0][0]; // the rate ID

    if ( 'flat_rate:10' == $rate_id ){
        echo pll__("Text 1");
    } else {
        echo pll__("Text 2");
    }
}
</code>```

What is wrong or obsolete in this code?

What changes need to be done to make it work again?

答:
Here is the correct way to get the Shipping methods used in the Order and make this function works as expected:

```<code>add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for "Customer Completed Order" email notification
    if( 'customer_completed_order' != $email->id ) return;

    $found = false; // Initializing variable

    // Iterating through Order shipping methods
    foreach($order->get_shipping_methods() as $value){
        $rate_id = $value->get_method_id(); // Get the shipping rate ID
        if ( 'flat_rate:10' == $rate_id )
            $found = true;
    }

    if ($found)
        echo '<p>'.__("Text 1 (found)","woocommerce").'</p>';
    else
        echo '<p>'.__("Text 2 (else)","woocommerce").'</p>';
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…

Body:
After Woocommerce update to 3.2, This code below does not work anymore.

add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for "Customer Completed Order" email notification
    if( 'customer_completed_order' != $email->id ) return;

    // Comptibility With WC 3.0+
    if ( method_exists( $order, 'get_id' ) ) {
        $order_id = $order->get_id();
    } else {
        $order_id = $order->id;
    }
    //$order->has_shipping_method('')
    $shipping_method_arr = get_post_meta($order_id, '_shipping_method', false); // an array
    $rate_id = $shipping_method_arr[0][0]; // the rate ID

    if ( 'flat_rate:10' == $rate_id ){
        echo pll__("Text 1");
    } else {
        echo pll__("Text 2");
    }
}

What is wrong or obsolete in this code?

What changes need to be done to make it work again?

Body:
Here is the correct way to get the Shipping methods used in the Order and make this function works as expected:

add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for "Customer Completed Order" email notification
    if( 'customer_completed_order' != $email->id ) return;

    $found = false; // Initializing variable

    // Iterating through Order shipping methods
    foreach($order->get_shipping_methods() as $value){
        $rate_id = $value->get_method_id(); // Get the shipping rate ID
        if ( 'flat_rate:10' == $rate_id )
            $found = true;
    }

    if ($found)
        echo '<p>'.__("Text 1 (found)","woocommerce").'</p>';
    else
        echo '<p>'.__("Text 2 (else)","woocommerce").'</p>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…