问:
SQL query giving error on Oracle database
I'm trying to write a query to list accounts along with current balance, branch no to which it belongs and the average balance of that branch having a balance more than a average balance of the branch to which the account belongs.

The table name is acmaster, columns are acno, currbal, and branchno.

Records:

```<code>acno currbal branchno
1    1000     2
2    2000     2
3    3000     3
4    2000     3
</code>```

I am expecting result like this:

```<code>acno  currbal  branchno   AVG(currbal)
2     2000      2           1500
3     3000      3           2500
</code>```

This is my current query:

```<code>select acno,currbal,branchno,AVG(currbal) abal
from acmaster
group by branchno as bno
having abal < (select currbal from acmaster group by (select branchno from acmaster where branchno=bno));
</code>```

which gets error:

```<code>ORA-00933: SQL command not properly ended
00933. 00000 - "SQL command not properly ended"
*Cause:
*Action:
Error at Line: 3 Column: 19
</code>```

答:
The immediate cause of the error you're getting, as FoxCy mentioned, is the presence of as bno in your group-by clause. The error message is trying to help you there: it refers to line 3 column 19, which is the start of that. SQL Developer even underlines it in red to tell you it's wrong, and I imagine other clients will do something similar.

But you also have columns in your select list which are not aggregates and are not in the group-by; you can't refer to the abal alias in the same level of query it was defined - you would have to  do having avg(currbal) > ... - and by the same token if you added an alias for branchno in the select list instead you couldn't then refer to that either.

Your having clause doesn't make much sense though; the subquery you're trying to compare that average against will get multiple rows, and has an invalid subquery in its own group-by clause. At this point it's probably simpler to start again...

A simplistic way to get the result you want is with something like:

```<code>select a1.acno, a1.currbal, a1.branchno, (
    select avg(a2.currbal)
    from acmaster a2
    where a2.branchno = a1.branchno
    group by a2.branchno
  ) as abal
from acmaster a1
where a1.currbal > (
    select avg(a3.currbal)
    from acmaster a3
    where a3.branchno = a1.branchno
    group by a3.branchno
  );

      ACNO    CURRBAL   BRANCHNO       ABAL
---------- ---------- ---------- ----------
         2       2000          2       1500
         3       3000          3       2500
</code>```

The same subquery is repeated as a column expression in the select list, and in the where clause, which is messy, repetitive, hard to maintain, and hard to follow.

A slightly better option is to get the average once in an inline view and then filter the results from that:

```<code>select * from (
  select a1.acno, a1.currbal, a1.branchno, (
    select avg(a2.currbal)
    from acmaster a2
    where a2.branchno = a1.branchno
    group by a2.branchno) as abal
  from acmaster a1
)
where currbal > abal;
</code>```

Notice that you can now refer to the abal alias, as it is being used in a different level of query to where it was defined.

Oracle also has analytic/window functions to simplify that even more, so you don't need the subquery; if you do:

```<code>select a.acno, a.currbal, a.branchno,
  avg(a.currbal) over (partition by a.branchno) as abal
from acmaster a;

      ACNO    CURRBAL   BRANCHNO       ABAL
---------- ---------- ---------- ----------
         1       1000          2       1500
         2       2000          2       1500
         3       3000          3       2500
         4       2000          3       2500
</code>```

you can see the average for every branch against each row again, and can filter that as an inline view instead:

```<code>select * from (
  select a.acno, a.currbal, a.branchno,
    avg(a.currbal) over (partition by a.branchno) as abal
  from acmaster a
)
where currbal > abal;

      ACNO    CURRBAL   BRANCHNO       ABAL
---------- ---------- ---------- ----------
         2       2000          2       1500
         3       3000          3       2500
</code>```

Body:
I'm trying to write a query to list accounts along with current balance, branch no to which it belongs and the average balance of that branch having a balance more than a average balance of the branch to which the account belongs.

The table name is acmaster, columns are acno, currbal, and branchno.

Records:

acno currbal branchno
1    1000     2
2    2000     2
3    3000     3
4    2000     3

I am expecting result like this:

acno  currbal  branchno   AVG(currbal)
2     2000      2           1500
3     3000      3           2500

This is my current query:

select acno,currbal,branchno,AVG(currbal) abal
from acmaster
group by branchno as bno
having abal < (select currbal from acmaster group by (select branchno from acmaster where branchno=bno));

which gets error:

ORA-00933: SQL command not properly ended
00933. 00000 - "SQL command not properly ended"
*Cause:
*Action:
Error at Line: 3 Column: 19

Body:
The immediate cause of the error you're getting, as FoxCy mentioned, is the presence of as bno in your group-by clause. The error message is trying to help you there: it refers to line 3 column 19, which is the start of that. SQL Developer even underlines it in red to tell you it's wrong, and I imagine other clients will do something similar.

But you also have columns in your select list which are not aggregates and are not in the group-by; you can't refer to the abal alias in the same level of query it was defined - you would have to  do having avg(currbal) > ... - and by the same token if you added an alias for branchno in the select list instead you couldn't then refer to that either.

Your having clause doesn't make much sense though; the subquery you're trying to compare that average against will get multiple rows, and has an invalid subquery in its own group-by clause. At this point it's probably simpler to start again...

A simplistic way to get the result you want is with something like:

select a1.acno, a1.currbal, a1.branchno, (
    select avg(a2.currbal)
    from acmaster a2
    where a2.branchno = a1.branchno
    group by a2.branchno
  ) as abal
from acmaster a1
where a1.currbal > (
    select avg(a3.currbal)
    from acmaster a3
    where a3.branchno = a1.branchno
    group by a3.branchno
  );

      ACNO    CURRBAL   BRANCHNO       ABAL
---------- ---------- ---------- ----------
         2       2000          2       1500
         3       3000          3       2500

The same subquery is repeated as a column expression in the select list, and in the where clause, which is messy, repetitive, hard to maintain, and hard to follow.

A slightly better option is to get the average once in an inline view and then filter the results from that:

select * from (
  select a1.acno, a1.currbal, a1.branchno, (
    select avg(a2.currbal)
    from acmaster a2
    where a2.branchno = a1.branchno
    group by a2.branchno) as abal
  from acmaster a1
)
where currbal > abal;

Notice that you can now refer to the abal alias, as it is being used in a different level of query to where it was defined.

Oracle also has analytic/window functions to simplify that even more, so you don't need the subquery; if you do:

select a.acno, a.currbal, a.branchno,
  avg(a.currbal) over (partition by a.branchno) as abal
from acmaster a;

      ACNO    CURRBAL   BRANCHNO       ABAL
---------- ---------- ---------- ----------
         1       1000          2       1500
         2       2000          2       1500
         3       3000          3       2500
         4       2000          3       2500

you can see the average for every branch against each row again, and can filter that as an inline view instead:

select * from (
  select a.acno, a.currbal, a.branchno,
    avg(a.currbal) over (partition by a.branchno) as abal
  from acmaster a
)
where currbal > abal;

      ACNO    CURRBAL   BRANCHNO       ABAL
---------- ---------- ---------- ----------
         2       2000          2       1500
         3       3000          3       2500


来源: stackexchange

问:
Passing struct with char* to C++ dll function in C#
I'm using a C++ dll in C# and have problems with passing char* to it and back.

First of all the function looks the following:

```<code>[DllImport("xyz.dll")]
public static extern int ReadWrite_VCP(IntPtr handle, ref DATA_BUFFER readBuffer, ref DATA_BUFFER writeBuffer, int timeout);
</code>```

The struct is defined as:

```<code>public struct DATA_BUFFER
{
    public string buffer;
    [MarshalAs(UnmanagedType.U4)]
    public int length;
    [MarshalAs(UnmanagedType.U4)]
    public int transferCount;
}
</code>```

The function call is:

```<code>ReadWrite_VCP(handle, ref rBuffer, ref wrBuffer, 5000);
</code>```

In general this works fine, but the problem is, that the ReadWrite_VCP function writes a char array (including '\0' characters). This results in the problem that if the data is '\0' '1' '2' '3' , The string is empty as it is terminated by '\0'.

I've already tried to use Stringbuilder or byte array, without any success.

On C++ Side the function looks like:

```<code>typedef struct
{
    UCHAR *buffer;
    UINT32 length;
    UINT32 transferCount;
} DATA_BUFFER ;
</code>```

And the Function:

```<code>unsigned int ReadWrite_VCP (HANDLE handle, DATA_BUFFER* ReadBuffer, DATA_BUFFER* writeBuffer, UINT32 timeout);
</code>```

I hope anyone can help me!

Thank you!

答:
Yes you were totally right!

my struct changed to:

```<code>        public struct DATA_BUFFER
    {
        public IntPtr  buffer;
        [MarshalAs(UnmanagedType.U4)]
        public int length;
        [MarshalAs(UnmanagedType.U4)]
        public int transferCount;
    }
</code>```

and before I call the function a allocate a Byte array and set the pointer to it

```<code> buf.length = 10;
 byte[] input = new byte[buf.length];
 buf.buffer = Marshal.UnsafeAddrOfPinnedArrayElement(input, 0);
</code>```

Thank you!

ContentLicense: CC BY-SA 3.0

Body:
I'm using a C++ dll in C# and have problems with passing char* to it and back.

First of all the function looks the following:

[DllImport("xyz.dll")]
public static extern int ReadWrite_VCP(IntPtr handle, ref DATA_BUFFER readBuffer, ref DATA_BUFFER writeBuffer, int timeout);

The struct is defined as:

public struct DATA_BUFFER
{
    public string buffer;
    [MarshalAs(UnmanagedType.U4)]
    public int length;
    [MarshalAs(UnmanagedType.U4)]
    public int transferCount;
}

The function call is:

ReadWrite_VCP(handle, ref rBuffer, ref wrBuffer, 5000);

In general this works fine, but the problem is, that the ReadWrite_VCP function writes a char array (including '\0' characters). This results in the problem that if the data is '\0' '1' '2' '3' , The string is empty as it is terminated by '\0'.

I've already tried to use Stringbuilder or byte array, without any success.

