问:
Alias nested struct columns
How can I alias field1 as index & & field 2 as value

The query gives me an error:

```<code>#standardsql
with q1 as (select 1 x, ARRAY<struct<id string, cd ARRAY<STRUCT<index STRING,value STRING>>>>
                    [struct('h1',[('1','a')
                                 ,('2','b')
                                 ])
                          ,('h2',[('3','c')
                                 ,('4','d')
                                 ])] hits
       )

Select * from q1
ORDER by x

Error: Array element type STRUCT<STRING, ARRAY<STRUCT<STRING, STRING>>> does not coerce to STRUCT<id STRING, cd ARRAY<STRUCT<index STRING, value STRING>>> at [5:26]
</code>```

Thanks a lot for your time in responding

Cheers!

答:
When I try to simulate data in BigQuery using the Standard Version I usually try to name all variables and aliases everywhere possible. For instance, your data works if you build it like so:

```<code>with q1 as (
select 1 x, ARRAY<struct<id string, cd ARRAY<STRUCT<index STRING,value STRING>>>>  [struct('h1' as id,[STRUCT('1' as index,'a' as value) ,STRUCT('2' as index ,'b' as value)] as cd), STRUCT('h2',[STRUCT('3' as index,'c' as value) ,STRUCT('4' as index,'d' as value)] as cd)] hits
)

select * from q1
order by x
</code>```

Notice I've built structs and put aliases inside of them in order for this to work (if you remove the aliases and the structs it might not work, but I found that this seems to be rather intermittent. If you fully describe the variables then it works all the time).

Also as a recommendation, I try to build simulated data piece by piece. First I create the struct and test it to see if BigQuery accepts it. After the validator is green, then I proceed to add more values. If you try to build everything at once you might find this a somewhat challenging task.

Title: Alias nested struct columns

Body:
How can I alias field1 as index & & field 2 as value

The query gives me an error:

#standardsql
with q1 as (select 1 x, ARRAY<struct<id string, cd ARRAY<STRUCT<index STRING,value STRING>>>>
                    [struct('h1',[('1','a')
                                 ,('2','b')
                                 ])
                          ,('h2',[('3','c')
                                 ,('4','d')
                                 ])] hits
       )

Select * from q1
ORDER by x

Error: Array element type STRUCT<STRING, ARRAY<STRUCT<STRING, STRING>>> does not coerce to STRUCT<id STRING, cd ARRAY<STRUCT<index STRING, value STRING>>> at [5:26]

Thanks a lot for your time in responding

Cheers!

Body:
When I try to simulate data in BigQuery using the Standard Version I usually try to name all variables and aliases everywhere possible. For instance, your data works if you build it like so:

with q1 as (
select 1 x, ARRAY<struct<id string, cd ARRAY<STRUCT<index STRING,value STRING>>>>  [struct('h1' as id,[STRUCT('1' as index,'a' as value) ,STRUCT('2' as index ,'b' as value)] as cd), STRUCT('h2',[STRUCT('3' as index,'c' as value) ,STRUCT('4' as index,'d' as value)] as cd)] hits
)

select * from q1
order by x

Notice I've built structs and put aliases inside of them in order for this to work (if you remove the aliases and the structs it might not work, but I found that this seems to be rather intermittent. If you fully describe the variables then it works all the time).

Also as a recommendation, I try to build simulated data piece by piece. First I create the struct and test it to see if BigQuery accepts it. After the validator is green, then I proceed to add more values. If you try to build everything at once you might find this a somewhat challenging task.


来源: stackexchange

问:
Match row value in df1 with column name in df2 to return same row value of df2
This question is similar to what I found here: Multiply rows (with row names) in one data frame with matching column names in another

But instead of matching rows and multiplying, I want to match a column's values from df1 with a column name in df2 and return the corresponding row values of df2 in a new df3.

```<code>df1 <- data.frame(V1=c(1:6),V2=c("X3", "X3_8", "NA", "X5", "X4_5", "X3_8"))
df1
    V1 V2
  1 1  X3
  2 2  X3_8
  3 3  NA
  4 4  X5
  5 5  X4_5
  6 6  X3_8

df2 <- data.frame(name=c("John", "Mary", "Joe", "Tim", "Bob", "Pat"),
                  X3=c(0.5, 1.2, 0.75, 3.1, 2.0, 1.1),
                  X5=c(1.0, 2.3, 4.2, 5, 1.1, 3.0),
                  X3_8=c(0.6, 1.0, 2.0, 1.0, 0.7, 1.4),
                  X4_5=c(0.4, 0.3, 3.0, 1.0, 2.0, 0.9))
df2
     name   X3    X5    X3_8  X4_5
  1  John   0.5   1.0   0.6   0.4
  2  Mary   1.2   2.3   1.0   0.3
  3  Joe    0.75  4.2   2.0   3.0
  4  Tim    3.1   5.0   1.0   1.0
  5  Bob    2.0   1.1   0.7   2.0
  6  Pat    1.1   3.0   1.4   0.9
</code>```

This is what I want:

```<code>df3 <- data.frame(name=c("John", "Mary", "Joe", "Tim", "Bob", "Pat"),
                  values=c(0.5, 1.0, NA, 5.0, 1.0, 1.4))
    name values
  1 John    0.5
  2 Mary    1.0
  3  Joe     NA
  4  Tim    5.0
  5  Bob    1.0
  6  Pat    1.4
</code>```

In my real df1 and df2 there are 64 rows, where "V1" in df1 corresponds to a numeric index for the "name" column in df2. In my df2, there are 22 columns, i.e., one with "name" and another 21 with "X*" to match "V2" in df1. I tried converting "V2" to row names, but this doesn't work because there are NA's and repeating values.

Bonus but not necessary: I have 10 df1s and 10 df2s and need to do this for each pair of df1s and df2s where the names of the df1s and the df2s contain common years. For example, I need to match df1_2004 with df2_2004, create df3_2004, and move on to df1_2005 and df2_2005, and so on. I'm sure there's an elegant way to do this without a for loop and an if statement.

Thanks for any assistance. I'm sure there's a simple base R or tidyrverse solution to this, but I'm struggling to put the pieces together. Forgive my newbie understanding of indexing in R.

答:
With a combination of reshaping df2 into long format and a left join with df1 you can get the desired result.

Using:

```<code>library(dplyr)
library(tidyr)

df3 <- df1 %>%
  mutate(name = df2$name[V1]) %>%  # or just mutate(name = df2$name) when the index is equal to the rownumbers
  left_join(., df2 %>%
              gather(V2, values, -1) %>%
              group_by(V2) %>%
              mutate(V1 = row_number()),
            by = c('V2','V1')) %>%
  select(name = name.x, values)
</code>```

gives:

```<code>> df3
  name values
1 John    0.5
2 Mary    1.0
3  Joe     NA
4  Tim    5.0
5  Bob    2.0
6  Pat    1.4
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This question is similar to what I found here: Multiply rows (with row names) in one data frame with matching column names in another

But instead of matching rows and multiplying, I want to match a column's values from df1 with a column name in df2 and return the corresponding row values of df2 in a new df3.

df1 <- data.frame(V1=c(1:6),V2=c("X3", "X3_8", "NA", "X5", "X4_5", "X3_8"))
df1
    V1 V2
  1 1  X3
  2 2  X3_8
  3 3  NA
  4 4  X5
  5 5  X4_5
  6 6  X3_8

df2 <- data.frame(name=c("John", "Mary", "Joe", "Tim", "Bob", "Pat"),
                  X3=c(0.5, 1.2, 0.75, 3.1, 2.0, 1.1),
                  X5=c(1.0, 2.3, 4.2, 5, 1.1, 3.0),
                  X3_8=c(0.6, 1.0, 2.0, 1.0, 0.7, 1.4),
                  X4_5=c(0.4, 0.3, 3.0, 1.0, 2.0, 0.9))
df2
     name   X3    X5    X3_8  X4_5
  1  John   0.5   1.0   0.6   0.4
  2  Mary   1.2   2.3   1.0   0.3
  3  Joe    0.75  4.2   2.0   3.0
  4  Tim    3.1   5.0   1.0   1.0
  5  Bob    2.0   1.1   0.7   2.0
  6  Pat    1.1   3.0   1.4   0.9

This is what I want:

df3 <- data.frame(name=c("John", "Mary", "Joe", "Tim", "Bob", "Pat"),
                  values=c(0.5, 1.0, NA, 5.0, 1.0, 1.4))
    name values
  1 John    0.5
  2 Mary    1.0
  3  Joe     NA
  4  Tim    5.0
  5  Bob    1.0
  6  Pat    1.4

In my real df1 and df2 there are 64 rows, where "V1" in df1 corresponds to a numeric index for the "name" column in df2. In my df2, there are 22 columns, i.e., one with "name" and another 21 with "X*" to match "V2" in df1. I tried converting "V2" to row names, but this doesn't work because there are NA's and repeating values.

Bonus but not necessary: I have 10 df1s and 10 df2s and need to do this for each pair of df1s and df2s where the names of the df1s and the df2s contain common years. For example, I need to match df1_2004 with df2_2004, create df3_2004, and move on to df1_2005 and df2_2005, and so on. I'm sure there's an elegant way to do this without a for loop and an if statement.

Thanks for any assistance. I'm sure there's a simple base R or tidyrverse solution to this, but I'm struggling to put the pieces together. Forgive my newbie understanding of indexing in R.

Body:
With a combination of reshaping df2 into long format and a left join with df1 you can get the desired result.

Using:

library(dplyr)
library(tidyr)

df3 <- df1 %>%
  mutate(name = df2$name[V1]) %>%  # or just mutate(name = df2$name) when the index is equal to the rownumbers
  left_join(., df2 %>%
              gather(V2, values, -1) %>%
              group_by(V2) %>%
              mutate(V1 = row_number()),
            by = c('V2','V1')) %>%
  select(name = name.x, values)

gives:

> df3
  name values
1 John    0.5
2 Mary    1.0
3  Joe     NA
4  Tim    5.0
5  Bob    2.0
6  Pat    1.4


问:
How do I keep the divs side by side in the container?
I want to create container that has two elements with colors given in the picture.  The two are different divs and must stay side by side.  How do I do it?

Here is my code:

  <title>Testing</title>

```

答:
You didn't set a height on the body of the document so setting a percentage on the divs won't do anything until you do. You also needed to float the sidenav div.

.container {
  width: 50%;
  height: 50%;
}

.sidenav {
  width: 25%;
  height: 100%;
  background-color: black;
  float: left
}

.bgrnd {
  width: 75%;
  height: 100%;
  background-color: blue;
  float: left;
}

