问:
Java lambda meta factory
```<code>CallSite lambdaFactory = LambdaMetafactory.metafactory(
   lookup,
   "call",
   MethodType.methodType(BiConsumer.class),
   MethodType.methodType(void.class,Long.class),
      lookup.findVirtual(CallClass.class, "call",
   MethodType.methodType(void.class,Long.class)),
   MethodType.methodType(void.class));
lambdaFactory.getTarget().invoke(callId);

private void call(Long callId){
     ---
}
</code>```

I am getting this exception
java.lang.invoke.LambdaConversionException: Incorrect number of parameters for instance method invokeVirtual call:()void; 0 captured parameters, 0 functional interface method parameters, 0 implementation parameters

答:
There is almost everything wrong in this invocation:

CallSite lambdaFactory = LambdaMetafactory.metafactory(

  lookup,

  "call", this must be the name of the interface method needed to be implemented. For BiConsumer, this is "accept".

  MethodType.methodType(BiConsumer.class), this is the invokedType which must match the invoke call at (10).

  MethodType.methodType(void.class,Long.class), this is the signature of the interface method to implement at the bytecode level, i.e. after type erasure. For BiConsumer, this is always MethodType.methodType(void.class, Object.class, Object.class).

  lookup.findVirtual(CallClass.class, "call",

    MethodType.methodType(void.class,Long.class)),

  MethodType.methodType(void.class) this is the specialization of the interface or identical to (5) when the interface is not generic. In either case, the number of parameters must match with (5). For your case, you likely want match the target method, so it must be MethodType.methodType(void.class, CallClass.class, Long.class).

  );

lambdaFactory.getTarget().invoke(callId); the invoke call must match the invokedType signature specified in (4). The specified arguments are the values to be captured. Since you’ve chosen to implement BiConsumer, which has the same functional signature as your target method, there is no use for an additional value.

The biggest problem is the mismatch between (4) and (10), as it makes it unclear what you actually want to achieve. Do you want to capture an existing callId as invoke(callId) suggests or do you want to create a non-capturing function, as the invokedType argument and the choice of BiConsumer suggest?

For a straight-forward BiConsumer generation, the fixed code would look like:

```<code>CallSite callSite = LambdaMetafactory.metafactory(
   lookup, "accept", MethodType.methodType(BiConsumer.class),
   MethodType.methodType(void.class, Object.class, Object.class),
   lookup.findVirtual(CallClass.class,"call", MethodType.methodType(void.class,Long.class)),
   MethodType.methodType(void.class, CallClass.class, Long.class)
);
BiConsumer<CallClass,Long> bc = (BiConsumer<CallClass, Long>)callSite.getTarget().invoke();
</code>```

If you want to capture an existing callId, you would have to change the functional interface to a type not expecting a second argument. Further, you’d need an adapter, because the LambdaMetafactory expects captured arguments first and the interface method arguments afterwards. So, since this is not supported directly, the simplest solution is to generate a BiConsumer<CallClass,Long> as above, followed by Consumer<CallClass> c = cc -> bc.apply(cc, callId);, capturing the existing callId.

Only if you also have an already existing CallClass instance you want to bind, you can do it directly:

```<code>CallSite callSite = LambdaMetafactory.metafactory(
   lookup, "run", MethodType.methodType(Runnable.class, LambdaMF.class, Long.class),
   MethodType.methodType(void.class),
   lookup.findVirtual(LambdaMF.class, "call", MethodType.methodType(void.class,Long.class)),
   MethodType.methodType(void.class)
);
Runnable r = (Runnable)callSite.getTarget().invoke(callClassInstance, callId);
</code>```

Title: Java lambda meta factory

Body:
CallSite lambdaFactory = LambdaMetafactory.metafactory(
   lookup,
   "call",
   MethodType.methodType(BiConsumer.class),
   MethodType.methodType(void.class,Long.class),
      lookup.findVirtual(CallClass.class, "call",
   MethodType.methodType(void.class,Long.class)),
   MethodType.methodType(void.class));
lambdaFactory.getTarget().invoke(callId);

private void call(Long callId){
     ---
}

I am getting this exception
java.lang.invoke.LambdaConversionException: Incorrect number of parameters for instance method invokeVirtual call:()void; 0 captured parameters, 0 functional interface method parameters, 0 implementation parameters

Body:
There is almost everything wrong in this invocation:

CallSite lambdaFactory = LambdaMetafactory.metafactory(

  lookup,

  "call", this must be the name of the interface method needed to be implemented. For BiConsumer, this is "accept".

  MethodType.methodType(BiConsumer.class), this is the invokedType which must match the invoke call at (10).

  MethodType.methodType(void.class,Long.class), this is the signature of the interface method to implement at the bytecode level, i.e. after type erasure. For BiConsumer, this is always MethodType.methodType(void.class, Object.class, Object.class).

  lookup.findVirtual(CallClass.class, "call",

    MethodType.methodType(void.class,Long.class)),

  MethodType.methodType(void.class) this is the specialization of the interface or identical to (5) when the interface is not generic. In either case, the number of parameters must match with (5). For your case, you likely want match the target method, so it must be MethodType.methodType(void.class, CallClass.class, Long.class).

  );

lambdaFactory.getTarget().invoke(callId); the invoke call must match the invokedType signature specified in (4). The specified arguments are the values to be captured. Since you’ve chosen to implement BiConsumer, which has the same functional signature as your target method, there is no use for an additional value.

The biggest problem is the mismatch between (4) and (10), as it makes it unclear what you actually want to achieve. Do you want to capture an existing callId as invoke(callId) suggests or do you want to create a non-capturing function, as the invokedType argument and the choice of BiConsumer suggest?

For a straight-forward BiConsumer generation, the fixed code would look like:

CallSite callSite = LambdaMetafactory.metafactory(
   lookup, "accept", MethodType.methodType(BiConsumer.class),
   MethodType.methodType(void.class, Object.class, Object.class),
   lookup.findVirtual(CallClass.class,"call", MethodType.methodType(void.class,Long.class)),
   MethodType.methodType(void.class, CallClass.class, Long.class)
);
BiConsumer<CallClass,Long> bc = (BiConsumer<CallClass, Long>)callSite.getTarget().invoke();

If you want to capture an existing callId, you would have to change the functional interface to a type not expecting a second argument. Further, you’d need an adapter, because the LambdaMetafactory expects captured arguments first and the interface method arguments afterwards. So, since this is not supported directly, the simplest solution is to generate a BiConsumer<CallClass,Long> as above, followed by Consumer<CallClass> c = cc -> bc.apply(cc, callId);, capturing the existing callId.

Only if you also have an already existing CallClass instance you want to bind, you can do it directly:

CallSite callSite = LambdaMetafactory.metafactory(
   lookup, "run", MethodType.methodType(Runnable.class, LambdaMF.class, Long.class),
   MethodType.methodType(void.class),
   lookup.findVirtual(LambdaMF.class, "call", MethodType.methodType(void.class,Long.class)),
   MethodType.methodType(void.class)
);
Runnable r = (Runnable)callSite.getTarget().invoke(callClassInstance, callId);


来源: stackexchange

问:
How to add two category lists to dictionary in python
I have a dataframe

```<code>df =
          name     age     character
0          A        10       fire
1          A        15       water
2          A        20       earth
3          A        25       air
4          B        10       fire
5          B        7        air
</code>```

I want to convert this dataframe to dictionary, so that output will be,

```<code>dic = {'A': [[10, 15, 20, 25], ['fire', 'water', 'earth', 'air']],
       'B': [[10, 7], ['fire', 'air']] }
</code>```

What I tried is,

from collections import defaultdict
dic = defaultdict(list)
for i in range(len(df)):
    dic[df.loc['name', i]].append(df.loc['age', i])
    dic[df.loc['name', i]].append(df.loc['character', i]) # this is wrong. It appends to existing list.
```

If I declare dic = defaultdict([[], []]), it throws error that first argument of defaultdict must be callable or None.

How can I improve this dictionary?

答:
Here's a solution that returns np.array, which is similar enough to list:

```<code>{k: d[['age','character']].T.to_numpy() for k,d in df.groupby('name')}
</code>```

Output:

```<code>{'A': array([[10, 15, 20, 25],
        ['fire', 'water', 'earth', 'air']], dtype=object),
'B': array([[10, 7],
        ['fire', 'air']], dtype=object)}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe

df =
          name     age     character
0          A        10       fire
1          A        15       water
2          A        20       earth
3          A        25       air
4          B        10       fire
5          B        7        air

I want to convert this dataframe to dictionary, so that output will be,

dic = {'A': [[10, 15, 20, 25], ['fire', 'water', 'earth', 'air']],
       'B': [[10, 7], ['fire', 'air']] }

What I tried is,

from collections import defaultdict
dic = defaultdict(list)
for i in range(len(df)):
    dic[df.loc['name', i]].append(df.loc['age', i])
    dic[df.loc['name', i]].append(df.loc['character', i]) # this is wrong. It appends to existing list.

If I declare dic = defaultdict([[], []]), it throws error that first argument of defaultdict must be callable or None.

How can I improve this dictionary?

Body:
Here's a solution that returns np.array, which is similar enough to list:

{k: d[['age','character']].T.to_numpy() for k,d in df.groupby('name')}

Output:

{'A': array([[10, 15, 20, 25],
        ['fire', 'water', 'earth', 'air']], dtype=object),
'B': array([[10, 7],
        ['fire', 'air']], dtype=object)}


问:
R summarise_at dynamically by condition : mean for some columns, sum for others
I would like that but with the conditions in the summarise_at()

Edit #1: I've added the word dynamically in the title: When I use vars(c()) in the summarise_at() it's for fast and clear examples, but in fact it's for use contains(), starts_with() and matches(,, perl=TRUE), because I have 50 columns, with many sum() and some mean().

And the goal is for generate dynamic SQL with tbl()..%>% group_by() ... %>% summarise_at()...%>% collect().

Edit #2: I added example with SQL generated in my second example

```<code>library(tidyverse)
(mtcars
  %>% group_by(carb)
  %>% summarise_at(vars(c("mpg","cyl","disp")), list (~mean(.),~sum(.)))
  # I don't want this line below, I would like a conditional in summarise_at() because I have 50 columns in my real case
  %>% select(carb,cyl_mean,disp_mean,mpg_sum)
)
#> # A tibble: 6 x 4
#>    carb cyl_mean disp_mean mpg_sum
#>   <dbl>    <dbl>     <dbl>   <dbl>
#> 1     1     4.57      134.   177.
#> 2     2     5.6       208.   224
#> 3     3     8         276.    48.9
#> 4     4     7.2       309.   158.
#> 5     6     6         145     19.7
#> 6     8     8         301     15

Created on 2020-02-19 by the reprex package (v0.3.0)

</code>```

This works, but I want only sum for mpg, and only mean for cyl and disp:

```<code>library(RSQLite)
library(dbplyr)
library(tidyverse)
library(DBI)

db <- dbConnect(SQLite(),":memory:")

dbCreateTable(db, "mtcars_table", mtcars)

(tbl( db, build_sql( con=db,"select * from mtcars_table" ))
  %>% group_by(carb)
  %>% summarise_at(vars(c("mpg","cyl","disp")), list (~mean(.),~sum(.)))
  %>% select(carb,cyl_mean,disp_mean,mpg_sum)
  %>% show_query()
)
#> <SQL>
#> Warning: Missing values are always removed in SQL.[...]  to silence this warning
#> SELECT `carb`, `cyl_mean`, `disp_mean`, `mpg_sum`
#> FROM (SELECT `carb`, AVG(`mpg`) AS `mpg_mean`, AVG(`cyl`) AS `cyl_mean`, AVG(`disp`) AS `disp_mean`, SUM(`mpg`) AS `mpg_sum`, SUM(`cyl`) AS `cyl_sum`, SUM(`disp`) AS `disp_sum`
#> FROM (select * from mtcars_table)
#> GROUP BY `carb`)
#> # Source:   lazy query [?? x 4]
#> # Database: sqlite 3.30.1 [:memory:]
#> # … with 4 variables: carb <dbl>, cyl_mean <lgl>, disp_mean <lgl>,
#> #   mpg_sum <lgl>
</code>```

I tried all possibilities like that but it doesn't work or it produces error.

```<code>(mtcars %>% group_by(carb)%>% summarise_at(vars(c("mpg","cyl","disp")),ifelse(vars(contains(names(.),"mpg")),list(sum(.)),list(mean(.)))) )
</code>```

Not good, too many columns

```<code>library(tidyverse)
(mtcars %>% group_by(carb)%>% summarise_at(vars(c("mpg","cyl","disp")),ifelse ((names(.)=="mpg"), list(~sum(.)) , list(~mean(.)))))
#> # A tibble: 6 x 34
#>    carb mpg_sum cyl_sum disp_sum mpg_mean..2 cyl_mean..2 disp_mean..2
#>   <dbl>   <dbl>   <dbl>    <dbl>       <dbl>       <dbl>        <dbl>
#> 1     1   177.       32     940.        25.3        4.57         134.
#> 2     2   224        56    2082.        22.4        5.6          208.
#> 3     3    48.9      24     827.        16.3        8            276.
#> 4     4   158.       72    3088.        15.8        7.2          309.
#> 5     6    19.7       6     145         19.7        6            145
#> 6     8    15         8     301         15          8            301
#> # … with 27 more variables: mpg_mean..3 <dbl>, cyl_mean..3 <dbl>,
#> #   disp_mean..3 <dbl>, mpg_mean..4 <dbl>, cyl_mean..4 <dbl>,
#> #   disp_mean..4 <dbl>, mpg_mean..5 <dbl>, cyl_mean..5 <dbl>,
#> #   disp_mean..5 <dbl>, mpg_mean..6 <dbl>, cyl_mean..6 <dbl>,
#> #   disp_mean..6 <dbl>, mpg_mean..7 <dbl>, cyl_mean..7 <dbl>,
#> #   disp_mean..7 <dbl>, mpg_mean..8 <dbl>, cyl_mean..8 <dbl>,
#> #   disp_mean..8 <dbl>, mpg_mean..9 <dbl>, cyl_mean..9 <dbl>,
#> #   disp_mean..9 <dbl>, mpg_mean..10 <dbl>, cyl_mean..10 <dbl>,
#> #   disp_mean..10 <dbl>, mpg_mean..11 <dbl>, cyl_mean..11 <dbl>,
#> #   disp_mean..11 <dbl>
</code>```

Some other attempts and remarks: I would like conditional sum(.) or mean(.) depending of the name of the column in the summarise().

It could be good if it accepts not only primitive functions.

At then end it's for tbl()..%>% group_by() ... %>% summarise_at()...%>% collect() to generate conditional SQL with AVG() and SUM().

T-SQL function like ~(convert(varchar()) works for mutate_at() and similar ~AVG()works for summarise_at() but I arrive at the same point: conditional summarise_at() doesn't work depending of name of columns.

:)

答:
An option is to group_by the 'carb',  and then create the sum of 'mpg' as another grouping variable and then use summarise_at with the rest of the variables needed

```<code>library(dplyr)
mtcars %>%
    group_by(carb) %>%
    group_by(mpg_sum = sum(mpg), .add = TRUE) %>%
    summarise_at(vars(cyl, disp), list(mean = mean))
# A tibble: 6 x 4
# Groups:   carb [6]
#   carb mpg_sum cyl_mean disp_mean
#  <dbl>   <dbl>    <dbl>     <dbl>
#1     1   177.      4.57      134.
#2     2   224       5.6       208.
#3     3    48.9     8         276.
#4     4   158.      7.2       309.
#5     6    19.7     6         145
#6     8    15       8         301
</code>```

Or using the devel version of dplyr, this can be done in a single summarise by wrapping the blocks of columns in across and the single column by themselves and apply different functions on it

```<code>mtcars %>%
  group_by(carb) %>%
  summarise(across(one_of(c("cyl", "disp")), list(mean = mean)),
            mpg_sum = sum(mpg))
# A tibble: 6 x 4
#   carb cyl_mean disp_mean mpg_sum
#  <dbl>    <dbl>     <dbl>   <dbl>
#1     1     4.57      134.   177.
#2     2     5.6       208.   224
#3     3     8         276.    48.9
#4     4     7.2       309.   158.
#5     6     6         145     19.7
#6     8     8         301     15
</code>```

NOTE: summarise_at/summarise_if/mutate_at/mutate_if/... etc. will be superseded by the across verb with the default functions (summarise/mutate/filter/...) in the upcoming releases

Body:
I would like that but with the conditions in the summarise_at()

Edit #1: I've added the word dynamically in the title: When I use vars(c()) in the summarise_at() it's for fast and clear examples, but in fact it's for use contains(), starts_with() and matches(,, perl=TRUE), because I have 50 columns, with many sum() and some mean().

And the goal is for generate dynamic SQL with tbl()..%>% group_by() ... %>% summarise_at()...%>% collect().

Edit #2: I added example with SQL generated in my second example

library(tidyverse)
(mtcars
  %>% group_by(carb)
  %>% summarise_at(vars(c("mpg","cyl","disp")), list (~mean(.),~sum(.)))
  # I don't want this line below, I would like a conditional in summarise_at() because I have 50 columns in my real case
  %>% select(carb,cyl_mean,disp_mean,mpg_sum)
)
#> # A tibble: 6 x 4
#>    carb cyl_mean disp_mean mpg_sum
#>   <dbl>    <dbl>     <dbl>   <dbl>
#> 1     1     4.57      134.   177.
#> 2     2     5.6       208.   224
#> 3     3     8         276.    48.9
#> 4     4     7.2       309.   158.
#> 5     6     6         145     19.7
#> 6     8     8         301     15

Created on 2020-02-19 by the reprex package (v0.3.0)

This works, but I want only sum for mpg, and only mean for cyl and disp:

library(RSQLite)
library(dbplyr)
library(tidyverse)
library(DBI)

db <- dbConnect(SQLite(),":memory:")

dbCreateTable(db, "mtcars_table", mtcars)

(tbl( db, build_sql( con=db,"select * from mtcars_table" ))
  %>% group_by(carb)
  %>% summarise_at(vars(c("mpg","cyl","disp")), list (~mean(.),~sum(.)))
  %>% select(carb,cyl_mean,disp_mean,mpg_sum)
  %>% show_query()
)
#> <SQL>
#> Warning: Missing values are always removed in SQL.[...]  to silence this warning
#> SELECT `carb`, `cyl_mean`, `disp_mean`, `mpg_sum`
#> FROM (SELECT `carb`, AVG(`mpg`) AS `mpg_mean`, AVG(`cyl`) AS `cyl_mean`, AVG(`disp`) AS `disp_mean`, SUM(`mpg`) AS `mpg_sum`, SUM(`cyl`) AS `cyl_sum`, SUM(`disp`) AS `disp_sum`
#> FROM (select * from mtcars_table)
#> GROUP BY `carb`)
#> # Source:   lazy query [?? x 4]
#> # Database: sqlite 3.30.1 [:memory:]
#> # … with 4 variables: carb <dbl>, cyl_mean <lgl>, disp_mean <lgl>,
#> #   mpg_sum <lgl>

I tried all possibilities like that but it doesn't work or it produces error.

(mtcars %>% group_by(carb)%>% summarise_at(vars(c("mpg","cyl","disp")),ifelse(vars(contains(names(.),"mpg")),list(sum(.)),list(mean(.)))) )

Not good, too many columns

library(tidyverse)
(mtcars %>% group_by(carb)%>% summarise_at(vars(c("mpg","cyl","disp")),ifelse ((names(.)=="mpg"), list(~sum(.)) , list(~mean(.)))))
#> # A tibble: 6 x 34
#>    carb mpg_sum cyl_sum disp_sum mpg_mean..2 cyl_mean..2 disp_mean..2
#>   <dbl>   <dbl>   <dbl>    <dbl>       <dbl>       <dbl>        <dbl>
#> 1     1   177.       32     940.        25.3        4.57         134.
#> 2     2   224        56    2082.        22.4        5.6          208.
#> 3     3    48.9      24     827.        16.3        8            276.
#> 4     4   158.       72    3088.        15.8        7.2          309.
#> 5     6    19.7       6     145         19.7        6            145
#> 6     8    15         8     301         15          8            301
#> # … with 27 more variables: mpg_mean..3 <dbl>, cyl_mean..3 <dbl>,
#> #   disp_mean..3 <dbl>, mpg_mean..4 <dbl>, cyl_mean..4 <dbl>,
#> #   disp_mean..4 <dbl>, mpg_mean..5 <dbl>, cyl_mean..5 <dbl>,
#> #   disp_mean..5 <dbl>, mpg_mean..6 <dbl>, cyl_mean..6 <dbl>,
#> #   disp_mean..6 <dbl>, mpg_mean..7 <dbl>, cyl_mean..7 <dbl>,
#> #   disp_mean..7 <dbl>, mpg_mean..8 <dbl>, cyl_mean..8 <dbl>,
#> #   disp_mean..8 <dbl>, mpg_mean..9 <dbl>, cyl_mean..9 <dbl>,
#> #   disp_mean..9 <dbl>, mpg_mean..10 <dbl>, cyl_mean..10 <dbl>,
#> #   disp_mean..10 <dbl>, mpg_mean..11 <dbl>, cyl_mean..11 <dbl>,
#> #   disp_mean..11 <dbl>

Some other attempts and remarks: I would like conditional sum(.) or mean(.) depending of the name of the column in the summarise().

It could be good if it accepts not only primitive functions.

At then end it's for tbl()..%>% group_by() ... %>% summarise_at()...%>% collect() to generate conditional SQL with AVG() and SUM().

T-SQL function like ~(convert(varchar()) works for mutate_at() and similar ~AVG()works for summarise_at() but I arrive at the same point: conditional summarise_at() doesn't work depending of name of columns.

:)

Body:
An option is to group_by the 'carb',  and then create the sum of 'mpg' as another grouping variable and then use summarise_at with the rest of the variables needed

library(dplyr)
mtcars %>%
    group_by(carb) %>%
    group_by(mpg_sum = sum(mpg), .add = TRUE) %>%
    summarise_at(vars(cyl, disp), list(mean = mean))
# A tibble: 6 x 4
# Groups:   carb [6]
#   carb mpg_sum cyl_mean disp_mean
#  <dbl>   <dbl>    <dbl>     <dbl>
#1     1   177.      4.57      134.
#2     2   224       5.6       208.
#3     3    48.9     8         276.
#4     4   158.      7.2       309.
#5     6    19.7     6         145
#6     8    15       8         301