On C++ Side the function looks like:

typedef struct
{
    UCHAR *buffer;
    UINT32 length;
    UINT32 transferCount;
} DATA_BUFFER ;

And the Function:

unsigned int ReadWrite_VCP (HANDLE handle, DATA_BUFFER* ReadBuffer, DATA_BUFFER* writeBuffer, UINT32 timeout);

I hope anyone can help me!

Thank you!

Body:
Yes you were totally right!

my struct changed to:

        public struct DATA_BUFFER
    {
        public IntPtr  buffer;
        [MarshalAs(UnmanagedType.U4)]
        public int length;
        [MarshalAs(UnmanagedType.U4)]
        public int transferCount;
    }

and before I call the function a allocate a Byte array and set the pointer to it

 buf.length = 10;
 byte[] input = new byte[buf.length];
 buf.buffer = Marshal.UnsafeAddrOfPinnedArrayElement(input, 0);

Thank you!


问:
HTML & CSS - How to place DIVs next to each other on the same line?
I'm building a chat interface, and my task is now to add a date between messages. The date must be centered, and messages must be traditionally on the left and right.

Messages are working correctly, but dates are a problem.

How it looks:

Chat is divided by sections. Each section has a date. Each section can have multiply messages.

Code of section is following:

```<code>        <div>
            <div class="discussionMessageDate">{date here}</div>
            <ul className="noDot">
                <li className="noDot + ..logic to figure out if to apple 'right' class"><span class="discussionMessage">{message}</span></li>
            </ul>
        </div>
</code>```

classes are

```<code>.discussionMessage {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 13px;
  list-style-type: none;
  max-width: 300px;
  float: left;
  clear: both;
}

.discussionMessageDate {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 13px;
  max-width: 300px;
  display: block
}

.noDot {
  list-style-type: none;
  padding: 0;
  margin: 0 0 5px 0;
}

.right {
   float: right;
  clear: both;
}
</code>```

What am I doing wrong?

答:
You shoud add the "text-align: center;" property to your "discussionMessageDate" class, in order to center the text. A div displays its content aligned to the left, by default.

Also, I imagine you need to specify the max size of the container also, to 300px, otherwise, your list will spread across your screen, meanwhile, your date has a fixed size.

And you need to clear your float, because otherwise the parent of the floated element loses its height.

Like this:

```<code>body{
    max-width: 300px;
}
.discussionMessageDate {
    background: rgba(255, 255, 255, 0.8);
    border-radius: 10px;
    padding: 5px 13px;
    max-width: 300px;
    display: block;
    text-align: center;
}

.clearer{
    clear: both;
}

<div>
    <div class="discussionMessageDate">{date here}</div>
        <ul class="noDot">
            <li class="right"><span class="discussionMessage">{message}</span></li>
            <li class=""><span class="discussionMessage">{message}</span></li>
            <li class="right"><span class="discussionMessage">{message}</span></li>
        </ul>
    </div>
    <div class="clearer"></div>
    <div>
        <div class="discussionMessageDate">{date here}</div>
            <ul class="noDot">
                <li class="noDot + ..logic to figure out if to apple 'right' class"><span class="discussionMessage">{message}</span></li>
            </ul>
        </div>
    </div>
</code>```

Body:
I'm building a chat interface, and my task is now to add a date between messages. The date must be centered, and messages must be traditionally on the left and right.

Messages are working correctly, but dates are a problem.

How it looks:

Chat is divided by sections. Each section has a date. Each section can have multiply messages.

Code of section is following:

{date here}

{message}

classes are

.discussionMessage {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 13px;
  list-style-type: none;
  max-width: 300px;
  float: left;
  clear: both;
}

.discussionMessageDate {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 13px;
  max-width: 300px;
  display: block
}

.noDot {
  list-style-type: none;
  padding: 0;
  margin: 0 0 5px 0;
}

.right {
   float: right;
  clear: both;
}

What am I doing wrong?

Body:
You shoud add the "text-align: center;" property to your "discussionMessageDate" class, in order to center the text. A div displays its content aligned to the left, by default.

Also, I imagine you need to specify the max size of the container also, to 300px, otherwise, your list will spread across your screen, meanwhile, your date has a fixed size.

And you need to clear your float, because otherwise the parent of the floated element loses its height.

Like this:

body{
    max-width: 300px;
}
.discussionMessageDate {
    background: rgba(255, 255, 255, 0.8);
    border-radius: 10px;
    padding: 5px 13px;
    max-width: 300px;
    display: block;
    text-align: center;
}

.clearer{
    clear: both;
}

<div>
    <div class="discussionMessageDate">{date here}</div>
        <ul class="noDot">
            <li class="right"><span class="discussionMessage">{message}</span></li>
            <li class=""><span class="discussionMessage">{message}</span></li>
            <li class="right"><span class="discussionMessage">{message}</span></li>
        </ul>
    </div>
    <div class="clearer"></div>
    <div>
        <div class="discussionMessageDate">{date here}</div>
            <ul class="noDot">
                <li class="noDot + ..logic to figure out if to apple 'right' class"><span class="discussionMessage">{message}</span></li>
            </ul>
        </div>
    </div>


问:
R - function cgarchspec working well alone but not in apply function
I want to run an apply function that is using different multivariate GARCH models with more and more data. To run the GARCH model, I need to run the cgarchspec function determining the number of variables I will fit afterwards. For some reason, the following apply function doesn't work

```<code>library(rmgarch)
func.garch.i <- function(x) {
cgarch11spec.loop <- cgarchspec(uspec =multispec(replicate(x,garch11.spec)), VAR = TRUE, robust = FALSE, lag = 1, lag.max = NULL,
                              lag.criterion = c("AIC", "HQ", "SC", "FPE"), external.regressors = NULL,
                              robust.control = list(gamma = 0.25, delta = 0.01, nc = 10, ns = 500),
                              dccOrder = c(1, 1), asymmetric = FALSE,
                              distribution.model = list(copula = c("mvnorm"),
                                                        method = c("Kendall"), time.varying = TRUE,
                                                        transformation = c("parametric")),
                              start.pars = list(), fixed.pars = list())
}
nb <- seq(2,3)
apply(nb, func.garch.i(x))
</code>```

Argument garch11.spec being defined as followed:

```<code>garch11.spec = ugarchspec(mean.model = list(armaOrder = c(0,0)),
                        variance.model = list(garchOrder = c(1,1),
                                              model = "sGARCH"),
                        distribution.model = "norm")
</code>```

But if I try to run func.garch.i(2) for example, it works well... Why is the function not working in the apply function?

答:
For those who might have the same issue, I finally found the solution. The function multispec has to be isolated and computed before:

```<code>func.garch.i <- function(x) {
uspec <- multispec(replicate(x,garch11.spec))
cgarch11spec.loop <- cgarchspec(uspec, VAR = TRUE, robust = FALSE, lag = 1, lag.max = NULL,
                              lag.criterion = c("AIC", "HQ", "SC", "FPE"), external.regressors = NULL,
                              robust.control = list(gamma = 0.25, delta = 0.01, nc = 10, ns = 500),
                              dccOrder = c(1, 1), asymmetric = FALSE,
                              distribution.model = list(copula = c("mvnorm"),
                                                        method = c("Kendall"), time.varying = TRUE,
                                                        transformation = c("parametric")),
                              start.pars = list(), fixed.pars = list())
}
</code>```

Body:
I want to run an apply function that is using different multivariate GARCH models with more and more data. To run the GARCH model, I need to run the cgarchspec function determining the number of variables I will fit afterwards. For some reason, the following apply function doesn't work

library(rmgarch)
func.garch.i <- function(x) {
cgarch11spec.loop <- cgarchspec(uspec =multispec(replicate(x,garch11.spec)), VAR = TRUE, robust = FALSE, lag = 1, lag.max = NULL,
                              lag.criterion = c("AIC", "HQ", "SC", "FPE"), external.regressors = NULL,
                              robust.control = list(gamma = 0.25, delta = 0.01, nc = 10, ns = 500),
                              dccOrder = c(1, 1), asymmetric = FALSE,
                              distribution.model = list(copula = c("mvnorm"),
                                                        method = c("Kendall"), time.varying = TRUE,
                                                        transformation = c("parametric")),
                              start.pars = list(), fixed.pars = list())
}
nb <- seq(2,3)
apply(nb, func.garch.i(x))

Argument garch11.spec being defined as followed:

garch11.spec = ugarchspec(mean.model = list(armaOrder = c(0,0)),
                        variance.model = list(garchOrder = c(1,1),
                                              model = "sGARCH"),
                        distribution.model = "norm")

But if I try to run func.garch.i(2) for example, it works well... Why is the function not working in the apply function?

Body:
For those who might have the same issue, I finally found the solution. The function multispec has to be isolated and computed before:

func.garch.i <- function(x) {
uspec <- multispec(replicate(x,garch11.spec))
cgarch11spec.loop <- cgarchspec(uspec, VAR = TRUE, robust = FALSE, lag = 1, lag.max = NULL,
                              lag.criterion = c("AIC", "HQ", "SC", "FPE"), external.regressors = NULL,
                              robust.control = list(gamma = 0.25, delta = 0.01, nc = 10, ns = 500),
                              dccOrder = c(1, 1), asymmetric = FALSE,
                              distribution.model = list(copula = c("mvnorm"),
                                                        method = c("Kendall"), time.varying = TRUE,
                                                        transformation = c("parametric")),
                              start.pars = list(), fixed.pars = list())
}


问:
Android emulator reboots if I try to fix the gps coordinates
I've created a virtual device with the 2.3 platform (api level 9) and I just launched it and tried to fix GPS location via telnet, as follows:

```<code>telnet localhost 5554
geo fix 41.41 174.64
</code>```

The emulator returns an "OK" message as the output of my command, and I am simply trying to see if the Google Maps/Latitude app will be able to see these coordinates as my location, but when I load them they will simply reboot the emulator (actually the OS does not come back, I have to close the emulator and launch it again).

Am I doing anything wrong or is there a bug in the emulator?

答: This is a bug in the emulator. The issue tracker entry has some more information.</p>