html,
body {
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="sidenav">
  </div>
  <div class="bgrnd">
  </div>
</div></code>```

Body:
You didn't set a height on the body of the document so setting a percentage on the divs won't do anything until you do. You also needed to float the sidenav div.

.container {
  width: 50%;
  height: 50%;
}

.sidenav {
  width: 25%;
  height: 100%;
  background-color: black;
  float: left
}

.bgrnd {
  width: 75%;
  height: 100%;
  background-color: blue;
  float: left;
}

html,
body {
  height: 100%;
}

<div class="container">
  <div class="sidenav">
  </div>
  <div class="bgrnd">
  </div>
</div>


问:
using a conditional variable which is defined later in verilog
Suppose I have the following instantiation

first_mux_input=top.middle.down[i];
 second_mux_input=top.middle.down[i+1];
 assign down = (select[i])? first_mux_input:second_mux_input;

supposing there are a lot of muxes and their outputs go to the inputs to muxes that are placed below them.

I'm using the variable "down" before I define it. is this legal since verilog compiles all the lines subsequently and not by order(in this case)?

thanks

答:
The assign statement is not a declaration.  A declaration would be:

```<code>wire down;
</code>```

If you never declare down such as this, it will be implicitly declared.
Section 6.10 of IEEE 1800-2012 states:

If an identifier appears on the left-hand side of a continuous assignment statement, and that identifier
  has not been declared previously in the scope where the continuous assignment statement appears or
  in any scope whose declarations can be directly referenced from the scope where the continuous
  assignment statement appears (see 23.9), then an implicit scalar net of default net type shall be
  assumed. See 10.3 for a discussion of continuous assignment statements.

and then:

See 22.8 for a discussion of control of the type for implicitly declared nets with the `default_nettype
  compiler directive.

This (I believe) typically means a wire in Verilog and logic in SystemVerilog.

Now, as far as using the value before it is assigned, that's perfectly legal.  As long as not declared after it is used or assigned.

Body:
The assign statement is not a declaration.  A declaration would be:

wire down;

If you never declare down such as this, it will be implicitly declared.
Section 6.10 of IEEE 1800-2012 states:

If an identifier appears on the left-hand side of a continuous assignment statement, and that identifier
  has not been declared previously in the scope where the continuous assignment statement appears or
  in any scope whose declarations can be directly referenced from the scope where the continuous
  assignment statement appears (see 23.9), then an implicit scalar net of default net type shall be
  assumed. See 10.3 for a discussion of continuous assignment statements.

and then:

See 22.8 for a discussion of control of the type for implicitly declared nets with the `default_nettype
  compiler directive.

This (I believe) typically means a wire in Verilog and logic in SystemVerilog.

Now, as far as using the value before it is assigned, that's perfectly legal.  As long as not declared after it is used or assigned.


问:
How can I read the android sdkmanager output so I can install a package?
The android sdkmanager tool has a way to almost list the available packages, like so:

```<code>$ sdkmanager --list

  system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
  system-images;a...-10;default;x86 | 4            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
  system-images;a...ult;armeabi-v7a | 2            | ARM EABI v7a System Image
  system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
  system-images;a...15;default;mips | 1            | MIPS System Image
  system-images;a...-15;default;x86 | 4            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
  system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
  system-images;a...16;default;mips | 1            | MIPS System Image
  system-images;a...-16;default;x86 | 5            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
  system-images;a...ult;armeabi-v7a | 5            | ARM EABI v7a System Image
  system-images;a...17;default;mips | 1            | MIPS System Image
  system-images;a...-17;default;x86 | 3            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
  system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
  system-images;a...-18;default;x86 | 3            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
</code>```

I would like to understand how I can actually read the output so I can install one of those packages from the command line.

答:
You need to use the --verbose flag to get full package names:

```<code>sdkmanager --list --verbose
</code>```

The output will be looking like this:

```<code>system-images;android-25;android-wear;armeabi-v7a
    Description:        Android Wear ARM EABI v7a System Image
    Version:            3
    Dependencies:
        patcher;v4

system-images;android-25;android-wear;x86
    Description:        Android Wear Intel x86 Atom System Image
    Version:            3
    Dependencies:
        patcher;v4

system-images;android-25;google_apis;arm64-v8a
    Description:        Google APIs ARM 64 v8a System Image
    Version:            4

system-images;android-25;google_apis;armeabi-v7a
    Description:        Google APIs ARM EABI v7a System Image
    Version:            4

system-images;android-25;google_apis;x86
    Description:        Google APIs Intel x86 Atom System Image
    Version:            4

system-images;android-25;google_apis;x86_64
    Description:        Google APIs Intel x86 Atom_64 System Image
    Version:            4
</code>```

Body:
The android sdkmanager tool has a way to almost list the available packages, like so:

$ sdkmanager --list

  system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
  system-images;a...-10;default;x86 | 4            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
  system-images;a...ult;armeabi-v7a | 2            | ARM EABI v7a System Image
  system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
  system-images;a...15;default;mips | 1            | MIPS System Image
  system-images;a...-15;default;x86 | 4            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
  system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
  system-images;a...16;default;mips | 1            | MIPS System Image
  system-images;a...-16;default;x86 | 5            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
  system-images;a...ult;armeabi-v7a | 5            | ARM EABI v7a System Image
  system-images;a...17;default;mips | 1            | MIPS System Image
  system-images;a...-17;default;x86 | 3            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
  system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
  system-images;a...-18;default;x86 | 3            | Intel x86 Atom System Image
  system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
  system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...

I would like to understand how I can actually read the output so I can install one of those packages from the command line.

Body:
You need to use the --verbose flag to get full package names:

sdkmanager --list --verbose

The output will be looking like this:

system-images;android-25;android-wear;armeabi-v7a
    Description:        Android Wear ARM EABI v7a System Image
    Version:            3
    Dependencies:
        patcher;v4

system-images;android-25;android-wear;x86
    Description:        Android Wear Intel x86 Atom System Image
    Version:            3
    Dependencies:
        patcher;v4

system-images;android-25;google_apis;arm64-v8a
    Description:        Google APIs ARM 64 v8a System Image
    Version:            4

system-images;android-25;google_apis;armeabi-v7a
    Description:        Google APIs ARM EABI v7a System Image
    Version:            4

system-images;android-25;google_apis;x86
    Description:        Google APIs Intel x86 Atom System Image
    Version:            4

system-images;android-25;google_apis;x86_64
    Description:        Google APIs Intel x86 Atom_64 System Image
    Version:            4


问:
Issues with Multi Indexing in a pandas data frame
Hello I have data in the format shown below

I am trying to perform some data munging on this data set whose column index (first level) spans several months. As an instance If I just need the first month information, I proceed to do the following. But it just keeps erring out and the documentation is not really helping me. I have tried many times now.

```<code>    VolData = pd.read_excel(VolDataFilePath,sheetname=r'BaseFwdVols',header=[0,1],index_col=None)
IndexList = ['SPTR','SPTRMDCP','NDDUEAFE','RU20INTR','AGGBOND','HYBOND']

Test = VolData.loc[:,(slice(1),IndexList)]
</code>```

It keeps erring out with the message below:`

```<code>`KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'
</code>```

What am I missing here?

Many thanks

答:
You'll need to sort your MultiIndex. Here's a quick example I put together:

```<code>df

foo     b                         a
b       5     4      3     1      3      2       1
a
abc   NaN  47.0    NaN  45.0  243.0    NaN   123.0
def   NaN   NaN  456.0   NaN    NaN    NaN  1176.0
ghb   NaN   NaN    NaN   NaN    NaN  567.0     NaN
lop  12.0   NaN    NaN   NaN    NaN    NaN     NaN
mno   NaN   NaN   87.0   NaN    NaN    NaN     NaN
</code>```

Notice the Column multiindex is ordered descending.

Attempting this gives me an error:

```<code>df.loc[:, ('b', [5,4])]
KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (0)'
</code>```

The fix:

```<code>df.sort_index(axis=1).loc[:, ('b', [5,4])]
foo     b
b       4     5
a
abc  47.0   NaN
def   NaN   NaN
ghb   NaN   NaN
lop   NaN  12.0
mno   NaN   NaN
</code>```

Body:
Hello I have data in the format shown below

I am trying to perform some data munging on this data set whose column index (first level) spans several months. As an instance If I just need the first month information, I proceed to do the following. But it just keeps erring out and the documentation is not really helping me. I have tried many times now.

    VolData = pd.read_excel(VolDataFilePath,sheetname=r'BaseFwdVols',header=[0,1],index_col=None)
IndexList = ['SPTR','SPTRMDCP','NDDUEAFE','RU20INTR','AGGBOND','HYBOND']

Test = VolData.loc[:,(slice(1),IndexList)]

It keeps erring out with the message below:`

`KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'

What am I missing here?

Many thanks

Body:
You'll need to sort your MultiIndex. Here's a quick example I put together:

df

foo     b                         a
b       5     4      3     1      3      2       1
a
abc   NaN  47.0    NaN  45.0  243.0    NaN   123.0
def   NaN   NaN  456.0   NaN    NaN    NaN  1176.0
ghb   NaN   NaN    NaN   NaN    NaN  567.0     NaN
lop  12.0   NaN    NaN   NaN    NaN    NaN     NaN
mno   NaN   NaN   87.0   NaN    NaN    NaN     NaN

Notice the Column multiindex is ordered descending.

Attempting this gives me an error:

df.loc[:, ('b', [5,4])]
KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (0)'

The fix:

df.sort_index(axis=1).loc[:, ('b', [5,4])]
foo     b
b       4     5
a
abc  47.0   NaN
def   NaN   NaN
ghb   NaN   NaN
lop   NaN  12.0
mno   NaN   NaN


问:
RubyMine: Duplicity lines on steps.rb files
I have two files .feature and both are about diferent feature on my system.

Feature A is about Login and Feature B is about Register.

However in both files contains:

```<code>And(/^I click on button "([^"]*)"$/) do |arg|
    pending
end
</code>```

When I create the steps.rb one for each .feature, it is accusses duplicity, but the buttons are completely different.

Is there a way to implement two different clicks on the same file step.rb to the same line?

答:
You can create two different scenarios and pass the button's element id inside the double quotes?

I click on button "Login"

I click on button "Login1"

You can have one step definitions and invoke multiple gherkin steps with this way

Creating two step definitions steps for each scenario will lead to duplication when the rubymine tries to auto populate the gherkin steps used.

Body:
I have two files .feature and both are about diferent feature on my system.

Feature A is about Login and Feature B is about Register.

However in both files contains:

And(/^I click on button "([^"]*)"$/) do |arg|
    pending
end

When I create the steps.rb one for each .feature, it is accusses duplicity, but the buttons are completely different.

Is there a way to implement two different clicks on the same file step.rb to the same line?


问:
MedusaFX elements in an Array, if editing the array, do not update screen
I'm using the MedusaFX Library to get gauges for a project I'm working on. I'm using a JavaFX Application to run everything and Scene Builder to create an FXML file in order to create the layout. What I've observed is that if I do

```<code>    @FXML private Gauge gauge1 = new Gauge();
    gauge1.setValue(30);