Or using the devel version of dplyr, this can be done in a single summarise by wrapping the blocks of columns in across and the single column by themselves and apply different functions on it

mtcars %>%
  group_by(carb) %>%
  summarise(across(one_of(c("cyl", "disp")), list(mean = mean)),
            mpg_sum = sum(mpg))
# A tibble: 6 x 4
#   carb cyl_mean disp_mean mpg_sum
#  <dbl>    <dbl>     <dbl>   <dbl>
#1     1     4.57      134.   177.
#2     2     5.6       208.   224
#3     3     8         276.    48.9
#4     4     7.2       309.   158.
#5     6     6         145     19.7
#6     8     8         301     15

NOTE: summarise_at/summarise_if/mutate_at/mutate_if/... etc. will be superseded by the across verb with the default functions (summarise/mutate/filter/...) in the upcoming releases


问:
Dynamics 365 - Get the value for selected option from Global Option Set
I'm trying to find a way to get a value for my field which is based on a GlobalOptionSet.
I'm managing to pull back data from my endpoint
https://TEST.test.dynamics.com/api/data/v9.1/projects which is returning my list of projects.
some of the fields on this dataset just show as GUID's which I've managed to expand into and get their values.
However, some of the fields returned are showing just numbers like 866110000 which I believe is an option in a GlobalOptionSet.

I know I can get the GlobalOptionSet definition and match up its value but I'm hoping to be able to get this information in a single query similar to the way I got other fields by expanding.

Does anyone know how to get it to return the selected Value for an option field instead of the ID of the option that was picked?

Thanks

答:
All you have to do is include the below header to get the needed optionset & lookup display name values. Read more

```<code>Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"
</code>```

Sample request:

```<code>GET [Organization URI]/api/data/v9.1/accounts?$select=name,donotpostalmail,accountratingcode,numberofemployees,revenue
&$top=1 HTTP/1.1
Accept: application/json
OData-MaxVersion: 4.0
OData-Version: 4.0
Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"
</code>```

If its AJAX request using jQuery or XmlHttpRequest, for ex.

```<code>req.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
</code>```

Reference

Body:
All you have to do is include the below header to get the needed optionset & lookup display name values. Read more

Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"

Sample request:

GET [Organization URI]/api/data/v9.1/accounts?$select=name,donotpostalmail,accountratingcode,numberofemployees,revenue
&$top=1 HTTP/1.1
Accept: application/json
OData-MaxVersion: 4.0
OData-Version: 4.0
Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"

If its AJAX request using jQuery or XmlHttpRequest, for ex.

req.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");

Reference


问:
Digital camera algorithms
I'm working on a simple video device and I'd like to introduce some standard cool camera features. Amongst all I'd like to introduce

Focus indicator

Auto focus

Auto exposure (ideal exposure time estimation)

Right now I'm looking for some examples, how these features can be implemented. Do you have any useful links?

EDIT :
Ok, I will use standard CCD camera, which can provide me ~ 20fps in ~1MPix resolution. I'm planning to write it in C#, in case of performance issues, I'll use C++. I'll have lens + CCD camera + motor.

EDIT :
I'd like to see some more detailed algorithm description. I'm sure some have to be taught in university courses, but I have troubles finding some. For focus indicator I've tried a primitive approach, but in some cases it failed.

```<code> int verticalPoints = 0, horizontalPoints = 0;
 ///Calculate the vertical differences
 for (int x = 0; x < toAnalyze.Width; x++)
 {
     for (int y = 1; y < toAnalyze.Height; y++)
     {
        byte* pixel = (byte*)data.Scan0 + y * stride + x;
        verticalDiff += Math.Abs(*pixel - *(pixel - stride));;
     }
  }
  verticalDiff /= toAnalyze.Width * (toAnalyze.Height-1);
  ///Calculate horizontal differences
  for (int y = 0; y < toAnalyze.Height; y++)
  {
     for (int x = 1; x < toAnalyze.Width; x++)
     {
        byte* pixel = (byte*)data.Scan0 + y * stride + x;
        horizontalDiff += Math.Abs(*pixel - *(pixel - 1));
     }
   }
   horizontalDiff /= (toAnalyze.Width-1) * toAnalyze.Height;
   ///And return the average value
   return(verticalDiff + horizontalDiff) / 2;
</code>```

Thanks

答: The AForge.net has alot of stuff for doing image processing , including edge detection and convolution filters. Another (larger) library you might want to look at is OpenCV but only has wrappers for .net, where as AForge is written in c# directly</p>

ContentLicense: CC BY-SA 3.0

Title: Digital camera algorithms

Body:
I'm working on a simple video device and I'd like to introduce some standard cool camera features. Amongst all I'd like to introduce

Focus indicator

Auto focus

Auto exposure (ideal exposure time estimation)

Right now I'm looking for some examples, how these features can be implemented. Do you have any useful links?

EDIT :
Ok, I will use standard CCD camera, which can provide me ~ 20fps in ~1MPix resolution. I'm planning to write it in C#, in case of performance issues, I'll use C++. I'll have lens + CCD camera + motor.

EDIT :
I'd like to see some more detailed algorithm description. I'm sure some have to be taught in university courses, but I have troubles finding some. For focus indicator I've tried a primitive approach, but in some cases it failed.

 int verticalPoints = 0, horizontalPoints = 0;
 ///Calculate the vertical differences
 for (int x = 0; x < toAnalyze.Width; x++)
 {
     for (int y = 1; y < toAnalyze.Height; y++)
     {
        byte* pixel = (byte*)data.Scan0 + y * stride + x;
        verticalDiff += Math.Abs(*pixel - *(pixel - stride));;
     }
  }
  verticalDiff /= toAnalyze.Width * (toAnalyze.Height-1);
  ///Calculate horizontal differences
  for (int y = 0; y < toAnalyze.Height; y++)
  {
     for (int x = 1; x < toAnalyze.Width; x++)
     {
        byte* pixel = (byte*)data.Scan0 + y * stride + x;
        horizontalDiff += Math.Abs(*pixel - *(pixel - 1));
     }
   }
   horizontalDiff /= (toAnalyze.Width-1) * toAnalyze.Height;
   ///And return the average value
   return(verticalDiff + horizontalDiff) / 2;

Thanks


问:
Codeigniter bootstrap load only on index.php page
I'm loading bootstrap this way on my view page :

```<code><link rel="stylesheet" href="<? echo base_url('assets/css/bootstrap.min.css')?>">
</code>```

autoload:  $autoload['helper'] = array('url');

configs:  $config['base_url'] = 'http://localhost/helloby/';

Below is the path of the controller:

http://localhost/helloby/index.php/login/home

But when I copy the same code at welcome_message view bootstrap loads normally. I don't know why it's happening.

答:
I solved the problem, I was reading an e-book of best practice of Codeigniter and the call of bootstrap was a little bit different.

This way : href="<?=base_url('/assets/css/bootstrap.min.css')?>

and working fine!

Body:
I'm loading bootstrap this way on my view page :

<link rel="stylesheet" href="<? echo base_url('assets/css/bootstrap.min.css')?>">

autoload:  $autoload['helper'] = array('url');

configs:  $config['base_url'] = 'http://localhost/helloby/';

Below is the path of the controller:

http://localhost/helloby/index.php/login/home

But when I copy the same code at welcome_message view bootstrap loads normally. I don't know why it's happening.


问:
Sample code for KeystoneJS 5 custom fields?
I'm interested in writing custom fields for KeystoneJS 5.  The documentation is here, but I find it somewhat opaque (i.e., not fully explicatory).  Is there sample code available?  I looked in 'demo projects' and 'test projects' in the Keystone repo, but didn't see anything.  </p>

答:
KeystoneJs custom fields are poorly documented and not easily accessible. in fact the whole concept of writing the whole custom field may be overkill.

here is the example one core team member has put copied form the test-project. - https://github.com/MadeByMike/keystone-custom-field/blob/7caf0139c189eadda1884a86073c6945bdd6ff05/index.js#L15

this is what you need to do:
 1. you need to create a folder for the field
 2. you can copy the Text field implementation to start with
 3. there index.js file must export specific object (default export) like this ( I have added some comment for each line)

```<code>{
  type: 'Stars', // name of the implementation
  implementation: Stars, // implementation itself
  views: { // all views are required you can copy the implementation from Text field)
    Controller: Integer.views.Controller, // it is using controller from Integer field type
    Field: require.resolve('./views/Field'), // field which goes into edit page or create dialog
    Filter: Integer.views.Filter, // this adds filters in the list page
    Cell: require.resolve('./views/Cell'), // view for list page where you usually see the text, for Relationship it is rendered as link.
  },
  adapters: {
    mongoose: MongoIntegerInterface, // mongoose adapter specific inplementation
    knex: KnexIntegerInterface, // knex adapter specific implementation,.
  },
}
</code>```

create views for each type (Field, Filter, Cell etc.)

import the field (default import) in the schema definition and use it like regular field. any custom option is passed on to the custom implementation.

Body:
KeystoneJs custom fields are poorly documented and not easily accessible. in fact the whole concept of writing the whole custom field may be overkill.

here is the example one core team member has put copied form the test-project. - https://github.com/MadeByMike/keystone-custom-field/blob/7caf0139c189eadda1884a86073c6945bdd6ff05/index.js#L15

this is what you need to do:
 1. you need to create a folder for the field
 2. you can copy the Text field implementation to start with
 3. there index.js file must export specific object (default export) like this ( I have added some comment for each line)

{
  type: 'Stars', // name of the implementation
  implementation: Stars, // implementation itself
  views: { // all views are required you can copy the implementation from Text field)
    Controller: Integer.views.Controller, // it is using controller from Integer field type
    Field: require.resolve('./views/Field'), // field which goes into edit page or create dialog
    Filter: Integer.views.Filter, // this adds filters in the list page
    Cell: require.resolve('./views/Cell'), // view for list page where you usually see the text, for Relationship it is rendered as link.
  },
  adapters: {
    mongoose: MongoIntegerInterface, // mongoose adapter specific inplementation
    knex: KnexIntegerInterface, // knex adapter specific implementation,.
  },
}

create views for each type (Field, Filter, Cell etc.)

import the field (default import) in the schema definition and use it like regular field. any custom option is passed on to the custom implementation.


问:
Translate R for loop into apply function
I have written a for loop in my code

```<code>for(i in 2:nrow(ProductionWellYear2)) {

  if (ProductionWellYear2[i,ncol(ProductionWellYear2)] == 0) {
    ProductionWellYear2[i, ncol(ProductionWellYear2)] = ProductionWellYear2[i-1,ncol(ProductionWellYear2)] +1}

  else {ProductionWellYear2[i,ncol(ProductionWellYear2)] = ProductionWellYear2[i,ncol(ProductionWellYear2)]}

  }

</code>```

However, this is very time intensive as this dataframe has over 800k rows.  How can I make this quicker and avoid the for loop?