ContentLicense: CC BY-SA 2.5

Body:
I've created a virtual device with the 2.3 platform (api level 9) and I just launched it and tried to fix GPS location via telnet, as follows:

telnet localhost 5554
geo fix 41.41 174.64

The emulator returns an "OK" message as the output of my command, and I am simply trying to see if the Google Maps/Latitude app will be able to see these coordinates as my location, but when I load them they will simply reboot the emulator (actually the OS does not come back, I have to close the emulator and launch it again).

Am I doing anything wrong or is there a bug in the emulator?


问:
Rotating an image matrix around its center in MATLAB
Assume I have a 2x2 matrix filled with values which will represent a plane. Now I want to rotate the plane around itself in a 3-D way, in the "z-Direction". For a better understanding, see the following image:

I wondered if this is possible by a simple affine matrix, thus I created the following simple script:

```<code>%Create a random value matrix
A = rand*ones(200,200);

%Make a box in the image
A(50:200-50,50:200-50) = 1;
</code>```

Now I can apply transformations in the 2-D room simply by a rotation matrix like this:

```<code>R = affine2d([1 0 0; .5 1 0; 0 0 1])
tform = affine3d(R);
transformed = imwarp(A,tform);
</code>```

However, this will not produce the desired output above, and I am not quite sure how to create the 2-D affine matrix to create such behavior.

I guess that a 3-D affine matrix can do the trick. However, if I define a 3-D affine matrix I cannot work with the 2-D representation of the matrix anymore, since MATLAB will throw the error:

```<code>The number of dimensions of the input image A must be 3 when the
specified geometric transformation is 3-D.
</code>```

So how can I code the desired output with an affine matrix?

答:
The answer from m3tho correctly addresses how you would apply the transformation you want: using fitgeotrans with a 'projective' transform, thus requiring that you specify 4 control points (i.e. 4 pairs of corresponding points in the input and output image). You can then apply this transform using imwarp.

The issue, then, is how you select these pairs of points to create your desired transformation, which in this case is to create a perspective projection. As shown below, a perspective projection takes into account that a viewing position (i.e. "camera") will have a given view angle defining a conic field of view. The scene is rendered by taking all 3-D points within this cone and projecting them onto the viewing plane, which is the plane located at the camera target which is perpendicular to the line joining the camera and its target.

Let's first assume that your image is lying in the viewing plane and that the corners are described by a normalized reference frame such that they span [-1 1] in each direction. We need to first select the degree of perspective we want by choosing a view angle and then computing the distance between the camera and the viewing plane. A view angle of around 45 degrees can mimic the sense of perspective of normal human sight, so using the corners of the viewing plane to define the edge of the conic field of view, we can compute the camera distance as follows:

```<code>camDist = sqrt(2)./tand(viewAngle./2);
</code>```

Now we can use this to generate a set of control points for the transformation. We first apply a 3-D rotation to the corner points of the viewing plane, rotating around the y axis by an amount theta. This rotates them out of plane, so we now project the corner points back onto the viewing plane by defining a line from the camera through each rotated corner point and finding the point where it intersects the plane. I'm going to spare you the mathematical derivations (you can implement them yourself from the formulas in the above links), but in this case everything simplifies down to the following set of calculations:

```<code>term1 = camDist.*cosd(theta);
term2 = camDist-sind(theta);
term3 = camDist+sind(theta);
outP = [-term1./term2  camDist./term2; ...
         term1./term3  camDist./term3; ...
         term1./term3 -camDist./term3; ...
        -term1./term2 -camDist./term2];
</code>```

And outP now contains your normalized set of control points in the output image. Given an image of size s, we can create a set of input and output control points as follows:

```<code>scaledInP = [1 s(1); s(2) s(1); s(2) 1; 1 1];
scaledOutP = bsxfun(@times, outP+1, s([2 1])-1)./2+1;
</code>```

And you can apply the transformation like so:

```<code>tform = fitgeotrans(scaledInP, scaledOutP, 'projective');
outputView = imref2d(s);
newImage = imwarp(oldImage, tform, 'OutputView', outputView);
</code>```

The only issue you may come across is that a rotation of 90 degrees (i.e. looking end-on at the image plane) would create a set of collinear points that would cause fitgeotrans to error out. In such a case, you would technically just want a blank image, because you can't see a 2-D object when looking at it edge-on.

Here's some code illustrating the above transformations by animating a spinning image:

```<code>img = imread('peppers.png');
s = size(img);
outputView = imref2d(s);
scaledInP = [1 s(1); s(2) s(1); s(2) 1; 1 1];
viewAngle = 45;
camDist = sqrt(2)./tand(viewAngle./2);

for theta = linspace(0, 360, 360)
  term1 = camDist.*cosd(theta);
  term2 = camDist-sind(theta);
  term3 = camDist+sind(theta);
  outP = [-term1./term2  camDist./term2; ...
           term1./term3  camDist./term3; ...
           term1./term3 -camDist./term3; ...
          -term1./term2 -camDist./term2];
  scaledOutP = bsxfun(@times, outP+1, s([2 1])-1)./2+1;
  tform = fitgeotrans(scaledInP, scaledOutP, 'projective');
  spinImage = imwarp(img, tform, 'OutputView', outputView);
  if (theta == 0)
    hImage = image(spinImage);
    set(gca, 'Visible', 'off');
  else
    set(hImage, 'CData', spinImage);
  end
  drawnow;
end
</code>```

And here's the animation:

Body:
Assume I have a 2x2 matrix filled with values which will represent a plane. Now I want to rotate the plane around itself in a 3-D way, in the "z-Direction". For a better understanding, see the following image:

I wondered if this is possible by a simple affine matrix, thus I created the following simple script:

%Create a random value matrix
A = rand*ones(200,200);

%Make a box in the image
A(50:200-50,50:200-50) = 1;

Now I can apply transformations in the 2-D room simply by a rotation matrix like this:

R = affine2d([1 0 0; .5 1 0; 0 0 1])
tform = affine3d(R);
transformed = imwarp(A,tform);

However, this will not produce the desired output above, and I am not quite sure how to create the 2-D affine matrix to create such behavior.

I guess that a 3-D affine matrix can do the trick. However, if I define a 3-D affine matrix I cannot work with the 2-D representation of the matrix anymore, since MATLAB will throw the error:

The number of dimensions of the input image A must be 3 when the
specified geometric transformation is 3-D.

So how can I code the desired output with an affine matrix?

Body:
The answer from m3tho correctly addresses how you would apply the transformation you want: using fitgeotrans with a 'projective' transform, thus requiring that you specify 4 control points (i.e. 4 pairs of corresponding points in the input and output image). You can then apply this transform using imwarp.

The issue, then, is how you select these pairs of points to create your desired transformation, which in this case is to create a perspective projection. As shown below, a perspective projection takes into account that a viewing position (i.e. "camera") will have a given view angle defining a conic field of view. The scene is rendered by taking all 3-D points within this cone and projecting them onto the viewing plane, which is the plane located at the camera target which is perpendicular to the line joining the camera and its target.

Let's first assume that your image is lying in the viewing plane and that the corners are described by a normalized reference frame such that they span [-1 1] in each direction. We need to first select the degree of perspective we want by choosing a view angle and then computing the distance between the camera and the viewing plane. A view angle of around 45 degrees can mimic the sense of perspective of normal human sight, so using the corners of the viewing plane to define the edge of the conic field of view, we can compute the camera distance as follows:

camDist = sqrt(2)./tand(viewAngle./2);

Now we can use this to generate a set of control points for the transformation. We first apply a 3-D rotation to the corner points of the viewing plane, rotating around the y axis by an amount theta. This rotates them out of plane, so we now project the corner points back onto the viewing plane by defining a line from the camera through each rotated corner point and finding the point where it intersects the plane. I'm going to spare you the mathematical derivations (you can implement them yourself from the formulas in the above links), but in this case everything simplifies down to the following set of calculations:

term1 = camDist.*cosd(theta);
term2 = camDist-sind(theta);
term3 = camDist+sind(theta);
outP = [-term1./term2  camDist./term2; ...
         term1./term3  camDist./term3; ...
         term1./term3 -camDist./term3; ...
        -term1./term2 -camDist./term2];

And outP now contains your normalized set of control points in the output image. Given an image of size s, we can create a set of input and output control points as follows:

scaledInP = [1 s(1); s(2) s(1); s(2) 1; 1 1];
scaledOutP = bsxfun(@times, outP+1, s([2 1])-1)./2+1;

And you can apply the transformation like so:

tform = fitgeotrans(scaledInP, scaledOutP, 'projective');
outputView = imref2d(s);
newImage = imwarp(oldImage, tform, 'OutputView', outputView);

The only issue you may come across is that a rotation of 90 degrees (i.e. looking end-on at the image plane) would create a set of collinear points that would cause fitgeotrans to error out. In such a case, you would technically just want a blank image, because you can't see a 2-D object when looking at it edge-on.

Here's some code illustrating the above transformations by animating a spinning image:

img = imread('peppers.png');
s = size(img);
outputView = imref2d(s);
scaledInP = [1 s(1); s(2) s(1); s(2) 1; 1 1];
viewAngle = 45;
camDist = sqrt(2)./tand(viewAngle./2);

for theta = linspace(0, 360, 360)
  term1 = camDist.*cosd(theta);
  term2 = camDist-sind(theta);
  term3 = camDist+sind(theta);
  outP = [-term1./term2  camDist./term2; ...
           term1./term3  camDist./term3; ...
           term1./term3 -camDist./term3; ...
          -term1./term2 -camDist./term2];
  scaledOutP = bsxfun(@times, outP+1, s([2 1])-1)./2+1;
  tform = fitgeotrans(scaledInP, scaledOutP, 'projective');
  spinImage = imwarp(img, tform, 'OutputView', outputView);
  if (theta == 0)
    hImage = image(spinImage);
    set(gca, 'Visible', 'off');
  else
    set(hImage, 'CData', spinImage);
  end
  drawnow;
end

And here's the animation:


问:
Error while applying OOPM in python
First of all I am new to python programming.
Here is my code:-

```<code>class login_ok(object):
    """docstring for instalogin"""
 def __init__(self):
 pass

def open_website(self,websiteName):
print(websiteName)

def login(self,email,password):
print(email)

def search(self,searchVariable):
print(searchVariable)

login1 = login_ok()
web = "a"
email_pass = "c"
password_pass = "b"
search_variable = "d"
login1.open_website(web)
login1.login(email_pass,password_pass)
login1.search(search_variable)
</code>```

I am using sublime and i am getting this error 'login_ok' object has no attribute 'open_website' .

答:
Welcome to the world of Python.

You have some basic indentation problems, which are fundamental to how Python works. I'd recommend you going through some tutorials and learning stages to help get the basics right.

Here's a link to a good place to start:
http://docs.python-guide.org/en/latest/intro/learning/

And by way of example, here are just a couple of examples of fixed errors:

```<code>class login_ok(object):
    """docstring for instalogin"""
    def __init__(self):
        # For example, all the code defined within a method or function is indented.
        pass

    # Similarly, all methods defined 'within' a class need to be indented four spaces.
    def open_website(self,websiteName):
        # Through proper indentation, you're telling the Python interpreter
        # that `open_website` is a method of the parent `login_ok` class
        print(websiteName)
</code>```

Title: Error while applying OOPM in python

Body:
First of all I am new to python programming.
Here is my code:-

class login_ok(object):
    """docstring for instalogin"""
 def __init__(self):
 pass

def open_website(self,websiteName):
print(websiteName)

def login(self,email,password):
print(email)

def search(self,searchVariable):
print(searchVariable)

login1 = login_ok()
web = "a"
email_pass = "c"
password_pass = "b"
search_variable = "d"
login1.open_website(web)
login1.login(email_pass,password_pass)
login1.search(search_variable)

I am using sublime and i am getting this error 'login_ok' object has no attribute 'open_website' .

Body:
Welcome to the world of Python.

You have some basic indentation problems, which are fundamental to how Python works. I'd recommend you going through some tutorials and learning stages to help get the basics right.

Here's a link to a good place to start:
http://docs.python-guide.org/en/latest/intro/learning/

And by way of example, here are just a couple of examples of fixed errors:

class login_ok(object):
    """docstring for instalogin"""
    def __init__(self):
        # For example, all the code defined within a method or function is indented.
        pass

    # Similarly, all methods defined 'within' a class need to be indented four spaces.
    def open_website(self,websiteName):
        # Through proper indentation, you're telling the Python interpreter
        # that `open_website` is a method of the parent `login_ok` class
        print(websiteName)


问:
How to shift slice in go template?
I'm using confd to populate a file through a template.

In this file, I want to have a list of elements shifted and inserted.
This slice contains strings like

```<code>0=container-1
1=container-2
2=container-3
3=container-4
</code>```

(in fact, it is a string that I split using split confd function).
 I want, on each container, be able to filter container name out and shift the list to have the ones after my container appear first.

As an example, on container-2 I would like to have as result

```<code>2=container-3
3=container-4
0=container-1
</code>```