</code>```

then the gauge1 variable gets the correct value set. However, if I do

```<code>    @FXML private Gauge gauge1 = new Gauge();
    ArrayList<Gauge> list = new ArrayList<>();
    list.add(gauge1);
    list.get(0).setValue(30);

    System.out.println(gauge1);
    System.out.println(list.get(0));
</code>```

My output is

```<code>{"title":"Temperature","subTitle":"Temperature","unit":"°F","value":0.0,"minValue":0.0,"maxValue":175.0,"threshold":60.0,"minMeasuredValue":0.0,"maxMeasuredValue":0.0}
{"title":"","subTitle":"","unit":"","value":30.0,"minValue":0.0,"maxValue":100.0,"threshold":100.0,"minMeasuredValue":30.0,"maxMeasuredValue":30.0}
</code>```

This output confuses me as it looks like the ArrayList creates a new instance of Gauge instead of modifying the one that it has within it. Any suggestions?

答:
When you load an fxml file with FXMLLoader.load(), it will parse the file, and it will create an instance of every node it finds.

So, assuming that there is a Gauge node in your fxml file with fx:id="gauge1", when you add this to your controller:

```<code>@FXML private Gauge gauge1;
</code>```

the FXMLLoader will create an instance for you. You can then set a value like:

```<code>public void initialize() {
    gauge1.setValue(30);
}
</code>```

But when you do:

```<code>@FXML private Gauge gauge1 = new Gauge();
</code>```

what is happening is that you are actually creating a second instance: the first one is created by reflexion, just based on the fx:id label, and added to the scene graph by the FXMLLoader, while the second you create is never added to the scene graph.

Later on, you don't know what is the actual instance you are modifying. When you do the printout, probably you are accessing both objects, being that on the list the one not added to the scene graph.

So the solution is easy: don't create the second instance, and use just this:

```<code>@FXML private Gauge gauge1;
</code>```

Body:
I'm using the MedusaFX Library to get gauges for a project I'm working on. I'm using a JavaFX Application to run everything and Scene Builder to create an FXML file in order to create the layout. What I've observed is that if I do

    @FXML private Gauge gauge1 = new Gauge();
    gauge1.setValue(30);

then the gauge1 variable gets the correct value set. However, if I do

    @FXML private Gauge gauge1 = new Gauge();
    ArrayList<Gauge> list = new ArrayList<>();
    list.add(gauge1);
    list.get(0).setValue(30);

    System.out.println(gauge1);
    System.out.println(list.get(0));

My output is

{"title":"Temperature","subTitle":"Temperature","unit":"°F","value":0.0,"minValue":0.0,"maxValue":175.0,"threshold":60.0,"minMeasuredValue":0.0,"maxMeasuredValue":0.0}
{"title":"","subTitle":"","unit":"","value":30.0,"minValue":0.0,"maxValue":100.0,"threshold":100.0,"minMeasuredValue":30.0,"maxMeasuredValue":30.0}

This output confuses me as it looks like the ArrayList creates a new instance of Gauge instead of modifying the one that it has within it. Any suggestions?

Body:
When you load an fxml file with FXMLLoader.load(), it will parse the file, and it will create an instance of every node it finds.

So, assuming that there is a Gauge node in your fxml file with fx:id="gauge1", when you add this to your controller:

@FXML private Gauge gauge1;

the FXMLLoader will create an instance for you. You can then set a value like:

public void initialize() {
    gauge1.setValue(30);
}

But when you do:

@FXML private Gauge gauge1 = new Gauge();

what is happening is that you are actually creating a second instance: the first one is created by reflexion, just based on the fx:id label, and added to the scene graph by the FXMLLoader, while the second you create is never added to the scene graph.

Later on, you don't know what is the actual instance you are modifying. When you do the printout, probably you are accessing both objects, being that on the list the one not added to the scene graph.

So the solution is easy: don't create the second instance, and use just this:

@FXML private Gauge gauge1;


问:
How to check if a float is infinity/zero/denormal?
```<code>int is_infinity/is_zero/is_denormal(float f){
    //do something, return 0 or 1
}
</code>```

This is what I did for checking if a float is negative.  I want to do something similar for the other functions, but I'm not sure how.

```<code>int is_negative(float val){
    union sp_object copy;
    copy.frep = val;
    if((copy.irep & 0x80000000) != 0)
        return 1;
    else
        return 0;
}
</code>```

答:
ISO C99 provides an INFINITY and NAN macro that can be compared against. It is recommended to use the functions isfinite(), isnormal(), and isnan(). Note that as EOF points out, comparing against the NAN macro will not determine whether a value is actually NAN.

For C99:

https://www.gnu.org/software/libc/manual/html_node/Floating-Point-Classes.html#Floating-Point-Classes

https://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html

For earlier code you're out of luck:

http://c-faq.com/fp/nan.html

ContentLicense: CC BY-SA 4.0

Body:
int is_infinity/is_zero/is_denormal(float f){
    //do something, return 0 or 1
}

This is what I did for checking if a float is negative.  I want to do something similar for the other functions, but I'm not sure how.

int is_negative(float val){
    union sp_object copy;
    copy.frep = val;
    if((copy.irep & 0x80000000) != 0)
        return 1;
    else
        return 0;
}


问:
How to set a placeholder for a Image control (while it downloads)?
I have an app that show a list of images. The image source is set to a http URL, and the images are downloaded and display automatically.

However, while the app is taking time to download, the image control shows nothing. The user experience is not good this way.

How may I display a loading placeholder image, or a loading gauge, for each of the image control?

答:
In addition to the 2 other suggestions (from Josh & Mick) you could display a placeholder in the xaml and then, in code, download the actual desired image in the background using HttpWebRequest. Then when the image has fully downloaded save it to isolated storage and then update the source to the displayed image.

Yes this is more complex than the other solutions but would simplify the visual tree and avoid a blank image being displayed while the image is downloaded.

It would also give you offline caching of images too.

ContentLicense: CC BY-SA 2.5


问:
Send email with embedded images through excel
Emails I send through excel do not display the embedded images on the receivers end. However the embedded images do display on my end. My guess is that the path is associated with my desktop.

How can I get the images to be displayed? Having trouble figuring out a fix. My code is below:

```<code>Sub EmailDailyFlow()
Dim mainWB As Workbook

Set otlApp = CreateObject("Outlook.Application")
Set olMail = otlApp.CreateItem(olMailItem)
Set mainWB = ActiveWorkbook

With olMail
    .To = "email@gmail.com"
    .Cc = ""
    .Subject = Format(Date - 1, "M.dd.yyyy") & " " & "MF & VIT Daily Fund Flow"
    .HTMLBody = "<html><body style='font-family: Times New Roman, Times, serif; font-size: 16px;'>" & _
            "<p>Please see below.</p>" & _
            "<p><u><b>Volatility:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\MF.png'>" & _
            "<p><u><b>Muni:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\MUNI.png'>" & _
            "<p><u><b>AFC:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\AFC.png'>" & _
            "<p><u><b>AFT:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\AFT.png'>" & _
            "<p><u><b>VIT:</u></b></p>" & _
            "<img src='C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images\VIT.png'>" & _
            "<p>Thank you,</p>" & _
            "</body></html>"
.Send

End With
MsgBox ("Daily flow emails sent!")
End Sub`
</code>```

答:
Try this code. Taken from some site long back, but still work like a charm.

Idea is to attach the image in hidden manner and later add it to using image name in the HtmlBody.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Update:

I've added another function to retrieve image width and height. I've also updated existing sub to incorporate image size.

```<code>Sub EmailDailyFlow()
    Dim SendID
    Dim CCID
    Dim Subject
    Dim stdPic As StdPicture
    Dim imageSize As String

    Dim strPathImg1 As String
    Dim strFileImg1 As String
    Dim lngWidthImg1 As Long
    Dim lngHeightImg1 As Long

    Dim strPathImg2 As String
    Dim strFileImg2 As String
    Dim lngWidthImg2 As Long
    Dim lngHeightImg2 As Long

    Dim olMail As MailItem  'REQUIRES MICROSOFT OBJECT OUTLOOK LIBRARY REFERENCE

    strPathImg1 = "C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images"
    strFileImg1 = "MF.png"
    imageSize = GetImageSize(strPathImg1, strFileImg1)
    lngWidthImg1 = CLng(Split(imageSize, ":")(0))
    lngHeightImg1 = CLng(Split(imageSize, ":")(1))

    strPathImg2 = "C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images"
    strFileImg2 = "MUNI.png"
    imageSize = GetImageSize(strPathImg2, strFileImg2)
    lngWidthImg2 = CLng(Split(imageSize, ":")(0))
    lngHeightImg2 = CLng(Split(imageSize, ":")(1))

    Set otlApp = CreateObject("Outlook.Application")
    Set olMail = otlApp.CreateItem(olMailItem)

    SendID = "email@gmail.com"
    CCID = ""
    Subject = Format(Date - 1, "M.dd.yyyy") & " " & "MF & VIT Daily Fund Flow"

    With olMail
        .To = SendID
        If CCID <> "" Then
          .CC = CCID
        End If
        .Subject = Subject
        'ADD THE IMAGE IN HIDDEN MANNER, POSITION AT 0 WILL MAKE IT HIDDEN
        .Attachments.Add strPathImg1 & "\" & strFileImg1, olByValue, 0
        .Attachments.Add strPathImg2 & "\" & strFileImg2, olByValue, 0

        'NOW ADD IT TO THE HTML BODY USING IMAGE NAME
        'CHANGE THE SRC PROPERTY TO 'cid:your image filename'
        'IT WILL BE CHANGED TO THE CORRECT CID WHEN ITS SENT.
        .HTMLBody = "<html><body style='font-family: Times New Roman, Times, serif; font-size: 16px;'>" & _
                    "<p>Please see below.</p>" & _
                    "<p><u><b>Volatility:</u></b></p>" & _
                    "<img src='cid:" & strFileImg1 & "' width='" & lngWidthImg1 & "' height='" & lngHeightImg1 & "'>" & _
                    "<p><u><b>Muni:</u></b></p>" & _
                    "<img src='cid:" & strFileImg2 & "' width='" & lngWidthImg2 & "' height='" & lngHeightImg2 & "'>" & _
                    "<p><u><b>AFC:</u></b></p>" & _
                    "<p>Thank you,</p>" & _
                    "</body></html>"
        '.Display 'UNCOMMENT ME IF YOU WANT TO DISPLAY THE EMAIL
        .Send
    End With

    MsgBox ("Daily flow emails sent!")
End Sub

Function GetImageSize(filePath As String, fileName As String) As String
    'THIS WILL RETURN IMAGE SIZE IN "xyz:xyz" STRING FORMAT
    Dim strImageDimensions As String
    Dim objShell As Object
    Dim objFolder As Object
    Dim objFile As Object

    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.Namespace((filePath))
    Set objFile = objFolder.ParseName(fileName)

    strImageDimensions = objFile.ExtendedProperty("Dimensions")
    strImageDimensions = Replace(Mid(strImageDimensions, 2, Len(strImageDimensions) - 2), " x ", ":")
    GetImageSize = strImageDimensions

    Set objFile = Nothing: Set objFolder = Nothing: Set objShell = Nothing
End Function
</code>```