答:
This should work for you, but without seeing your data I can't verify the results are what you want. That being said, there's really not much different here in the process as originally written, but benchmarking does seem to show it is faster with my example data, but not necessarily "fast".</p>
```<code>library(microbenchmark)
# Create fake data
set.seed(1)
ProductionWellYear <- data.frame(A = as.integer(rnorm(2500)),
                                 B = as.integer(rnorm(2500)),
                                 C = as.integer(rnorm(2500))
)

# Copy it to confirm results of both processes are the same
ProductionWellYear2 <- ProductionWellYear

# Slightly modified original version
method1 <- function() {
  cols <- ncol(ProductionWellYear)
  for(i in 2:nrow(ProductionWellYear)) {
    if (ProductionWellYear[i, cols] == 0) {
      ProductionWellYear[i, cols] = ProductionWellYear[i - 1, cols] +1
    }
    else {
      ProductionWellYear[i, cols] = ProductionWellYear[i, cols]
    }
  }
}

# New version
method2 <- function() {
  cols <- ncol(ProductionWellYear2)
  sapply(2:nrow(ProductionWellYear2), function(i) {
    if (ProductionWellYear2[i, cols] == 0) {
      ProductionWellYear2[i, cols] <<- ProductionWellYear2[i - 1, cols] +1
    }
  })
}

# Comparing the outputs
all(ProductionWellYear == ProductionWellYear2)
#[1] TRUE

result <- microbenchmark(method1(), method2())
result
#Unit: milliseconds
#      expr      min       lq     mean   median       uq       max neval
#  method1() 151.78802 167.3932 190.14905 176.2855 197.60406 337.9904   100
#  method2()  45.56065  53.7744  67.55549  59.9299  72.81873 174.1417   100
</code>```

Body:
I have written a for loop in my code

for(i in 2:nrow(ProductionWellYear2)) {

  if (ProductionWellYear2[i,ncol(ProductionWellYear2)] == 0) {
    ProductionWellYear2[i, ncol(ProductionWellYear2)] = ProductionWellYear2[i-1,ncol(ProductionWellYear2)] +1}

  else {ProductionWellYear2[i,ncol(ProductionWellYear2)] = ProductionWellYear2[i,ncol(ProductionWellYear2)]}

  }

However, this is very time intensive as this dataframe has over 800k rows.  How can I make this quicker and avoid the for loop?

Body:
This should work for you, but without seeing your data I can't verify the results are what you want. That being said, there's really not much different here in the process as originally written, but benchmarking does seem to show it is faster with my example data, but not necessarily "fast".

library(microbenchmark)
# Create fake data
set.seed(1)
ProductionWellYear <- data.frame(A = as.integer(rnorm(2500)),
                                 B = as.integer(rnorm(2500)),
                                 C = as.integer(rnorm(2500))
)

# Copy it to confirm results of both processes are the same
ProductionWellYear2 <- ProductionWellYear

# Slightly modified original version
method1 <- function() {
  cols <- ncol(ProductionWellYear)
  for(i in 2:nrow(ProductionWellYear)) {
    if (ProductionWellYear[i, cols] == 0) {
      ProductionWellYear[i, cols] = ProductionWellYear[i - 1, cols] +1
    }
    else {
      ProductionWellYear[i, cols] = ProductionWellYear[i, cols]
    }
  }
}

# New version
method2 <- function() {
  cols <- ncol(ProductionWellYear2)
  sapply(2:nrow(ProductionWellYear2), function(i) {
    if (ProductionWellYear2[i, cols] == 0) {
      ProductionWellYear2[i, cols] <<- ProductionWellYear2[i - 1, cols] +1
    }
  })
}

# Comparing the outputs
all(ProductionWellYear == ProductionWellYear2)
#[1] TRUE

result <- microbenchmark(method1(), method2())
result
#Unit: milliseconds
#      expr      min       lq     mean   median       uq       max neval
#  method1() 151.78802 167.3932 190.14905 176.2855 197.60406 337.9904   100
#  method2()  45.56065  53.7744  67.55549  59.9299  72.81873 174.1417   100


问:
Is there a way to ignore jackson fields at runtime without using @JsonIgnore
I'm trying to serialize an object and at runtime choose the fields to be ignored without using @JsonIgnore annotation, I'm trying the follow code:

```<code>            @Override
            protected boolean _isIgnorable(Annotated a) {
                if (a.getName().contains("foo")) {
                    return true;
                }
            }
        });
</code>```

but this code doesn't work because I cant get the fields, anyone can help me?

答:
Are you sure, what your implementation of AnnotationIntrospector used?

Put breakpoint on if (a.getName().contains("foo")) { line.

And inside _isIgnorable of com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector class

pic

Body:
I'm trying to serialize an object and at runtime choose the fields to be ignored without using @JsonIgnore annotation, I'm trying the follow code:

            @Override
            protected boolean _isIgnorable(Annotated a) {
                if (a.getName().contains("foo")) {
                    return true;
                }
            }
        });

but this code doesn't work because I cant get the fields, anyone can help me?


问:
SQL turn a dynamic number of rows into columns with multiple columns
I have a large table with up to 90 rows and 40 columns. For sake of SSRS reporting this data needs to be converted into one column so that it can be displayed as a single page report. I will not use all rows but a good 50 are applicable to the reporting dataset.

I've looked around for several solutions but they often hinge on a 3 column dataset and it does not work because of the number of columns & rows I need to rotate.

The question is, is it possible? And if so, what would be the best approach?

Pivot might be a solution but I was wondering if there is a faster way to move all 2nd, 3rd etc rows to the top row and add the identifier in front of the columnName from the row being moved up?

Sample table:

```<code>        -------------------------------------------------------------------------------------------------
        |ActID | MList | List | Seg | Amt1  | Amt2 | Amt3 | Amt4 | Date1  | Date2  | Char1  |... Char30 |
        -------------------------------------------------------------------------------------------------
        |ABCD  |    1  |   1  | AA  | 20.00 | 5.00 | 0    | 0    | 1/2/19 | 2/5/19 | Null   |    Text1  |
        |ABCD  |    1  |   2  | AB  | 0     | 0    | 0    | 0    | Null   | Null   | Null   |    Null   |
        |ABCD  |    1  |   3  | AC  | 35.00 | 24.00| 33.00| 0    | Null   | Null   | Text3  |    Text4  |
        |ABCD  |    2  |   1  | AA  | 0     | 0    | 0    | 0    | 5/5/17 | 3/5/12 | Text19 |    Text30 |
        |ABCD  |    2  |   2  | AB  | 25.00 | 99.00| 18.00| 5.00 | 2/2/14 | 3/3/19 | Null   |    Null   |
        |FGHA  |    1  |   1  | AA  | 0     | 0    | 0    | 0    | Null   | Null   | Text22 |    Null   |
        |FGHA  |    1  |   2  | AB  | 0     | 0    | 0    | 0    | 1/1/20 | 1/1/20 | Null   |    Text5  |
        -------------------------------------------------------------------------------------------------
</code>```

What I'm attempting to do is use the first two columns as identifiers and then conflate all amount/character/date field columns by using List+Seg fields as helpful markings.

So the end result would be something like:

```<code>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|ActID | MList | 1AAAmt1 | 1AAAmt2 | 1AAAmt3 | 1AAAmt4 |1AADate1 |1AADate2 | 1AAChar1 |...1AAChar30 | 2ABAmt1 | 2ABAmt2 | 2ABAmt3 | 2ABAmt4 | 2ABDate1 |2ABDate2 | 2ABChar1 |...2ABChar30 | ...etc |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|ABCD  |   1   | 20.00   | 5.00    | 0       | 0       | 1/2/19  | 2/5/19  | Null     |     Text1   | 0       | 0       | 0       | 0       | Null     | Null    | Null     | Null        | ...etc |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
</code>```

First time asking a question, I normally browse but found nothing that quite resolves my issue of sheer row/column numbers and the dynamics of it.  Hope this illustrates the problem well.

This is using SQL Server 2012

答:
SSRS allows you to create Row and Column groups to dynamically pivot your data in a matrix. In this example you would have a Row group on ActID and a Column group on List. The column group would encompass those ~37 columns and repeat them all for each List number in the dataset.

If you query the Char fields in rows instead of columns, you could have a variable number of them and use that as a nested column group in the report.

In general, I've found that it's best to query data into rows whenever possible and let the report grouping do the heavy lifting.

Body:
I have a large table with up to 90 rows and 40 columns. For sake of SSRS reporting this data needs to be converted into one column so that it can be displayed as a single page report. I will not use all rows but a good 50 are applicable to the reporting dataset.

I've looked around for several solutions but they often hinge on a 3 column dataset and it does not work because of the number of columns & rows I need to rotate.

The question is, is it possible? And if so, what would be the best approach?

Pivot might be a solution but I was wondering if there is a faster way to move all 2nd, 3rd etc rows to the top row and add the identifier in front of the columnName from the row being moved up?

Sample table:

        -------------------------------------------------------------------------------------------------
        |ActID | MList | List | Seg | Amt1  | Amt2 | Amt3 | Amt4 | Date1  | Date2  | Char1  |... Char30 |
        -------------------------------------------------------------------------------------------------
        |ABCD  |    1  |   1  | AA  | 20.00 | 5.00 | 0    | 0    | 1/2/19 | 2/5/19 | Null   |    Text1  |
        |ABCD  |    1  |   2  | AB  | 0     | 0    | 0    | 0    | Null   | Null   | Null   |    Null   |
        |ABCD  |    1  |   3  | AC  | 35.00 | 24.00| 33.00| 0    | Null   | Null   | Text3  |    Text4  |
        |ABCD  |    2  |   1  | AA  | 0     | 0    | 0    | 0    | 5/5/17 | 3/5/12 | Text19 |    Text30 |
        |ABCD  |    2  |   2  | AB  | 25.00 | 99.00| 18.00| 5.00 | 2/2/14 | 3/3/19 | Null   |    Null   |
        |FGHA  |    1  |   1  | AA  | 0     | 0    | 0    | 0    | Null   | Null   | Text22 |    Null   |
        |FGHA  |    1  |   2  | AB  | 0     | 0    | 0    | 0    | 1/1/20 | 1/1/20 | Null   |    Text5  |
        -------------------------------------------------------------------------------------------------

What I'm attempting to do is use the first two columns as identifiers and then conflate all amount/character/date field columns by using List+Seg fields as helpful markings.

So the end result would be something like:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|ActID | MList | 1AAAmt1 | 1AAAmt2 | 1AAAmt3 | 1AAAmt4 |1AADate1 |1AADate2 | 1AAChar1 |...1AAChar30 | 2ABAmt1 | 2ABAmt2 | 2ABAmt3 | 2ABAmt4 | 2ABDate1 |2ABDate2 | 2ABChar1 |...2ABChar30 | ...etc |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|ABCD  |   1   | 20.00   | 5.00    | 0       | 0       | 1/2/19  | 2/5/19  | Null     |     Text1   | 0       | 0       | 0       | 0       | Null     | Null    | Null     | Null        | ...etc |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

First time asking a question, I normally browse but found nothing that quite resolves my issue of sheer row/column numbers and the dynamics of it.  Hope this illustrates the problem well.

This is using SQL Server 2012


问:
Calculating the speed of routines?
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

```<code>// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process
</code>```

I look forward to hearing some suggestions.

Thanks.

Craig.

答: Try Eric Grange's Sampling Profiler.</p>

Title: Calculating the speed of routines?

Body:
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process

I look forward to hearing some suggestions.

Thanks.

Craig.