How to do that in a confd go template ? I think I know how to do that in go (but I'm not that good in that particular language), but I don't find how to do that using only a template ...

答:
If you are unable to manipulate the slice/string outside the template, and if you are unable to add custom functions to the template either you will have do this inside the template. It's more verbose, but doable.

One approach is to have two loops nested inside a parent loop. The parent will look for the container you want to leave out, at which point it will spawn the two child loops with $i holding the index of the one to be left out. The first child loop can then list containers whose index is greater than $i and the second child loop will list containers whose index is less than $i.

```<code>{{range $i, $c := $cons}}
    {{/* find item to be skipped */}}
    {{if (eq $c $.Skip)}}

        {{range $j, $c := $cons}}
            {{/* list items that come after the one to be skipped */}}
            {{if (gt $j $i)}}
                {{$c}}
            {{end}}
        {{end}}

        {{range $j, $c := $cons}}
            {{/* list items that come before the one to be skipped */}}
            {{if (lt $j $i)}}
                {{$c}}
            {{end}}
        {{end}}

    {{end}}
{{end}}
</code>```

https://play.golang.org/p/lGdExfHAvy

Title: How to shift slice in go template?

Body:
I'm using confd to populate a file through a template.

In this file, I want to have a list of elements shifted and inserted.
This slice contains strings like

0=container-1
1=container-2
2=container-3
3=container-4

(in fact, it is a string that I split using split confd function).
 I want, on each container, be able to filter container name out and shift the list to have the ones after my container appear first.

As an example, on container-2 I would like to have as result

2=container-3
3=container-4
0=container-1

How to do that in a confd go template ? I think I know how to do that in go (but I'm not that good in that particular language), but I don't find how to do that using only a template ...

Body:
If you are unable to manipulate the slice/string outside the template, and if you are unable to add custom functions to the template either you will have do this inside the template. It's more verbose, but doable.

One approach is to have two loops nested inside a parent loop. The parent will look for the container you want to leave out, at which point it will spawn the two child loops with $i holding the index of the one to be left out. The first child loop can then list containers whose index is greater than $i and the second child loop will list containers whose index is less than $i.

{{range $i, $c := $cons}}
    {{/* find item to be skipped */}}
    {{if (eq $c $.Skip)}}

        {{range $j, $c := $cons}}
            {{/* list items that come after the one to be skipped */}}
            {{if (gt $j $i)}}
                {{$c}}
            {{end}}
        {{end}}

        {{range $j, $c := $cons}}
            {{/* list items that come before the one to be skipped */}}
            {{if (lt $j $i)}}
                {{$c}}
            {{end}}
        {{end}}

    {{end}}
{{end}}

https://play.golang.org/p/lGdExfHAvy


问:
summernote table add row
I've just worked my way through a summernote configuration only to find at the last minute that once you insert a table, it's not possible to change the number of rows or columns. And the editor only supports tables up to 10x10.

For me this makes the table editor in summernote redundant. This issue is reported at https://github.com/summernote/summernote/issues/93

However, there doesn't seem to be any progress on fixing it. Summernote has a lot of forks - has anybody forked and fixed this issue?

答:
Try following code. </p>

```<code>  $('#summer-note').summernote({
   // insertTable max size
   insertTableMaxSize: {
     col: 20,
     row: 20
   },
 });
</code>```

Title: summernote table add row

Body:
Try following code.

  $('#summer-note').summernote({
   // insertTable max size
   insertTableMaxSize: {
     col: 20,
     row: 20
   },
 });


问:
Where does software protection store its data?
I am in the process of exploring the software protection schemes for my company. Sure enough, there are so many alternatives and almost all of them give a facility to limit:

Number of usage (executions)

Number of days

Now if I think about it, there must be some place in computer where "number of times the application has been used" or "number of days it has been used for" is stored. Here I assume that an application protected using one of these mechanism would NOT require it to run with Administrative privileges. And I understand that an application with normal user rights cannot modify a place which affects other users. Which would mean that if an application is expired for user A, it will still run for user B (which looks foolish enough). I wonder what place these schemes can possibly hide their information in to make it work?

答:
Software protections store time trial info either into the registry or into a file. You can use programs such as registry and file monitor in order to have a quick idea about the attempts of reading this data from the registry or from a file.
Another way is through reverse engineering. With the use of a debugger you can place breakpoints on the well known win APis that are used for this scope such as RegOpenKeyEx/RegQueryValueEx for reading data from the registry and CreateFile/ReadFile/GetFileSize etc in order to read info from a file.
You should consider reading the documentation of those API onto the MSDN.</p>

OwnerDisplayName: Hemant Jangid

LastEditorDisplayName: Hemant Jangid


问:
How to write a value into access database faster - VBA (excel)
I am trying to store the values inside an access database from excel using vba.

I have a form in Excel where I get the Inputs from the User.

On VBA, In the Locals window, I could see the values assigned to the object as below,

```<code>Name = Mike
Age = 23
Occupation = Student
</code>```

On the Access database, I have a table called as UserTable which has columns called as ID, Name, Age, Occupation and now how do I pass the values from VBA to Access database.

I would want to add the value record by record and faster at the same time.

Here is where I am getting the error

```<code>strSQL = "PARAMETERS [Name] TEXT(255), [Age] INTEGER, [Occupation] TEXT(255);" _
               & " INSERT INTO UserTable([User Name], [User Age], [User Occupation]);"
</code>```

Please help me with this on my learning.

答:
Create a reference to the ADO recordset library

create and open a Connection object to the access database

```<code> Dim Conn as new adodb.connection
  conn.connectionstring = "google for connection string here"
  conn.open
</code>```

create a string holding an append query (watch out: you need commas between fields and ' around strings)

```<code>Dim strSQL as string
StrSql = "INSERT INTO [Usertable] ( Name, Age, Occupation ) "
strsql = strsql & "Values('" & me.Name & "'," & me.age & ",'" & me.occupation & "')"
</code>```

Use EXECUTE to run this string

```<code>conn.execute  strsql
</code>```

Body:
I am trying to store the values inside an access database from excel using vba.

I have a form in Excel where I get the Inputs from the User.

On VBA, In the Locals window, I could see the values assigned to the object as below,

Name = Mike
Age = 23
Occupation = Student

On the Access database, I have a table called as UserTable which has columns called as ID, Name, Age, Occupation and now how do I pass the values from VBA to Access database.

I would want to add the value record by record and faster at the same time.

Here is where I am getting the error

strSQL = "PARAMETERS [Name] TEXT(255), [Age] INTEGER, [Occupation] TEXT(255);" _
               & " INSERT INTO UserTable([User Name], [User Age], [User Occupation]);"

Please help me with this on my learning.

Body:
Create a reference to the ADO recordset library

create and open a Connection object to the access database

 Dim Conn as new adodb.connection
  conn.connectionstring = "google for connection string here"
  conn.open

create a string holding an append query (watch out: you need commas between fields and ' around strings)

Dim strSQL as string
StrSql = "INSERT INTO [Usertable] ( Name, Age, Occupation ) "
strsql = strsql & "Values('" & me.Name & "'," & me.age & ",'" & me.occupation & "')"

Use EXECUTE to run this string

conn.execute  strsql


问:
.Click in a Onchange not working on Mac OS but works on Windows/linux
so I have an HTML part which is like

```<code><select name="espece-prise" id="espece-prise" size="1" onchange="selectespece();">
    <option value="{liste.espece}">{liste.espece}</option>
</select>
</code>```

then I have an input type='file' in order to upload an image, this input is hidden and has the class 'btn_poster_photo'.

What I want

when the user uses the select (and click on an option) it triggers the 'onchange' and through the 'selectespece()' function a click on the hidden button thanks to the .Click function in selectespece().So after all these js function the result is:

select an option => it opens a window where you choose the file to upload

What I did

```<code>function selectespece() {
    especeprise = $("#espece-prise").val();  //just a variable getting the value of my select (it works)
    document.getElementById("btn_poster_photo").click();
}
</code>```

I also did it in many different ways with jQuery

```<code>$("#espece-prise").on('change', function(){
    especeprise = $("#espece-prise").val();
    $(".btn_poster_photo").click();
})
</code>```

What is happening?

When I select an option it triggers the click so it asks me to upload an image which is alright. This works on Chrome/Firefox/Opera... when I do it from a Windows/Ubuntu/archlinux computer

BUT

When I try it on safari/chrome from a MacOS it doesn't work, no error in console, I just select something and nothing happens. I tried to put an alert in my function 'onchange' it works, all works but not the .Click function...

I made several searches on Google but only found a few topics talking about an onclick after an onchange but not a .click in an onchange.

答:
You can only programmatically trigger a file dialog window from a user-initiated event.

https://blog.mariusschulz.com/2016/05/31/programmatically-opening-a-file-dialog-with-javascript

In this case, I'm not sure if a change event would count, as typically a user-initiated event would be something like click, mousedown, mouseup, scroll, resize, keyup, etc.

Perhaps try to refactor to react to one of the above events (from your <select>) instead.

ContentLicense: CC BY-SA 4.0

Body:
so I have an HTML part which is like

<select name="espece-prise" id="espece-prise" size="1" onchange="selectespece();">
    <option value="{liste.espece}">{liste.espece}</option>
</select>

then I have an input type='file' in order to upload an image, this input is hidden and has the class 'btn_poster_photo'.

What I want

when the user uses the select (and click on an option) it triggers the 'onchange' and through the 'selectespece()' function a click on the hidden button thanks to the .Click function in selectespece().So after all these js function the result is:

select an option => it opens a window where you choose the file to upload

What I did

function selectespece() {
    especeprise = $("#espece-prise").val();  //just a variable getting the value of my select (it works)
    document.getElementById("btn_poster_photo").click();
}

I also did it in many different ways with jQuery

$("#espece-prise").on('change', function(){
    especeprise = $("#espece-prise").val();
    $(".btn_poster_photo").click();
})

What is happening?

When I select an option it triggers the click so it asks me to upload an image which is alright. This works on Chrome/Firefox/Opera... when I do it from a Windows/Ubuntu/archlinux computer

BUT

When I try it on safari/chrome from a MacOS it doesn't work, no error in console, I just select something and nothing happens. I tried to put an alert in my function 'onchange' it works, all works but not the .Click function...

I made several searches on Google but only found a few topics talking about an onclick after an onchange but not a .click in an onchange.


问:
Where does the ASP.NET development server keep its logs?
I am trying to sort out a problem where some relative urls are not resolving properly in an ASP.NET website. I want to see the HTTP logs to determine which URLs are being requested from the web server. I am using the ASP.NET Development Server, not IIS.

So are there logs produced by the ASP.NET Development Server where I can check which files are being requested?

Windows 7, 64bit

VS2008

ASP.NET 3.5 SP1

答:
If you are willing to replace the basic ASP.NET development server that comes with Visual Studio...

CassiniDev includes a real-time request/response viewer and logging facility.  As I understand it you can drop it in as a replacement web server very easily.

CassiniDev seems to do exactly what you need.  If you absolutely cannot use IIS for your site this may be the only other option in terms of being able to generate a request log.


问:
Is there any "switch case" in UML use-case specification?
Is there any "switch case" in use-case specification?

In the requirements:

When user select "contract" in combobox, a "contract" tab appears, then user will interact with the "contract" tab.

When user select "Independently funded", a "Funding" tab appears, then user will interact with the "funding" tab.

How can I specify this use-case in my use-case specification?

Those two "case" will be in basic flow, won't they? Then how can I specify the "switch-case"?

Edit: (Because many mistakes what I'm doing, I will make it clear)

I'm not in progress of drawing use-case or drawing activity diagram, I'm in the between. I'm writing use-case specification (which is used to describe a use-case, and will be used later to draw activity diagram).

For more detail: https://www.google.com.vn/search?q=use-case+specification&biw=1280&bih=683&source=lnms&tbm=isch&sa=X&ved=0CAYQ_AUoAWoVChMIn6ujsMDRxwIVC5COCh3aNQGY#

答: PlantUML suggests elseif-chains which gives also a nice graph.


问:
Take separate time and timezone strings, and convert into UTC
I know a bunch of ways to convert local times into UTC time with Ruby, but I'm not sure how to do this when the time and the zone are separate pieces of data.  If I have something like "12:00 PM -0500", I can easily convert this into UTC with .getutc().  However, what if I have "12:00 PM" and "Eastern Time (US & Canada)"?  How can I combine these two to find the UTC time?

答:
The DateTime::parse method may be what you are looking for.

```<code>x = DateTime.parse("12:00 PM Eastern Time (US & Canada)")
</code>```

will return a result of

```<code>#<DateTime: 2017-11-15T12:00:00-05:00 ((2458073j,61200s,0n),-18000s,2299161j)>
</code>```

From there, there are many ways to convert the time to UTC. For example,

```<code>utc = x.new_offset(0)
</code>```

will return a result of

```<code>#<DateTime: 2017-11-15T17:00:00+00:00 ((2458073j,61200s,0n),+0s,2299161j)>
</code>```

Body:
The DateTime::parse method may be what you are looking for.

x = DateTime.parse("12:00 PM Eastern Time (US & Canada)")

will return a result of

#<DateTime: 2017-11-15T12:00:00-05:00 ((2458073j,61200s,0n),-18000s,2299161j)>

From there, there are many ways to convert the time to UTC. For example,

utc = x.new_offset(0)

will return a result of

#<DateTime: 2017-11-15T17:00:00+00:00 ((2458073j,61200s,0n),+0s,2299161j)>


问:
Query Performance Check
My SQL script has 10 queries in a BEGIN END block. I need to check performance of each query separately for single Run.

Example:
when i run the SQL script
there are 10 queries
so need performance data for each query once it is executed
like

```<code>BEGIN
query1
performance data for query one
query2
performance data for query one
END
</code>```

答:
In SQL*Plus you can SET TIMING ON to get the elapsed time of each query. It's a simple as this:

```<code>set timing on

select * from t23
/

select * from t42
/

select * from t69
/

set timing off
</code>```

But wall-clock timings are a pretty crude measure of performance. Oracle has more to offer.

If you have a friendly DBA (and aren't they all?) get them to grant you the PLUSTRACE role. With this role you can just SET AUTOTRACE ON STATISTICS and get useful information regarding resource consumption for each query. Also you can set it with EXPLAIN to get a Explain Plan after each query too.

Find out more

Title: Query Performance Check

Body:
My SQL script has 10 queries in a BEGIN END block. I need to check performance of each query separately for single Run.

Example:
when i run the SQL script
there are 10 queries
so need performance data for each query once it is executed
like

BEGIN
query1
performance data for query one
query2
performance data for query one
END

Body:
In SQL*Plus you can SET TIMING ON to get the elapsed time of each query. It's a simple as this:

set timing on

select * from t23
/

select * from t42
/

select * from t69
/

set timing off

But wall-clock timings are a pretty crude measure of performance. Oracle has more to offer.

If you have a friendly DBA (and aren't they all?) get them to grant you the PLUSTRACE role. With this role you can just SET AUTOTRACE ON STATISTICS and get useful information regarding resource consumption for each query. Also you can set it with EXPLAIN to get a Explain Plan after each query too.

Find out more


问:
How to edit application configuration settings? App.config best way to go?
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

```<code>    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }
</code>```

Gives me a read-only error when I compile.

答: This is silly ... and I think I am going to have to apologize for wasting everyone's time!  But it looks like I just need to set the scope to User instead of Application and I can the write the new value.

OwnerDisplayName: MattRuma

Body:
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }

Gives me a read-only error when I compile.

LastEditorDisplayName: MattRuma


问:
How to reach bottom of listview, load more items
When I reach the bottom of my ListView (Scroll down until the end), how do I load more items?
Here is my class (maybe it will help) </p>

```<code>public class ListFood extends Activity {

    int userid;
    String cat;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.list_food);

      ListView lv = (ListView) findViewById(R.id.ListView01);
      TextView tv = (TextView) findViewById(R.id.TextView01);
      Webservice ws = new Webservice();
      List<Afood> list = new ArrayList<Afood>();
      int i;

      Bundle bundle = getIntent().getExtras();
      userid = bundle.getInt("userid");
      cat = bundle.getString("cat");

      list = ws.getFoodFromCat(cat);
      String [] food = new String [list.size()];

      for(i=0;i<list.size();i++)
      {
        food[i] = list.get(i).name;
      }

      if(cat.equalsIgnoreCase("FastFood"))
          tv.setText("Fast Food");
      else
          tv.setText(cat);

      lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list, food));

      lv.setTextFilterEnabled(true);

      lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
          // When clicked, show a toast with the TextView text
          Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
              Toast.LENGTH_SHORT).show();
        }
      });
    }

}
</code>```

答: In addition to the answer that @jleedev provided, you can also use my EndlessAdapter for this.

Body:
When I reach the bottom of my ListView (Scroll down until the end), how do I load more items?
Here is my class (maybe it will help)

public class ListFood extends Activity {

    int userid;
    String cat;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.list_food);

      ListView lv = (ListView) findViewById(R.id.ListView01);
      TextView tv = (TextView) findViewById(R.id.TextView01);
      Webservice ws = new Webservice();
      List<Afood> list = new ArrayList<Afood>();
      int i;

      Bundle bundle = getIntent().getExtras();
      userid = bundle.getInt("userid");
      cat = bundle.getString("cat");

      list = ws.getFoodFromCat(cat);
      String [] food = new String [list.size()];

      for(i=0;i<list.size();i++)
      {
        food[i] = list.get(i).name;
      }

      if(cat.equalsIgnoreCase("FastFood"))
          tv.setText("Fast Food");
      else
          tv.setText(cat);

      lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list, food));

      lv.setTextFilterEnabled(true);

      lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
          // When clicked, show a toast with the TextView text
          Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
              Toast.LENGTH_SHORT).show();
        }
      });
    }

}