Body:
Emails I send through excel do not display the embedded images on the receivers end. However the embedded images do display on my end. My guess is that the path is associated with my desktop.

How can I get the images to be displayed? Having trouble figuring out a fix. My code is below:

Sub EmailDailyFlow()
Dim mainWB As Workbook

Set otlApp = CreateObject("Outlook.Application")
Set olMail = otlApp.CreateItem(olMailItem)
Set mainWB = ActiveWorkbook

With olMail
    .To = "email@gmail.com"
    .Cc = ""
    .Subject = Format(Date - 1, "M.dd.yyyy") & " " & "MF & VIT Daily Fund Flow"
    .HTMLBody = "" & _
            "
Please see below.
" & _
            "
Volatility:
" & _
            "" & _
            "
Muni:
" & _
            "" & _
            "
AFC:
" & _
            "" & _
            "
AFT:
" & _
            "" & _
            "
VIT:
" & _
            "" & _
            "
Thank you,
" & _
            ""
.Send

End With
MsgBox ("Daily flow emails sent!")
End Sub`

Body:
Try this code. Taken from some site long back, but still work like a charm.

Idea is to attach the image in hidden manner and later add it to using image name in the HtmlBody.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Update:

I've added another function to retrieve image width and height. I've also updated existing sub to incorporate image size.

Sub EmailDailyFlow()
    Dim SendID
    Dim CCID
    Dim Subject
    Dim stdPic As StdPicture
    Dim imageSize As String

    Dim strPathImg1 As String
    Dim strFileImg1 As String
    Dim lngWidthImg1 As Long
    Dim lngHeightImg1 As Long

    Dim strPathImg2 As String
    Dim strFileImg2 As String
    Dim lngWidthImg2 As Long
    Dim lngHeightImg2 As Long

    Dim olMail As MailItem  'REQUIRES MICROSOFT OBJECT OUTLOOK LIBRARY REFERENCE

    strPathImg1 = "C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images"
    strFileImg1 = "MF.png"
    imageSize = GetImageSize(strPathImg1, strFileImg1)
    lngWidthImg1 = CLng(Split(imageSize, ":")(0))
    lngHeightImg1 = CLng(Split(imageSize, ":")(1))

    strPathImg2 = "C:\Users\Name\Desktop\MF-VIT Daily Fund Flow\images"
    strFileImg2 = "MUNI.png"
    imageSize = GetImageSize(strPathImg2, strFileImg2)
    lngWidthImg2 = CLng(Split(imageSize, ":")(0))
    lngHeightImg2 = CLng(Split(imageSize, ":")(1))

    Set otlApp = CreateObject("Outlook.Application")
    Set olMail = otlApp.CreateItem(olMailItem)

    SendID = "email@gmail.com"
    CCID = ""
    Subject = Format(Date - 1, "M.dd.yyyy") & " " & "MF & VIT Daily Fund Flow"

    With olMail
        .To = SendID
        If CCID <> "" Then
          .CC = CCID
        End If
        .Subject = Subject
        'ADD THE IMAGE IN HIDDEN MANNER, POSITION AT 0 WILL MAKE IT HIDDEN
        .Attachments.Add strPathImg1 & "\" & strFileImg1, olByValue, 0
        .Attachments.Add strPathImg2 & "\" & strFileImg2, olByValue, 0

        'NOW ADD IT TO THE HTML BODY USING IMAGE NAME
        'CHANGE THE SRC PROPERTY TO 'cid:your image filename'
        'IT WILL BE CHANGED TO THE CORRECT CID WHEN ITS SENT.
        .HTMLBody = "<html><body style='font-family: Times New Roman, Times, serif; font-size: 16px;'>" & _
                    "<p>Please see below.</p>" & _
                    "<p><u><b>Volatility:</u></b></p>" & _
                    "<img src='cid:" & strFileImg1 & "' width='" & lngWidthImg1 & "' height='" & lngHeightImg1 & "'>" & _
                    "<p><u><b>Muni:</u></b></p>" & _
                    "<img src='cid:" & strFileImg2 & "' width='" & lngWidthImg2 & "' height='" & lngHeightImg2 & "'>" & _
                    "<p><u><b>AFC:</u></b></p>" & _
                    "<p>Thank you,</p>" & _
                    "</body></html>"
        '.Display 'UNCOMMENT ME IF YOU WANT TO DISPLAY THE EMAIL
        .Send
    End With

    MsgBox ("Daily flow emails sent!")
End Sub

Function GetImageSize(filePath As String, fileName As String) As String
    'THIS WILL RETURN IMAGE SIZE IN "xyz:xyz" STRING FORMAT
    Dim strImageDimensions As String
    Dim objShell As Object
    Dim objFolder As Object
    Dim objFile As Object

    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.Namespace((filePath))
    Set objFile = objFolder.ParseName(fileName)

    strImageDimensions = objFile.ExtendedProperty("Dimensions")
    strImageDimensions = Replace(Mid(strImageDimensions, 2, Len(strImageDimensions) - 2), " x ", ":")
    GetImageSize = strImageDimensions

    Set objFile = Nothing: Set objFolder = Nothing: Set objShell = Nothing
End Function


问:
Select value and column that value have changed
I have a historian that is logging 1 row each time 1 of the value changes. So in each Row there should always only 1 value that has changed from the previous Row

My table looks like this. (i have more than 5 Columns and they don't have generic name, these column name will change for each project. I'd like to avoid hardcoding Column name)

```<code>INDEX|Column1|Column2|Column3|Column4|Column5|TimeStamp
1    |      0|      0|      0|      0|      0|2017-03-28 13:00:00
2    |      0|      0|      0|      1|      0|2017-03-28 14:00:00
3    |      2|      0|      0|      1|      0|2017-03-28 15:00:00
4    |      3|      0|      0|      1|      0|2017-03-28 16:00:00
5    |      3|     22|      0|      1|      0|2017-03-28 17:00:00
6    |      3|     22|      6|      1|      0|2017-03-28 18:00:00
</code>```

The result i want to get in my report.

```<code>Name   |NewValue|PreviousValue|TimeStamp
Column4|       1|            0|2017-03-28 14:00:00
Column1|       2|            0|2017-03-28 15:00:00
Column1|       3|            2|2017-03-28 16:00:00
Column2|      22|            0|2017-03-28 17:00:00
Column3|       6|            0|2017-03-28 18:00:00
</code>```

What would be the best way to achieve this?

Im using MariaDB 10.1.22.

答:
```<code>SELECT 'Column5', column5, max(timestamp) from mytable where column5 <> 0 group by column5
Union
SELECT 'Column4', column4, max(timestamp) from mytable where column4 <> 0 group by column4
Union
SELECT 'Column3', column3, max(timestamp) from mytable where column3 <> 0 group by column3
Union
SELECT 'Column2', column2, max(timestamp) from mytable where column2 <> 0 group by column2
Union
SELECT 'Column1', column1, max(timestamp) from mytable where column1 <> 0 group by column1
</code>```

Body:
I have a historian that is logging 1 row each time 1 of the value changes. So in each Row there should always only 1 value that has changed from the previous Row

My table looks like this. (i have more than 5 Columns and they don't have generic name, these column name will change for each project. I'd like to avoid hardcoding Column name)

INDEX|Column1|Column2|Column3|Column4|Column5|TimeStamp
1    |      0|      0|      0|      0|      0|2017-03-28 13:00:00
2    |      0|      0|      0|      1|      0|2017-03-28 14:00:00
3    |      2|      0|      0|      1|      0|2017-03-28 15:00:00
4    |      3|      0|      0|      1|      0|2017-03-28 16:00:00
5    |      3|     22|      0|      1|      0|2017-03-28 17:00:00
6    |      3|     22|      6|      1|      0|2017-03-28 18:00:00

The result i want to get in my report.

Name   |NewValue|PreviousValue|TimeStamp
Column4|       1|            0|2017-03-28 14:00:00
Column1|       2|            0|2017-03-28 15:00:00
Column1|       3|            2|2017-03-28 16:00:00
Column2|      22|            0|2017-03-28 17:00:00
Column3|       6|            0|2017-03-28 18:00:00

What would be the best way to achieve this?

Im using MariaDB 10.1.22.


问:
create a custom view programmatically then animate it
I'm creating a custom view programmatically, which is working fine, then I'm trying to animate the view.  For some strange reason the view is animating at all, I'm not sure why.  Here is the code:</p>

```<code>  override func viewDidLoad() {
    super.viewDidLoad()

    let customView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))

    customView.backgroundColor = UIColor.blue
    customView.layer.cornerRadius = 25
    customView.layer.borderWidth = 8
    customView.layer.borderColor = UIColor.red.cgColor

    self.view.addSubview(customView)

    UIView.animate(withDuration: 4, animations: {

      customView.transform.translatedBy(x: 40, y: 60)
      customView.transform.rotated(by: CGFloat.pi/2)
      customView.transform.scaledBy(x: 0, y: 0.5)

    })
  }
</code>```

答:
you better call this animation block in viewDidAppear, with some delay.   </p>

```<code>import UIKit

class ViewController: UIViewController {