Body: Try Eric Grange's Sampling Profiler.


问:
Deleting ummerged Git branches that were actually merged after rebasing
Git is able to pick up the merged branches and we can delete them but in some cases, let's say you have a bunch of branches which were rebased before a merge and its tracking branch at remote wasn't updated. Now this local branch was deleted as well.

Any way to figure out which branches on remote are the ones that are safe to delete?

答:
The easiest thing to do would be recreate local tracking branches for all those remotes.

You can then run something like the following to show all commits in any of the local branches that are not in the master branch of some remote:

```<code>git log master --not --remotes=*/master
</code>```

Body:
The easiest thing to do would be recreate local tracking branches for all those remotes.

You can then run something like the following to show all commits in any of the local branches that are not in the master branch of some remote:

git log master --not --remotes=*/master


问:
How to Navigating from SwiftUI View to UIKit UIViewController
As of now, I have an application built entirely using UIKit. However, I wish to be able to start implementing some SwiftUI Views to replace some UIViewControllers.

I've been able to do this to navigate from the UIViewController to SwiftUI View on button tap:

```<code>    @IBAction func buttonTapped(_ sender: Any) {
        let newView = UIHostingController(rootView: SwiftUIView(viewObj: self.view, sb: self.storyboard, dismiss: self.dismiss) )
        view.window?.rootViewController = newView
        view.window?.makeKeyAndVisible()
    }
</code>```

My question is, how would I transition from a single SwiftUI View to a UIViewController?(Since the rest of the application is in UIKit)? I've got a button in the SwiftUI View, to navigate back to the UIViewController on tap. I've tried:

Passing the view and storyboard objects to the SwiftUI View, then calling doing something similar to the code above to change the current view controller. However, when tried on the simulator nothing happens.

Using .present to show the SwiftUI View modally. This works and I can allow the SwiftUI View to .dismiss itself. However, this only works modally, and I hope to make this work properly (i.e change screen)

Here is my simple SwiftUI View:

```<code>struct SwiftUIView: View {
    var viewObj:UIView? // Perhaps use this for transition back?
    var sb:UIStoryboard?
    var dismiss: (() -> Void)?

    var body: some View {

        Button(action: {
            // Do something here to Transition
        }) {
            Text("This is a SwiftUI view.")
        }
    }
}
</code>```

I'm having trouble understanding how to properly integrate SwiftUI into UIKit NOT the other way around, and I'm not sure if UIViewControllerRepresentable is the answer to this. Any solution to this, alternatives or helpful knowledge is very much appreciated. Thanks again!

答:
You can do the same, only in mirror order, like following (scratchy) ...</p>

```<code>    Button(action: {
        if let vc = self.sb?.instantiateViewController(withIdentifier: "some_identifier") {
            self.viewObj?.window?.rootViewController = vc
            // or via present as alternate
            // self.viewObj?.window?.rootViewController.present(vc, animated: true, completion: nil)
        }
    }) {
</code>```

Body:
As of now, I have an application built entirely using UIKit. However, I wish to be able to start implementing some SwiftUI Views to replace some UIViewControllers.

I've been able to do this to navigate from the UIViewController to SwiftUI View on button tap:

    @IBAction func buttonTapped(_ sender: Any) {
        let newView = UIHostingController(rootView: SwiftUIView(viewObj: self.view, sb: self.storyboard, dismiss: self.dismiss) )
        view.window?.rootViewController = newView
        view.window?.makeKeyAndVisible()
    }

My question is, how would I transition from a single SwiftUI View to a UIViewController?(Since the rest of the application is in UIKit)? I've got a button in the SwiftUI View, to navigate back to the UIViewController on tap. I've tried:

Passing the view and storyboard objects to the SwiftUI View, then calling doing something similar to the code above to change the current view controller. However, when tried on the simulator nothing happens.

Using .present to show the SwiftUI View modally. This works and I can allow the SwiftUI View to .dismiss itself. However, this only works modally, and I hope to make this work properly (i.e change screen)

Here is my simple SwiftUI View:

struct SwiftUIView: View {
    var viewObj:UIView? // Perhaps use this for transition back?
    var sb:UIStoryboard?
    var dismiss: (() -> Void)?

    var body: some View {

        Button(action: {
            // Do something here to Transition
        }) {
            Text("This is a SwiftUI view.")
        }
    }
}

I'm having trouble understanding how to properly integrate SwiftUI into UIKit NOT the other way around, and I'm not sure if UIViewControllerRepresentable is the answer to this. Any solution to this, alternatives or helpful knowledge is very much appreciated. Thanks again!