问:
Understanding the Amazon S3 Data Consistency Model's caveat for HEAD and GET request before creating the object
I am reading the Amazon S3 data consistency from the docs http://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html

Amazon S3 provides read-after-write consistency for PUTS of new
  objects in your S3 bucket in all regions with one caveat. The caveat
  is that if you make a HEAD or GET request to the key name (to find if
  the object exists) before creating the object, Amazon S3 provides
  eventual consistency for read-after-write.

I understand that Amazon S3 provides read after write consistency while putting new objects to S3 bucket. But I didn't quite get that caveat for HEAD and GET request before creating the object, what does that mean?

答:
The actual internals of S3 are proprietary to AWS, but here's a theory:

When you request an object, it goes to its cache to see if it's there.

If it is not in the cache, it pulls the data from the underlying storage and puts it in the cache.

This is the read-after-write consistency. You'll get the new version immediately.

If it is already in the cache, it returns the data.

This is the eventual consistency for read-after-write for updates. You update the object, and then the cached version must expire before you get the new version.

If it is not in the cache, and the object is not there, it caches the "not present" result.

This is the behaviour you're asking about. Like the old data being in the cache, S3 has cached "the key does not exist" as the "old data". So again, you must wait for the cache to expire before the actual data can be returned.

Again, this is not stated with any authority. I'd welcome any S3 experts to correct or dispute any errors I may have.


问:
Can I reload a page form Service Worker (or Secondary Thread)?
I have a functional progressive web app. In it to upload data I'm first caching it in IndexDB and then uploading it and if the upload is successful delete the data from IndexDB. Now, I want to reload the page once the data is deleted. Is there any way to achieve this outside the main thread(ie. form service worker)?

NOTE:window object is not accessible in service worker.

答:
You have to communicate first with your page over the postMessage function, then you can access window and reload the page. Here you can find a good description:

http://craig-russell.co.uk/2016/01/29/service-worker-messaging.html#.WgxuSmjWzIU


问:
How can I rearrange the outputfile in order to obtain the numbers in lane and separated by a blank space?
Here's my script. It takes only 4 positional parameters. The output should be all the positional parameters, the number of characters that each one has and the first character of each one.

```<code>#!/bin/bash
rm -r param.out
declare -i cont
cont=$#
if [ $cont -eq 4 ]
then
  echo "Positional parameters" >> param.out
  echo $* >> param.out
  echo "Number of characters of each positional parameter" >> param.out
  echo -n $1 | wc -c >> param.out
  echo -n $2 | wc -c >> param.out
  echo -n $3 | wc -c >> param.out
  echo -n $4 | wc -c >> param.out
  echo "First character of each parameter" >> param.out
  echo $1 | head -c 1 >> param.out
  echo $2 | head -c 1 >> param.out
  echo $3 | head -c 1 >> param.out
  echo $4 | head -c 1 >> param.out
else
   echo "Error"
  exit
fi
</code>```

With an input of ./file 12 23 34 456 The obtained file is the following one:

```<code>Positional parameters

    12 23 34 456

Number of characters of each positional parameter

    2
    2
    2
    3

First character of each parameter

    1234
</code>```

The ideal would be obtaining the outputs as the first one (12 23 34 456)

PD. I know this could be done using a for/while in order to avoid repetitions of echo but I'm learning bash :/

答:
echo -n $1 | wc -c >> param.out

wc appends a new line to it's output, which has to be removed or replaced by a space in order to the get number of characters of each parameter on a single line. You could do that with sed:

```<code>echo -n $1 | wc -c | sed 's/\n/ /' >> param.out
</code>```

echo $1 | head -c 1 >> param.out

Use echo to append a space to the first character of a parameter:

```<code>echo "$(echo $1 | head -c 1) " >> param.out
</code>```

Body:
Here's my script. It takes only 4 positional parameters. The output should be all the positional parameters, the number of characters that each one has and the first character of each one.

#!/bin/bash
rm -r param.out
declare -i cont
cont=$#
if [ $cont -eq 4 ]
then
  echo "Positional parameters" >> param.out
  echo $* >> param.out
  echo "Number of characters of each positional parameter" >> param.out
  echo -n $1 | wc -c >> param.out
  echo -n $2 | wc -c >> param.out
  echo -n $3 | wc -c >> param.out
  echo -n $4 | wc -c >> param.out
  echo "First character of each parameter" >> param.out
  echo $1 | head -c 1 >> param.out
  echo $2 | head -c 1 >> param.out
  echo $3 | head -c 1 >> param.out
  echo $4 | head -c 1 >> param.out
else
   echo "Error"
  exit
fi

With an input of ./file 12 23 34 456 The obtained file is the following one:

Positional parameters

    12 23 34 456

Number of characters of each positional parameter

    2
    2
    2
    3

First character of each parameter

    1234

The ideal would be obtaining the outputs as the first one (12 23 34 456)

PD. I know this could be done using a for/while in order to avoid repetitions of echo but I'm learning bash :/

Body:
echo -n $1 | wc -c >> param.out

wc appends a new line to it's output, which has to be removed or replaced by a space in order to the get number of characters of each parameter on a single line. You could do that with sed:

echo -n $1 | wc -c | sed 's/\n/ /' >> param.out

echo $1 | head -c 1 >> param.out

Use echo to append a space to the first character of a parameter:

echo "$(echo $1 | head -c 1) " >> param.out


问:
SQL - Database Hierarchy Structure
I have a table with value like this

```<code>id | parent | folder_name
-------------------------
1  | 0      | Root
2  | 1      | NSW
3  | 1      | QLD
4  | 2      | Sydney
5  | 3      | Brisbane
</code>```

from this table i want to get a folder with all parents until higher level. Example: folder_name = Brisbane

```<code>id | parent | folder_name
-------------------------
5  | 3      | Brisbane
3  | 1      | QLD
1  | 0      | Root
</code>```

i want to use JOIN in sql not CTE

Any help would be great

答:
Recursive CTE is what you are looking for

```<code>;WITH cte
     AS (SELECT *
         FROM   Yourtable
         WHERE  folder_name = 'Brisbane'
         UNION ALL
         SELECT b.*
         FROM   cte a
                INNER JOIN Yourtable b
                        ON a.parent = b.id)
SELECT *
FROM   cte
</code>```

Title: SQL - Database Hierarchy Structure

Body:
I have a table with value like this

id | parent | folder_name
-------------------------
1  | 0      | Root
2  | 1      | NSW
3  | 1      | QLD
4  | 2      | Sydney
5  | 3      | Brisbane

from this table i want to get a folder with all parents until higher level. Example: folder_name = Brisbane

id | parent | folder_name
-------------------------
5  | 3      | Brisbane
3  | 1      | QLD
1  | 0      | Root

i want to use JOIN in sql not CTE

Any help would be great

Body:
Recursive CTE is what you are looking for

;WITH cte
     AS (SELECT *
         FROM   Yourtable
         WHERE  folder_name = 'Brisbane'
         UNION ALL
         SELECT b.*
         FROM   cte a
                INNER JOIN Yourtable b
                        ON a.parent = b.id)
SELECT *
FROM   cte


问:
Android Studio 3 constraint layout editor Issue
I'm using Android Studio 3.0 with the latest update on macOS recently the constraint layout editor stopped working. It's working when i run on the code on emulator/device but for the design and preview tabs it doesn't show up.

I'm using constraint layout 1.0.2 i tried the other versions as well not working.

i have tried support library 26, 26-beta1 and 26-beta2 no good there as well.

答:
Change the theme to Material will solve the issue.
By default it will be AppTheme</p>


问:
Physics Engine - Determining the velocity of objects after collision
While researching information for my physics engine, I have come across a problem with determining the velocities of objects (or the magnitude of the "impulse" of the collision) after a collision. Numerous sources have said to use the Coefficient of restitution, but according to Wikipedia, this depends on the properties of both the objects in the collision. Unfortunately, to determine the CoR, you need to know the final velocities of the objects!</p>

答:
What you'll want to do is to define the CoR for a particular object to some value and use that to calculate final velocity.

You'll have to choose how "bouncy" a particular object is somewhere - there's no magic involved.


问:
Crontab Python Script Not Working
I am running a python script on a Linux EC2 instance (the standard AMI) and I am having trouble executing a python script through the Crontab. I have another cron job already running and followed the same format. I think I'm missing something simple, but have had trouble identifying the cause. Here is what pops up when I run crontab -e

```<code>*/5 * * * * ~/scripts/aws-scripts-mon/mon-put-instance-data.pl --mem-used-incl-cache-buff --mem-util --disk-space-util --disk-path=/ --from-cron
*/1 * * * * ~/scripts/python cpu-util.py
</code>```

The error I get in the logs is /bin/sh: /root/scripts/python: No such file or directory

I'm a little confused about this error message because the path from when I log in is ~/scripts, which has my Python script.

I also tried */1 * * * * ~/scripts python cpu-util.py (which I thought made more sense), but rearranged my code based on this other post to no avail.

Also, does it matter if I run these tasks from root or ec2-user? I just put the same scripts in both to be safe (sorry if this is two questions in one, but just curious about this...)

Any input would be great. Thanks!

答:
in your line you are looking for

