evaluate $ \int \frac{4x^5-1}{(x^5+x+1)^2}dx$

Question: As an exercise in section "Integration By Partial Fraction"  I tried to evaluate  $$ \int \frac{4x^5-1}{(x^5+x+1)^2}dx$$ by partial fraction,and I faild to solve it.After I see the answer it's evident that the derivative of $- \frac{x}{x^5+x+1}$ is $\frac{4x^5-1}{(x^5+x+1)^2}$,but I don't think it's evident if I didn't look at the answer.Is there any technique to evaluate integrals like this?
Thanks.
Progress:
I get an idea that if a rational function is in this form $$ \frac{P(x)}{G(x)^2} $$G(x) is a polynomial of degree $n$,and P(x) is a polynomial of degree $k( n-1 \leq k \leq2n-1)$,then we could suppose a polynomial  of degree $k-n+1$ $$f(x)= \sum_{i=0}^{k-n+1} c_i x^i$$ and use  the numerator part of quotient rule we can list an equation: $$f'(x)G(x)-f(x)G'(x)=P(x)$$ and  get $k+1$ linear equations,and use linear Algebra to check it whether it has a solution.
ATTENTION
This ONLY works for some particular partial fraction problem. It may be useful on an exam where the problems are intentionally simple. The general way to integrate rational function is using partial fraction.
Comment: Are you sure the numerator is $4x^5-1$ and not $+1$?
Comment: Yes,I'm sure.It's $4x^5-1$.
Comment: @5xum Link to wolframalpha, [derivative of the stated answer](http://www.wolframalpha.com/input/?i=differentiate+%E2%88%92%28x%2F%28x%5E5%2Bx%2B1%29%29). Question is all right.
Comment: Are you sure that jives? Remember my answer was a very special case.
Comment: The idea can't always find a solution.I find my question very hard to attack by partial fraction integration.So it maybe a shortcut if $k-n+1$ is small.
Comment: This ONLY works when the denominator is of the form $g(x)^2$ It turns a particular partial fraction problem into a logic problem. It may be useful on an exam where the problems are intentionally simple.  But you need to learn and be comfortable with partial fractions because 75% of the problems your face will not be in the correct form.
Comment: You're right.I add your comment into attention.
Answer: The quotient rule may provide a way to reverse engineer the problem. (the denominator being of the form $G(x)^2$)
Here goes... $$d(f(x)(x^5+x+1)^{-1})= [f'(x)(x^5+x+1)-(5x^4+1)(f(x)]\space(\text {over $g(x)^2$})$$ Then $$f'(x)(x^5+x+1)+(-5x^4-1)f(x)=4x^5-1$$ since I need to have only terms of $x^5$ while I have $(-5x^4-1)$ f(x) and $f'(x)$ must not raise the power of the $x^5$ term I already have, f(x)must be $\frac{+}{-}x$ and since I need $+4x^5,f(x)\text{must be} -x$
This will yield the true statement
 $$-x^5-x-1+5x^5+x=4x^5-1$$ So the integral must be $$-x(x^5+x+1)^{-1}$$All that being said, ( you wanted an easier way in THIS case) this ONLY works because the denominator is of the form $g(x)^2$, an even power, (and it will get unbearably hairy for any even power over 2); and the numerator is so clean.
I am sure these folks will tell you ( and I am inclined to agree) that it is better to learn Integration by partial fractions.
Comment: Nice reverse engineering. +1 :D
Comment: It's nice.I get an idea from your post.And add it to my progress.
Answer: Here is an actual method to solve this integral, using integration by parts.
$\begin{align}
I&=\int\frac{4x^5-1}{(x^5+x+1)^2}\,\mathrm{d}x\\
&=\int\frac{4x^5-1}{5x^4+1}\frac{5x^4+1}{(x^5+x+1)^2}\,\mathrm{d}x\\
&=\frac{1-4x^5}{(5x^4+1)(x^5+x+1)}+\int\frac{20x^3}{(5x^4+1)^2}\,\mathrm{d}x\\
&=\frac{-x}{x^5+x+1}+C
\end{align}$
Comment: Another nice answer!!!
Answer: Actually, there is a way to solve this integral only with substitution. Note that
$$\begin{aligned}
\int \frac{4x^5 - 1}{\left(x^5 + x + 1\right)^2}\,\mathrm{d}x&=\int\frac{4x^5 - 1}{\left[x\left(x^4 + 1/ x + 1\right)\right]^2}\,\mathrm{d}x\\
&=\int\frac{4x^3 - 1/x^2}{\left(x^4 + 1/x + 1\right)^2}\,\mathrm{d}x
\end{aligned} $$
Now, set $u = x^4 + 1/x+1 $ and $\mathrm{d}u = \left(4x^3 - 1/x^2\right)\mathrm{d}x$ to obtain
$$\int\frac{\mathrm{d}u}{u^2} = -\frac{1}{u} + C. $$
Then,
$$\begin{aligned}
\int \frac{4x^5 - 1}{\left(x^5+x+1\right)^2}\,\mathrm{d}x &= -\frac{1}{x^4 + 1/x+1}+C\\
&=-\frac{x}{x^5 +x+1} + C,
\end{aligned}$$
as desired.


Google Cloud Storage returning 403 for user present in ACL

Question: I have a google cloud bucket where I want to give individual users permission to access individual files. So I have a file with the uri: gs://my-bucket/my-file and on the ACL list for that object, I have firstname.lastname@example.com listed as a "user" with "read" permissions.
However, any attempt to access that file using the url:
https://storage.cloud.google.com/my-bucket/myfile through the browser returns a short page stating 403 forbidden even though I am logged in. If I open an incognito tab, I am prompted to log in to google when I go to that URL, but once I have finished the login, I get the same 403 message.
With the same credentials I can easily download the file using gsutil, or from the google developers console. But I can't seem to download it with an authenticated user from a web link.
EDIT: To be clear, this object is not meant to be public, it should only be accessible to project owner/editors and any person specifically named in the objects ACL. I am going off of this document.
EDIT2: This is the entry for the user in the object's ACL
{
    "email": "firstname.lastname@example.com",
    "entity": "email@example.com",
    "role": "READER"
 }

Answer: You have to also provide bucket permission to that user.
Comment: What role should I give them so that they don't have access to *every* file in the bucket, only that *one* file?


Carregar arquivo HTML dentro de outro arquivo HTML

Question: Eu tenho um arquivo index.html:

E tenho o header, o main e o footer em pastas separadas.
Gostaria de saber como posso adicionar esses arquivos externos dentro desse arquivo principal, assim que a página for carregada.
Estou tentando criar de forma mais pura possível (usando somente HTML, CSS e JS, evitando frameworks). Mas se só for possível com alguma biblioteca, eu posso incluir.
Comment: Faz um include com PHP https://pt.stackoverflow.com/questions/273072/carregar-html-de-outro-html/273090#273090 apenas com HTML isso pode te dar uma luz https://pt.stackoverflow.com/questions/281023/que-recurso-encontro-em-html-como-op%c3%a7%c3%a3o-ao-include-do-php/281044#281044 e com JS vc pode salvar seu .html da outra pasta como um .JS e na sua página vc faz o append desse script como o template do html dentro algo do tipo
Answer: Com o Jquery
Arquivo template.html

Comment: Cara, valeu mesmo, funcionou aqui! Agradeço de verdade.


Android: Tracking mouse pointer movement

Question: Assuming that I am using a generic mouse, is it possible to track the X and Y coordinates of the mouse pointer in android?
Answer: You need a OnGenericMotionListener:
OnGenericMotion(...., MotionEvent me) {
if (me.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE) {

}

api 14+ needed
[confirmed] Found me a tablet with usb mouse and can confirm this works for mouse movement. You WILL get flooded with messages, so simple operations or sleeping should be considered.
Comment: Hmm in my case i attached it to a webview and I only get events when I click on the left mouse button...
Comment: `View.OnGenericMotion(View v, MotionEvent event)` is available starting with api level 12: [http://developer.android.com/reference/android/view/View.OnGenericMotionListener.html#onGenericMotion](http://developer.android.com/reference/android/view/View.OnGenericMotionListener.html#onGenericMotion)
Answer: The docs to ACTION_MOVE lead me to think that only drag events would be reported:

Constant for getAction(): A change has
  happened during a press gesture
  (between ACTION_DOWN and ACTION_UP).
  The motion contains the most recent
  point, as well as any intermediate
  points since the last down or move
  event.
Comment: Thank so much for your insight Matthew. I've also read about that. I think what I need to know if there is any way to track the mouse movement without having an ACTION_DOWN MotionEvent?
Comment: Do you have an Android device that has a mouse? If so you could test this out. I wasn't aware that there were any with mice.
Comment: Yeah, I actually have an android tablet that can use a mouse through USB port. Also, I already have a method using ACTION_DOWN, ACTION_MOVE, and ACTION_DOWN and yes, they are working fine. But is there any way to have an ACTION_MOVE event for a mouse pointer without having an ACTION_DOWN first?
Comment: Hi. I'm facing the same problem. Save you found a way to track the mouse movements. I heard that it is possible to get the mouse movements using Internal classes, but not easy.
Comment: does any one know how to use mouse from other system i.e mouse is connected to my laptop and laptop and tablet are connected using wi-fi direct.Now i want to use mouse in tablet..
Answer: In my case the OnGenericMotion solution did not work but attaching an OnHoverListener to the main view did the trick.


Stop WordPress from enclosing script in CDATA

Question: I am importing HTML pages using HTML import plugin for WordPress.
I have a code snippet for google maps, which is imported.
However, after import, it encloses the script tag in CDATA. If I remove CDATA, the map works fine. How do I stop WordPress from enclosing the script with CDATA?
Here's the script :

Answer: $content = str_replace(']]>', ']]>', $content);

wp-includes\post-template.php line 167
Comment: Thanks for the help Badri , I found the solution on line 167 by changing code to this :

wp-includes\post-template.php line 167

    $content = str_replace('','',$content);
    $content = str_replace('','',$content);
 //$content = str_replace(']]>', ']]>', $content);
Comment: Ugh. Don't *ever* overwrite WP core files.
Comment: should I comment this line ? This is adding closing brackets , where are opening brackets being added ?
Comment: Mhh, sorry for my minimalist answer, I thought I wrote it more clear. Don't forget to change it every time you upgrade Wordpress. Or write it somehow to your functions.php theme file.
Answer: You can also do in this way in template page file:
   <?php $content = str_replace(']]>', ']]>', the_content()); echo $content; ?>

Comment: if it's a mistake, click on `edit` below the post to correct the mistake. [help]
Comment: The above is mistake.
 $content = str_replace(']]>', ']]>', the_content()); echo $content;


slack not providing original message on interaction

Question: I am responding to an incoming Slack slash command with this JSON (not a POST after receipt):
{
  "text": "Testing some interactions!",
  "attachments": [{
    "callback_id": "testing_interactions",
    "attachment_type": "default",
    "actions": [{
      "name": "action",
      "text": "Click Me",
      "value": "clicked",
      "style": "primary",
      "type": "button"
    }]
  }]
}

That gives me a nice, pretty, green button to click on and everything seems just fine for the most part; however, according to the Slack documentation for Interactive Messages, I should be getting an original_message property in the interaction payload.
This does not occur and I only get a sample POST with a payload like this:
{
  "type": "interactive_message",
  "actions": [
    {
      "name": "action",
      "type": "button",
      "value": "clicked"
    }
  ],
  "callback_id": "testing_interactions",
  "team": {
    "id": "TEAMID",
    "domain": "mydomain"
  },
  "channel": {
    "id": "CHANNELID",
    "name": "directmessage"
  },
  "user": {
    "id": "USERID",
    "name": "me"
  },
  "action_ts": "123456",
  "message_ts": "123456",
  "attachment_id": "1",
  "token": "my_token",
  "is_app_unfurl": false,
  "response_url": "https://hooks.slack.com/actions/...",
  "trigger_id": "some.id"
}

I was hoping to be able to the original_message property to be able to provide an approve/cancel operation in my target implementation but am unable to.
So two questions:

What am I missing to get the original_message posted back to me on interaction?
It seems wrong, but is there a need to persist the original data in order to easily recreate a message?
Comment: D'OH!   RTFM.  That's it.  I must have completely glanced over that in the doc.  If you leave that as the answer I'll accept it.
Comment: Is your interactive message ephemeral by any chance? From the docs: `The original_message is not provided for ephemeral messages.`
Comment: Glad I could help you out here!
Answer: Is your interactive message ephemeral by any chance? From the docs: The original_message is not provided for ephemeral messages.


node-sass size after upgrading to Node 11.1 with build-tools on windows

Question: initially I was using Node v10 (I believe) and when generating a new angular project (v7) my node_modules were a "modest" ~140 Mb.
I then decided to upgrade to Node v11.1 and install the build-tools, that the installer now optionally allows you to install.
My node_modules size went to over 700 MB.
The culprit is the node-sass package, which is now downloading the whole project (cpp files, .sln and all) and getting fully compiled on the initial npm install (using node-gyp).
Is there any way to change this behavior to the way it did things without the installed build tools? (short of manually uninstalling the build pipeline that node automatically installed)
Or is there any advantage that I'm not seeing? To me it all worked just fine (including everything scss and sass-related) without the huge increase in occupied space.
Comment: You could contribute a built binary back to node-sass or wait for them to update with one. I think it will go down on it's own once that happens.
Answer: So, I found out what's going on.
The current version of angular (cli version 7.0.6) installs node-sass at version 4.9.3.
Version 4.9.3 does not support node v11. Support for node v11 was added with 4.10.0. As such the install script that node-sass is running can't find a pre-built binary to download from github and falls back to building the source files (which results in 400 MB wasted space).
That's why the problem started cropping up after I updated to the latest node version.
For now there's 2 solutions:

Stick with LTS v10 of node (for which there is a pre-built binary)
Manually upgrade to the latest version of node-sass and hope angular doesn't break because of it

I went with option 1 and installed the LTS node version.
This is a problem that will probably fix itself in time, as angular updates its node-sass dependency. For the time being I hope the answer will help someone facing the same situation.


what is the best way to parse out the text after the last instance of a character

Question: I have the following string:
string test = /test/test1/tse3/ttese3/test3-45-NameToParseOut

and i need to parse out the word "NameToParseOut".  I basically need to find the last "-" and return all of the text after the last instance of "-".  What is the most elegant way of parsing this out in C#?
Answer: string test = "/test/test1/tse3/ttese3/test3-45-NameToParseOut";
test = test.Substring(test.LastIndexOf('-')+1);

This works even for strings that do not contain dashes (in these cases the entire string is returned).
Answer: Try:
string test = "/test/test1/tse3/ttese3/test3-45-NameToParseOut";
int index = test.LastIndexOf('-');
string value;
if(index != -1) {
    value = test.Substring(index) + 1;
}

Read more on LastIndexOf(char) here: http://msdn.microsoft.com/en-us/library/aa904293%28v=VS.71%29.aspx


How Are Little Endian Structs With Bitfields and Longwords Stored?

Question: So, I can understand that a word of 0x1234, when stored as little-endian, becomes 0x3412 in memory. I am also seeing that byte 0x12 as a bitfield a:4 and b:4 would be stored as 0x21. But what if I have something more complex? Data like 0x1700581001FFFFFF with the following struct ordering? I'm seeing the data stored as 0x7180051001FFFFFF which is making very little sense to me. It seems 'a' and 'b' got swapped but they remained at the beginning of the struct and g remained at the end along with other seemingly random swaps. Why? Also, I left the "LONGWORD" denotion because that is there in the code. I'm not sure how 4 bits can be a longword, but perhaps that has something to do with this craziness?
LONGWORD a: 4
LONGWORD b: 4
LONGWORD c: 4
LONGWORD d: 12
LONGWORD e: 8
LONGWORD f: 8
LONGWORD g: 24

Comment: it does **not** become 0x3412. The value is still 0x1234 but it's stored as 2 bytes in order 0x34 0x12
Comment: I said "becomes 0x3412 IN MEMORY" which is true. But when interpreted, it is still 0x1234.
Comment: See also: http://stackoverflow.com/questions/32677235/bit-fields-memory-management-in-c
Answer: In an "implementation-defined manner".  Per 22.214.171.124 Structure and union specifiers, paragraph 11, of the C Standard:

An implementation may allocate any addressable storage unit large
  enough to hold a bit-field.  If enough space remains, a bit-field
  that immediately follows another bit-field in a structure shall be
  packed into adjacent bits of the same unit.  If insufficient space
  remains, whether a bit-field that does not fit is put into the next
  unit or overlaps adjacent units is implementation-defined.  The order
  of allocation of bit-fields within a unit (high-order to low-order or
  low-order to high-order) is implementation-defined.  The alignment of
  the addressable storage unit is unspecified.

To answer your question But what if I have something more complex? Data like 0x1700581001FFFFFF with the following struct ordering?
The proper answer in that case, if you want portable and reliable code, is to not use bit-fields.  The fact that you have failed to provide enough information in your question for anyone to provide an answer as to how that data will be placed into the bit-fields you described should inform you what the problems are when using bit-fields.
For example, given your bit-fields
LONGWORD a: 4
LONGWORD b: 4
LONGWORD c: 4
LONGWORD d: 12
LONGWORD e: 8
LONGWORD f: 8
LONGWORD g: 24

If one assumes 16-bit int-type values are used for bit-fields, it would be perfectly proper to lay out the data thusly:
16-bit `int` with `c`,`b`,`a` - in that order
16-bit `int` with `d`
16-bit `int` with `f`,`e` - in that order
16-bit `int` with first 16 bits of `g`
16-bit `int` with last 8 bits of `g` - **after** 8 bits of padding.

And that's not even getting into endianness of the storage.
Comment: Well crap. i guess that explains it then :-P. Now to find out if that's a problem... Thanks! :-)
Comment: The advice that "if you want portable and reliable code, to not use bit-fields" can be misleading.  Bit-fields are no less portable than any other C data structure.  If all you do with your bit-field is write to and read from it in C code, it's perfectly portable.  If you try to write or read it to or from the outside world, however, you're going to have terrible portability problems -- but they're exactly the same portability problems you always have with size, endianness, and alignment.
Comment: Bit-fields have long struck me as being an almost-useful part of C.  What would be necessary to make them genuinely be useful would be a means of *specifying* the required layout.  Other than chicken-and-egg issues, there shouldn't be any problem; if a compiler needs to be able to access bitfields of any size up the maximum, at any bit offset within a word, for bitfields it places itself, adding support for directives to explicitly set the order should be simple by comparison, and would allow them to be usable in portable code.
Comment: I included all information I understood to be relevant. So anything lacking doesn't inform me of anything since I'm not sure what's lacking. I understood the entire point of a bitfield is to designate, in order, the meaning of bits to data. Is this not particularly true? Can it store it however it finds most beneficial and it just remembers where it put it all when referencing it by name?
Comment: @CodeMonkey *I understood the entire point of a bitfield is to designate, in order, the meaning of bits to data.*  Bit-fields most certainly do not designate any order to data.  They can not be used, for example, as part of a union in order to interpret a `char` array of raw data, for example.  They might work on one implementation and fail disastrously on another with no code changes.  Even changing compilier optimization levels can change how a `struct` is laid out in memory.
Comment: @CodeMonkey - *Well crap. i guess that explains it then :-P. Now to find out if that's a problem...*  if you have a specific problem, you're usually better off actually stating what the problem is, providing the code and sample output.
Comment: I don't have a specific problem. As I stated, I have to figure out if this does pose a problem because I do not yet know if it does.
Comment: @CodeMonkey "Can it store it however it finds most beneficial and it just remembers where it put it all when referencing it by name?"  Yes.  That's exactly it.  Couldn't have put it better myself. (And to a very real extent that's what the compiler does with every piece of data you declare and every line of code you write.)
Comment: @SteveSummit I had thought my answer was pretty clearly in response to the OP's question about using bit fields to match an ordered set of binary data, such as one stored in an array of `char`:  *The proper answer in that case, if you want portable and reliable code, is to not use bit-fields.*
Answer: Questions like (and the point made in a comment about how to "designate, in order, the meaning of bits to data") inevitably boil down to: what are you trying to do with the data?
If you're declaring a data structure so that some C code can write to it, and other C code can read from it, you rarely if ever care about the byte order, or the bitfield order (or the padding, or the alignment, or any of that).
Where it gets tricky -- very tricky -- is when you try to take that data structure, as your C compiler laid it out in memory, and write it out to or read it in from the outside world.  When you try to do that, you end up having to worry forever about type sizes, and byte order, and padding, and alignment, and the order in which bitfields are assigned.
In fact there are so many things to worry about, and nailing them all down is such a nuisance, that many people (myself included) recommend simply not trying to define data structures which can be directly read and written in this way, at all.
My memory is that compilers for big-endinan machines tend to lay out the bits in bitfields one way, and for little-endian the other way.  But I can never remember which way is which.  (And even if I thought I could remember, you shouldn't trust me.)  If for some reason you care, you're going to have to do what I always do, which is to write some little test programs to construct some binary data and print it out in hex and figure out how it's done for the machine/compiler combination you're using today.  (And of course you also have to decide what you're going to do about the possibility that your machine/compiler combination might change next week.)
Answer: Upon re-reading the documentation, I do not see any allowance for packing the bitfields in simply any order. There is indeed a specified ordering but it is implementation dependent in which way it is done. But it is still quite determinable. In short, from what I am seeing, it is packing up the bits by groups of 8 IN ORDER. The difference for our Little Endian compiler (or maybe some option somewhere) is that the concatenation of the bits puts the first-defined bits AFTER the next-defined bits (i.e. made the first defined less significant than the next-defined). For example:
a:3 = 111 (binary)
b:4 = 0000 (binary)
c:9 = 011111111 (binary)

Our Little Endian compiler (or, again, perhaps some other option) will take the 3 bits from 'a' and concatenate with b by adding 'a' to the end of 'b'. This, I believe, is opposite what Big Endian compilers would do which would put 'a' before the 'b'. So I'm speculating it's the endianness that does this, but ours would get 7 bits of 0000111 by making ba rather than ab. It then needs one more bit from c to create a full 8. It takes the least significant bit of 'c' which is a 1 and, again, the previous bits get tacked on to the end of that new bit. So we have 10000111. This byte, 0x87, is then stored to memory and it grabs another 8 bits. In this example the next 8 bits is 01111111 and so it stores that byte, 0x7F, after the 0x87. So in memory we now have 0x877F. Another method (likely Big Endian) would have ended up with 0xE0FF. The 0x877F which is now in memory, if interpreted as a word in Little Endian would be a value of 0x7F87 or, in binary, 0111111110000111. This happens to be the exact reverse of the data structure above concatenating 'cba'.
So let's do that same reverse ordering of the data I provided earlier:
(0x1700581001FFFFFF was meant to be parsed as below but I guess that might not have been obvious since it is a Big Endian construct I assumed)
LONGWORD a: 4 = 0x1
LONGWORD b: 4 = 0x7
LONGWORD c: 4 = 0x0
LONGWORD d: 12 = 0x058
LONGWORD e: 8 = 0x10
LONGWORD f: 8 = 0x01
LONGWORD g: 24 = 0xFFFFFF

With the Little Endian configuration we have, this could be interpreted as one giant structure with a value of 0xFFFFFF0110058071 by concatenating in the order gfedcba. If we store this back to memory in Little Endian format, we would get 0x7180051001FFFFFF which is the exact data I said we were seeing. Big Endian, in theory, would have done it in the order I assumed as obvious (0x1700581001FFFFFF) both as interpreted and stored.
Well, it makes sense to me. Hopefully it makes sense to someone else trying to figure out the same thing! I still don't get why they all say LONGWORD before them though...


What is the cardinality of the set of equivalence classes of countable order types under bi-embeddability?

Question: Two ordered sets have the same order type if there exists an order isomorphism between them.  Now the set $X$ of all order types of countable totally ordered sets has cardinality $2^{\aleph_0}$; see here.  But I'd like to find the cardinality of a smaller set.
Let us define an equivalence relation $\sim$ on $X$ as follows.  If $a$ is the order type of $A$ and $b$ is the order type of $B$, then we say that $a\sim b$ if there exists an order isomorphism between $A$ and a subset of $B$, and an order isomorphism between $B$ and a subset of $A$.  My question is, what is the cardinality of the set of equivalence classes of elements of $X$ under this equivalence relation?
Is it still $2^{\aleph_0}$, or is it smaller than that?
Comment: Nice question. A small remark: The order of the rationals is *universal* in the sense that any countable linear order embeds into it. An order is *scattered* if and only if it contains no copy of $\mathbb Q$. Clearly, you can limit your attention to scattered orders. [This](https://math.stackexchange.com/a/38626/462) answer (and the references given there) is now relevant: in particular, you cannot have infinite families of incomparable orders (under embeddability).
Comment: Well, there are definitely still $\aleph_1$ different equivalence classes (the countable ordinals), so you can't prove in ZFC that there are less than $2^{\aleph_0}$.
Comment: @EricWofsey Either an answer showing that there are $2^{\aleph_0}$ equivalence classes, or an answer showing that there are $\aleph_1$ equivalence classes, would satisfy me.
Comment: @EricWofsey I guess the question is whether the number of equivalence classes is (in ZFC) provably equal to $\aleph_1$, or provably equal to $\mathfrak c$, or neither.
Comment: @AndrésE.Caicedo Silly question: under AD, can there be a well-quasi-order which surjects onto $\mathbb{R}$? If not, that plus Laver's theorem, the AD-version of Burgess' theorem, and the fact that $V$ and $L(\mathbb{R})$ agree about this question shows that the answer is $\omega_1$ assuming large cardinals ... :P (But seriously, I don't see how to cook up a "really long" wqo under AD.)
Comment: @AndrésE.Caicedo Your linked answer is relevant to another question of mine: https://math.stackexchange.com/q/2936721/71829 Can you post an answer to that question?
Answer: The cardinality is $\aleph_1$.
As noted by Andrés Caicedo, the nonscattered countable linear orders form a single $\sim$-class, so it suffices to explain why there are only $\aleph_1$-many $\sim$-classes of scattered types.
Rich Laver proved that the embeddability quasiorder of (countable) nonscattered types is a well-quasiorder. Call this quasiorder $W$. Let $P=W/\sim$ be the quotient poset. The poset $P$ has no infinite antichains or infinite properly descending chains. The task is to determine the size of $P$.
Recursively partition $P$ into levels: $L_0$ is the antichain of minimal elements of $P$, and for each $\alpha>0$, define $L_{\alpha}$ to be the antichain of minimal elements of $P-\bigcup_{\beta<\alpha} L_{\beta}$. Let $\gamma$ be the least ordinal that does not index any level. Then $|P| = |\bigcup_{\alpha<\gamma} L_{\alpha}| = |\gamma|$, since $\gamma$ is infinite and the levels are finite and partition $P$.
The question asks for the number of $\sim$-classes, which is the cardinality of $P$. We have just shown that this is $|\gamma|$. By Eric Wofsey's comment, $|\gamma|\geq \aleph_1$.
To obtain a contradiction, assume that $|\gamma|>\aleph_1$. Choose an ordinal $\delta$ so that $\aleph_1<\delta<\gamma$. Level $L_{\delta}$ is not empty, since $\delta<\gamma$, so pick a countable linear order $\Lambda_{\delta}$ so that $(\Lambda_{\delta}/\sim)\in L_{\delta}$. Every level $L_{\varepsilon}$, for $\varepsilon <\delta$, contains some $\Lambda_{\varepsilon}/\sim$, where $\Lambda_{\varepsilon}$ is a countable linear order embeddable in $\Lambda_{\delta}$. (If there exists some $\varepsilon < \delta$ whose level $L_{\varepsilon}$ does not contain the $\sim$-class of any poset embeddable in $\Lambda_{\delta}$, then the least-indexed level with this property would have to contain $\Lambda_{\delta}/\sim$, contradicting either $\varepsilon <\delta$ or the disjointness of the levels.)
But now we have a countable linear order $\Lambda_{\delta}$ which has $|\delta|$-many order types of pairwise $\sim$-inequivalent, countable linear orders that are embeddable into it, namely the $\Lambda_{\varepsilon}$'s. And remember that $\delta$ is uncountable. We have now obtained a contradiction to
Fraisse's Second Conjecture (also proved by Laver), which states that a countable scattered linear order has only countably many $\sim$-types of suborders.   \\\\\
You will find the statements of all four of Fraisse's Conjectures on page 178 of Rosenstein's book Linear Orderings, Academic Press, 1982. The proof (due to Laver) of Fraisse's Second Conjecture is Theorem 10.52 of this book.


Nonhomogenous Differential Equation of Bessel Type

Question: Trying to solve the differential equation: $x^2y''+xy'+(-1-x^2)y=f(x)$ with $f(x)=x$, $f(0)=f(1)=0$.  We're supposed to use the previous problem (for which we did an eigenfunction expansion of $f(x)=x$ with the equation $x^2y''+xy'+(\lambda x^2-1)y=f(x)$ (same boundary conditions.
When I did that eigenfunction expansion, I got that there are no negative eigenvalues, (since when we consider $\lambda<0$, $\lambda=-\mu^2$, we get a solution of the form $y(x)=c_1I_1(\mu x)+c_2K_1(\mu x)$.  In order to satisfy the boundary conditions, $c_1=c_2=0$, (since for small x, $c_2K_1(\mu x)=\dfrac{c_2}{\mu x}$, so $c_2=0$ and for larger x, $c_1I_1(\mu x)=\dfrac{c_1 e^{\mu x}}{\sqrt{2 \pi \mu x}}$, so $c_1=0$)).  Therefore for any negative lambda I get the trivial solution.
So would I only get a particular solution for the equation $x^2y''+xy'+(-1-x^2)y=x$?
Not looking for a complete answer, just a thought as to whether or not my thought process is right, or where I've gone wrong.
Answer: According to http://www.wolframalpha.com/input/?i=x%5E2y%22%2Bxy%27%2B%28-1-x%5E2%29y%3Dx, the inhomogeneous part can be expressed as $-\dfrac{i\pi(J_1(ix)Y_0(-ix)+J_0(ix)Y_1(-ix))}{2}$ .
Comment: hmm, it gives a solution for the homogenous part, so i guess my initial conclusion that there are no negative eigenvalues for that one problem is incorrect.  thanks!


How to change the div style when you move the mouse over another element in another div?

Question: I'm working on my personal project and i need to change div style which is my cursor (from width and height 10px to width and height 100px) when i'm hovering it on h1 element inside another div.
I tried
h1:hover ~ .cursor{
  width: 100px;
  height: 100px;
}

and
h1:hover + .cursor{
  width: 100px;
  height: 100px;
}

but it didn't work in this case. Do you know how to do it?
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test</title>
    <link rel="stylesheet" href="css/main.css">

WELCOME

CSS:
@import url('https://fonts.googleapis.com/css?family=Montserrat:400,700,800&display=swap');

*, html{
    margin: 0;
    font-family: 'Montserrat', sans-serif;
    cursor: none;
}

.mainHeader{
    background: rgb(255, 255, 255);
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

h1{
    color: rgb(255, 255, 255), 255);
    font-weight: 800;
}

.cursor{
    width: 10px;
    height: 10px;
    background: rgb(255, 255, 255);
    position: absolute;
    border-radius: 50%;
    box-sizing: border-box;
    pointer-events: none;
    transition: 200ms ease-out;
    mix-blend-mode: difference;
}

h1:hover ~ .cursor{
    width: 100px;
    height: 100px;
}

here is my js code responsible for following div with the mouse:
const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
    cursor.setAttribute("style", "top: " + (e.pageY - 5) + "px; left: " + (e.pageX - 5) + "px;");
});

The cursor works because when I changed the code so that the "~" works, everything was ok.
I'm open to solutions in javascript.
Codepen version: https://codepen.io/Flayy/pen/vYBwzgE
Comment: Just a UX note - the easing of the cursor makes it feel laggy and is not nice.
Comment: You are right but that's personal project made for fun. But I agree 100%.
Answer: Hey in CSS you can only change the CSS properties of another element on hover if the element is a child or adjacent to the hovered element.
I moved your cursor div to be adjacent to the H1 element and added a + to your h1 hover css property:
CodePen: https://codepen.io/sudoxx2/pen/dybEqqY
Answer: just write two functions one on mouseenter and second on mouseleave
document.getElementById(hoverElement).addEventListener("mouseenter",function(){
     document.getElementById(cursorElement).style.width = "100px"
     document.getElementById(cursorElement).style.height = "100px"})

and add another on mouseleave
document.getElementById(hoverElement).addEventListener("mouseleave",function(){
     document.getElementById(cursorElement).style.width = "10px"
     document.getElementById(cursorElement).style.height = "10px"})

Answer: You need to add a class (or an id) on the H1 tag to be able to select it in the script, e.g.:

WELCOME

And in the script:
const bigCursor = document.querySelector('.bigCursor')

So change your 'mousemove' event function to a more flexible way to edit style:
document.addEventListener('mousemove', e => {
    cursor.style.top = e.pageY + 'px';
    cursor.style.left = e.pageX + 'px';
});

And add this to functions to respectively increase and decrease size of the cursor
bigCursor.addEventListener('mouseenter', e => {
    cursor.style.width = "100px";
    cursor.style.height = "100px";
});

bigCursor.addEventListener('mouseleave', e => {
    cursor.style.width = "10px";
    cursor.style.height = "10px";
});

At this point you may have realised that the cursor is not centered on the mouse, so add this line inside the .cursor CSS tag to fix this:
transform: translate(-50%, -50%);

Codepen version


Unable to deploy service to PCF with no-route

Question: I have this strange issue while pushing one of my application to PCF.
I wants to implement blue-green deployment for my service and I want to deploy app-v2 version with no-route and then add temp route after deployment done.
because I need to bind one marketplace service UAA Single Sign-on(Provides identity capabilities via UAA as a Service) service at application startup time.
This UAA service is causing issue while pushing.

cf command using for deployment
cf push -f manifest-dev.yml --no-route

Error screenshot:

PCF version 2.x
Answer: I have a couple ideas that might help to get around this.

Don't use --no-route. You said I want to deploy app-v2 version with no-route and then add temp route after deployment done, so just skip the --no-route part and put the temp route directly into your manifest-dev.yml file. If you already have a route in that file, you could make a copy and call it manifest-dev-v2.yml and put the route there.
Split this up. Remove your service from the manifest-dev.yml file. Run cf push -f manifest-dev.yml --no-route --no-start. Then map the temp route. Then bind the service. Then run cf start. You could alternatively drop the manifest all together, and just script your cf cli actions in a shell script or something like that.
You could look at using one of the blue/green plugins for the cf cli. There's a few and I can't recommend one over another. You can see them all here (search for blue/green).
http://plugins.cloudfoundry.org/

For a little background on the error that's being reported, the authorization code grant (Oauth2) cannot work without a redirect URL. For this flow, a user get's redirected to the login page and then get's redirected back to your redirect URL once login has occurred. Without that redirect URL, users can't complete the flow. It appears to be failing since you don't have any routes and thus cannot have a redirect URL.
Hope that helps!
Comment: Thanks for various options. I really didn't wanted to go with Option 1 as I already have more than one manifest file due to multiple environments. trying to implement option 2 and will explorer option 3 surely in future..


Animation in a single file

Question: I have the following animation for a button, for another button I need to a change few parameters. How do I do that in the same xml file. The following code is present in res/anim directory
<code><?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
 android:fromXDelta="300%" android:toXDelta="0%" android:fromYDelta="300%"
android:toYDelta="0%" android:duration="1000" android:zAdjustment="bottom" />
</code>
Comment: Copying it might be the easiest thing to do, you usually end up changing everything at the end anyway :)
Comment: Copy it to a new xml file you mean? Cant I make some changes in the same file?
Answer: The best solution although cumbersome at first is to make each animation separate, in its own file.  It may feel like duplicate code but after a while you will see that when you're changing settings in different place just to get the right effect then you'll be glad you didn't tie the two widget animations together.

Animation in a single file


Compute the likelihood in Metropolis–Hastings: How does it relate to a posterior in Bayesian Analysis?

Question: Basic question about MCMC Metropolis–Hastings algorithm. I am trying to understand the Metropolis–Hastings algorithm and it's connection to Bayesian Analysis. Suppose I want to construct an MCMC MH algrorithm to evaluate my posterior distribution in the my Bayesian Analysis.
I am looking at the step where $\alpha$ is being computed:
$$\alpha = \frac{P(\theta^* | \textbf{Y})}{P(\theta^{(i)} | \textbf{Y})}$$
Here I have (for simplicity) assumed that my prposal density in MH algorithm is symmetric.
$P(\theta^* | \textbf{Y})$ is the likelihood of $\theta^*$ given our data. So basically before the MH algorithm we need to assume a distribution for $\theta$, right? And is $P(\theta^* | \textbf{Y})$ our posterior distribution? How do I compute $P(\theta^* | \textbf{Y})$?
Also, feel free to provide an oral (in words) explanation of $P(\theta^* | \textbf{Y})$ and it's connection the posterior distribution we wish to compute.  My confusion arises with the fact that we are not able to know our posterior distribution and that is the whole point of MH. So how can comput the likelihood ...
Answer: There is a lot of confusion.
You want to evaluate  the posterior
$$
f(\theta|\mathbf{y}) =\frac{f(\mathbf{y}|\theta)f(\theta)}{f(\mathbf{y})}
$$
where I use $f()$ to indicate a density, to be as general as possible.
You have to decide the likelihood of your model, i.e., $f(\mathbf{y}|\theta)$, and the prior over $\theta$, i.e., $f(\theta)$. In other words, you have to assume a particular distribution for each of them. Then you know the functional forms of both.
To obtain samples from the posterior using an MH, you choose a starting value of $\theta$, that we call $\theta^0$. You now propose a value, from some symmetrical distribution (to make things as simple as possible), indicated with $\theta^*$. We then compute the following
$$
\alpha = \min(1,\frac{f(\mathbf{y}|\theta^*)f(\theta^*)}{f(\mathbf{y}|\theta^0)f(\theta^0)})
$$
and we sample from the uniform distribution
$$
u \sim \text{Unif}(0,1).
$$
Now, if $u<\alpha$ you set $\theta^1=\theta^*$, otherwise $\theta^1=\theta^0$.
Then you repeat the same steps to find the values of $\theta^2,\theta^3,...$, until convergence.
Comment: So the probability density is given by the prior. Ok! But It still leaves my main confusion unanswered. How should one compute $f(\textbf{Y} | \theta^*)$ or $f(\theta^*| \textbf{Y} )$ Let's for instance say I have a standard normal distribution as my prior. My observations are independent so $f(\textbf{Y} | \theta^*)$ should be $f(\textbf{Y})$ because my parameters in f is fixed
Answer: You have still a lot of confusion. I'll try to explain with an example.
Let suppose $\mathbf{Y}= (y_1, \dots ,y_n)'$,and you have
$$
Y_i = \beta_0+\beta_1x_i+\epsilon_i
$$, with
$$
\epsilon \sim N(0,\sigma^2)
$$
 i.e. a regression model.
Then your parameters are $\theta= (\beta_0, \beta_1, \sigma^2)'$.
The observation, given $\theta$, are independent and then the likelihood is
$$
f(\mathbf{Y}|\theta)= \prod_{i=1}^n f(y_i|\theta)
$$
where $f(y_i|\theta)$ is normal with mean $\beta_0+\beta_1x_i$ and variance $\sigma^2$.
As you can see, you can generally compute $f(\mathbf{Y}|\theta)$ since it is your model, it is what you assume.
Of course you have also to define prior for $\beta_0$, $\beta_1$ and $\sigma^2$, that is $f(\theta)= f(\beta_0)f(\beta_1)f(\sigma^2)$, for example.
$f(\mathbf{Y}|\theta)$ is not equal to $f(\mathbf{Y})$ because the normal likelihood depends on the parameters  $theta$.
Now, if you want to have posterior samples, $f(\theta|Y)$, you start defining some initial value $\beta_0^0$, $\beta_1^0$ and $\sigma^{2,0}$, you propose some new values, $\beta_0^*$, $\beta_1^*$ and $\sigma^{2,*}$, and using the answer that I gave previously you can update your parameters.
Notice that
$$
f(\mathbf{Y}|\theta^*)= \prod_{i=1}^n f(y_i|\theta^*)
$$
where $f(y_i|\theta^*)$ is normal with  mean $\beta_0^*+\beta_1^*x_i$ and variance $\sigma^{2,*}$.
BTW: you don't need to compute the posterior, the idea is to get samples from the psoterior $f(\theta|\mathbf{Y})$
Comment: I would suggest you merge both answers into one.


Write dynamically allocated structure to file

Question: Suppose we have following structure:
    struct Something {
        int i;
    };

If I want to write in a file any data of this type(dynamically allocated), I do this:
struct Something *object = malloc(sizeof(struct Something));
object->i = 0; // set member some value
FILE *file = fopen("output_file", "wb");
fwrite(object, sizeof(struct Something), 1 file);
fclose(file);

Now, my questions:
How we do this with a structure what contains pointers? I tested using same method, it worked fine, data could been read, but I want to know if there are any risks?
Comment: the pointers are only relevant during THIS particular instance of the program. if you write a pointer out to a file, then read it back into some other process later on, it'll be just a random number and cause major problems - the new instance's memory layout/usage will be completely different.
Comment: If you are talking about structures like Linked Lists, then write the data in order without pointers. When reading, you will need to recreate the List with pointer allocations after reading the data.
Answer: What you want is called serialization. See also XDR (a portable binary data format) & libs11n (a C++ binary serialization library); you often care about data portability: being able to read the data on some different computer.
"serialization" means to "convert" some complex data structure (e.g. a list, a tree, a vector or even your Something...) into a (serial) byte stream (e.g. a file, a network connection, etc...), and backwards. Dealing with circular data structures or shared sub-components may be tricky.
You don't want to write raw pointers inside a file (but you could), because the written address probably won't make any sense at the next execution of your program (e.g. because of ASLR), i.e. when you'll read the data again.
Read also about application checkpointing and persistence.
For pragmatic reasons (notably ease of debugging and resilience w.r.t. small software evolution) it is often better to use some textual data format (like e.g. JSON or Yaml) to store such persistent data.
You might also be interested in databases. Look first into sqlite, and also into DBMS ("relational" -or SQL based- ones like PostGreSQL, NoSQL ones like e.g. MongoDB)
The issue is not writing a single dynamically allocated struct (since you want mostly to write the data content, not the pointer, so it is the same to fwrite  a malloc-ed struct or a locally allocated one), it is to serialize complex data structures which use lots of weird internal pointers!
Notice that copying garbage collectors use algorithms similar to serialization algorithms (since both need to scan a complex graph of references).
Also, on today's computers, disk -or network- IO is a lot  (e.g. a million times) slower than the CPU, so it makes sense to do some significant computation before writing files.


Why does the rcp-Plugin-product does not start in the excepted way and why does after launching the property 'preferenceCustomization' disappear?

Question: I created a product of my RCP-Plugin-project. In my RCP-Plugin-project I have implemented an own perspective for my plugin to start with. Running my plugin as application, everything works fine and I can see my perspective.
To set my perspective as default I have added a 'property' preferenceCustomization to the plugin.xml of my product. The code of related plugin_customization.ini is the following:
org.eclipse.ui/SHOW_PROGRESS_ON_STARTUP = false
org.eclipse.ui/defaultPerspectiveId=de.cau.cs.bdd.perspective

The plugin.xml of the application:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
   <extension
         point="org.eclipse.ui.perspectives">
      <perspective
        class="bdd.klighd.Perspective"
        fixed="true"
        id="de.cau.cs.bdd.perspective"
        name="BDD Perspective">
      </perspective>
   </extension>
   <extension
         point="de.cau.cs.kieler.klighd.diagramSyntheses">
       <diagramSynthesis
         class="de.cau.cs.kieler.klighd.syntheses.GuiceBasedSynthesisFactory:bdd.klighd.BDDDiagramSynthesis"
         id="bdd.klighd.BDDDiagramSynthesis">
       </diagramSynthesis>
   </extension>
   <extension
     point="de.cau.cs.kieler.klighd.ui.view.controller">
      <controller
        class="bdd.klighd.BDDEditorViewController">
      </controller>
   </extension>
   <extension
         point="org.eclipse.ui.editors">
      <editor
        class="bdd.klighd.BDDEditor"
        default="true"
        id="bdd.klighd.BDDEditor"
        name="BDDEditor">
      </editor>
   </extension>
   <extension
     point="org.eclipse.ui.commands">
      <command
        defaultHandler="bdd.klighd.CallBDDEditor"
        id="bdd.klighd.openBDDEditor"
        name="Open BDDEditor">
      </command>
   </extension>
   <extension
     point="de.cau.cs.kieler.klighd.ui.view.editor">
      <editor
        controllerID="bddcontroller"
        editorID="bdd.klighd.BDDEditor">
      </editor>
   </extension>
   <extension
     point="org.eclipse.ui.elementFactories">
      <factory
        class="bdd.klighd.ElementFactory"
        id="bdd.klighd.factory">
      </factory>
   </extension>
   <extension
    point="org.eclipse.ui.perspectiveExtensions">
    <perspectiveExtension
 targetID="de.cau.cs.bdd.perspective">
     <hiddenMenuItem id="org.eclipse.ui.run"></hiddenMenuItem>
     <hiddenMenuItem id="navigate"></hiddenMenuItem>
     <hiddenMenuItem id="file"></hiddenMenuItem>
     <hiddenMenuItem id="project"></hiddenMenuItem>
     <hiddenMenuItem id="window"></hiddenMenuItem>
     <hiddenMenuItem id="help"></hiddenMenuItem>
     <hiddenMenuItem id="edit"></hiddenMenuItem>
      <hiddenMenuItem id=" org.eclipse.search.menu"></hiddenMenuItem>
         </perspectiveExtension>
 </extension>
</plugin>

The plugin.xml of the product:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
    <plugin>
   <extension
     id="product"
     point="org.eclipse.core.runtime.products">
      <product
        application="org.eclipse.ui.ide.workbench"
        name="BDDProduct">
         <property
           name="appName"
           value="BDDProduct">
         </property>
         <property
           name="rendererFactoryUri"
           value="bundleclass://swt.renderer/swt.renderer.RendererFactory">
         </property>
         <property
           name="preferenceCustomization"
           value="plugin_customization.ini">
         </property>
      </product>
   </extension>
 </plugin>

Oddly enough launching my product I obtain an empty eclipse-window and the property preferenceCustomization has disappeared.
Does anybody know why this could happen? And how to fix it?
Comment: Show us your plugin.xml defining the application and product.
Comment: @greg-449: I have added the `plugin.xml` code.
Comment: Is the `plugin_customization.ini` file in the root directory of the plugin containing the products extension point and is it included in the `build.properties`?
Comment: @greg-449: Yes, the `plugin_customization.ini` is included in the `build.properties` of the product and the files `plugin_customization.ini`, `build.properties` and `plugin.xml` of the product are in the same directory.
Answer: To preserve the preferenceCustomization property when you synchronize the product add this to the end of the .product file:
   <preferencesInfo>
      <targetfile overwrite="false" path="/my-project/plugin_customization.ini"/>
   </preferencesInfo>

   <cssInfo>
   </cssInfo>

I discovered this when I was researching the purpose of the Customization tab in the product view.
(tested on Eclipse Neon.2 - 4.6.2)
Answer: The RCP-Plugin did not start at the excepted way, because some plugins were missed at auto-start and an exception in the perspective-class was not catched. The solution was to add org.eclipse.ui.ide.application, org.eclipse.core.runtime, org.eclipse.equinox.common, org.eclipse.equinox.ds, org.eclipse.equinox.event and org.eclipse.equinox.simpleconfigurator to the Start Levels at the Configuration -tab of the product and to catch the exception in the perspective-class.
Synchronizing the product initiated that the property disappeared. (I still don`t know why!) Exporting the product without synchronizing was the help.


Integration of a equation

Question: $$\int_{x}^{y}\left[\sum_{i=1}^{N}\sqrt{a}\cos\left(\frac{2\pi(d_{i}-a)}{\lambda} \right)\right]^{\!2}da$$
Can anyone solve this integration for me
I don't know how the summation and integration will behave with each other
Comment: It's a finite sum as you've written it. You can easily switch the order of integration and summation if you wish. Incidentally, this would be a better question on Mathematics.StackExchange.
Comment: If you do post it elsewhere, it's best to delete it here. Stack Exchange discourages posting identical questions in multiple places. https://meta.stackexchange.com/questions/64068/is-cross-posting-a-question-on-multiple-stack-exchange-sites-permitted-if-the-qu
Comment: Do you mean the variable of integration $a=d_k$ for some $1\le k\le N?$
Comment: Okay Thanks @AdrianKeister for your help. I will post there  my question
Comment: Oh, forgot about the fact that the sum is squared. I would probably try to expand out the sum, then see if I could integrate term-by-term.
Comment: Do you have any notion what the $d_i$ are?
Comment: $$d_{i}$$ is the random value generated for N times and (a) is also one of them
Comment: Yes @AdrianKeister you got the point right
Comment: @AdrianKeister can you suggest how to get it in a right way
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/125037/discussion-between-parveen-and-adrian-keister).
Answer: You have to square the sum first. Note that the $\sqrt{a}$ is common to all terms in
$$\sqrt{a}\cos\left(\frac{2\pi(d_{i}-a)}{\lambda} \right)\cdot \sqrt{a}\cos\left(\frac{2\pi(d_{j}-a)}{\lambda} \right),$$
so it can factor out as $a.$ That is, we have
$$\int_{x}^{y}a\left[\sum_{i=1}^{N}\cos\left(\frac{2\pi(d_{i}-a)}{\lambda} \right)\right]^{\!2}da.$$
We must now square the sum in order to proceed:
\begin{align*}
&\phantom{=}\left[\sum_{i=1}^{N}\cos\left(\frac{2\pi(d_{i}-a)}{\lambda} \right)\right]^{\!2}\\
&=\sum_{i,j=1}^{N}\cos\left(\frac{2\pi(d_i-a)}{\lambda} \right)\cos\left(\frac{2\pi(d_j-a)}{\lambda} \right)\\
&=\sum_{i,j=1}^{N}\cos\left(\frac{2\pi d_i}{\lambda}-\frac{2\pi a}{\lambda} \right)\cos\left(\frac{2\pi d_j}{\lambda}-\frac{2\pi a}{\lambda}\right)\\
&=\frac12\sum_{i,j=1}^{N}\left[\cos\left(\frac{2\pi d_i}{\lambda}-\frac{2\pi d_j}{\lambda} \right)+\cos\left(\frac{2\pi d_i}{\lambda}+\frac{2\pi d_j}{\lambda}-\frac{4\pi a}{\lambda}\right)\right]\\
&=\frac12\sum_{i,j=1}^{N}\left[\cos\left(\frac{2\pi(d_i-d_j)}{\lambda}\right)+\cos\left(\frac{2\pi(d_i+d_j)}{\lambda}-\frac{4\pi a}{\lambda}\right)\right].
\end{align*}
Now we can move the integral inside the sum:
\begin{align*}
\int&=\int_x^y\frac{a}{2}\sum_{i,j=1}^{N}\left[\cos\left(\frac{2\pi(d_i-d_j)}{\lambda}\right)+\cos\left(\frac{2\pi(d_i+d_j)}{\lambda}-\frac{4\pi a}{\lambda}\right)\right]da\\
&=\frac12\sum_{i,j=1}^{N}\int_x^y a\left[\cos\left(\frac{2\pi(d_i-d_j)}{\lambda}\right)+\cos\left(\frac{2\pi(d_i+d_j)}{\lambda}-\frac{4\pi a}{\lambda}\right)\right]da\\
&=\frac12\sum_{i,j=1}^{N}\left[\int_x^y a\cos\left(\frac{2\pi(d_i-d_j)}{\lambda}\right)da+\int_x^ya\cos\left(\frac{2\pi(d_i+d_j)}{\lambda}-\frac{4\pi a}{\lambda}\right)da\right].
\end{align*}
To continue, we note that according to the comments, there exists $k,\;1\le k\le N$ such that $d_k=a.$ Without loss of generality, we will just assume that $k=N,$ so that $d_N=a.$ Now with the double-sum over $i$ and $j,$ we have four cases to deal with:

$i\not=N, j\not=N.$ The integral is then
\begin{align*}
&\phantom{=}\frac12\sum_{i,j=1}^{N-1}\left[\int_x^y a\cos\left(\frac{2\pi(d_i-d_j)}{\lambda}\right)da+\int_x^ya\cos\left(\frac{2\pi(d_i+d_j)}{\lambda}-\frac{4\pi a}{\lambda}\right)da\right]\\
&=\frac12\sum_{i,j=1}^{N-1}\Bigg[\left(\frac{y^2}{2}-\frac{x^2}{2}\right)\cos\left(\frac{2\pi(d_i-d_j)}{\lambda}\right)\\
&\qquad+\int_x^ya\cos\left(\frac{2\pi(d_i+d_j)}{\lambda}-\frac{4\pi a}{\lambda}\right)da\Bigg]
\end{align*}
$i\not=N, j=N.$ For this case, there are $N-1$ terms, and the integral is
\begin{align*}
&\phantom{=}\frac12\sum_{i=1}^{N-1}\left[\int_x^y a\cos\left(\frac{2\pi(d_i-a)}{\lambda}\right)da+\int_x^ya\cos\left(\frac{2\pi(d_i+a)}{\lambda}-\frac{4\pi a}{\lambda}\right)da\right]\\
&=\frac12\sum_{i=1}^{N-1}\left[\int_x^y a\cos\left(\frac{2\pi(d_i-a)}{\lambda}\right)da+\int_x^ya\cos\left(\frac{2\pi(d_i-a)}{\lambda}\right)da\right]\\
&=\sum_{i=1}^{N-1}\int_x^y a\cos\left(\frac{2\pi(d_i-a)}{\lambda}\right)da.
\end{align*}
$i=N, j\not=N.$ For this case, there are $N-1$ terms, and the integral is
\begin{align*}
&\phantom{=}\frac12\sum_{j=1}^{N-1}\left[\int_x^y a\cos\left(\frac{2\pi(a-d_j)}{\lambda}\right)da+\int_x^ya\cos\left(\frac{2\pi(a+d_j)}{\lambda}-\frac{4\pi a}{\lambda}\right)da\right]\\
&=\frac12\sum_{j=1}^{N-1}\left[\int_x^y a\cos\left(\frac{2\pi(d_j-a)}{\lambda}\right)da+\int_x^ya\cos\left(\frac{2\pi(d_j-a)}{\lambda}\right)da\right]\\
&=\sum_{j=1}^{N-1}\int_x^y a\cos\left(\frac{2\pi(d_j-a)}{\lambda}\right)da.
\end{align*}
This is the same expression as in Case 2, so we can consolidate these two cases into one case that's doubled: Case 2 and 3:
$$2\sum_{j=1}^{N-1}\int_x^y a\cos\left(\frac{2\pi(d_j-a)}{\lambda}\right)da.$$
$i=j=N.$ For this case, there's only $1$ term, and the integral is
$$\frac12\left[\int_x^y a\,da+\int_x^ya\,da\right]=\int_x^ya\,da=\frac{y^2}{2}-\frac{x^2}{2}.$$

This is getting rather unwieldy to continue writing down. I would just remark that the integral
$$\int_x^y a\cos(c+a)\,da=\cos(c+y)+y\sin(c+y)-\cos(c+x)-x\sin(c+x).$$
All the remaining integrals are of this form. I'll let you finish.

Integration of a equation


Windows Store App Standard styles vs. Windows store App Guidelines for Fonts

Question: I'm developing my first Windows store app, and I have an issue with styles. Any new Windows store app project in VS 2012 has a StandardStyles.xaml resources dictionary. This resources dictionary contais a lot of styles for all the textblock controls, but this styles aren't consistencies with the styles in the Windows Store App Guidelines For Fonts. For example
- HeaderTextStyle is a style for page headers in StandardStyles.xaml and it has a FontSize setter with value=56;
- Page header, in Windows Store App Guidelines for Font, has the FontSize property value equal to 42
What is the right choise?
Someone can help me?
Answer: This is a matter of units.  It is a 42pt font, which is 56 pixels.
Here is a blog post that might help: http://w8isms.blogspot.com/2012/06/metro-fonts-points-pixels.html


Sum of subspace and its orthogonal complement

Question: Let $V$ be a (not necessarily finite-dimensional) vector space (over a field $K$), $U$ a subspace of $V$ and $\beta\colon V \times V \to K$ a bilinear form. Define $U^\perp = \{v\in V : \beta(v,u)=0 \ \  \forall u \in U \}$ to be the (left) orthogonal complement of $U$. Which conditions do we need in order to get the identity $V = U + U^\perp$ or $V = U \oplus U^\perp$? I think one needs $U$ to be finite-dimensional and $\beta|_{U\times U}$ to be non-degenerate. Is it then possible for any given vector $v\in V$ to construct a (probably unique) vector $u\in U$ (dependent on $v$) such that $v-u\in U^\perp$, maybe via the map $v \mapsto \sum_{i=1}^m \beta(v,u_i)u_i $ for any given basis $\{u_1,\dotsc,u_m\}$ of $U$?
A more general thought:
The condition of $\beta|_{U\times U}$ being non-degenerate means that if $u\in U$ and $\beta(u,u')=0$ for all $u'\in U$ then $u=0$. So this is equivalent to $U\cap U^\perp = \{0\}$. If we ignore this condition, that means $U\cap U^\perp \ne \{0\}$, what do we still need for $V = U + U^\perp$?
Comment: Thanks, but what if $\beta(u_i,u_i)=0$, for example when $\beta$ is an alternating bilinear form?
Answer: $\newcommand{\R}{\mathbf R}$
$\newcommand{\C}{\mathbf C}$
$\newcommand{\Q}{\mathbb Q}$
$\newcommand{\Z}{\mathbb Z}$
$\newcommand{\set}[1]{\{#1\}}$
$\newcommand{\lrset}[1]{\left\{#1\right\}}$
$\newcommand{\mc}{}$
$\newcommand{\rank}{\text{rank}}$
$\newcommand{\ann}{\text{Ann}}$
Until otherwise mentioned, $V$ is a finite dimensional vector space over a field $F$ and $f$ is a Bilinear form on $V$.
We will use $L^2(V, F)$ to denote the set of all the bilinear forms on $V$ and $\ann(W)$ will denote the annihilator of a subspace $W$ of $V$.
#Fundamentals

Definition.
For each $f\in \mc L^2(V;\ F)$ define $L_f:V\to V^*$ as
$$
 L_f(u)=g_u,\quad \forall u\in V
$$
where $g_u\in V^*$ is define as
$$
 g_u(v)=f(u,v),\quad\forall v\in V
$$

Similarly, for each $f\in \mc L^2(V,F)$ define $R_f:V\to V^*$
as
$$
 R_f(v)=h_v,\quad \forall v\in V
$$
where $h_v\in V^*$ is defined as
$$
 h_v(u)=f(u,v),\quad\forall u\in V
$$
It can be seen that $L_f$ and $R_f$ are linear transformations for each $f\in \mc L^2(V;\ F)$.
The following theorem is immediate:

Theorem.
Let  $f\in \mc L^2(V;\ F)$.
Then $\rank L_f=\rank R_f$.

Proof.
Identifying $V^{**}$ with $V$, it can be easily seen that $L_f^t=R_f$.
$\blacksquare$

Definition.
Let $f\in \mc L^2(V;\ F)$.
Then the rank of $f$ is defined as
$$\rank f=\rank L_f=\rank R_f$$
We say say that $f$ is non-degenerate if $\rank f=\dim V$.
More generally, we say that $f$ is non-degenerate on a subspace $W$ of $V$ if $\rank L_{f|W}=\dim W$.

#Orthogonality
Let $f\in \mc L^2(V;\ F)$.
Let $u$ and $v$ be two vectors in $V$.
We say that $u$ is perpendicular to $v$, written $u\perp v$, if $f(u,v)=0$.
Given subspace $W$ of $V$, we define the orthogonal complement of $W$ as $W^\perp=\set{u\in V:\ w\perp u\text{ for all } w\in W}$.
Note that $v\in W^\perp$ if and only if $R_fv\in \ann(W)$.

Theorem.
Let $f$ be a non-degenerate bilinear form on a finite dimensional vector space $V$.
Then for any subspace $W$ of $V$, we have $\dim(W)+\dim(W^\perp)=\dim(V)$.

Proof.
Since $f$ is non-degenerate, we have $R_f:V\to V^*$ is an isomorphism.
As just commented, we have $v\in W^\perp$ if and only if $R_fv\in W^\perp$.
Thus $W^\perp=R_f^{-1}(\ann(W))$.
Since $R_f$ is an isomorphism, we  have $\dim(R_f^{-1}(\ann(W)))=\dim(\ann(W))=\dim(V)-\dim(W)$.
Thus $\dim(W^\perp)=\dim(V)-\dim(W)$, and we have the desired equality.
$\blacksquare$
The conclusion is no longer true if we drop the non-degenracy condition. This is because if we construct a bilinear form for which the image of $R_f:V\to V^*$ intersects $\ann(W)$ only in $0$, then we would have $W^\perp=0$
Comment: Thank you! Does this also hold if the surrounding vector space is infinite-dimensional while the subspace is finite-dimensional? Do we still get a direct sum, provided that the bilinear form is non-degenerate on that subspace? Maybe I should have formulated my original question that way because it is a more interesting issue for me.
Comment: I am no expert on infinte dimensional vector spaces. But the isomorphism $L^2(V, F)\cong L(V, V^*)$ does not fold for infinite dimensional spaces (I think). So I wouldn't think that the above goes through for infinite dimensional spaces.
Answer: A friend of mine was able to construct a vector $u$ such that $v-u \in U^\perp$.
Assume that $U$ is finite-dimensional and $\beta|_{U\times U}$ is non-degenerate (which of course is equivalent to $U \cap U^\perp = \{0\}$). Now for any given basis $\{u_1, \dotsc, u_m\}$ of U consider the map $\phi\colon V \to U$ given by $v \mapsto \sum_{i=1}^m \beta(v,u_i)u_i$ as in my original post. How does the kernel of this map look like? We have $v \in \ker(\phi) \Leftrightarrow 0 = \phi(v) = \sum_{i=1}^m \beta(v,u_i)u_i \Leftrightarrow \forall i\in\{1,\dotsc,m\}\colon \beta(v,u_i)=0\Leftrightarrow v \in U^\perp$ (the second right implication is true because of linear independency). So we have $\ker(\phi) = U^\perp$ and it follows for the restriction $\phi|_U$ that $\ker(\phi|_U) = \ker(\phi) \cap U = U^\perp \cap U = \{0\}$ which means that $\phi|_U$ is injective. Since $U$ is finite-dimensional, it is also bijective.
Now consider the map $\psi \colon U \to V$ given by $u \mapsto  (\phi|_U)^{-1}(u)$. One can easy check the identity $\phi\circ\psi = \mathrm{id}_U$ and also $\mathrm{im}(\psi) = U$. Now let $v \in V$ be any vector, which we can write as $v = \psi\circ\phi(v) + (v - \psi\circ\phi(v))$. The first summand obviously is an element of $U$, the second one an element of $U^\perp = \ker(\phi)$ because of $\phi(v - \psi\circ\phi(v)) = \phi(v) - \phi \circ \psi \circ \phi(v) = \phi(v) - \mathrm{id}_U \circ\phi(v) = 0$.
So all in all, $\psi\circ\phi(v)$ is the vector I was searching for and one does not need $V$ to be finite-dimensional.


Warn user about unsaved changes to a form, when a form is being replaced during an AJAX call?

Question: I'm new to Javascript and JQuery, and I'm implementing a warning to users that displays when they have made unsaved changes to a form's input/select/textarea elements if they navigate away from a page. I currently have the following which works fine when they leave a static form page:
/*
 * Warn users when leaving a page with unsaved content, watches elements: (input, textarea, select) unless
 * they are tagged with the "noWarning" class
 */
$(document).ready(function() {
    $(document).on('change', 'input:not(.noWarning),textarea:not(.noWarning),select:not(.noWarning)', function () {
        window.onbeforeunload =  function(e) {
              return 'You have unsaved changes';
        };
    });
});

The only page where it does not work, is in our main editing page. This page, unlike the others, has multiple tabs for editing different aspects of an item, which when clicked, trigger an AJAX call which replaces the content div with the appropriate form for editing the different aspect.
No warning dialog is displayed when a user clicks on a tab though, so any unsaved changes to the input are lost.
My intuition is that because the url is not changing, onBeforeUnload() is not executing. So I would have to check for any changes directly in the function which handles the AJAX call for replacing the form when a tab is clicked:
function clickedTabbedMenu() {
   // This function replaces the content div with a new div and form
}

So my question is, how do I go about checking if any changes have been made to the elements in the current form before I replace the content div with another??? Can I directly call the "change" event listener for a true/false??? Or perhaps a different approach to handle this page's warning messages?
Any help is appreciated
Comment: If you are looking for a solution which raises onbeforeunload event when an ajax call made then it is nearly impossible. You need to have your own implementation to detect changes when makeing ajax call.
Comment: It is not necessary to call onbeforeunload.... I was thinking more along the lines of, when I call the function on the tab to switch forms, query the currently loaded form for a "has the user made changes to any element?" and if so display an alert on whether to continue or not, else, just continue replacing the form
Answer: Attach a change event handler to all the elements of the form. Have a variable outside the handler's scope dirty (or even a data on the form element) be set to false when a form is loaded, and true on every change event. Then, before replacing the form, check if dirty.
This would also be a good strategy for your non-AJAX pages as well - instead of setting the whole onBeforeUnload each time an element changes, just set onBeforeUnload once, and check if dirty inside it. This makes handling your AJAX and non-AJAX pages very similar.
EDIT: Untested because it's late and I need bed, but basically:
$(document).ready(function() {
    var dirty = false;
    $(document).on('change', 'input:not(.noWarning),textarea:not(.noWarning),select:not(.noWarning)', function () {
        dirty = true;
    });
    function checkDirty() {
          if (dirty) {
              alert('You have unsaved changes');
              return false;
          }
          return true;
    }
    // for non-AJAX pages
    window.onbeforeunload =  function(e) {
        return checkDirty();
    };
    // for AJAX pages
    $('.ajax_navigation_tab').on('click', function() {
        if (!checkDirty()) {
            // do the ajax thing
            dirty = false;
        }
    });
});

Comment: Could you explain this a bit more indepth? How would this be different from what the first $document.on('change'....) function does
Answer: I would try checking for and calling window.onbeforeunload() in your ajax script.
If it exists and returns a string, use it as an error message and halt the operation :)


2 joomla sites in the same webserver

Question: people i have to create a second site in the same webserver that i already have my first site. i,m not sure on how i can do this, i would not like to have to change all the url that i have already created. i was thinking on installing a second joomla inside the folder where is the first one. the url will be www.myweb1.com/joomla2, that is something that i would not like is there a way by my dns that i can  change that www.myweb1.com/joomla2, to www.joomla2.com
I just want to create a new joomla site in the same webserver that i already have one joomla site. I,m using apache2 with opensuse. the first site already have a vhost to manage https rewrite conditions.
Any recomendation.
Answer: You can use the proxy functionality of Apache HTTPD.
Such configuration might look like:
<code><VirtualHost *>
ServerName www.joomla2.com

ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>

ProxyPass / http://www.myweb1.com/joomla2
ProxyPassReverse / http://www.myweb1.com/joomla2
<Location />
Order allow,deny
Allow from all
</Location>
</VirtualHost>
</code>

2 joomla sites in the same webserver


SELECT COM FORMATAÇÃO DE STRING

Question: Utilizando o Banco de Dados MySQL, tendo a intenção de realizar a consulta em uma determinada tabela cujo um de seus campos data possui como tipo VARCHAR(8).
Query SQL - Atual
SELECT `t_movimentacao`.`data` FROM t_movimentacao
WHERE `t_movimentacao`.`id` = '1';

Executando a query atual obtemos o seguinte retorno: 23072019
|   data   |
- 23072019 -

Sabendo que a string contem uma data no formato dd/mm/yyyy, sem a caractere de / como podemos formatar e personalizar este campo diretamente na consulta do mesmo.
Desejo uma Query SQL - Formatando o campo data para obeter o segunte resultado na consulta: 23/07/2019
|    data    |
- 23/07/2019 -

Como formatar a string para colocar as / e receber a data no formato desejado diretamente no SQL?
Answer: Se não tiver a necessidade de trabalhar com DATA, somente para formatação e apresentação a partir do sql pode utilizar a função CONCAT e SUBSTR.
A função CONCAT concatena um ou mais parâmetros e a função SUBSTR extrai uma substring de uma string passando a string o inicio que deseja iniciar e quantos caracteres. Caso tenha necessidade, acredito que terá q converter a string em data e considerar a configuração do mysql.
SELECT
  CONCAT(SUBSTR(t_movimentacao.data, 1, 2), "/", SUBSTR(t_movimentacao.data, 3, 2), "/", SUBSTR(t_movimentacao.data, 5, 4))
FROM t_movimentacao
WHERE t_movimentacao.id = '1';

Comment: Muito obrigado amigo, funcionou perfeitamente! Eu sabia que o SQL detêm funcionalidades avançadas de consulta embora não as conheça. Agradeço pelo espirito solicito de todos que aqui me ajudaram a resolver o problema. Obrigado.
Answer: SELECT cast(left(data,2) as nvarchar) + '-' + SUBSTRING(data,3,2) + '-' +
cast(RIGHT(data,4) as nvarchar) as data FROM t_movimentacao
WHERE id = 1;

Answer: SELECT DATE_FORMAT(`t_movimentacao`.`data`, '%d / %m / %y') FROM t_movimentacao
WHERE `t_movimentacao`.`id` = '1';

veja se vai assim
Comment: Infelizmente o valor retornou nulo.
Comment: Tenta alterar a letra maiuscula, ou algo pois o banco é Case Sensitive.
Comment: esse DATE_FORMAT funciona com uma data prevista já, o que pode ser feito é um outro select dentro retornando no primeiro select e utilizando após
Comment: Essa dica deve funcionar mesmo se o campo for vachar? infelizmente não estou logrando exito aqui.
Comment: Eu consigo obter algum resultado usando isso ```format(`t_movimentacao`.`11_data_de_movimentacao`, '%d/%m/%yyyy')``` e como resultado recebo a data nesse formato: `2,372,019`.
Comment: ATENÇÃO, não será útil utilizar a função DATE_FORMAT pois o campo não é do tipo DATE, é do tipo VARCHAR, ou seja, o DATE_FORMAT não irá entender como se o valor fosse data.

SELECT COM FORMATAÇÃO DE STRING


C# ExcelPackage (EPPlus) DeleteRow does not change sheet dimension?

Question: I am trying to build a data import tool that accepts an EXCEL file from the user  and parses the data from the file to import data into my application.
I am running across a strange issue with DeleteRow that I cannot seem to find any information online, although it seems like someone would have come across this issue before. If this is a duplicate question, I apologize, however I could not find anything related to my issue after searching the web, except for this one which still isn't solving my problem.
So the issue:
I use the following code to attempt to "remove" any row that has blank data through ExcelPackage.
<code>                for (int rowNum = 1; rowNum <= ws.Dimension.End.Row; rowNum++)
                {
                    var rowCells = from cell in ws.Cells
                                        where (cell.Start.Row == rowNum)
                                        select cell;
                    if (rowCells.Any(cell => cell.Value != null))
                    {
                        nonEmptyRowsInFile += 1;
                        continue;
                    }
                    else ws.DeleteRow(rowNum);
                    //Update: ws.DeleteRow(rowNum, 1, true) also does not affect dimension
                }
</code>
Stepping through that code, I can see that the DeleteRow is indeed getting called for the proper row numbers, but the issue is when I go to set the "total rows in file" count on the returned result object:
<code>parseResult.RowsFoundInFile = (ws.Dimension.End.Row);
</code>
ws.Dimension.End.Row will still return the original row count even after the calls to DeleteRow.
My question is...do I have to "save" the worksheet or call something in order for the worksheet to realize that those rows have been removed? What is the point of calling "DeleteRow" if the row still "exists"? Any insight on this would be greatly appreciated...
Thanks
Comment: *Have* you tried saving? Besides, Excel isn't affected by how many rows or columns are actually stored in a sheet. If you specify a larger range for calculations or for filling, it will work just fine. There are no *removed* rows, there are only empty rows
Comment: Saving the file in excel? Of course I saved the file in excel...but when I upload the file with the last 5 "blank rows", and execute the above code to *delete* those 5 rows using ExcelPackage (my intention *is* to remove those rows, similar to how one would "delete and shift rows up" in excel, the EPPlus method even gives that option as a parameter), the Dimenion of the file still shows those 5 rows as being in the document, even after a call to DeleteRow with those 5 row ids.

Is there a way I am supposed to "save" the worksheet (ws) in EPPlus before calling the dimension?
Comment: The point is - it shouldn't matter! Once you save the sheet *in your code* it should remove redundant rows. But it still wouldn't matter because it's perfectly valid to address cells, rows that are empty. What if your data started at row 10? Would you consider 1-9 as deleted?
Comment: Why this question? Is there a different problem you are trying to solve? Did you encounter some other issue and think that deleting rows is the answer?
Comment: I think you are misunderstanding...if rows 1-9 were blank, (as in there are no cells with non null data in that row), it will call DeleteRow on that row number.

I have finally figured out the issue. It is a closure problem inside my for loop. I still have to figure out how I'm going to approach this, since it appears that as soon as you "delete" a row, you have to call:

ws = excelPackage.Workbook.Worksheets.First();

again to grab a new reference to the worksheet. If you call dimension on that, it will return the correct row count (with the removed rows).
Answer: I think I figured out the problem. This is yet again another closure issue in C#. The problem is that the reference to "ws" is still the same reference from before the DeleteRow call.
In order to get the "updated" dimension, you have to redeclare the worksheet, for example:
<code> ws = excelPackage.Workbook.Worksheets.First();
</code>
Once you get a new reference to the worksheet, it will have the updated dimensions, including any removed/added rows/columns.
Hopefully this helps someone.
Comment: Just a note to mention thanks for posting the answer to your own (somewhat obscure) question. Doing this probably saved me many hours. I owe you a beer!


Text box should not accept 0's using jQuery

Question: I'm trying to validate the textbox that should not contain all 0's or even just 1 zero, but it can contain any alphanumeric..
Condition is if we give just 0 or all 0's, it should not allow. Can we just check with the val?
Here is the code
$(document).ready(function () {
  $("#btnSave").click(function(){
    AlertSave();
  });
});

function AlertSave(){
  if($('#txt').val() == '0'){
    alert('should not be 0')
  }
}

Fiddle
Comment: You're probably better off using a regex than just checking the value.
Comment: You are checking if the entire value is '0' not whether or not it *contains* a '0'.  You could use regex or just do `$('#txt').val().IndexOf('0') > -1`.
Answer: Check if all characters are '0':
if ([].every.call($('#txt').val(), _ => _ === '0')){
      alert('should not be 0')
    }

Comment: super.. every.call will check all characters by keeping in the array?
Comment: It just treats the string like an array, passing each character to the compare function.
Answer: Try using Parsley pattern tag with regex to validate your field. check out this How to use the parsley.js pattern tag?
Answer: Remove extra spaces, break lines, tabs
    function AlertSave() {
    var val = $('#txt').val().replace(/[\s\n\r]/g,"");
         if( val == 0 || val.indexOf("0") > -1){
          alert('should not be 0')
        }
    }


What would cause ifconfig NIC frame drop counts to increase SLOWLY (90-100 frames per day)?

Question: I have a web appliance running CentOS 5.11.  It sees a fair amount of traffic (apologies, I don't have specific numbers but I know it's in use).
For some reason, I'm seeing ifconfig error counts slowly incrementing on it.
eth0      Link encap:Ethernet  HWaddr AA:BB:CC:DD:EE:FF
          inet addr:22.214.171.124  Bcast:184.108.40.206  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:202723544 errors:0 dropped:4959 overruns:0 frame:37
          TX packets:158354057 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4261083782 (3.9 GiB)  TX bytes:1224803677 (1.1 GiB)
          Interrupt:83 Memory:f6bf0000-f6c00000

(IP and MACs are renamed to protect the innocent).
The dropped count increases roughly 90-100 frames per day.  Does this indicate any issues? Is this "normal"?
Also, what does frame:37 mean?
Comment: `frame:37` are Ethernet frames that failed the CRC check
Answer: I came across a blog post that I believe answers this question:
Here's the lowdown:

RX packets: represent the total number of packets that were received. This includes ALLLLLLLLL network data units that made it to the interface (including stuff that was malformed/invalid/rejected).
(RX) errors: represent the number of packets that had "errors".  A lot of documentation on the net is quick to label this counter as the number of frames that failed CRC checks. While that's certainly a possible explanation, that's not the ONLY reason why an error could occur.  Other possibilities include (but aren't limited to):

Frames that are too long.
Ring-buffer overflow (The ring buffer is "a buffer that the NIC transfers frames to before raising an IRQ with the kernel")
fifo overruns (explained below)
Missed packets

(RX) overruns: represent the number of fifo overruns.  Overruns are caused when kernel can't keep up with the rate that the ring-buffer is being drained at.
(RX) frames:represent the number of incoming frames that were misaligned (frame size that is indivisible by eight).

Sources:
http://searchnetworking.techtarget.com/tip/Common-network-errors-and-causes
http://www.gnu.org/software/inetutils/manual/inetutils.html
http://blog.hyfather.com/blog/2013/03/04/ifconfig/
Answer: I believe "frame" is a count of the packets received with framing errors (which generally mean bad frame checksums).  Some kind of corruption.  Bad hardware somewhere is a likely cause, but you can see this with a duplex mismatch (full-duplex on one side, half on the other) so check that first.
You're not seeing that many, so it's likely a component that's marginal rather than totally failing.
Comment: If it was framing errors though, wouldn't the actual `errors:` field go up?


AFT models in Stata with time-varying covariates

Question: The AFT models from Stata's streg can handle time-varying covaraites. In particular, the manual states that

streg is suitable only for data that have been stset. By stsetting your data, you define the
variables _t0, _t, and _d, which serve as the trivariate response variable $(t_0, t, d)$. Each response
corresponds to a period under observation, $(t_0, t]$, resulting in either failure $(d = 1)$ or right-censoring
$(d = 0)$ at time $t$. As a result, streg is appropriate for data exhibiting delayed entry, gaps, time-varying
covariates, and even multiple-failure data.

The question is how this actually works? Suppose that I use a log-normal distribution. Then the density and survival function without time-varying covariates is
$$
\begin{align*}
f(t\mid \vec x)&= \frac 1{t\sigma\sqrt{2\pi}}\exp\left(-
  \frac{(\log t - \vec x^\top\vec\beta)^2}{2\sigma^2}\right) \\
S(t \mid \vec x) &= 1 - \Phi\left(
     \frac{\log t - \vec x^\top\vec\beta}{\sigma}
  \right)
\end{align*}
$$
and the hazard is given by $\lambda (t\mid\vec x) = f(t\mid\vec x)S(t \mid \vec x)^{-1}$.
This is fairly easy to interpret as it states that $\log T \mid \vec x$ is normally distributed with mean $\vec x^\top\vec\beta$ and variance $\sigma^2$.
What I presume that what streg does is the following: Suppose that $\vec x(t)$ is the time-varying covariates which is modeled as having jumps as is typical. Then the
assumptions is the the hazards is given by $\lambda (t\mid\vec x(t)) = f(t\mid\vec x(t))S(t \mid \vec x(t))^{-1}$. Is this correct? If not, how does streg handle the time-varying covariates?

Given EdM's answer, the model is in counting process setup like I state above. Thus, suppose that we look at left-truncation time $t_i$ with covariate $\vec x_i$. Let
$$
D(t, \vec x) = \Phi\left(
  \frac{\log t - \vec x^\top\vec\beta}{\sigma}
  \right)
$$
Then the density, CDF, and survival function are:
$$
\begin{align*}
  f(t\mid\vec x_i, t_i) &= \begin{cases}
    \frac{f(t\mid \vec x_i)}{S(t_i \mid \vec x_i)} & t \geq t_i \\
    0 & t < t_i
  \end{cases} \\
  F(t \mid \vec x_i, t_i) &= \begin{cases}
   \frac{D(t, \vec x_i) - D(t_i, \vec x_i)}{S(t_i \mid \vec x_i)}
     & t \geq t_i \\
    0 & t < t_i
  \end{cases} \\
&= \begin{cases}
   \frac{D(t, \vec x_i) - D(t_i, \vec x_i)}{1 - D(t_i, \vec x_i)}
     & t \geq t_i \\
    0 & t < t_i
  \end{cases} \\
S(t\mid\vec x_i, t_i) &= 1 - F(t \mid \vec x_i, t_i) =
  \begin{cases}
   \frac{1 - D(t, \vec x_i)}{1 - D(t_i, \vec x_i)}
     & t \geq t_i \\
    1 & t < t_i
  \end{cases} \\
&= \begin{cases}
   \frac{S(t, \vec x_i)}{S(t_i, \vec x_i)}
     & t \geq t_i \\
    1 & t < t_i
  \end{cases}
\end{align*}
$$
Thus, the hazard is
$$
\lambda(t\mid \vec x_i, t_i) =
  \frac{f(t\mid\vec x_i, t_i)}{S(t\mid\vec x_i, t_i)}
  = \frac{f(t\mid\vec x_i)}{S(t\mid\vec x_i)}
  = \lambda(t \mid \vec x_i)
$$
as I stated in my question.
The distribution of the survival time is not that obvious I guess but I figure that it is best expressed in terms of the hazards. In particular, suppose that covariates are given by:
$$
\vec x(t) = \begin{cases}
  \vec x_1 & t < t_1 \\
  \vec x_2 & t_1 \leq t < t_2 \\
  \vdots & \vdots \\
  \vec x_k & t_{k - 1} \leq t < t_k
\end{cases}
$$
for some $k \geq 1$. Then the hazard is
$$
\lambda(t \mid \vec x(t)) = \begin{cases}
  \lambda(t\mid \vec x_1) & t < t_1 \\
  \lambda(t\mid \vec x_2) & t_1 \leq t < t_2 \\
  \vdots & \vdots \\
  \lambda(t\mid \vec x_k) & t_{k - 1} \leq t < t_k
\end{cases}
$$
Answer: In the data format you describe (also called "counting process" format), an observation is considered left-truncated at $t_0$ (no information until after that time).
Your formula is the definition of the instantaneous hazard, given covariate values. Technically, the software to solve a parametric AFT model finds parameter values that maximize the likelihood of the data (covariate values and event times).
For a case left-truncated at $t_0$ having an event at $t$, the contribution to likelihood is proportional to $f(t)/S(t_0)$, with $f(t)$ and $S(t_0)$ determined for the corresponding covariate values.* That's the classic parametric modeling approach (which I assume Stata implements).

*This page summarizes the likelihood expressions for combinations of events and left or right censorings and truncations.
Comment: Thank you for your answer. Of course, the observations must be handled as left-truncated! This answered my questions assuming that this is correct (see the updated question). A few remarks: I does really matter how I express the model (hazard, survival function, density, etc.). Ultimately, I can derive the likelihood I need from any of them. The likelihood is only proportional to $f(t)/S(t_0)$ if there is an event.
Comment: Oh right, you do state that:" _For a case left-truncated at $t_0$ having an event at $t$, ..._"


Silverlight DataGridTextColumn Binding Visibility

Question: Following my earlier post I am now trying now to bind the visibility of DataGridColumns to a VM notification property. MSDN suggests I should be able to do this with ease.
I already have a value convertor and VM notification property that I know works (I have tested these on another element on my page:
<CheckBox x:Name="chkAllTeams" Visibility="{Binding Converter={StaticResource BoolToVisibilityConverter}, Path=AllTeams}"/>

This checkbox control visibility reacts as I would expect. When I set the same binding on the DataTextColumn I get an AG_E_BAD_PARSER error on the Visibility= line of XAML:
<data:DataGridTextColumn
Visibility="{Binding Converter={StaticResource BoolToVisibilityConverter}, Path=AllTeams}"
/>

Any ideas anyone?
Thanks,
Mark
Answer: Visibility on the DataGridTextColumn is a different beast on the checkbox.  Basically, it isn't a dependency property and can't be data-bound.  If you need this functionality, you can subclass DataGridTextColumn and add your own dependency property to get the behavior.

Rectangle gets its Visibility property from UIElement and is a dependency property
DataGridTextColumn gets its Visibility from DataGridColumn and isn't a dependency property.
Comment: I don't know of any particular examples for DataGridTextColumn.  The general approach would be to subclass, add a new dependency property for visibility and then use the new subclass in the Datagrid.Columns .  Jesse has a good explanation of dependency properties: http://silverlight.net/blogs/jesseliberty/archive/2008/09/30/dependency-property-system-deeper-dive-part-1.aspx
Comment: how about using an attached property instead?
Comment: Ah this is what I expected :-( Is that an easy task to subclass the DataGridTextColumn? Do you know of any online example for that? Mark
Comment: That link is dead now, this is the new one: http://jesseliberty.com/2008/09/30/dependency-property-system-%E2%80%93-deeper-dive-part-1/
Answer: Did you set BoolToVisibilityConverter as a resource?
Comment: Yep. Previous example on the checkbox proves that.
Comment: actually your example only shows half the code... anyway, as others have said that might not be your problem.

Answer: You'll need to use a datatemplate:
<DataTemplate x:Key="cBDT">
 <(UIELEMENT HERE) x:Name="chkAllTeams" Visibility="{Binding Converter={StaticResource BoolToVisibilityConverter}, Path=AllTeams}"/>
</DataTemplate>
As was mentioned before, only UIElement has the "Visibility" dependency property.
To see an example of this in context:
http://blogs.msdn.com/scmorris/archive/2008/04/14/defining-silverlight-datagrid-columns-at-runtime.aspx
Comment: Not a good answer - this hides the *element* in the column, not the *column* itself.


Storing filter definition on Solr server

Question: I have a situation where all my queries have some sub filter queries which are added each time and are very long.
The query filters are the same each time so it is a waste of time sending them over and over to Solr server and parsing them on the other side just to find them in the cache.
Is there a way I can send filter query definition once to the Solr server and then reference it in following queries?
Answer: You can add a static configuration directive in your solr config (solrconfig.xml):
<requestHandler name="/select" class="solr.SearchHandler">
    <lst name="appends">
        <str name="fq">foo:value</str>
    </lst>
</requestHandler>

.. this will always append a fq= term to the query string before the SearchHandler receives the query. Other options are invariants or defaults. See Request Handlers and Search Handlers on the community wiki for more information.


Facebook tab app using Dropbox Public Link (Link Error SOLVED)

Question: Creating a Facebook tab app using a Dropbox public link used to be simple, util Facebook made changes to it recently.
An unknown error "There was a problem saving your changes. Please try again later." will surface if you pump in the direct Dropbox link into the (Secure) Page Tab Url.
Answer: To solve this, you have to input into the Page Tab Url your Dropbox public link of the html file from

https://dl.dropboxusercontent.com/u/123456/foldername/index.html

to

https://dl-web.dropbox.com/u/123456/foldername/index.html

This is accurate as of August 2013. Enjoy!
Answer: I had this trouble recently, as mentioned by @George, you will have to edit the url link to your dropbox file. You will also have to point your canvas/secure canvas and page tab url to a directory by adding a "/" or to a string with "?" at the end.
You will need to change this:
https://www.dropbox.com/s/ak280yy2ey6ns/MY-FILE.html
to this:
https://dl.dropboxusercontent.com/s/ak280yy2ey6ns/MY-FILE.html?
correct as of 24th April 2014.
hope this helps :)
see my Facebook Tab
Comment: yes, I have a few Facebook tabs/apps that call html from a Dropbox file... still working :)
Comment: Hello @user3535811, are you still able to use this method now 15th Feb 2015?


Can I run a regression when both independent and dependent variables are all dichotomous?

Question: I have conducted a survey where all my questions are asked in a dichotomous manner (Yes/No).
Eg
IV:"Are you a smoker?", "Are you obese", "Is your gender male/Female" etc.
DV: "Have you ever had a stroke?"
Therefore both my dependent variable and independent variables are all dichotomous(Binary= measured in 0s and 1s).
My question is, is it appropriate to run a regression to determine the independent variables that drives the dependent variable given the fact that every single one of my variables (both dependent and independent) are dichotomous in nature?
If so, what kind of regression is the most appropriate? (Logistic regression?) and is there anything I should do to make the regression model more accurate?
I have rudimentary understanding of statistics and regression modelling and would be so grateful if someone would point me in the right direction.
Comment: Perhaps you should consider moving this question from here (Math.SE) to [Cross Validated](http://stats.stackexchange.com/), for it fits better there, I think.
Answer: Logistic regression is indeed one possible way to model your data. It expresses the probability for the event of interest as a function of some independent variables $X$, that can be either categorical (in particular, dichotomous) or continuous. So,
$$
P(Y=1|X)=\frac{1}{1+e^{-\beta'x}},
$$
such that if $X_1 \in \{1,0\}$, lets say $1$ stands for female and $0$ for male, then the odds ratio of your event of interest between females and males is $e^{\beta_1}$.
Another possible, rather simpler way, to analyse these kind of data is to use contingency tables. This approach can help with $2$ and sometimes $3$ categorical variables.

On the technical side, you have to assure that your data satisfy the requirements in order to estimate the model. Another issue that you should address is that you have "enough" data points at each level and each class in order to produce more reliable estimators. On the conceptual side, you should ask yourself whether you post the problem as probability estimating problem (then logistic regression is a good choice) or binary classification (in this case, logistic regression may fit as well, but there are plenty other classifiers) or just dependence/independence problem (in this case, in a presence of two binary variables, a simple  Pearson's chi-squared test will do the job).
Comment: Thank you for your reply. Indeed logistic regression seem to be the most suitable. But would the fact that every single one of my dependent variable being a binary variable be an issue? Would be the model be more accurate (Have better fit?) if it has independent variables that are continuous?

I guess the crux of my question is, what are the implications of having independent variables that are all binary vs independent variables with a mixture of binary and continuous (or all continuous)? Is one preferred over the other?
Comment: Due of the length of the comment, I rather edit the answer.


putting data into array and then JTable

Question: Referring to an earlier question i asked
lining up data in console output java
I wish to put my output in an array so that i can then further put this into a JTable
The extract for my code so far is, i am currently printing out the output to the console.
String assd = null;
String eventy = null;
String assdFT = null;

for (int i = 0; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
String nodeName = element.getNodeName();

switch (nodeName) {
case "assd":
assd = element.getChildNodes().item(0).getNodeValue();

break;
case "eventy":
eventy = element.getChildNodes().item(0).getNodeValue();

break;
case "assdFT":

assdFT = element.getChildNodes().item(0).getNodeValue();
break;

System.out.printf("%-30s  %-20s  %s%n", assd,  eventy,assdFT);

Object[][] data = {{assd,  eventy,assdFT}};//this only appears to put the elements in row 1, since System.out.println(data[1][0]) causes an out of array exception but System.out.println(data[0][0]) prints out all the elements of assd

Comment: This code is horrible, please format and indent your code, there are braces that are missing and the `switch` is just a mess. :)!
Comment: i have now improved the appearance of the code
Comment: [How to Use Tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) - Have a look at the `DefaultTableModel`
Comment: I can't see how you code could actually print anything.  How do you know when to actually print a line?
Comment: @ MadProgrammer the code looks through an XML schema and finds the item and prints it
Answer: To put data directly into a JTable pass an instance of your custom AbstractTableModel to the JTable constructor. Within TableModel, you can define what data is displayed and how it is accessed.
It would probably look something like this:
public class HeaderTableModel extends AbstractTableModel {

/**
 *
 */
private static final long serialVersionUID = 8974549762036798969L;

private Object[][] myData;

public HeaderTableModel(final Object[][] theRows) {
    myHeaderRows = theRows;
}

/*
 * (non-Javadoc)
 *
 * @see javax.swing.table.TableModel#getColumnCount()
 */
@Override
public int getColumnCount() {
    return LocalStorage.getNumColumns();
}

/*
 * (non-Javadoc)
 *
 * @see javax.swing.table.TableModel#getRowCount()
 */
@Override
public int getRowCount() {
    return LocalStorage.getNumRows();
}

/*
 * (non-Javadoc)
 *
 * @see javax.swing.table.TableModel#getValueAt(int, int)
 */
@Override
public Object getValueAt(final int theRow, final int theColumn) {
    return myHeaderRows[theRow][theColumn];
}

Comment: but how do i get each element assd,  eventy, assdFT into the table? I am just a novice
Comment: you pass them in part of your data into the table model.
Comment: okay, do i need this part of the code to create the array?                 Object[][] data = new Object[1000][10];
for (int r=0; r<data.length; r++) {
for (int c=0; c<data[r].length; c++) {
 data[r][c]=assd;//your value
}}
Comment: @Mr. Assistance, if that's the data you wanna display, then yes
Comment: but the problem with my array is that i am only adding assd, how do i build it to add all three elements assd,  eventy,assdFT ?
Comment: that all depends on what you want to achieve. I took from your question what I could easily discern and answer it. you might be better served by rewriting your question with clearer objectives.
Comment: well my understanding of Jtables from web references is that i create an array of items and then the array is put into a table. From web references the  typical example is Object[][] data = {
    {"Kathy", "Smith",
     "Snowboarding", new Integer(5), new Boolean(false)},
    {"John", "Doe",
     "Rowing", new Integer(3), new Boolean(true)},
    {"Sue", "Black",
     "Knitting", new Integer(2), new Boolean(false)},
    {"Jane", "White",
     "Speed reading", new Integer(20), new Boolean(true)},
    {"Joe", "Brown",
     "Pool", new Integer(10), new Boolean(false)}
};
Comment: if i did something like Object[][] data = {assd,eventy,assdFT} then i think all i would be doing is adding the data to row 1 as it loops, rather than filling down the rows.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/86934/discussion-between-andrewdleach-and-mr-assistance).

putting data into array and then JTable


Represent any number with two factorials

Question: I was wondering if it is possible to represent any positive integer with x! - y! ? If not, is there any proof?
Answer: For $x, y > 1$, $x! - y!$ is always an even number, so the only odd numbers representable in this form are numbers that are smaller than $n!$ by $1$ for some $n$. Taking $k = 3$, as $k+1 = 4 \ne n!$ for any $n$, we see that $3$ is not representable in the form $x! - y!$.
Answer: If $x \in \mathbb{N}, x>1 \implies 2|x!$ It means, that some odd numbers can not be represented as $x!-y!$
e.g. number 7. You have only 1 possibility:
i)  8 - 1 (but $\not \exists x\in \mathbb{N} : 8 = x!$)
Answer: Hint:
For all $y>x$
$$y!-x!\geq x!$$
Now are there $x,y\in\mathbb N$ such that $y!-x!=3?$ If there are, $x$ must be equal to 1 or 2.
Comment: This is not true for $y=2, x=1,0$, but it is for anything larger.
Answer: Hint: Say that $x  = y + 1$. Then
$$
x! - y! = (y+1)! - y! = y!(y+1 - 1) = y!\cdot y
$$
Now try to express $3$ as $x! - y!$.
Answer: You didn't say that $x$ and $y$ have to be integers!
So, for any real $z$, since the factorial
can be written in terms of the gamma function
($x! = \Gamma(x+1)$),
and $\Gamma(x)$ is continuous
for $x > 0$,
any real number can be written as
the difference of two factorials.
It's always a requirements problem.