    var customView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        customView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
        customView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))

        customView.backgroundColor = UIColor.blue
        customView.layer.cornerRadius = 25
        customView.layer.borderWidth = 8
        customView.layer.borderColor = UIColor.red.cgColor

        self.view.addSubview(customView)
    }

    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 5, delay: 1, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
          self.customView.transform = CGAffineTransform(scaleX: 1, y: 0.5)
          self.customView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
          self.customView.transform = CGAffineTransform(translationX: 40, y: 60)
        }, completion: nil)
    }

    func handleTap() {
        UIView.animate(withDuration: 5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            self.customView.transform = CGAffineTransform(scaleX: 1, y: 0.5)
            self.customView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
            self.customView.transform = CGAffineTransform(translationX: 40, y: 60)
        }, completion: nil)
    }

}
</code>```

Body:
I'm creating a custom view programmatically, which is working fine, then I'm trying to animate the view.  For some strange reason the view is animating at all, I'm not sure why.  Here is the code:

  override func viewDidLoad() {
    super.viewDidLoad()

    let customView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))

    customView.backgroundColor = UIColor.blue
    customView.layer.cornerRadius = 25
    customView.layer.borderWidth = 8
    customView.layer.borderColor = UIColor.red.cgColor

    self.view.addSubview(customView)

    UIView.animate(withDuration: 4, animations: {

      customView.transform.translatedBy(x: 40, y: 60)
      customView.transform.rotated(by: CGFloat.pi/2)
      customView.transform.scaledBy(x: 0, y: 0.5)

    })
  }

Body:
you better call this animation block in viewDidAppear, with some delay.

import UIKit

class ViewController: UIViewController {

    var customView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        customView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
        customView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))

        customView.backgroundColor = UIColor.blue
        customView.layer.cornerRadius = 25
        customView.layer.borderWidth = 8
        customView.layer.borderColor = UIColor.red.cgColor

        self.view.addSubview(customView)
    }

    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 5, delay: 1, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
          self.customView.transform = CGAffineTransform(scaleX: 1, y: 0.5)
          self.customView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
          self.customView.transform = CGAffineTransform(translationX: 40, y: 60)
        }, completion: nil)
    }

    func handleTap() {
        UIView.animate(withDuration: 5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            self.customView.transform = CGAffineTransform(scaleX: 1, y: 0.5)
            self.customView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
            self.customView.transform = CGAffineTransform(translationX: 40, y: 60)
        }, completion: nil)
    }

}


问:
C# how to enable button from another class
I have a form1, there's a "download" button, and a "next" button. By default, the "next" button is disabled. When I click "download" button, I will call a method from download.cs, different from form1.cs. After downloading, I want the "next" button to be enabled, so in download.cs, after receiving all files, I put

form1.btnNext.Enabled = true;

But it doesn't work. I also put this in form1.cs

public void enableButton(bool enabled)

{
     btnNext.Enabled = enabled;
  }

and in download.cs I put:

private form1 form1;
  ...

form1.enableButton(true);

but it doesn't work either. Could any1 show me where I'm wrong? thanks in advance.

答: You can pass through a reference to the Button to the new class.  So when you call the method from download.cs, pass the name of the button through as a parameter and then you can use it within the new class as you would any other reference.</p>


问:
Stop processing more rules when needed
Using Outlook 2010, I want to add "stop processing more rules" to a rule.

I have a rule defined using the normal rules interface in Outlook. That rule is one of many rules, all of which have "stop processing more rules" set except for this one. The rule runs a script. This one does not have "stop processing more rules". Until the script is run I don't know if I want to stop processing more rules. I don't want to change this rule (or any rule) in VBA, just decide in the VBA script whether to stop processing more rules.

Code I'm using (edited down a bit)

```<code>Public Sub checkforvalidfiletype(Item As Outlook.MailItem)
    Dim olkAtt As Outlook.Attachment
    Dim orule As Outlook.Rules
    Dim oRuleAction As Outlook.RuleAction
    'Check each attachment
    Stop
    For Each olkAtt In Item.Attachments
        'If the attachment's file name ends with .xls .csv or .xlsx
        If Right(LCase(olkAtt.FileName), 4) = ".xls" Or Right(LCase(olkAtt.FileName), 4) = ".csv" Or Right(LCase(olkAtt.FileName), 5) = ".xlsx" Then
            'then assign it to the Unknown .xls .xlxs or .csv to be processed category
            Item.Categories = "Unknown .xls .xlxs or .csv to be processed"
            Item.Save
            'and stop processing more rules
            Set oRuleAction = orule.Actions.Stop
            With oRuleAction
                .Enabled = True
            End With
            'No need to check any of this message's remaining attachments (just one valid attachment is enough for us to want to know about it)
            Exit For
        End If
    Next
    Set olkAtt = Nothing
End Sub
</code>```

I get a run-time error '91' Object variable or With block variable not set error, on the Set oRuleAction = orule.Actions.Stop line. (I have the right object library referenced.)

答:
You've probably figured this out yourself by now. Just from what you've posted, the oRule object is not set, and you probably want Rules object from which you'll set the Rule object ...

```<code>Dim colRules As Outlook.Rules
Dim oRule As Outlook.Rule
</code>```

Illustrative similar code at:
https://msdn.microsoft.com/en-us/library/office/ff867254(v=office.14).aspx

Title: Stop processing more rules when needed

Body:
Using Outlook 2010, I want to add "stop processing more rules" to a rule.

I have a rule defined using the normal rules interface in Outlook. That rule is one of many rules, all of which have "stop processing more rules" set except for this one. The rule runs a script. This one does not have "stop processing more rules". Until the script is run I don't know if I want to stop processing more rules. I don't want to change this rule (or any rule) in VBA, just decide in the VBA script whether to stop processing more rules.

Code I'm using (edited down a bit)

Public Sub checkforvalidfiletype(Item As Outlook.MailItem)
    Dim olkAtt As Outlook.Attachment
    Dim orule As Outlook.Rules
    Dim oRuleAction As Outlook.RuleAction
    'Check each attachment
    Stop
    For Each olkAtt In Item.Attachments
        'If the attachment's file name ends with .xls .csv or .xlsx
        If Right(LCase(olkAtt.FileName), 4) = ".xls" Or Right(LCase(olkAtt.FileName), 4) = ".csv" Or Right(LCase(olkAtt.FileName), 5) = ".xlsx" Then
            'then assign it to the Unknown .xls .xlxs or .csv to be processed category
            Item.Categories = "Unknown .xls .xlxs or .csv to be processed"
            Item.Save
            'and stop processing more rules
            Set oRuleAction = orule.Actions.Stop
            With oRuleAction
                .Enabled = True
            End With
            'No need to check any of this message's remaining attachments (just one valid attachment is enough for us to want to know about it)
            Exit For
        End If
    Next
    Set olkAtt = Nothing
End Sub

I get a run-time error '91' Object variable or With block variable not set error, on the Set oRuleAction = orule.Actions.Stop line. (I have the right object library referenced.)

Body:
You've probably figured this out yourself by now. Just from what you've posted, the oRule object is not set, and you probably want Rules object from which you'll set the Rule object ...

Dim colRules As Outlook.Rules
Dim oRule As Outlook.Rule

Illustrative similar code at:
https://msdn.microsoft.com/en-us/library/office/ff867254(v=office.14).aspx


问:
Can I post formatted Source Code on Facebook?
I want to create a page on the Facebook, where I want to post Code from different languages.

Does Facebook provide any means of posting formatted code on the
wall?

Is there an API for doing so on Facebook?

答: You can use static html to write your own codes on a facebook page. It will create new tabs where you can write all html, javascript codes as you wish.</p>


问:
Error in gfconv (Galois field function) in Matlab
I am trying to multiply a hexdecimal value AA by 2 in the galois field using the gfconv(a,b) function of Matlab, the console returns to me an error saying: "The input elements must be binary.", but my two elements are binary

```<code>a=hexToBinaryVector('AA');
b=de2bi(2);
c=gfconv(a,b);
disp(c);
</code>```

The error code:

```<code>Error using gfconv_mex
The input elements must be binary.

Error in gfconv (line 120)
        c = gfconv_mex(varargin{:});

Error in test(line 3)
c=gfconv(a,b);
</code>```

Any idea how to solve that?

答:
I'm not doing all the code here, but here's the steps that I would take to solve it.

Problem

It's in binary form, but b is a vector of binary numbers.

Solution

Look up https://www.mathworks.com/help/matlab/ref/mat2str.html

Convert your vector to the string

Parse the string and pull out the ones and zeros

use str2num to convert back to a number: https://www.mathworks.com/help/matlab/ref/str2num.html

Try that and see if it works.

Note - Expansion of step 3:

if we have variable a = '[0+11]';, we can select individual characters from the string like:

```<code> a(3)
ans = '+'
a(4)
ans = '1'
a(1)
and = '['
</code>```

Therefore, you can parse the string with a loop"

```<code>for n = 1 : length(a)
    if a(n) == '1' || a(n) == '0'
        str(n) = a(n);
    end
end
</code>```

Finally, convert the string:

```<code>num = str2num(str);
</code>```

done

Body:
I am trying to multiply a hexdecimal value AA by 2 in the galois field using the gfconv(a,b) function of Matlab, the console returns to me an error saying: "The input elements must be binary.", but my two elements are binary

a=hexToBinaryVector('AA');
b=de2bi(2);
c=gfconv(a,b);
disp(c);

The error code:

Error using gfconv_mex
The input elements must be binary.

Error in gfconv (line 120)
        c = gfconv_mex(varargin{:});

Error in test(line 3)
c=gfconv(a,b);

Any idea how to solve that?

Body:
I'm not doing all the code here, but here's the steps that I would take to solve it.

Problem

It's in binary form, but b is a vector of binary numbers.

Solution

Look up https://www.mathworks.com/help/matlab/ref/mat2str.html

Convert your vector to the string

Parse the string and pull out the ones and zeros

use str2num to convert back to a number: https://www.mathworks.com/help/matlab/ref/str2num.html

Try that and see if it works.

Note - Expansion of step 3:

if we have variable a = '[0+11]';, we can select individual characters from the string like:

 a(3)
ans = '+'
a(4)
ans = '1'
a(1)
and = '['

Therefore, you can parse the string with a loop"

for n = 1 : length(a)
    if a(n) == '1' || a(n) == '0'
        str(n) = a(n);
    end
end

Finally, convert the string:

num = str2num(str);

done


问:
Why don't my Rails server render times add up?
I'm having some trouble with my Rails app being very slow on my staging server. What is most confusing is that the final line of the log output for each request.

It seems the View and Database times aren't even close to the entire render time. On one page it is as bad as ~1000ms for Completion, ~450ms for the View and ~20ms Database.

Where does the rest of the time required to render the page come from?

答: I recommend using New Relic's RPM service. It has a free version, but the Bronze service ($40 a month) is wonderful and further helps track down these issues.</p>

OwnerDisplayName: Ben

OwnerDisplayName: Matt Darby


答:
Using Static SQL:

This is the basic code you want. But everything is hardcoded. That cannot be avoided without "dynamic SQL".

```<code>SELECT
CASE
    WHEN t1.Column1 <> t2.Column1 THEN 'Column1'
    WHEN t1.Column2 <> t2.Column2 THEN 'Column2'
    WHEN t1.Column3 <> t2.Column3 THEN 'Column3'
    WHEN t1.Column4 <> t2.Column4 THEN 'Column4'
    WHEN t1.Column5 <> t2.Column5 THEN 'Column5'