the python application inside your scripts folder

I guess this is not what you intended. Try this out:

```<code>*/1 * * * * /usr/bin/python ~/scripts/cpu-util.py
</code>```

I think this should work.

Also you can call it directly using ./ just putting inside your python script as the first line.

```<code>#!/usr/bin/env python
</code>```

Then you can run it like this

```<code>*/1 * * * * /usr/bin/sh ~/scripts/cpu-util.py
</code>```

Title: Crontab Python Script Not Working

Body:
I am running a python script on a Linux EC2 instance (the standard AMI) and I am having trouble executing a python script through the Crontab. I have another cron job already running and followed the same format. I think I'm missing something simple, but have had trouble identifying the cause. Here is what pops up when I run crontab -e

*/5 * * * * ~/scripts/aws-scripts-mon/mon-put-instance-data.pl --mem-used-incl-cache-buff --mem-util --disk-space-util --disk-path=/ --from-cron
*/1 * * * * ~/scripts/python cpu-util.py

The error I get in the logs is /bin/sh: /root/scripts/python: No such file or directory

I'm a little confused about this error message because the path from when I log in is ~/scripts, which has my Python script.

I also tried */1 * * * * ~/scripts python cpu-util.py (which I thought made more sense), but rearranged my code based on this other post to no avail.

Also, does it matter if I run these tasks from root or ec2-user? I just put the same scripts in both to be safe (sorry if this is two questions in one, but just curious about this...)

Any input would be great. Thanks!

Body:
in your line you are looking for

the python application inside your scripts folder

I guess this is not what you intended. Try this out:

*/1 * * * * /usr/bin/python ~/scripts/cpu-util.py

I think this should work.

Also you can call it directly using ./ just putting inside your python script as the first line.

#!/usr/bin/env python

Then you can run it like this

*/1 * * * * /usr/bin/sh ~/scripts/cpu-util.py


问:
Texel data in case of GL_LUMINANCE when glTexImage2D is called
Usually a texel is an RGBA value. What data does a texel represent in the following code:</p>

```<code>const int TEXELS_W = 2, TEXELS_H = 2;
GLubyte texels[] = {
    100, 200,  0,  0,
    200,  250,  0,  0
};
glBindTexture(GL_TEXTURE_2D, textureId);
glTexImage2D(
    GL_TEXTURE_2D,
    0,                  // mipmap reduction level
    GL_LUMINANCE,
    TEXELS_W,
    TEXELS_H,
    0,                  // border (must be 0)
    GL_LUMINANCE,
    GL_UNSIGNED_BYTE,
    texels);
</code>```

答:
```<code>GLubyte texels[] = {
    100, 200,  0,  0,
    200,  250,  0,  0
};
</code>```

OpenGL will only read 4 of these values. Because GL_UNPACK_ALIGNMENT defaults to 4, OpenGL expects each row of pixel data to be aligned to 4 bytes. So the two 0's in each row are just padding, because the person who wrote this code didn't know how to change the alignment.

So OpenGL will read 100, 200 as the first row, then skip to the next 4 byte boundary and read 200, 250 as the second row.

Body:
Usually a texel is an RGBA value. What data does a texel represent in the following code:

const int TEXELS_W = 2, TEXELS_H = 2;
GLubyte texels[] = {
    100, 200,  0,  0,
    200,  250,  0,  0
};
glBindTexture(GL_TEXTURE_2D, textureId);
glTexImage2D(
    GL_TEXTURE_2D,
    0,                  // mipmap reduction level
    GL_LUMINANCE,
    TEXELS_W,
    TEXELS_H,
    0,                  // border (must be 0)
    GL_LUMINANCE,
    GL_UNSIGNED_BYTE,
    texels);

Body:
GLubyte texels[] = {
    100, 200,  0,  0,
    200,  250,  0,  0
};

OpenGL will only read 4 of these values. Because GL_UNPACK_ALIGNMENT defaults to 4, OpenGL expects each row of pixel data to be aligned to 4 bytes. So the two 0's in each row are just padding, because the person who wrote this code didn't know how to change the alignment.

So OpenGL will read 100, 200 as the first row, then skip to the next 4 byte boundary and read 200, 250 as the second row.


问:
openpyxl - Active sheet is grouped to selected sheet

Using openpyxl, I loaded an existing workbook, and set a new active sheet.
Then when opening the workbook in Excel i noticed that the new active sheet got grouped with the original one prior to changing with openpyxl.

Is there any way to ungroup the sheets or any explanation for this behavior?

```<code>wb = openpyxl.load_workbook("test.xlsx")
wb.active = 3
wb.save("test.xlsx")
</code>```

And after running here are the "grouped" sheets i'm talking about: Grouped Sheets Image

It's as if the active sheet i set in the code ("Four") doesn't fully change the selected sheet but selects the new sheet alongside the originally selected sheet ("One")

Another discussion of the problem: https://bitbucket.org/openpyxl/openpyxl/issues/878/index-0-worksheet-creation-in-existing

Thanks!

答:
Well i have solved the problem by changing a property called tabSelected to False.

You can access that property by getting the tab you want to deselect (in this case the tab named "One") as written in the code below.

```<code>wb = openpyxl.load_workbook("test.xlsx")
wb.active = 3
wb["One"].views.sheetView[0].tabSelected = False
wb.save("test.xlsx")
</code>```

The third line turns the first tab to not selected therefore the only tab selected is the forth one.
The solution is kinda more of a workaround for this weird problem but still it works anyway.

Body:
Using openpyxl, I loaded an existing workbook, and set a new active sheet.
Then when opening the workbook in Excel i noticed that the new active sheet got grouped with the original one prior to changing with openpyxl.

Is there any way to ungroup the sheets or any explanation for this behavior?

wb = openpyxl.load_workbook("test.xlsx")
wb.active = 3
wb.save("test.xlsx")

And after running here are the "grouped" sheets i'm talking about: Grouped Sheets Image

It's as if the active sheet i set in the code ("Four") doesn't fully change the selected sheet but selects the new sheet alongside the originally selected sheet ("One")

Another discussion of the problem: https://bitbucket.org/openpyxl/openpyxl/issues/878/index-0-worksheet-creation-in-existing

Thanks!

Body:
Well i have solved the problem by changing a property called tabSelected to False.

You can access that property by getting the tab you want to deselect (in this case the tab named "One") as written in the code below.

wb = openpyxl.load_workbook("test.xlsx")
wb.active = 3
wb["One"].views.sheetView[0].tabSelected = False
wb.save("test.xlsx")

The third line turns the first tab to not selected therefore the only tab selected is the forth one.
The solution is kinda more of a workaround for this weird problem but still it works anyway.


问:
python: writing a wrapper around a third-party class
I need some functionality from a class X of a third-party module m. I could just use m.X directly, but I may need to replace m.X with another class n.Y in the future (e.g., if I discover a better implementation).

I'd like to avoid changing the rest of the code in such a situation.

For now, I want the full interface of m.X, including initialization, to pass through unchanged. I wrote a wrapper W for m.X as follows:

```<code>class W(m.X):
    def __init__(self, *args):
        super().__init__(*args)
</code>```

In the future, should the need arise, I plan to rewrite the above as:

```<code>class W(n.Y):
    def __init__(self, *args):
        super().__init__(*args)
    # override instance methods of n.Y that don't share the semantics with m.X
    # for example, in case f1 is hard to replicate in n.Y:
    # def f1(self, *args):
    #     print("this method is no longer available")
    #     raise MyDeprecatedMethod()
    # for example, in case f2 needs to be recalculated
    # def f2(self, *args):
          # do the calculations required to keep W.f2 unchanged
</code>```

Is my current wrapper for m.X acceptable? Are there are problems with it, or with the planned wrapper for n.Y?

答:
The simplest method is to write:

```<code>W = m.X
</code>```

Practically everything in Python is a first-class object - including types. A class is almost indistinguishable from any other variable, for example:

```<code>def W(*args, **kwargs):
    return m.X(*args, **kwargs)
</code>```

can instantiate an instance of m.X while appearing that W is the actual name of it. (Note that with this method isinstance will not work correctly - it will work fine with the first example.)

In some cases, using assignment may not play nicely with IDEs. In this case:

```<code>class W(m.X): pass
</code>```

will also produce the same result, though with the added overhead in that instances of W are only instances of m.X because W is a subclass: using W=m.X; W(args)  will create an instance of m.X.

Body:
I need some functionality from a class X of a third-party module m. I could just use m.X directly, but I may need to replace m.X with another class n.Y in the future (e.g., if I discover a better implementation).

I'd like to avoid changing the rest of the code in such a situation.

For now, I want the full interface of m.X, including initialization, to pass through unchanged. I wrote a wrapper W for m.X as follows:

class W(m.X):
    def __init__(self, *args):
        super().__init__(*args)

In the future, should the need arise, I plan to rewrite the above as:

class W(n.Y):
    def __init__(self, *args):
        super().__init__(*args)
    # override instance methods of n.Y that don't share the semantics with m.X
    # for example, in case f1 is hard to replicate in n.Y:
    # def f1(self, *args):
    #     print("this method is no longer available")
    #     raise MyDeprecatedMethod()
    # for example, in case f2 needs to be recalculated
    # def f2(self, *args):
          # do the calculations required to keep W.f2 unchanged

Is my current wrapper for m.X acceptable? Are there are problems with it, or with the planned wrapper for n.Y?

Body:
The simplest method is to write:

W = m.X

Practically everything in Python is a first-class object - including types. A class is almost indistinguishable from any other variable, for example:

def W(*args, **kwargs):
    return m.X(*args, **kwargs)

can instantiate an instance of m.X while appearing that W is the actual name of it. (Note that with this method isinstance will not work correctly - it will work fine with the first example.)

In some cases, using assignment may not play nicely with IDEs. In this case:

class W(m.X): pass

will also produce the same result, though with the added overhead in that instances of W are only instances of m.X because W is a subclass: using W=m.X; W(args)  will create an instance of m.X.