Body:
You can do the same, only in mirror order, like following (scratchy) ...

    Button(action: {
        if let vc = self.sb?.instantiateViewController(withIdentifier: "some_identifier") {
            self.viewObj?.window?.rootViewController = vc
            // or via present as alternate
            // self.viewObj?.window?.rootViewController.present(vc, animated: true, completion: nil)
        }
    }) {


问:
Vim colorscheme change
I'm having difficulty getting my colorscheme to change. I've opened both ~/.vimrc and /usr/share/vim/vimrc and added:

```<code>colorscheme desert
</code>```

...and nothing. I noticed the color schemes are here:

```<code>/usr/share/vim/vim72/colors/desert.vim (...along with a bunch or others)
</code>```

which seems like the wrong place so I:

```<code>cp /usr/share/vim/vim72/colors/desert.vim ~/.vim/colors/
</code>```

and still no go.

答:
Currently, using Ubuntu and VIM 8, I did this:

Browse to your user directory:

```<code>cd ~
</code>```

Create and open a .vimrc file:

```<code>vim .vimrc
</code>```

Click i for insert mode.
Type the following command below to enable syntax and give a specific colorscheme. This example uses the desert colorscheme:

```<code>syntax on

colorscheme desert
</code>```

Hold Shift and hit : then type wq! to save and quit the file.
You should now be able to use vi and the colorscheme you choose to edit files on your Grid.

Below the default set of colour schemes for Vim 8:

blue

darkblue

delek

desert

elflord

evening

industry

koehler

morning

murphy

pablo

peachpuff

ron

shine

slate

torte

zellner

Title: Vim colorscheme change

Body:
I'm having difficulty getting my colorscheme to change. I've opened both ~/.vimrc and /usr/share/vim/vimrc and added:

colorscheme desert

...and nothing. I noticed the color schemes are here:

/usr/share/vim/vim72/colors/desert.vim (...along with a bunch or others)

which seems like the wrong place so I:

cp /usr/share/vim/vim72/colors/desert.vim ~/.vim/colors/

and still no go.

Body:
Currently, using Ubuntu and VIM 8, I did this:

Browse to your user directory:

cd ~

Create and open a .vimrc file:

vim .vimrc

Click i for insert mode.
Type the following command below to enable syntax and give a specific colorscheme. This example uses the desert colorscheme:

syntax on

colorscheme desert

Hold Shift and hit : then type wq! to save and quit the file.
You should now be able to use vi and the colorscheme you choose to edit files on your Grid.

Below the default set of colour schemes for Vim 8:

blue

darkblue

delek

desert

elflord

evening

industry

koehler

morning

murphy

pablo

peachpuff

ron

shine

slate

torte

zellner


问:
How is C++ array recognized?
When you pass an array in C++, they get passed as a pointer. So we have to pass the size of that array explicitly.

```<code>// This will not work.
int GetSize(int* arr){
  return sizeof(arr)/size(int);
}
</code>```

But if we don't use a function to get its size and use "sizeof" in the same function where the array was initialized, now we get the correct result.

```<code>int main(){
  int arr[5];
  int size = sizeof(arr)/sizeof(int);
  cout << size << endl;
}
</code>```

So is it adequate for me to look at the array as a class with a pointer, its size and type of elements in it?

Now that I think about it, I'm not sure how C++ knows array's size in the latter code if it's just handled the same as a pointer.

答:
The declaration

```<code>int *arr; // arr = ptr to int
</code>```

is different than the declaration

```<code>int arr[5];  // arr = base ptr to array of 5 ints
</code>```

Note the arr resolves to an address (ptr) in each case, but in the second case the compiler can resolve that arr is a base ptr to an array of 5 int's. Things get a little trickier if the second declaration is for a function parameter:

```<code>void foo(int arr[5]) { ... }
</code>```

then this is really no different than

```<code>void foo(int *arr) { ... }
void foo(int arr[]) { ... }
</code>```

i.e., only a ptr is passed and sizeof(arr) will return the number of bytes in a ptr.

Title: How is C++ array recognized?

Body:
When you pass an array in C++, they get passed as a pointer. So we have to pass the size of that array explicitly.

// This will not work.
int GetSize(int* arr){
  return sizeof(arr)/size(int);
}

But if we don't use a function to get its size and use "sizeof" in the same function where the array was initialized, now we get the correct result.

int main(){
  int arr[5];
  int size = sizeof(arr)/sizeof(int);
  cout << size << endl;
}

So is it adequate for me to look at the array as a class with a pointer, its size and type of elements in it?

Now that I think about it, I'm not sure how C++ knows array's size in the latter code if it's just handled the same as a pointer.

Body:
The declaration

int *arr; // arr = ptr to int

is different than the declaration

int arr[5];  // arr = base ptr to array of 5 ints

Note the arr resolves to an address (ptr) in each case, but in the second case the compiler can resolve that arr is a base ptr to an array of 5 int's. Things get a little trickier if the second declaration is for a function parameter:

void foo(int arr[5]) { ... }

then this is really no different than

void foo(int *arr) { ... }
void foo(int arr[]) { ... }

i.e., only a ptr is passed and sizeof(arr) will return the number of bytes in a ptr.


问:
Get Header name
Hello I am a bit lost with the control Templates, I have an expander and some control-styles that apply onto the Expander.
So the idea is to let the User insert the header

```<code><Expander Name="MyExpanderExpander"  Style="{StaticResource MyExpanderNewGeneration}" Header="UserChoice" OverridesDefaultStyle="True" VerticalAlignment="Top" Margin="0,0,0,0" Height="210">
</code>```

So now the Style : MyExpanderNewGeneration should get the header Name : UserChoic
 The ToggleButton has to get the Header Name : UserChoice and here is my problem ..but how to do it?

my Style applying is

```<code>    <Style TargetType="Expander" x:Key="MyExpanderNewGeneration" BasedOn="{StaticResource BaseControlStyle}" >
            <!--x:Key="GroupBoxStyle"-->
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Expander">
                        <Grid>
                            <!--Grid Rows split the GroupBox into two areas -->
                            <Grid.RowDefinitions>
                                <RowDefinition Height="30"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <!--Header area-->
                            <Border Name="HeaderArea"
      Grid.Row="0"
      Background="Transparent"

      BorderBrush="Transparent"
      BorderThickness="1"
      CornerRadius="2,2,0,0" >
                                <ToggleButton x:Name="ExpanderButton"

                           Grid.Row="0"
                          Grid.Column="0"
                          Margin="0,0,0,0"
                          VerticalAlignment="Top"
                          Template="{StaticResource TestToggleButton}"
                          Content="{TemplateBinding Header}"
                          IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}"
                          OverridesDefaultStyle="True">
                                </ToggleButton>
</code>```

Herer I want to get the UserChoice Name.

```<code> <ControlTemplate x:Key="TestToggleButton" TargetType="{x:Type ToggleButton}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="300"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Foreground="White" Width="300" Grid.Column="0" FontSize="15"
                    HorizontalAlignment="Left" FontWeight="Normal" Something={HEADER???}
</code>```

How to solve this?

答:
Since you are setting Content="{TemplateBinding Header}" in your ExpanderButton, you will need to bind to the Content property inside your TestToggleButton style's control template:

```<code><ControlTemplate x:Key="TestToggleButton" TargetType="{x:Type ToggleButton}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label
            ...
            Content={TemplateBinding Content} />
        ...
    </Grid>
</ControlTemplate>
</code>```

Title: Get Header name

Body:
Hello I am a bit lost with the control Templates, I have an expander and some control-styles that apply onto the Expander.
So the idea is to let the User insert the header

<Expander Name="MyExpanderExpander"  Style="{StaticResource MyExpanderNewGeneration}" Header="UserChoice" OverridesDefaultStyle="True" VerticalAlignment="Top" Margin="0,0,0,0" Height="210">

So now the Style : MyExpanderNewGeneration should get the header Name : UserChoic
 The ToggleButton has to get the Header Name : UserChoice and here is my problem ..but how to do it?

my Style applying is

Body:
Since you are setting Content="{TemplateBinding Header}" in your ExpanderButton, you will need to bind to the Content property inside your TestToggleButton style's control template:

<ControlTemplate x:Key="TestToggleButton" TargetType="{x:Type ToggleButton}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label
            ...
            Content={TemplateBinding Content} />
        ...
    </Grid>
</ControlTemplate>


问:
Defining Eq instance for Haskell GADTs
I have a GADT that's a lot like this:

```<code>data In a where
  M :: MVar a -> In a
  T :: TVar a -> In a
  F :: (a -> b) -> In a -> In b
</code>```

It wraps various input primitives, but the last constructor also allows for a Functor instance:

```<code>instance Functor In where
  fmap f (F g v) = F (f . g) v
  fmap f x = F f x
</code>```

The point of this type, BTW, is to support:

```<code>read :: In a -> IO a
read (M v) = takeMVar v
read (T v) = atomically (readTVar v)
read (F f v) = f <$> read v
</code>```

What I want to be able to do is define the obvious Eq instance on this type, something like:

```<code>instance Eq (In a) where
  (M x) == (M y) = x == y
  (T x) == (T y) = x == y
  (F _ x) == (F _ y) = x == y
  _ == _ = False
</code>```

The problem is the third case, which fails because x and y don't necessarily have the same type at that point.  I understand that.  In my own code I can make a long work-around, but it feels like there should be a way to define Eq directly.  In my mind the solution is something like "keep drilling through the F constructors until you hit M or T, then if they're the same constructor (i.e. both M or both T) and same type, do the equality comparison", but I'm not sure how I could write that.

答:
At one point, you need to test whether two things of different type are equal. There are two ways to do that:

The Typeable class.

A GADT data Equal a b where Eq :: Equal a a.

Since MVar and TVar don't support 2, you will have to use the Typeable class. In other words, you will have to augment your data type with Typeable constraints.

Fortunately, you have some freedom as to where to put the constraints. For instance, you can put them as follows:

```<code>data In a where
    M :: Typeable a => MVar a -> In a
    T :: Typeable a => TVar a -> In a
    F :: (a -> b) -> In a -> In b

equal :: In a -> In b -> Bool
equal (M x) (M y)     = Just x == cast y
equal (T x) (T y)     = Just x == cast y
equal (F _ x) (F _ y) = x `equal` y
equal _ _             = False

instance Eq (In a) where
    (==) = equal
</code>```

This way, you get to keep the Functor instance.

Title: Defining Eq instance for Haskell GADTs

Body:
I have a GADT that's a lot like this:

data In a where
  M :: MVar a -> In a
  T :: TVar a -> In a
  F :: (a -> b) -> In a -> In b

It wraps various input primitives, but the last constructor also allows for a Functor instance:

instance Functor In where
  fmap f (F g v) = F (f . g) v
  fmap f x = F f x

The point of this type, BTW, is to support:

read :: In a -> IO a
read (M v) = takeMVar v
read (T v) = atomically (readTVar v)
read (F f v) = f <$> read v

What I want to be able to do is define the obvious Eq instance on this type, something like:

instance Eq (In a) where
  (M x) == (M y) = x == y
  (T x) == (T y) = x == y
  (F _ x) == (F _ y) = x == y
  _ == _ = False

The problem is the third case, which fails because x and y don't necessarily have the same type at that point.  I understand that.  In my own code I can make a long work-around, but it feels like there should be a way to define Eq directly.  In my mind the solution is something like "keep drilling through the F constructors until you hit M or T, then if they're the same constructor (i.e. both M or both T) and same type, do the equality comparison", but I'm not sure how I could write that.

Body:
At one point, you need to test whether two things of different type are equal. There are two ways to do that:

The Typeable class.

A GADT data Equal a b where Eq :: Equal a a.

Since MVar and TVar don't support 2, you will have to use the Typeable class. In other words, you will have to augment your data type with Typeable constraints.

Fortunately, you have some freedom as to where to put the constraints. For instance, you can put them as follows:

data In a where
    M :: Typeable a => MVar a -> In a
    T :: Typeable a => TVar a -> In a
    F :: (a -> b) -> In a -> In b

equal :: In a -> In b -> Bool
equal (M x) (M y)     = Just x == cast y
equal (T x) (T y)     = Just x == cast y
equal (F _ x) (F _ y) = x `equal` y
equal _ _             = False

instance Eq (In a) where
    (==) = equal

This way, you get to keep the Functor instance.


问:
How to extract TNEF winmail.dat using a PHP script?
I am developing a functionality that will read all emails from a mailbox and will process the attachment files.

When any mail is sent from Outlook, its attachment is saved as winmail.dat. [Please note that I already have code to download attachments using IMAP PHP. My email attachments are stored in one folder in my codebase on the server.] I need to extract the winmail.dat attachment into its original format. The solutions I came across till now all need manual efforts like an online tool which gives extracted files, or software that enables us to convert .DAT files.

But I need to extract using a script or any automated process like cron or something. [I am using Linux - centos 5.7 server.]

Is there any library or any other way for my application to "unpack" theses files so I can get the attachments WITHOUT doing it MANUALLY one by one?

Thanks!

答:
There is this simple library: https://github.com/QualityUnit/TNEFDecoder

You can use it to easily extract attachments from TNEF files.

It is not very well documented, but it is quite simple, you should be able to use if after a little bit of digging into the code. It can be easily included using composer.

It is pure PHP implementation of TNEF decoding algorithm that was extracted from old Squirrelmail plugin and ported to be compatible with PHP 7.4


问:
How can I show encrypted field value in Laravel Nova?
I'm saving a password value on a "site" model using the Password::make field.

I would then like to display this password decrypted when a user with the correct privileges (which I already have working) presses an inline button "show password" on the detail view or index view.

I've tried using :

```<code>Text::make('Decrypted', function () {
    return decrypt($this->password);
})
</code>```

But unfortunately this gives me an "incorrect payload" error.

Any ideas?

答:
Hashes Are Irreversible

Your password was hashed and not encrypted.

You should now that Laravel uses one way hash functions.

A one-way hash function is a mathematical function which takes a
  plain text input string and converts it into a fixed-length
  binary sequence. Furthermore, a one-way hash function is designed in
  such a way that it is hard to reverse the process, that is, to find a
  string that hashes to a given value (hence the name one-way.) A good
  hash function also makes it hard to find two strings that would
  produce the same hash value.

Besides

Showing a user's password on screen, especially in a web app, is
  likely a security vulnerability and may render the system vulnerable
  to script injection, screen reader, or man in the middle attacks.

Read more

Body:
I'm saving a password value on a "site" model using the Password::make field.

I would then like to display this password decrypted when a user with the correct privileges (which I already have working) presses an inline button "show password" on the detail view or index view.

I've tried using :

Text::make('Decrypted', function () {
    return decrypt($this->password);
})

But unfortunately this gives me an "incorrect payload" error.

Any ideas?


问:
Subroutines in PLC - does it decrease scan time?
Does adding subroutines to a PLC program tend to decrease its scan time, or simply make it easier to T/S and program?

I came across an old exam question which asks what could be done to decrease the scan time of a PLC program.    The answers given were increasing clock speed, adding timer blocks, adding comparative blocks, and adding subroutines.

Personally, I don't see how any of these are a viable way to decrease scan time...

Thanks

答: Basically what the answer for your exam question says is that if you add timer blocks, comparative blocks and subroutines controlled by those elements (timers, comparative and many other PLC functions to control program flow), you run pieces of code selectively. With this scenario in my opinion you could considerably improve PLC scan time.


问:
PHP encourage loop part way through the loop
I am wanting to get a loop to loop without going through all the code for the loop. For instance in the example code I want to continue the loop without have to go through any of the if statements below the one that matches.

NOTE: I know something similar to this example would be better done using a switch statement but my set of if statements are not as simple as this.

```<code>foreach($array as $key=>$value){
    if(is_varchar($value)){loop;}
    if(is_text($value)){loop;}
    if(is_mediumText($value)){loop;}
    if(is_boolean($value)){loop;}
    if(is_integer($value)){loop;}
    if(is_float($value)){loop;}
    if(is_double($value)){loop;}
}
</code>```

答:
Do you mean like this?</p>

```<code>foreach($x as $y) {

    if ($y == 1) {
        doThis();
        continue;
    }

    // or something like this?
    switch($y) {
          case 2:
              doThat();
              continue;
     }
}
</code>```

Body:
I am wanting to get a loop to loop without going through all the code for the loop. For instance in the example code I want to continue the loop without have to go through any of the if statements below the one that matches.

NOTE: I know something similar to this example would be better done using a switch statement but my set of if statements are not as simple as this.

foreach($array as $key=>$value){
    if(is_varchar($value)){loop;}
    if(is_text($value)){loop;}
    if(is_mediumText($value)){loop;}
    if(is_boolean($value)){loop;}
    if(is_integer($value)){loop;}
    if(is_float($value)){loop;}
    if(is_double($value)){loop;}
}

Body:
Do you mean like this?

foreach($x as $y) {

    if ($y == 1) {
        doThis();
        continue;
    }

    // or something like this?
    switch($y) {
          case 2:
              doThat();
              continue;
     }
}


问:
GitLab auto devops: Dockerfile build-args
I'm new to GitLab auto-devops feature and I intend to build the project using my own Dockerfile available in the project root.

The problem is, my build is a bit complex and uses multiple build arguments. But, none of the documentation (or the resources I came across) explain how the auto devops would deal with build arguments -- in other words, how I should feed auto-build job with the necessary build arguments to build my docker image.

https://docs.gitlab.com/ee/topics/autodevops/index.html#custom-buildpacks

Or do I've to customise the auto devops .gitlab-ci.yml template to build the image using custom Dockerfile with build arguments?

答:
You can use the variable AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS in your job with, for example,--build-arg=YOUR_ARG=YOUR_VALUE as value

More info here: https://docs.gitlab.com/ee/topics/autodevops/#passing-arguments-to-docker-build


问:
How to display newline / CR in toast()?
I'm trying to include newlines in a toast() message, but this doesn't seem to work:

```<code> SpreadsheetApp.getActiveSpreadsheet().toast("Actions effectués: " + chargement + "\n Durée moyenne:\n - 10 + 32 par groupes simples \n - 42 + (64/groupes) pour les groupes composés.", "Chargement en cours:\n", 2);
</code>```

Is there a way to do that, or an alternative? (Because I doubt this is possible, that's not like if my code was hard to understand so I could have done a mistake.)

答:
I ran into the same, but I found \r seemed to work. Try:
SpreadsheetApp.getActiveSpreadsheet().toast("Actions effectués: " + chargement + "\r Durée moyenne:\r - 10 + 32 par groupes simples \r - 42 + (64/groupes) pour les groupes composés.", "Chargement en cours:\r", 2);

Title: How to display newline / CR in toast()?

Body:
I'm trying to include newlines in a toast() message, but this doesn't seem to work:

 SpreadsheetApp.getActiveSpreadsheet().toast("Actions effectués: " + chargement + "\n Durée moyenne:\n - 10 + 32 par groupes simples \n - 42 + (64/groupes) pour les groupes composés.", "Chargement en cours:\n", 2);

Is there a way to do that, or an alternative? (Because I doubt this is possible, that's not like if my code was hard to understand so I could have done a mistake.)


答:
In first case as I understand correctly, you're taking the size of a int* type which is a pointer to int and in most cases it will result in 4 bytes (depending on architecture and probably other factors).

In the second case, compiler also have all the information necessary to compute sizeof(arr) as there are explicitly given 5 elements of int as defined by int arr[5]; and as a result in most cases will equal 4 bytes * 5 elements, 20 bytes

Title: How is C++ array recognized?


问:
How to change the Android app package name when assembling with Gradle?
Is it possible to change the package name of an Android application using Gradle?

I need to compile two copies of the same app, having a unique package name (so I can publish to the market twice).

答:
I did not want to use Flavors, so I found a way to do so with buildTypes. I did this by changing my app/build.gradle file as follows:

```<code>defaultConfig {
        applicationId "com" // See buildTypes.type.applicationIdSuffix
        ...
    }

    ...

    buildTypes {
        debug {
            applicationIdSuffix ".domain.name.debug"
            ...
        }
        releaseStaging {
            applicationIdSuffix ".compagny.staging"
            ...
        }
        release {
            applicationIdSuffix ".domain.name"
            ...
        }
    }
</code>```

This allows me to have 3 apps next to each other on my devices.

I hope this helps others.

Body:
I did not want to use Flavors, so I found a way to do so with buildTypes. I did this by changing my app/build.gradle file as follows:

defaultConfig {
        applicationId "com" // See buildTypes.type.applicationIdSuffix
        ...
    }

    ...

    buildTypes {
        debug {
            applicationIdSuffix ".domain.name.debug"
            ...
        }
        releaseStaging {
            applicationIdSuffix ".compagny.staging"
            ...
        }
        release {
            applicationIdSuffix ".domain.name"
            ...
        }
    }

This allows me to have 3 apps next to each other on my devices.

I hope this helps others.


问:
Alternative for OnEventActivityAsync() in new Virtual Assistant Template
I am using a version of the Virtual Assistant Template based on SDK version 4.6 that implements Event Handling using OnEventActivityAsync(). I have been using this to implement Proactive Notifications. However after the latest update to the Virtual Assistant Solution template, the structure of the MainDialog has changed and I no longer see Event activities being handled. Is there an alternative in the new template that allows me to handle events, similar to the OnEventActivityAsync() method in the older template? My current setup is as follows:

```<code>protected override async Task OnEventActivityAsync(DialogContext innerDc, CancellationToken cancellationToken = default)
    {
        var ev = innerDc.Context.Activity.AsEventActivity();
        var value = ev.Value?.ToString();

        switch (ev.Name)
        {
            ....
            case Events.Broadcast:
                {
                    var eventData = JsonConvert.DeserializeObject<EventData>(innerDc.Context.Activity.Value.ToString());

                    var proactiveModel = await _proactiveStateAccessor.GetAsync(innerDc.Context, () => new ProactiveModel());

                    var hashedUserId = MD5Util.ComputeHash(eventData.UserId);

                    var conversationReference = proactiveModel[hashedUserId].Conversation;

                    await innerDc.Context.Adapter.ContinueConversationAsync(_appCredentials.MicrosoftAppId, conversationReference, ContinueConversationCallback(innerDc.Context, eventData.Message), cancellationToken);
                    break;
                }
        }
    }
</code>```

This entire method, is missing in the new version of the template, so is there any other way to implement this with the new VA template?

答:
I am guessing this is your question on the GitHub repo. Adding the answer from the issue so that it helps others as well and for more visibility.

You can process your events that do not need to be processed by the dialog stack in the DefaultActivityHandler.OnEventActivityAsync() method.

If your event needs to be processed by the dialog stack, for example a TokenResponse event, you can handle it in the MainDialog.RouteStepAsync() method.

The documentation will be updated soon reflecting the above changes.

Body:
I am using a version of the Virtual Assistant Template based on SDK version 4.6 that implements Event Handling using OnEventActivityAsync(). I have been using this to implement Proactive Notifications. However after the latest update to the Virtual Assistant Solution template, the structure of the MainDialog has changed and I no longer see Event activities being handled. Is there an alternative in the new template that allows me to handle events, similar to the OnEventActivityAsync() method in the older template? My current setup is as follows:

protected override async Task OnEventActivityAsync(DialogContext innerDc, CancellationToken cancellationToken = default)
    {
        var ev = innerDc.Context.Activity.AsEventActivity();
        var value = ev.Value?.ToString();

        switch (ev.Name)
        {
            ....
            case Events.Broadcast:
                {
                    var eventData = JsonConvert.DeserializeObject<EventData>(innerDc.Context.Activity.Value.ToString());

                    var proactiveModel = await _proactiveStateAccessor.GetAsync(innerDc.Context, () => new ProactiveModel());

                    var hashedUserId = MD5Util.ComputeHash(eventData.UserId);

                    var conversationReference = proactiveModel[hashedUserId].Conversation;

                    await innerDc.Context.Adapter.ContinueConversationAsync(_appCredentials.MicrosoftAppId, conversationReference, ContinueConversationCallback(innerDc.Context, eventData.Message), cancellationToken);
                    break;
                }
        }
    }

This entire method, is missing in the new version of the template, so is there any other way to implement this with the new VA template?


问:
Do variable length arrays start with default 0 values in C?
I know I cannot initialize variable-length arrays in C with explicitly provided values. The following code is not supported:

```<code>void main() {
  int l = 2;
  float test[l] = {1.0, 2.0};  // my compiler says: "Variable-sized object may not be initialized"
}
</code>```

My question is: if I don't attempt to give any values:

```<code>void main() {
  int l = 2;
  float test[l];
}
</code>```

…will a C compiler make sure it starts initialized to zero by default?

答:
Happy to accept better-documented answers, but empirically the answer is no: the memory is not zero-initialized.

Variants of the following code often (but not always!) abort:

```<code>int main() {
  int l = 99;
  float test[l];
  assert(test[0] == 0.0);
  assert(test[42] == 0.0);
  return 0;
}
</code>```

So unless I'm otherwise sure to initialize every member, it's necessary to get it to a known state myself, e.g.

```<code>int main() {
  int l = 99;
  float test[l];
  memset(test, 0, sizeof test);

 // …now the array content is in a known state…
}
</code>```

I believe that C++ behaves differently which was probably what I was remembering.

Body:
I know I cannot initialize variable-length arrays in C with explicitly provided values. The following code is not supported:

void main() {
  int l = 2;
  float test[l] = {1.0, 2.0};  // my compiler says: "Variable-sized object may not be initialized"
}

My question is: if I don't attempt to give any values:

void main() {
  int l = 2;
  float test[l];
}

…will a C compiler make sure it starts initialized to zero by default?

Body:
Happy to accept better-documented answers, but empirically the answer is no: the memory is not zero-initialized.

Variants of the following code often (but not always!) abort:

int main() {
  int l = 99;
  float test[l];
  assert(test[0] == 0.0);
  assert(test[42] == 0.0);
  return 0;
}

So unless I'm otherwise sure to initialize every member, it's necessary to get it to a known state myself, e.g.

int main() {
  int l = 99;
  float test[l];
  memset(test, 0, sizeof test);

 // …now the array content is in a known state…
}

I believe that C++ behaves differently which was probably what I was remembering.


问:
Is it possible to use GMB API to post product catalogue items?
I have been using Google My Business API but although I can create events and posts I can't create a product catalogue there. Is that even possible and if so what REST resource should be invoked? </p>

答:
It's seemingly possible. Check it out the changelog for v4.2
https://developers.google.com/my-business/content/change-log#v42

Product Posts

A new Local Post type, conaining product related content (e.g. name,
  price).

This would mean that you'd need to use the resource accounts.locations.localPosts. Something tells me they are still working on the reference page though because there is no product type. https://developers.google.com/my-business/reference/rest/v4/accounts.locations.localPosts#localposttopictype

I'm trying to figure this out myself as well, I want to use the API for managing our GMB products in bulk.

Try

Logging into GMB and create a product using the UI

Use the API to list local posts for your location (accounts.locations.localPosts.list)

Since products are a type of local post, they'd reveal their format in the list response (hopefully)

Lastly use the API to create a local post mimicking the product format (accounts.locations.localPosts.create)

I'd much rather give you a formatted call but I wanted to confirm that people are using the API to manage products in bulk before getting into it. Please report any discoveries!


问:
Unable to Create Prepared Statements in MySQL
I'm trying to create a prepared statement in MySQL that takes in a single parameter. When I try this on the command line I get a syntax error. However, when there are no variables in my prepared statement, I am able to create them fine. Below is a copy and paste of what I am seeing at the MySQL command prompt:

```<code>mysql> PREPARE state_name FROM "select * from ? limit 1";
</code>```

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? limit 1' at line 1

```<code>mysql> PREPARE state_name FROM "select * from documents limit 1";
</code>```

```
Query OK, 0 rows affected (0.00 sec)
Statement prepared
```

The version of MySQL I'm using is 5.0.77-log.

Is there a syntax error I'm not seeing? And are there any config parameters I have to set in order to get prepared statements to work?

答:
You can't pass in table names as prepared statement parameters, I'm afraid, neither can you pass columns to group or sort by. The only thing you can parametrize are fields in where clauses or for updates:</p>

```<code>PREPARE state_name FROM "select * from documents where id = ?";

PREPARE state_name FROM "update documents set field = ? where id = ?";
</code>```

Body:
I'm trying to create a prepared statement in MySQL that takes in a single parameter. When I try this on the command line I get a syntax error. However, when there are no variables in my prepared statement, I am able to create them fine. Below is a copy and paste of what I am seeing at the MySQL command prompt:

mysql> PREPARE state_name FROM "select * from ? limit 1";

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? limit 1' at line 1

mysql> PREPARE state_name FROM "select * from documents limit 1";

Query OK, 0 rows affected (0.00 sec)
Statement prepared

The version of MySQL I'm using is 5.0.77-log.

Is there a syntax error I'm not seeing? And are there any config parameters I have to set in order to get prepared statements to work?

Body:
You can't pass in table names as prepared statement parameters, I'm afraid, neither can you pass columns to group or sort by. The only thing you can parametrize are fields in where clauses or for updates:

PREPARE state_name FROM "select * from documents where id = ?";

PREPARE state_name FROM "update documents set field = ? where id = ?";


问:
how to set the consumer in Faust to a specific offset
From the Faust documentation I can't find out how to set the consumer to a specific offset.

With confluent-kafka I use consumer.offsets_for_times to find a start_offset and then assign the TopicPartition to that specific offset, something like:

```<code>start_offset = consumer.offsets_for_times([
    TopicPartition("prediction.OfferPredictionCheckpoint", 0, int(start_date)),
    TopicPartition("prediction.OfferPredictionCheckpoint", 1, int(start_date)),
])

consumer.assign([
    TopicPartition("prediction.OfferPredictionCheckpoint", partition_number, pos)
])
</code>```

With Faust I can't find much more than:

```<code>consumer_auto_offset_reset
</code>```

Which only let you set earliest or latest. How would I start reading from a specific hour or beginning of day?

答:
I think this might be what you're looking for: https://faust.readthedocs.io/en/latest/reference/faust.transport.consumer.html#faust.transport.consumer.Consumer.seek

It can go to a specific offset, however I don't think there's an easy way to tell it to go to a specific time or date without some extra logic (maybe binary search your way there using the offset?).

Body:
From the Faust documentation I can't find out how to set the consumer to a specific offset.

With confluent-kafka I use consumer.offsets_for_times to find a start_offset and then assign the TopicPartition to that specific offset, something like:

start_offset = consumer.offsets_for_times([
    TopicPartition("prediction.OfferPredictionCheckpoint", 0, int(start_date)),
    TopicPartition("prediction.OfferPredictionCheckpoint", 1, int(start_date)),
])

consumer.assign([
    TopicPartition("prediction.OfferPredictionCheckpoint", partition_number, pos)
])

With Faust I can't find much more than:

consumer_auto_offset_reset

Which only let you set earliest or latest. How would I start reading from a specific hour or beginning of day?


问:
How to fill in between rows gap comparing with other dataframe using pandas?
I want to compare df1 with df2 and fill only the blanks without overwriting other values. I have no idea how to achieve this without overwriting or creating an extra columns.

Can I do this by converting df2 into dictionary and mapping with df1?

```<code>df1 = pd.DataFrame({'players name':['ram', 'john', 'ismael', 'sam', 'karan'],
                   'hobbies':['jog','','photos','','studying'],
                   'sports':['cricket', 'basketball', 'chess', 'kabadi', 'volleyball']})
</code>```

df1:

```<code>  players name   hobbies      sports
0          ram       jog     cricket
1         john            basketball
2       ismael    photos       chess
3          sam                kabadi
4        karan  studying  volleyball
</code>```

And, df,

```<code>df2 = pd.DataFrame({'players name':['jagan', 'mohan', 'john', 'sam', 'karan'],
                   'hobbies':['riding', 'tv', 'sliding', 'jumping', 'studying']})
</code>```

df2:

```<code>  players name   hobbies
0        jagan    riding
1        mohan        tv
2         john   sliding
3          sam   jumping
4        karan  studying
</code>```

I want output like this:

答:
if blank space is NaN value

```<code>df1 = pd.DataFrame({"players name":["ram","john","ismael","sam","karan"],
"hobbies":["jog",pd.np.NaN,"photos",pd.np.NaN,"studying"],
"sports":["cricket","basketball","chess","kabadi","volleyball"]})
</code>```

then

```<code>dicts = df2.set_index("players name")['hobbies'].to_dict()
df1['hobbies'] = df1['hobbies'].fillna(df1['players name'].map(dicts))
</code>```

output:

```<code>  players name   hobbies      sports
0          ram       jog     cricket
1         john   sliding  basketball
2       ismael     photos       chess
3          sam   jumping      kabadi
4        karan  studying  volleyball
</code>```

Body:
I want to compare df1 with df2 and fill only the blanks without overwriting other values. I have no idea how to achieve this without overwriting or creating an extra columns.

Can I do this by converting df2 into dictionary and mapping with df1?

df1 = pd.DataFrame({'players name':['ram', 'john', 'ismael', 'sam', 'karan'],
                   'hobbies':['jog','','photos','','studying'],
                   'sports':['cricket', 'basketball', 'chess', 'kabadi', 'volleyball']})

df1:

  players name   hobbies      sports
0          ram       jog     cricket
1         john            basketball
2       ismael    photos       chess
3          sam                kabadi
4        karan  studying  volleyball

And, df,

df2 = pd.DataFrame({'players name':['jagan', 'mohan', 'john', 'sam', 'karan'],
                   'hobbies':['riding', 'tv', 'sliding', 'jumping', 'studying']})

df2:

  players name   hobbies
0        jagan    riding
1        mohan        tv
2         john   sliding
3          sam   jumping
4        karan  studying

I want output like this:

Body:
if blank space is NaN value

df1 = pd.DataFrame({"players name":["ram","john","ismael","sam","karan"],
"hobbies":["jog",pd.np.NaN,"photos",pd.np.NaN,"studying"],
"sports":["cricket","basketball","chess","kabadi","volleyball"]})

then

dicts = df2.set_index("players name")['hobbies'].to_dict()
df1['hobbies'] = df1['hobbies'].fillna(df1['players name'].map(dicts))

output:

  players name   hobbies      sports
0          ram       jog     cricket
1         john   sliding  basketball
2       ismael     photos       chess
3          sam   jumping      kabadi
4        karan  studying  volleyball


问:
cmake build failed on macos catalina 10.15
I have recently installed macos catalina with Xcode 11.1  and updated cmake, clang and llvm

```<code>sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install

$ cmake --version
cmake version 3.15.4

$ which cmake
/usr/local/bin/cmake

$ clang --version
Apple clang version 11.0.0 (clang-1100.0.33.8)
Target: x86_64-apple-darwin19.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

$ which clang
/usr/bin/clang
</code>```

The CMakeLists.txt looks as bellow:

```<code>cmake_minimum_required(VERSION 3.14)

project("ROZZETA" VERSION 0.0.1 LANGUAGES C)

# Allow us to import cmake scripts from  ./cmake
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}")
# Compiler flags
set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "")

find_package(GMP REQUIRED)
add_executable(Rozzeta main.c)
target_link_libraries(Rozzeta gmp libgmp libgmp.a)
</code>```

cmake detected gmp successfully :

```<code>/usr/local/bin/cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=/usr/bin/clang -DCMAKE_CXX_COMPILER=c++ -G "CodeBlocks - Unix Makefiles" /<path to project>
-- The C compiler identification is AppleClang 11.0.0.11000033
-- Check for working C compiler: /usr/bin/clang
-- Check for working C compiler: /usr/bin/clang -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Using toolchain file: .
-- Found GMP: /usr/local/include/gmp.h and /usr/local/lib/libgmp.a
-- Configuring done
-- Generating done
</code>```

build failed :

```<code>cmake --build  .
Scanning dependencies of target Rozzeta
[ 50%] Building C object CMakeFiles/Rozzeta.dir/main.c.o
/Users/gajaka/CLionProjects/Rozzeta/main.c:4:10: fatal error: 'gmp.h' file not found
#include <gmp.h>
         ^~~~~~~
1 error generated.
make[2]: *** [CMakeFiles/Rozzeta.dir/main.c.o] Error 1
make[1]: *** [CMakeFiles/Rozzeta.dir/all] Error 2
make: *** [all] Error 2

</code>```

I have compiled manually with:

```<code>cc main.c -lgmp
</code>```

Anyone can help me with this ?
Many thanks in advance

答:
after

```<code>xcode-select --install
</code>```

I got a clang but no cmake so I did

```<code>brew install cmake
</code>```

which installed cmake for Catalina.

Body:
I have recently installed macos catalina with Xcode 11.1  and updated cmake, clang and llvm

sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install

$ cmake --version
cmake version 3.15.4

$ which cmake
/usr/local/bin/cmake

$ clang --version
Apple clang version 11.0.0 (clang-1100.0.33.8)
Target: x86_64-apple-darwin19.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

$ which clang
/usr/bin/clang

The CMakeLists.txt looks as bellow:

cmake_minimum_required(VERSION 3.14)

project("ROZZETA" VERSION 0.0.1 LANGUAGES C)

# Allow us to import cmake scripts from  ./cmake
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}")
# Compiler flags
set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "")

find_package(GMP REQUIRED)
add_executable(Rozzeta main.c)
target_link_libraries(Rozzeta gmp libgmp libgmp.a)

cmake detected gmp successfully :

/usr/local/bin/cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=/usr/bin/clang -DCMAKE_CXX_COMPILER=c++ -G "CodeBlocks - Unix Makefiles" /<path to project>
-- The C compiler identification is AppleClang 11.0.0.11000033
-- Check for working C compiler: /usr/bin/clang
-- Check for working C compiler: /usr/bin/clang -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Using toolchain file: .
-- Found GMP: /usr/local/include/gmp.h and /usr/local/lib/libgmp.a
-- Configuring done
-- Generating done

build failed :

cmake --build  .
Scanning dependencies of target Rozzeta
[ 50%] Building C object CMakeFiles/Rozzeta.dir/main.c.o
/Users/gajaka/CLionProjects/Rozzeta/main.c:4:10: fatal error: 'gmp.h' file not found
#include <gmp.h>
         ^~~~~~~
1 error generated.
make[2]: *** [CMakeFiles/Rozzeta.dir/main.c.o] Error 1
make[1]: *** [CMakeFiles/Rozzeta.dir/all] Error 2
make: *** [all] Error 2

I have compiled manually with:

cc main.c -lgmp

Anyone can help me with this ?
Many thanks in advance

Body:
after

xcode-select --install

I got a clang but no cmake so I did

brew install cmake

which installed cmake for Catalina.


问:
Create a Modeless Messagebox
How might one go about creating a Modeless MessageBox? Do I have to just create my own Windows Form class and use that? If so, is there an easy way of adding a warning icon (rather than inserting my own image of one) and resizing based on text volume?</p>

答:
If you need a message box that just displays itself while your code continues running in the background (the box is still modal and will prevent the user from using other windows until OK is clicked), you can always start the message box in its own thread and continue doing what ever you do in the original thread:</p>

```<code>    // Do stuff before.
    // Start the message box -thread:
    new Thread(new ThreadStart(delegate
    {
      MessageBox.Show
      (
        "Hey user, stuff runs in the background!",
        "Message",
        MessageBoxButtons.OK,
        MessageBoxIcon.Warning
      );
    })).Start();
    // Continue doing stuff while the message box is visible to the user.
    // The message box thread will end itself when the user clicks OK.
</code>```

ContentLicense: CC BY-SA 2.5

Title: Create a Modeless Messagebox

Body:
If you need a message box that just displays itself while your code continues running in the background (the box is still modal and will prevent the user from using other windows until OK is clicked), you can always start the message box in its own thread and continue doing what ever you do in the original thread:

    // Do stuff before.
    // Start the message box -thread:
    new Thread(new ThreadStart(delegate
    {
      MessageBox.Show
      (
        "Hey user, stuff runs in the background!",
        "Message",
        MessageBoxButtons.OK,
        MessageBoxIcon.Warning
      );
    })).Start();
    // Continue doing stuff while the message box is visible to the user.
    // The message box thread will end itself when the user clicks OK.