END as Name,
CASE
    WHEN t1.Column1 <> t2.Column1 THEN t2.Column1
    WHEN t1.Column2 <> t2.Column2 THEN t2.Column2
    WHEN t1.Column3 <> t2.Column3 THEN t2.Column3
    WHEN t1.Column4 <> t2.Column4 THEN t2.Column4
    WHEN t1.Column5 <> t2.Column5 THEN t2.Column5
END as NewValue,
CASE
    WHEN t1.Column1 <> t2.Column1 THEN t1.Column1
    WHEN t1.Column2 <> t2.Column2 THEN t1.Column2
    WHEN t1.Column3 <> t2.Column3 THEN t1.Column3
    WHEN t1.Column4 <> t2.Column4 THEN t1.Column4
    WHEN t1.Column5 <> t2.Column5 THEN t1.Column5
END as PreviousValue,
t2.TimeStamp
FROM
MyTable t1
JOIN MyTable t2
    ON t2.Index = t1.Index + 1
</code>```

If it's possible for the columns to be NULL either before or after, you'll need to adjust the <>s accordingly.

Using Dynamic SQL:

Rather than hard-code the column names, you can generate code like the above by extracting column data from the information_schema tables. Set the @tablename variable to the name of the table you wish to process, and this code will set the variable @sql to hold code equivalent to that above. I've used \n to add new lines and so improve the formatting in the generated code.

```<code>-- Avoids the GROUP_CONCAT truncating the code we're building
SET SESSION GROUP_CONCAT_MAX_LEN=65535;

-- Specify your target table here
SELECT @tablename := 'MyTable';