问:
Need help adding multiple guard statements to check character count
I'm starting a 12 week program for iOS dev on the 27th. I've been going through this Swift Dev book that I bought on Amazon until I start. I'm currently at Functions. I need a little help with the "Bronze" challenge if you would be so kind.

This is the question:

"Like if/ else conditions, guard statements support the use of multiple clauses to perform additional checks. Using additional clauses with a guard statement gives you further control over the statement’s condition. Refactor the greetByMiddleName( name:) function to have an additional clause in its guard statement. This clause should check to see if the middle name is less than four characters long. If it is, then greet that person by their middle name. If it is not, then use the generic greeting."

This is the code:

```<code>func greetByMiddleName(fromFullName name: (first: String, middle: String?, last: String)) {

        guard
        let middleName = name.middle
        else { print(" Hey there!")
        return
    }
    print(" Hey \( middleName)") }
greetByMiddleName( fromFullName: ("Dexter","Yakuza"," Morgan"))
</code>```

I was trying to use dot notation to check against the object but that's definitely not working. I'd appreciate any help that I can get at solving this.

What I was trying:

let middleNameCount = middleName.characters.count <- something along those lines.

答:
On Swift 4 "character" has been deprecated so the guard statement should be as follow:

guard let middleName = name.middle, middleName.count > 4 else {

Body:
I'm starting a 12 week program for iOS dev on the 27th. I've been going through this Swift Dev book that I bought on Amazon until I start. I'm currently at Functions. I need a little help with the "Bronze" challenge if you would be so kind.

This is the question:

"Like if/ else conditions, guard statements support the use of multiple clauses to perform additional checks. Using additional clauses with a guard statement gives you further control over the statement’s condition. Refactor the greetByMiddleName( name:) function to have an additional clause in its guard statement. This clause should check to see if the middle name is less than four characters long. If it is, then greet that person by their middle name. If it is not, then use the generic greeting."

This is the code:

func greetByMiddleName(fromFullName name: (first: String, middle: String?, last: String)) {

        guard
        let middleName = name.middle
        else { print(" Hey there!")
        return
    }
    print(" Hey \( middleName)") }
greetByMiddleName( fromFullName: ("Dexter","Yakuza"," Morgan"))

I was trying to use dot notation to check against the object but that's definitely not working. I'd appreciate any help that I can get at solving this.

What I was trying:

let middleNameCount = middleName.characters.count <- something along those lines.


问:
TSQL Datetime conversion looses a period of time
i'm playing around with a MsSQL Server for some days now and stumbled upon a strange behaviour when converting a datetime to/from a decimal.

```<code>SELECT [date] = GETDATE()

, [as decimal] = CAST(GETDATE() AS decimal)
, [from decimal] = CAST(CAST(GETDATE() AS decimal) AS datetime)

, [as float] = CAST(GETDATE() AS float)
, [from float] = CAST(CAST(GETDATE() AS float) AS datetime)

--                                  should be: 2009-08-15
, [from stored float] = CAST(CAST('40039.9583333333' AS float) AS datetime)
</code>```

When i convert a datetime without adding anything specific the decimal will be handled as i would define it decimal(18, 0). So there is a data loss in some way.

If i directly convert a float back to datetime which was converted from a datetime (as shown in line 7 of my query) everything is fine.

But when i load a value from a database table, for example 40039.9583333333 which definitely was calculated from a user input (2009-08-15) and convert it back to a datetime, it'll add one day.

I wasn't able to find anything specific for this time loss.

Is somebody able to describe the problem behind this strange behaviour?
And, if possible: add an example on how to do those conversions correctly?

Thanks.

答:
What was your input source into the DB? The underlying issue could be the starting reference point for the date.

As an example: From reading online, in Excel the date value '1900-01-01' is equal to 1 numerically.

However, in SQL Server the date value '1900-01-01' is equal to 0 numerically.

```<code>SELECT CAST(CAST('1900-01-01' AS DATETIME) AS FLOAT)
</code>```

Body:
i'm playing around with a MsSQL Server for some days now and stumbled upon a strange behaviour when converting a datetime to/from a decimal.

SELECT [date] = GETDATE()

, [as decimal] = CAST(GETDATE() AS decimal)
, [from decimal] = CAST(CAST(GETDATE() AS decimal) AS datetime)

, [as float] = CAST(GETDATE() AS float)
, [from float] = CAST(CAST(GETDATE() AS float) AS datetime)

--                                  should be: 2009-08-15
, [from stored float] = CAST(CAST('40039.9583333333' AS float) AS datetime)

When i convert a datetime without adding anything specific the decimal will be handled as i would define it decimal(18, 0). So there is a data loss in some way.

If i directly convert a float back to datetime which was converted from a datetime (as shown in line 7 of my query) everything is fine.

But when i load a value from a database table, for example 40039.9583333333 which definitely was calculated from a user input (2009-08-15) and convert it back to a datetime, it'll add one day.

I wasn't able to find anything specific for this time loss.

Is somebody able to describe the problem behind this strange behaviour?
And, if possible: add an example on how to do those conversions correctly?

Thanks.

Body:
What was your input source into the DB? The underlying issue could be the starting reference point for the date.

As an example: From reading online, in Excel the date value '1900-01-01' is equal to 1 numerically.

However, in SQL Server the date value '1900-01-01' is equal to 0 numerically.

SELECT CAST(CAST('1900-01-01' AS DATETIME) AS FLOAT)


问:
FirebaseMessagingService 11.6.0 HandleIntent
The FirebaseMessagingService has the method onMessageReceived() which we should override to handle notifications, but this only works when the app is in Foreground.

To handle notifications even when the app is in background, I used to override the handleIntent, to just call the onMessageReceived().

In FirebaseMessagingService 11.6.0, the method handleIntent became final, with that said, I can't override it as I was doing.

How should I handle notifications when my app is in background in the 11.6.0?

```<code>public class NotificationsListenerService extends FirebaseMessagingService {
    private static final String TAG = "NotificationsListenerService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)

        String notifyData = remoteMessage.getData().get("notifData");

        if(notifyData.contains("|")){
            String[] itens = notifyData.split("\\|");
            notifyData = itens[0];
        }

        String notifyType = remoteMessage.getData().get("notifType");
        String title = remoteMessage.getData().get("title");
        String message = remoteMessage.getData().get("body");

        if(!isAppInForeground(App.getContext())){
            sendNotification(title, message, notifyData, notifyType);
        }
    }

    @Override
    public final void handleIntent(Intent intent) {
        ...
        this.onMessageReceived(builder.build());
        ...
    }

    private void sendNotification(String messageTitle, String messageBody, String notifyData, String notifyType) {
        ...
    }

    //Detect if app is in foreground
    private boolean isAppInForeground(Context context) {
        ...
    }
}
</code>```

答:
It's not intended for anyone to override handleIntent().  That's why it was made final.  Also, you'll notice that it's completely missing from the javadocs - that's intentional.

If you want to handle a message in any circumstance (both foreground and background), use onMessageReceived().  The javadoc for that method says:

Called when a message is received.

This is also called when a notification message is received while the
  app is in the foreground. The notification parameters can be retrieved
  with getNotification().

This should work for data messages, but not notification messages sent from the console.  Notification messages have different delivery behavior.  See the documentation about message types and how to handle them.

Body:
The FirebaseMessagingService has the method onMessageReceived() which we should override to handle notifications, but this only works when the app is in Foreground.

To handle notifications even when the app is in background, I used to override the handleIntent, to just call the onMessageReceived().

In FirebaseMessagingService 11.6.0, the method handleIntent became final, with that said, I can't override it as I was doing.

How should I handle notifications when my app is in background in the 11.6.0?

public class NotificationsListenerService extends FirebaseMessagingService {
    private static final String TAG = "NotificationsListenerService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)

        String notifyData = remoteMessage.getData().get("notifData");

        if(notifyData.contains("|")){
            String[] itens = notifyData.split("\\|");
            notifyData = itens[0];
        }

        String notifyType = remoteMessage.getData().get("notifType");
        String title = remoteMessage.getData().get("title");
        String message = remoteMessage.getData().get("body");

        if(!isAppInForeground(App.getContext())){
            sendNotification(title, message, notifyData, notifyType);
        }
    }

    @Override
    public final void handleIntent(Intent intent) {
        ...
        this.onMessageReceived(builder.build());
        ...
    }

    private void sendNotification(String messageTitle, String messageBody, String notifyData, String notifyType) {
        ...
    }

    //Detect if app is in foreground
    private boolean isAppInForeground(Context context) {
        ...
    }
}


问:
How to hide buttons in TinyMCE 4.0 - WordPress 3.9
In last version of TinyMCE there was simply code to hide buttons in visual editor (Remove Specific Buttons from WP Editor TinyMCE). But with WordPress 3.9 TinyMCE 4.0 have other API.

Someone know how to do it now?

答:
If I understood the question correctly, you can use something like this to remove the default buttons from the WP tinyMCE.

```<code>// Remove TinyMCE Default Button

function myplugin_tinymce_buttons( $buttons ) {
      //Remove the text color selector
      $remove = 'blockquote'; //default blockquote button

      //Find the array key and then unset
      if ( ( $key = array_search( $remove, $buttons ) ) !== false )
        unset( $buttons[$key] );

      return $buttons;
 }
add_filter( 'mce_buttons', 'myplugin_tinymce_buttons' );
</code>```

to know what is the name of the element you need to use your browser dev tools. Simply highlight the element and see the class. It will be also the name. For example:
where to see the name of the element

Body:
If I understood the question correctly, you can use something like this to remove the default buttons from the WP tinyMCE.

// Remove TinyMCE Default Button

function myplugin_tinymce_buttons( $buttons ) {
      //Remove the text color selector
      $remove = 'blockquote'; //default blockquote button

      //Find the array key and then unset
      if ( ( $key = array_search( $remove, $buttons ) ) !== false )
        unset( $buttons[$key] );

      return $buttons;
 }
add_filter( 'mce_buttons', 'myplugin_tinymce_buttons' );

to know what is the name of the element you need to use your browser dev tools. Simply highlight the element and see the class. It will be also the name. For example:
where to see the name of the element