SELECT @sql := GROUP_CONCAT(theCode SEPARATOR '')
FROM
(
-- theOrderBy is for keeping the various parts of this code in the correct sequence
-- SELECT plus the opening of the first CASE statement
SELECT 0 theOrderBy, 'SELECT\nCASE\n' theCode

UNION ALL

-- Generates the inner part first CASE statement
SELECT 1, CONCAT('    WHEN t1.',Column_Name,' <> t2.',Column_Name,' THEN ''', Column_Name,'''','\n')
FROM `information_schema`.`Columns`
WHERE table_name like @tablename
AND Column_Name NOT IN ('Index','Timestamp')

UNION ALL

-- Generates the end of the first CASE (and it's alias) and the beginning of the second one
SELECT 2, 'END as Name,\nCASE\n'

UNION ALL

-- Generates the inner part second CASE statement
SELECT 3, CONCAT('    WHEN t1.',Column_Name,' <> t2.',Column_Name,' THEN t2.', Column_Name, '\n')
from `information_schema`.`Columns`
WHERE table_name LIKE @tablename
AND Column_Name NOT IN ('Index','Timestamp')

UNION ALL

-- Generates the end of the second CASE (and it's alias) and the beginning of the third one
SELECT 4, 'END as NewValue,\nCASE\n'

UNION ALL

-- Generates the inner part third CASE statement
SELECT 5, CONCAT('    WHEN t1.',Column_Name,' <> t2.',Column_Name,' THEN t1.', Column_Name, '\n')
FROM `information_schema`.`Columns`
WHERE table_name like @tablename
AND Column_Name NOT IN ('Index','Timestamp')

UNION ALL

-- Generates the end of the final CASE statement plus the FROM clause
SELECT 6, CONCAT('END as PreviousValue,\nt2.Timestamp\nFROM\n    ',@tablename, ' t1\n    JOIN ',@tablename, ' t2 ON\n        t2.Index = t1.Index + 1')

ORDER BY theOrderBy
) as sub;

SELECT @sql;
</code>```

If you're happy with what you see in the variable, you can re-run replacing the last line with:

```<code>PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

The viability of this code depends heavily on your having the same essential structure for any targetted table, namely a sequentially increasing Index field and a Timestamp. As in the "Static" code, this is also using <> for all the comparisons, so effectively assuming the fields will not be NULL either before or after each change.

If those assumptions don't hold, you'll need to make adjustments. If you need help with that, do let me know.

Title: Select value and column that value have changed

Body:
Using Static SQL:

This is the basic code you want. But everything is hardcoded. That cannot be avoided without "dynamic SQL".

SELECT
CASE
    WHEN t1.Column1 <> t2.Column1 THEN 'Column1'
    WHEN t1.Column2 <> t2.Column2 THEN 'Column2'
    WHEN t1.Column3 <> t2.Column3 THEN 'Column3'
    WHEN t1.Column4 <> t2.Column4 THEN 'Column4'
    WHEN t1.Column5 <> t2.Column5 THEN 'Column5'
END as Name,
CASE
    WHEN t1.Column1 <> t2.Column1 THEN t2.Column1
    WHEN t1.Column2 <> t2.Column2 THEN t2.Column2
    WHEN t1.Column3 <> t2.Column3 THEN t2.Column3
    WHEN t1.Column4 <> t2.Column4 THEN t2.Column4
    WHEN t1.Column5 <> t2.Column5 THEN t2.Column5
END as NewValue,
CASE
    WHEN t1.Column1 <> t2.Column1 THEN t1.Column1
    WHEN t1.Column2 <> t2.Column2 THEN t1.Column2
    WHEN t1.Column3 <> t2.Column3 THEN t1.Column3
    WHEN t1.Column4 <> t2.Column4 THEN t1.Column4
    WHEN t1.Column5 <> t2.Column5 THEN t1.Column5
END as PreviousValue,
t2.TimeStamp
FROM
MyTable t1
JOIN MyTable t2
    ON t2.Index = t1.Index + 1

If it's possible for the columns to be NULL either before or after, you'll need to adjust the <>s accordingly.

Using Dynamic SQL:

Rather than hard-code the column names, you can generate code like the above by extracting column data from the information_schema tables. Set the @tablename variable to the name of the table you wish to process, and this code will set the variable @sql to hold code equivalent to that above. I've used \n to add new lines and so improve the formatting in the generated code.

-- Avoids the GROUP_CONCAT truncating the code we're building
SET SESSION GROUP_CONCAT_MAX_LEN=65535;

-- Specify your target table here
SELECT @tablename := 'MyTable';

SELECT @sql := GROUP_CONCAT(theCode SEPARATOR '')
FROM
(
-- theOrderBy is for keeping the various parts of this code in the correct sequence
-- SELECT plus the opening of the first CASE statement
SELECT 0 theOrderBy, 'SELECT\nCASE\n' theCode

UNION ALL

-- Generates the inner part first CASE statement
SELECT 1, CONCAT('    WHEN t1.',Column_Name,' <> t2.',Column_Name,' THEN ''', Column_Name,'''','\n')
FROM `information_schema`.`Columns`
WHERE table_name like @tablename
AND Column_Name NOT IN ('Index','Timestamp')

UNION ALL

-- Generates the end of the first CASE (and it's alias) and the beginning of the second one
SELECT 2, 'END as Name,\nCASE\n'

UNION ALL

-- Generates the inner part second CASE statement
SELECT 3, CONCAT('    WHEN t1.',Column_Name,' <> t2.',Column_Name,' THEN t2.', Column_Name, '\n')
from `information_schema`.`Columns`
WHERE table_name LIKE @tablename
AND Column_Name NOT IN ('Index','Timestamp')

UNION ALL

-- Generates the end of the second CASE (and it's alias) and the beginning of the third one
SELECT 4, 'END as NewValue,\nCASE\n'

UNION ALL

-- Generates the inner part third CASE statement
SELECT 5, CONCAT('    WHEN t1.',Column_Name,' <> t2.',Column_Name,' THEN t1.', Column_Name, '\n')
FROM `information_schema`.`Columns`
WHERE table_name like @tablename
AND Column_Name NOT IN ('Index','Timestamp')

UNION ALL

-- Generates the end of the final CASE statement plus the FROM clause
SELECT 6, CONCAT('END as PreviousValue,\nt2.Timestamp\nFROM\n    ',@tablename, ' t1\n    JOIN ',@tablename, ' t2 ON\n        t2.Index = t1.Index + 1')

ORDER BY theOrderBy
) as sub;

SELECT @sql;

If you're happy with what you see in the variable, you can re-run replacing the last line with:

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

The viability of this code depends heavily on your having the same essential structure for any targetted table, namely a sequentially increasing Index field and a Timestamp. As in the "Static" code, this is also using <> for all the comparisons, so effectively assuming the fields will not be NULL either before or after each change.

If those assumptions don't hold, you'll need to make adjustments. If you need help with that, do let me know.


问:
C# Tweetinvi Library - how to stop stream
Attempting to get a filtered stream using the Tweetinvi library via c#.

I am trying to do something similar to the search, which I have been able to successfully receive tweets:

```<code>public List<ITweet> SearchTweets(string query)
{
    List<ITweet> tweets = new List<ITweet>();

    TwitterCredentials.ExecuteOperationWithCredentials(Credentials, () =>
    {
        var searchParam = Search.GenerateSearchTweetParameter(query);
        searchParam.Lang = Language.English;
        searchParam.MaximumNumberOfResults = 100;
        tweets = Search.SearchTweets(searchParam);
    });

    return tweets;
}
</code>```

but the limitation here is that I can only get a max 100 tweets. I want to leverage the stream in a similar way and get a stream of tweets matching the tracks that I pass. I have tried this:

```<code>public void FilterStream(string query)
{
    IFilteredStream tweets;

    TwitterCredentials.ExecuteOperationWithCredentials(Credentials, () =>
    {
        var filteredStream = Tweetinvi.Stream.CreateFilteredStream();
        filteredStream.AddTrack(query);
        filteredStream.AddTrack("#" + query);
        filteredStream.MatchingTweetReceived += (sender, args) => { Debug.WriteLine(args.Tweet.Text); };
        filteredStream.StartStreamMatchingAllConditions();
    });
}
</code>```

but problem is it seems to run in an infinite loop and i'm unsure where to stop or limit the number of tweets I received from the stream to make it stop. The library's documentation is quite unclear and I have been unable to achieve the behavior I am seeking. I'm sure I am on the right route, just unsure how to stop the stream and store all the tweets I've received in a List<ITweet> construct.

答:
I know it's an old question, but I've just done this:</p>

```<code>    public void Start()
    {
        _stream = Stream.CreateFilteredStream(_creds);

        // Do whatever stream setup you want to do

        Task.Factory.StartNew(() => {
            Debug.WriteLine("Thread started");
            _stream.StartStreamMatchingAllConditions();
            Debug.WriteLine("Thread stopped");
            });
    }

    public void Stop()
    {
        _stream.StopStream();
    }
</code>```

Body:
Attempting to get a filtered stream using the Tweetinvi library via c#.

I am trying to do something similar to the search, which I have been able to successfully receive tweets:

public List<ITweet> SearchTweets(string query)
{
    List<ITweet> tweets = new List<ITweet>();

    TwitterCredentials.ExecuteOperationWithCredentials(Credentials, () =>
    {
        var searchParam = Search.GenerateSearchTweetParameter(query);
        searchParam.Lang = Language.English;
        searchParam.MaximumNumberOfResults = 100;
        tweets = Search.SearchTweets(searchParam);
    });

    return tweets;
}

but the limitation here is that I can only get a max 100 tweets. I want to leverage the stream in a similar way and get a stream of tweets matching the tracks that I pass. I have tried this:

public void FilterStream(string query)
{
    IFilteredStream tweets;

    TwitterCredentials.ExecuteOperationWithCredentials(Credentials, () =>
    {
        var filteredStream = Tweetinvi.Stream.CreateFilteredStream();
        filteredStream.AddTrack(query);
        filteredStream.AddTrack("#" + query);
        filteredStream.MatchingTweetReceived += (sender, args) => { Debug.WriteLine(args.Tweet.Text); };
        filteredStream.StartStreamMatchingAllConditions();
    });
}

but problem is it seems to run in an infinite loop and i'm unsure where to stop or limit the number of tweets I received from the stream to make it stop. The library's documentation is quite unclear and I have been unable to achieve the behavior I am seeking. I'm sure I am on the right route, just unsure how to stop the stream and store all the tweets I've received in a List<ITweet> construct.

Body:
I know it's an old question, but I've just done this:

    public void Start()
    {
        _stream = Stream.CreateFilteredStream(_creds);

        // Do whatever stream setup you want to do

        Task.Factory.StartNew(() => {
            Debug.WriteLine("Thread started");
            _stream.StartStreamMatchingAllConditions();
            Debug.WriteLine("Thread stopped");
            });
    }

    public void Stop()
    {
        _stream.StopStream();
    }


问:
How do I delete a specific row when I click a button using jquery?
I have a table of player data with a delete button next to each row.
When the button is clicked, it should delete that specific row instantly using jQuery. I have included my code thus far. I am really stuck when the button should be clicked. Should I use a header function?

index.php

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css"></link>
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/script.js"></script>
    </head>
<body>
    <!-- Create a table-->
    <table style width="800" border="1" cellpadding="1" cellspacing="1">
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <tr>
    <th>Player ID</th>
    <th>Player Name</th>
    <th>Player Position</th>
    <th>Delete</th>
    </tr>

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "<div class = 'row'>";
            echo "<tr>";
            echo "<td>".$row['id']."</td>";
            echo "<td>".$row['surname']."</td>";
            echo "<td>".$row['position']."</td>";
            echo "<td><button id = 'dlt_btn' type='button'>Delete</button></td>";
            echo "</tr>";
            echo "</div>";

        }

    ?>

</body>
</code>```

script.js

```<code>$(document).ready(function () {

    $("#dlt_btn").click(function(){
        //Activate 'delete.php'
    });

});
</code>```

delete.php

```<code>?
</code>```

答:
using DOM manipulate:

```<code>$(document).ready(function(){
  $("#dlt_btn").click(function () {
     var deleteRow = $(this)
     deleteRow.parents('.row').fadeOut(200);
  });
})
</code>```

if you wanna delete from database. trigger another line of code in php when the function runs in the same time

Body:
I have a table of player data with a delete button next to each row.
When the button is clicked, it should delete that specific row instantly using jQuery. I have included my code thus far. I am really stuck when the button should be clicked. Should I use a header function?

index.php

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="css/style.css"></link>

    Player ID
    Player Name
    Player Position
    Delete

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "
";
            echo "
";
            echo "".$row['id']."	";
            echo "".$row['surname']."	";
            echo "".$row['position']."	";
            echo "<button id = 'dlt_btn' type='button'>Delete</button>	";
            echo "
";
            echo "
";

        }

    ?>

script.js

$(document).ready(function () {

    $("#dlt_btn").click(function(){
        //Activate 'delete.php'
    });

});

delete.php

?

Body:
using DOM manipulate:

$(document).ready(function(){
  $("#dlt_btn").click(function () {
     var deleteRow = $(this)
     deleteRow.parents('.row').fadeOut(200);
  });
})

if you wanna delete from database. trigger another line of code in php when the function runs in the same time


问:
Place order from suiteCRM and redirect into magento for payment
I want to create one functionality in suiteCRR which is below.

Order place from the suiteCRM

When i click on place order button on suiteCRM then it will redirect into magento website with that order informations.

payment will be processed through magento only.

Any SuiteCRM guys help me would be very helpful.

Thanks in advance.

答: You will need to create and "after_save" logic hook to redirect to where ever you need it to go once the record is saved in SuiteCRM. </p>


问:
Understand normalized squared euclidean distance?
I'm trying to understand the normalized squared euclidean distance formula from the Wolfram documentation:

```<code>1/2*Norm[(u-Mean[u])-(v-Mean[v])]^2/(Norm[u-Mean[u]]^2+Norm[v-Mean[v]]^2)
</code>```

I searched around for this formula on the web but couldn't find it. Can someone explain how this formula is derived?

答:
Meaning of this formula is the following:

Distance between two vectors where there lengths have been scaled to
  have unit norm. This is helpful when the direction of the vector is
  meaningful but the magnitude is not.

https://stats.stackexchange.com/questions/136232/definition-of-normalized-euclidean-distance

Body:
I'm trying to understand the normalized squared euclidean distance formula from the Wolfram documentation:

1/2*Norm[(u-Mean[u])-(v-Mean[v])]^2/(Norm[u-Mean[u]]^2+Norm[v-Mean[v]]^2)

I searched around for this formula on the web but couldn't find it. Can someone explain how this formula is derived?


问:
Angular 2: Using service to share data between components
I am trying to use a service to define a shared resource client between several views.  I first select the client from an index and set it:

```<code>itemTapped(event, client) {
  this.clientService.get(`/${client.id}?model=client`, this.current_user.auth_token)
    .subscribe(
      data => {
        this.clientService.setClient(data)
        this.navCtrl.push(ClientGenericPage, {
          client_id: data['id'],
          tab: 'profile',
          current_user: this.current_user
        });
      },
      err => {
        this.clientService.handleResponse("Ut oh.. Could not locate the client !"),
        this.clientService.hideLoader()
      },
      () => this.clientService.hideLoader()
    )
}

export class ClientService {

  private client = new Subject<any>();

  constructor (private http: Http, private toastCtrl: ToastController, public storage: Storage ) {

  }

  setClient(client) {
    this.client.next(client)
  }

  getClient() {
    return this.client.asObservable();
  }

  get(url, token):Observable<Response> {
    let headers = new Headers();
    headers.append("authentication", token );
    let options = new RequestOptions({ headers: headers });

    let final_url = `${this.baseUrl}${url}`

    return this.http.get(final_url, options)
      .map(this.extractData)
      .catch(this.handleError)
  }
}
</code>```

Then I try to get the client that was just set and subscribe to it so that I can detect changes to client in this view and its siblings:

```<code>this.clientService.getClient()
  .subscribe(
    val => {
      console.log(val)
      this.client = val
    },
    err => console.log(err),
    () => {}
)
</code>```

but this call to getClient() never returns an error or anything at all.  What am I doing wrong with my observable?

EDIT:  Here is the component:

```<code>@Component({
  selector: 'page-client-details',
  templateUrl: 'client-details.html',
  providers: [FilterObject, ClientService]
})
export class ClientDetailsPage {
  client:any;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private filterObject: FilterObject,
    public http: Http,
    public modalController: ModalController,
    private clientService: ClientService,
    private app: App
  ) {

  this.clientService.getClient()
    .subscribe(
      val => {
        console.log(val)
        this.client = val
      },
      err => console.log(err),
      () => console.log("completed")
    )
}
</code>```

答:
why are you defining ClientService  in the component class. is ClientService related single component ?

you need provide ClientService in the app.module.ts and inject clientservice in the component class. if you provide clientservice in the component it will create different instance for the component

app.module.ts

```<code> providers: [ ClientService  ],
</code>```

ClientDetailsPage.ts    remove providers: [ ClientService  ]

```<code>{
constructor(clientService  : ClientService  ) {

  }
}
</code>```

Body:
I am trying to use a service to define a shared resource client between several views.  I first select the client from an index and set it:

itemTapped(event, client) {
  this.clientService.get(`/${client.id}?model=client`, this.current_user.auth_token)
    .subscribe(
      data => {
        this.clientService.setClient(data)
        this.navCtrl.push(ClientGenericPage, {
          client_id: data['id'],
          tab: 'profile',
          current_user: this.current_user
        });
      },
      err => {
        this.clientService.handleResponse("Ut oh.. Could not locate the client !"),
        this.clientService.hideLoader()
      },
      () => this.clientService.hideLoader()
    )
}

export class ClientService {

  private client = new Subject<any>();

  constructor (private http: Http, private toastCtrl: ToastController, public storage: Storage ) {

  }

  setClient(client) {
    this.client.next(client)
  }

  getClient() {
    return this.client.asObservable();
  }

  get(url, token):Observable<Response> {
    let headers = new Headers();
    headers.append("authentication", token );
    let options = new RequestOptions({ headers: headers });

    let final_url = `${this.baseUrl}${url}`

    return this.http.get(final_url, options)
      .map(this.extractData)
      .catch(this.handleError)
  }
}

Then I try to get the client that was just set and subscribe to it so that I can detect changes to client in this view and its siblings:

this.clientService.getClient()
  .subscribe(
    val => {
      console.log(val)
      this.client = val
    },
    err => console.log(err),
    () => {}
)

but this call to getClient() never returns an error or anything at all.  What am I doing wrong with my observable?

EDIT:  Here is the component:

@Component({
  selector: 'page-client-details',
  templateUrl: 'client-details.html',
  providers: [FilterObject, ClientService]
})
export class ClientDetailsPage {
  client:any;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private filterObject: FilterObject,
    public http: Http,
    public modalController: ModalController,
    private clientService: ClientService,
    private app: App
  ) {

  this.clientService.getClient()
    .subscribe(
      val => {
        console.log(val)
        this.client = val
      },
      err => console.log(err),
      () => console.log("completed")
    )
}

Body:
why are you defining ClientService  in the component class. is ClientService related single component ?

you need provide ClientService in the app.module.ts and inject clientservice in the component class. if you provide clientservice in the component it will create different instance for the component

app.module.ts

 providers: [ ClientService  ],

ClientDetailsPage.ts    remove providers: [ ClientService  ]

{
constructor(clientService  : ClientService  ) {

  }
}


问:
Scala: short form of pattern matching that returns Boolean
I found myself writing something like this quite often:

```<code>a match {
  case `b` => // do stuff
  case _ => // do nothing
}
</code>```

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

```<code>if (a matches b) // do stuff
</code>```

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

答:
The match operator in Scala is most powerful when used in functional style. This means, rather than "doing something" in the case statements, you would return a useful value. Here is an example for an imperative style:

```<code>var value:Int = 23
val command:String = ... // we get this from somewhere
command match {
  case "duplicate" => value = value * 2
  case "negate" => value = -value
  case "increment" => value = value + 1
  // etc.
  case _ => // do nothing
}
println("Result: " + value)
</code>```

It is very understandable that the "do nothing" above hurts a little, because it seems superflous. However, this is due to the fact that the above is written in imperative style. While constructs like these may sometimes be necessary, in many cases you can refactor your code to functional style:

```<code>val value:Int = 23
val command:String = ... // we get this from somewhere
val result:Int = command match {
   case "duplicate" => value * 2
   case "negate" => -value
   case "increment" => value + 1
   // etc.
   case _ => value
}
println("Result: " + result)
</code>```

In this case, you use the whole match statement as a value that you can, for example, assign to a variable. And it is also much more obvious that the match statement must return a value in any case; if the last case would be missing, the compiler could not just make something up.

It is a question of taste, but some developers consider this style to be more transparent and easier to handle in more real-world examples. I would bet that the inventors of the Scala programming language had a more functional use in mind for match, and indeed the if statement makes more sense if you only need to decide whether or not a certain action needs to be taken. (On the other hand, you can also use if in the functional way, because it also has a return value...)

Body:
I found myself writing something like this quite often:

a match {
  case `b` => // do stuff
  case _ => // do nothing
}

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

if (a matches b) // do stuff

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

Body:
The match operator in Scala is most powerful when used in functional style. This means, rather than "doing something" in the case statements, you would return a useful value. Here is an example for an imperative style:

var value:Int = 23
val command:String = ... // we get this from somewhere
command match {
  case "duplicate" => value = value * 2
  case "negate" => value = -value
  case "increment" => value = value + 1
  // etc.
  case _ => // do nothing
}
println("Result: " + value)

It is very understandable that the "do nothing" above hurts a little, because it seems superflous. However, this is due to the fact that the above is written in imperative style. While constructs like these may sometimes be necessary, in many cases you can refactor your code to functional style:

val value:Int = 23
val command:String = ... // we get this from somewhere
val result:Int = command match {
   case "duplicate" => value * 2
   case "negate" => -value
   case "increment" => value + 1
   // etc.
   case _ => value
}
println("Result: " + result)

In this case, you use the whole match statement as a value that you can, for example, assign to a variable. And it is also much more obvious that the match statement must return a value in any case; if the last case would be missing, the compiler could not just make something up.

It is a question of taste, but some developers consider this style to be more transparent and easier to handle in more real-world examples. I would bet that the inventors of the Scala programming language had a more functional use in mind for match, and indeed the if statement makes more sense if you only need to decide whether or not a certain action needs to be taken. (On the other hand, you can also use if in the functional way, because it also has a return value...)


问:
Javascript variable values changing between two console.log() lines
I'm using Fancytree, and I'm creating a new node using the ExtEdit extension. The title (main text) of the node appears to be set correctly, but the value consistently changes between two console.log() statements and the wrong value is being sent to the server.

What's going on here? This is boggling my mind.

Here's the FancytreeNode API.

This is the full function I'm using:

```<code>function createNode(data) {
    console.log('this is the data object');
    console.log(data);
    console.log('this is data.node.title');
    console.log(data.node.title);
    $.ajax({
        method: 'post',
        data: {
            name: data.node.title,
            parentId: data.node.parent !== undefined ? data.node.parent.key : null
        },
        url: '/my/url'
    }).success(function (thisData, status, jqXHR) {
        data.node.key = thisData.id;
    });
}
</code>```

This is the output. Notice how data.node.title is different.

答: I was able to figure it out from the comment by Nevosis. When an object is logged using console.log(), it is not actually evaluated--it's only a reference. The Fancytree event that causes the function to fire acts a little strangely; data.node.title isn't set to the new value until the event finishes, but I wasn't expanding the object in the console until after that point. data.node.title when logged directly is evaluated (because it has to be), which is why the value was different. I was able to see the correct data object by setting a breakpoint immediately after that console.log().

Body:
I'm using Fancytree, and I'm creating a new node using the ExtEdit extension. The title (main text) of the node appears to be set correctly, but the value consistently changes between two console.log() statements and the wrong value is being sent to the server.

What's going on here? This is boggling my mind.

Here's the FancytreeNode API.

This is the full function I'm using:

function createNode(data) {
    console.log('this is the data object');
    console.log(data);
    console.log('this is data.node.title');
    console.log(data.node.title);
    $.ajax({
        method: 'post',
        data: {
            name: data.node.title,
            parentId: data.node.parent !== undefined ? data.node.parent.key : null
        },
        url: '/my/url'
    }).success(function (thisData, status, jqXHR) {
        data.node.key = thisData.id;
    });
}

This is the output. Notice how data.node.title is different.


问:
To do a sortable column of different links in wicket
I would like to create a table, with a column of links, each link will open a page of the respective object it represents.
For example, the column will display the number of an invoice, which is a link. When we click on one of these links a page is opened displaying the details for that invoice.
I'm trying to do it like this:
I've created a class GuidLinkPanel.java, where I'm putting the ajaxLink

```<code>import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import nl.riskco.liberobc.client.business.model.InvoiceDomain;
import nl.riskco.liberobc.web.pages.details.DetailsPage;

public class GuidLinkPanel extends Panel {

    public GuidLinkPanel(final String id, IModel<InvoiceDomain> invoice)
    {
        super(id);

        add(new AjaxLink<Void>("guid"){

            private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            PageParameters params = new PageParameters();
            params.add("invoiceId", invoice.getObject().getInvoiceGUID());
            setResponsePage(DetailsPage.class, params);
            }
        });
    }
}
</code>```

Its markup

```<code><wicket:panel>
    <wicket:message key="invoice-header">[invoice-header]</wicket:message>
    <a href="#" wicket:id="guid"></a>
</wicket:panel>
</code>```

Now an excerpt of the class where the table is created, I also would like this column to be sortable, so I'm doing this:

```<code>columns.add(new PropertyColumn<InvoiceDomain, String>(new
StringResourceModel("invoice-id-label", this, null), "invoiceGUID",
"invoiceGUID"));

columns.add(new AbstractColumn<InvoiceDomain,String>(new Model<>("Invoice ID"),"invoiceGUID"){
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<InvoiceDomain>> item, String componentId, IModel<InvoiceDomain> rowmodel)
            {
                item.add(new GuidLinkPanel(componentId, rowmodel));
            }
        });
</code>```

The markup

```<code><wicket:panel>
  <div class="panel panel-default">
     <div class="panel-body">
        <div class="table">
         <table wicket:id="invoices-table" class="table table-striped"
</table>
        </div>
     </div>
 </div>
</wicket:panel>
</code>```

The result:

The column is added, but in each line the string

[GuidLinkPanel[Component id=cell]]]

and it is not a link.
Does anyone has a suggestion how to do this?

答:
Your AjaxLink doesn't have a text sub-element, e.g. Some Text to click.

You can do either:

ajaxLink.setBody(Model.of(invoice.getObject().getInvoiceGUID()))

or ajaxLink.add(new Label("linkLabel", invoice.getObject().getInvoiceGUID()). But here you will have to add an HTML element too: <wicket:container wicket:id="linkLabel"/>

Body:
I would like to create a table, with a column of links, each link will open a page of the respective object it represents.
For example, the column will display the number of an invoice, which is a link. When we click on one of these links a page is opened displaying the details for that invoice.
I'm trying to do it like this:
I've created a class GuidLinkPanel.java, where I'm putting the ajaxLink

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import nl.riskco.liberobc.client.business.model.InvoiceDomain;
import nl.riskco.liberobc.web.pages.details.DetailsPage;

public class GuidLinkPanel extends Panel {

    public GuidLinkPanel(final String id, IModel<InvoiceDomain> invoice)
    {
        super(id);

        add(new AjaxLink<Void>("guid"){

            private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            PageParameters params = new PageParameters();
            params.add("invoiceId", invoice.getObject().getInvoiceGUID());
            setResponsePage(DetailsPage.class, params);
            }
        });
    }
}

Its markup

<wicket:panel>
    <wicket:message key="invoice-header">[invoice-header]</wicket:message>

</wicket:panel>

Now an excerpt of the class where the table is created, I also would like this column to be sortable, so I'm doing this:

columns.add(new PropertyColumn<InvoiceDomain, String>(new
StringResourceModel("invoice-id-label", this, null), "invoiceGUID",
"invoiceGUID"));

columns.add(new AbstractColumn<InvoiceDomain,String>(new Model<>("Invoice ID"),"invoiceGUID"){
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<InvoiceDomain>> item, String componentId, IModel<InvoiceDomain> rowmodel)
            {
                item.add(new GuidLinkPanel(componentId, rowmodel));
            }
        });

The markup

<wicket:panel>

         <table wicket:id="invoices-table" class="table table-striped"

</wicket:panel>

The result:

The column is added, but in each line the string

[GuidLinkPanel[Component id=cell]]]

and it is not a link.
Does anyone has a suggestion how to do this?

Body:
Your AjaxLink doesn't have a text sub-element, e.g. <a ...>Some Text to click</a>.

You can do either:

ajaxLink.setBody(Model.of(invoice.getObject().getInvoiceGUID()))

or ajaxLink.add(new Label("linkLabel", invoice.getObject().getInvoiceGUID()). But here you will have to add an HTML element too: <a wicket:id="guid><wicket:container wicket:id="linkLabel"/></a>