Use ip route add to add multicast routes to multiple interfaces

Question: TLDR: Is there a way to use "ip route" to add multicast routes for multiple NICs?
We have software that uses two multicast groups to communicate with two different groups of devices on two separate physical networks. With the exception of this application, devices on one network do not need to communicate across our device to communicate with devices on the other network.

To do this the software creates two sockets. Each one is bound to the one of the ip addresses of the separate NICS. That socket is then joined to the multicast group that exists on that network, eg socket 1 is bound to 192.168.0.2 and joined to multicast group 188.8.131.52 while socket 2 is bound to 10.57.31.2 and joined to multicast group 220.127.116.11.
We are currently using a bash script (Linux kernel 3.14.39) to set multicast routes on the two network interfaces using route, eg
route add -net 126.96.36.199 netmask 240.0.0.0 eth0
route add -net 184.108.40.206 netmask 240.0.0.0 eth1

and verified via route -n
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
22.214.171.124       0.0.0.0         240.0.0.0       U     0      0        0 eth0
220.127.116.11       0.0.0.0         240.0.0.0       U     0      0        0 eth1

I recently read that route was deprecated/obsolete and that we should be using ip route instead, eg
ip route add 184.108.40.206/4 dev eth0
ip route add 220.127.116.11/4 dev eth1

Unfortunately, the second call fails with "RTNETLINK answers: File exists" and of course the second route doesn't show up after these calls.
Is there a way to use ip route to add multicast routes to multiple NICs?
I can use /8 as a netmask? eg
ip route add 188.8.131.52/8 dev eth0

and
ip route add 184.108.40.206/8 dev eth1

but this is problematic as the script that does this is not aware of what multicast address is associated with which device and its not always guaranteed to be the same depending on system configuration. Using my first example of route add makes this a non issue.
UPDATES
Thanks to an extended discussion with @Ron Maupin, I realized the error was in our code. We were not setting the interface to use for multicasting with IP_MULTICAST_IF. Once I added the setsockopt call to set IP_MULTICAST_IF, I no longer needed to add the routing tables.
struct in_addr multicastInterface = {};
multicastInterface.s_addr = interfaceAddressNetworkOrder;

// Set which outgoing interface to use
int result = setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_IF, (char*)&multicastInterface, sizeof(struct in_addr));

Comment: Multicast isn't routed the same way unicast is. Multicast routing involves PIM, and you need to software to help you do it correctly.
Comment: @Ron Maupin, What specific software are you referring to? route and iproute are software programs after all.
Comment: You need to use something like `mrouted` or `pimd`. Multicast routing is very different than unicast routing, and it needs to respond to IGMP requests.
Comment: How is it that our system works using route ... without using mrouted/pimd?
Comment: You got lucky. Linux doesn't normally handle multicast correctly, but to do it right, you need to understand multicast and configure multicast routing. The router should respond to IGMP.
Comment: @gnac, Did you find a solution for your issue?
Answer: That you have multicast going through your Linux box by using unicast routing is a combination of a couple of lucky circumstances.
Multicast routing is not the same as unicast routing. Unicast routing is based on the face that traffic is sent to a single address, but multicast traffic is sent to a group address that represents hosts which want to subscribe to the multicast group.
Hosts use IGMP to tell a multicast router that they want to join a multicast group, and the multicast router will then start sending multicast traffic for that group to the network of the hosts requesting this.
Modern switches will use IGMP Snooping to determine which switch ports have hosts requesting to join a particular multicast group, and they will only send traffic for that multicast group to the switch ports where the hosts have requested to join the multicast group.
Linux, by itself, doesn't support multicast routing, and you need to add something to the Linux device to support multicast routing. Refer to the diagram below:

When the multicast source starts to send multicast traffic for a multicast group, the switch probably has not seen any IGMP requests to join the multicast group, so the multicast traffic for that group goes nowhere.
When one of the PCs on the same switch wants to join the multicast group, it will send an IGMP Join message, and the switch will snoop on that and send the multicast traffic to the port where the requesting PC is connected.
If a PC on the other side of the Linux router wants to join the multicast group, it is out of luck because the multicast traffic is not flowing to that side of the Linux Router. The Linux Router has not even joined the multicast group, so the switch never sends the multicast traffic to it.
When you run multicast routing on a router, the router will respond to the host IGMP request, and the switch will know that it is a multicast router, and it will send multicast traffic to the switch port where the multicast router is connected. Simplistically, the router will not send the multicast traffic to another interface unless there is an active receiver on another interface (this depends on the multicast version, for instance, PIM-DM will start sending, but back off if no IGMP requests are seen).
With multicast routing enabled on the router, a PC connected to the other interface will send an IGMP Join message, and the Linux Router will begin sending the multicast traffic for the requested group to the interface. The switch will snoop on the request, and it will send multicast traffic to the switch port where the PC that requested to join the multicast group is connected.
It gets more complicated if you need to route throgh multiple routers. IGMP is used between the hosts and the local multicast router. PIM (or some other multicast routing protocol) is used between multicast routers.
This all prevents multicast traffic from going where it is not wanted.
There are add-ons to Linux to aid it in properly handling IGMP and multicast routing.
Comment: Thanks for the detailed response. I'm going to update my question to ensure it is clear. Namely, I have a linux device/application that is communicating on two different networks via multicast. It itself is not attempting to route multicast data from one network to the other, but rather publishing and receiving multicast data on two different multicast networks over two different physical interfaces.
Comment: As I explained, if you end up with a switch that does IGMP snooping, your box that connects the two networks may never even get the multicast in order to route it to the other network. It is not correctly configured, and you are lucky it works, but a simple change can break it. Multicast, like broadcast, is limited to a single broadcast domain (network). Moving traffic from one network to another network is routing , and you are trying to route multicast traffic.
Comment: I am not trying to route multicast traffic across my device. I am trying to ensure that the application on my device can communicate with other devices in a multicast group on a specific physical network. If I take away the fact that I'm connecting to two networks, I still need the route add statements or else no multicast traffic is sent of received from my device.
Comment: Yes, you are routing. That is the very definition of sending traffic from one network to another network. If you had bridged these networks then you would not need to use a `route` or `ip route` command because the traffic would be bridged from one interface to another interface.
Comment: but you need to use route even if you are only using one network/interface.
Comment: You can send multicast traffic out an interface without using `route` or `ip route`. If you have a problem with that, then your multicast source application needs to be fixed. A proper multicast source application will have a way for you to let it know on which interface(s) it should send traffic. This could be with the command line, configuration file, fields in the application, etc.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/48311/discussion-between-gnac-and-ron-maupin).
Comment: I'm seeing some software is able to emit multicast only on default route interface thus I'm suspecting it's not the answer for real. In despite routing itself (or should we say forwarding?) is being done differently for multicast it doesn't mean multicast announces aren't affected by host's routing table. At least in the cases I'm seeing `route add ` changes the behaviour of sending multicast beyond default route interface only.
Answer: To add multiple routes for a target, you can add the first as you have done, by using ip route add <address> dev <interface>. To add the second you then use ip route append <address> dev <interface2>.
For ipv4 you will need something to manage the IGMP or whichever multicast management protocol you are using. For ipv6 this is baked into the icmpv6 protocol so my understanding is that linux should handle this out of the box for you.
Comment: Thanks for this. It was exactly what i was looking for at the time. Yeah, we've both resurected zombie threads, but I ran into a similar issue recently and came across my old post with your "new" response, which was what I really needed.


Requests to website return "No route to host"

Question: As of about 3pm PDT today, about 50% of the requests made to my webserver via the domain name have failed from various locations worldwide (as reported by my monitoring service Pingdom). The error that Pingdom reports in their logs is "No route to host". When I try to access the website myself, I am able to connect only about half the time. However when I try accessing it by its IP number, the site immediately comes up. GoDaddy provides my DNS hosting services, and I have not made any changes to the A record in months. The A record is pointing to the correct IP number. I contacted GoDaddy, but they insist it is not a DNS issue and pointed me to the website http://www.whatsmydns.net/#A/. This tool showed that my domain name quickly resolves to the correct IP from all locations. But my hosting company, which so far has been very competent in resolving issues quickly, insists it's a DNS issue. They are not experiencing any issues, and the datacenter where my server is located (it's a hostway DC) says that they are not experiencing any issues at the time.  I have not touched the Apache config files recently at all.
Where else might the problem be?
Derek
Comment: Please indicate what domain you're talking about.
Answer:
I contacted GoDaddy, but they insist
  it is not a DNS issue

Most likely correct. Unless some of their DNS responses are answered with the wrong IP... this is not a DNS related error message.

The error that Pingdom reports in
  their logs is "No route to host"

Does Pingdom give the IP address it tries? If it is consistent AND CORRECT this is not a DNS issue at all.

But my hosting company, which so far
  has been very competent in resolving
  issues quickly, insists it's a DNS
  issue.

If the IP address tried to be contacted is correct everywhere, this can be ruled out. Once the requesting computer has the IP for the name, DNS is out of the question.

They are not experiencing any issues,
  and the datacenter where my server is
  located (it's a hostway DC) says that
  they are not experiencing any issues
  at the time.

Could be routing out odf their control.

I have not touched the Apache config
  files recently at all.

Also irrelevant. Apache is HTTP, not IP - basiaclly this is an error from the routing side, the request never reaches your server.
I would suggest setting up a second service (monitis) to validate the results. Plus finding out which IP addresses are tried to be reached. Maybe there is an issue at pingdom that makes them use the wrong IP sometimes.
Answer: It sounds like some issue with routing or with DNS. Let's investigate this:
Use NSLOOKUP to query check whether one or more DNS servers for your domain resolve wrong. Use the settings querytype=NS to query only NS entries, norecurse to disable recursive querying (we will do this by hand later) and set the Nameserver to a.root-servers.net
$ nslookup
> set querytype=NS
> set norecurse
> server a.root-servers.net
> example.org

You will receive a list of Nameservers responsible for the TLD of your domain
Server:  [126.96.36.199]
Address:  220.127.116.11

org     nameserver = b2.org.afilias-nst.org
org     nameserver = b0.org.afilias-nst.org
[...]
a0.org.afilias-nst.info internet address = 22.214.171.124
[...]

Set one of the nameservers you just received as server:
> server 220.127.116.11
> example.org

You will probably be represented with the DNS Root of your Registration or Provider. If you have a nested setup of DNS Servers you might also need to repeat the last step until you get to the autorative name server for your domain.
example.org     nameserver = a.iana-servers.net
example.org     nameserver = b.iana-servers.net

The fact that you aren't experiencing a 100% loss of resolution is a hint. If it is DNS related most probably one of the Nameservers on the recursive way to your domain delivers wrong data.
With the above method you should be able to iterate through the possible nameserver paths and check whether or not they are delivering correct data. (Don't forget to set querytype=any)
Comment: My host used pingability to run some tests, and one of the tests reported: "Error Failed getting glue records for ns19.domaincontrol.com from g.root-servers.net: SocketTimeoutException." So I changed name servers and that fixed the problem. I did this before having a chance to run your tests. Does this sound like the problem you were thinking of?
Answer: If you DNS is stable and consistent then......
It may just be a routing flap, where you home AS or destination AS is dropping routes. Try mtr  and see where your packets cease to be routed correctly.


force div to bottom

Question: I want the green div to be below the blue div instead of on top of it without changing either of their position values and using pure css only.
http://jsfiddle.net/LpjgLydv/40/
Is this possible?
Assumptions:

I may use inline css only
This is for a footer that needs to stay at the bottom regardless of how much content is on the page
Any other element on the page besides the footer (and html,head,body) may or may not exist at any given time
The footer is nested in  and cannot be placed anywhere else
Comment: Like this you mean? - http://jsfiddle.net/LpjgLydv/5/
Comment: If you are using fixed pixel values, this will never work.
Comment: It's not really clear what you are trying to do and why. Positioning is poor layout method unless used for specific effects.
Comment: Just search on SO for "sticky footer".
Comment: This feels like a **homework** question and I'm not comfortable with doing someone else's homework. No professional web developer would use those constraints.
Comment: You need absolute position?
Comment: @Paulie_D: Examples like [this](http://ryanfait.com/sticky-footer/layout.css) are quite bad since it requires that the css be put in a different element (the wrapper) which may or may not exist on the page at any given time.
Comment: @Paulie_D: No worries, please move onto the next question and I will wait for someone with the knowledge and ability to answer. Thanks for trying.
Answer: You can use this without positioning.
.inner-box
{
    border: solid 10px blue;
    height:900px;
    width:380px;
    margin-top: 5px;
    float:left;

}
.inner-box2
{
    border: solid 10px green;
    float:left;
    bottom:0px;
    height: 180px;
    width: 380px;
    clear:both;
}

Comment: You use float. It is not necessary to have a position in order to achieve what you want.
Comment: Add this `bottom:-170px;` to your code (green div). Even if is not a good practice.
Answer: I figured it out. Basically I had to add a relative position and a min-height to the html attribute as well as a margin-bottom to the body attribute:
http://jsfiddle.net/LpjgLydv/44/
html

css
html {
    position: relative;
    min-height: 100%;
}
body {
    margin: 0 0 250px;
}
.box
{
    border: solid 10px blue;
    position: relative;
    height:900px;
    width:380px;
    margin-top: 5px;
    margin-left: 8px;
}
.box2
{
    border: solid 10px green;
    position: absolute;
    bottom:0px;
    left:8px;
    height: 180px;
    width: 380px;
}

It now meets the criteria of all of the assumptions in the question.
Comment: Downvoting all answers you get, deleting your own comments, and in the end answering your own questions. You sure got it right how to use SO.
Comment: Thank you, honestly can't take credit for all of it but I do believe that my answer is definitely the best. For anyone else that views this question in future, this would most likely be the quickest solution to their problem.

force div to bottom


How much difference and how quickly can breathing exercises impact your singing and breathing?

Question: I've never done breathing exercises before and have just started after about a year of singing.
I know "breath control" is seen as very important but how specifically will such exercises improve my technique and skills? And over what kind of time-frame?
As a baseline I can currently inhale for about 5s, and exhale or sing a note for about 20s. I definitely don't feel I'm able to inhale very deeply especially through my nose - I notice this when swimming too. So as well as how exercising will affect my singing, I'm curious how my ability to perform such exercises will improve over time too.
Answer: Breathing is a huge part of singing. Think of your body as a wind instrument, if you are not breathing properly, how can you expect proper sound production? Remember to breath deep into your diaphragm. Here are some good exercises to keep in mind: http://www.bbc.co.uk/sing/learning/breathing.shtml
as someone who started with zero knowledge of sing before joining a university concert choir, I can tell you breathing makes all the difference
Answer: Breathing is pivotal to singing properly. Without proper breath control no-one can sing at their best. Singing, obviously, works on exhalation, so being able to control the level that works at is paramount. In order to exhale, inhalation is important, and often needs to be done quickly and efficiently. It makes sense physically that breathing in through the mouth is far quicker and more effective than through the nose,but some phrases will necessitate the latter, as a temporary intake.
Of course, learning correct breathing will help the singing - better phrasing, no dropping off at the end of a note, etc. It's surprising that it hasn't been addressed much earlier. Perhaps your breath control is naturally good.
Time frame - how long is a piece of string?
Answer: As for how long it would take I'm sure that would be unique to you. When I did voice in university's took me about a year to really improve with my breathing. The next year after that improvements came still. So expect to constantly improve slightly but to occasionally have things "click" in your mind where you notice a big difference or something profound.
Breathing exercises help with how long you can hold a note but also helps with many other things.
Consistency
It helps you hold notes with consistent volume pitch and tone. That is one of the things that clicked for me. I noticed after listening to a recording of myself that my voice was not smooth. I was cutting off the ends of longer notes and dropping in pitch and volume as well. Breathing exercises help you to hold up to the very end.
Stamina
Other technical things help you to sing longer and louder as well. What I mean by stamina here is the improved efficiency with which you will learn to use your precious air. In the beginning you would most likely be using way more air than necessary for pretty much everything. Breathing exercises help you recognize how much you need to do what. This will enable longer more productive practice sessions. It will also help you make it to the end of recitals more easily.
Answer: There's merit in filling up with air.  No particular merit in taking 5 or 10 seconds to do it, other than to remind yourself that when you THINK you've filled up there's often room for more!  Once you've established the principles, every phrase you sing is a 'breathing exercise'.


Serve drupal page to secondary domain

Question: I have a drupal site running on a server with two domains pointed to it: domainA.com and domainB.com. I would like domainB.com to serve a specific landing page, http://domainA.com/landing-page. I know I can do a normal htaccess redirect like this:
RewriteCond %{HTTP_HOST} ^domainB\.com
RewriteRule ^$ http://domainB.com/landing-page [L]

Which will serve my users the correct content.
But I would rather the path wasn't added to the url.  Is there a way to do a 'transparent' redirect for domainB.com so that http://domainB.com/ serves up the content from http://domainB.com/landing-page without modifying the url? So that it seems more like the 'homepage'?
Comment: I _believe_ the options stated [here](https://www.drupal.org/node/2377579) are the only way but I could easily be wrong.
Answer: At least two ways of doing this come to my mind:
1. "Masking" your subdomain and proxying the content. What you do in this case, is that besides your mod_rewrite's redirection, you use mod_proxy to show your other domain's content without changing your URL. Have a look at Using mod_rewrite for Proxying.
2. Using the Domain Access module. Another option, maybe overkill if you are going to use this only for one page, but useful if you have to repeat this with many domains/landing pages.
Since this module allows you to create individual homepages on a per domain basis, you just have to add a second domain (domainB.com) and set /landing-page as Drupal's default homepage in the domain settings. Now when you go to domainB.com, your url bar will just show http://domainB.com but will render /landing-page's contents (since it's the homepage).

Serve drupal page to secondary domain


How to integrate some files which are extra ones for one of the two productFlavors sharing same code

Question: I have developed an app which I was developing under staging environment and now deployed it to production environment which would be uploaded in google play store. So, for both environment app I am using productFlavors which would build the different variant defining in the build gradle file.

My problem is: I am having some java files which I have to include in
  production build but not into staging build. How can I achieve this?

One of the solution: when I am selecting build variants I would add/delete the java files which is not the appropriate solution as I would update the app in future with more java files added to production
Edited: I don't want to make different src folder for different flavors. Wouldn't it be possible without making different folders? As I have already mentioned I'm having same code for different flavors.
Comment: Possible duplicate of [Using Build Flavors - Structuring source folders and build.gradle correctly](http://stackoverflow.com/questions/16737006/using-build-flavors-structuring-source-folders-and-build-gradle-correctly)
Answer: You create a folder in your src directory next to main where you will add files for one flavor. For example:
- src/
-- main/
-- production/

You put your extra Java files that should only be in the production flavor in that new folder.
Comment: Without it can't be possible to add files? Is there any other way?
Comment: From your comment and your edit, I see that I didn't quite understand your question. I don't understand why you don't want to add folders. Do you mean that you have more than 2 flavors and you want, for example, to share the same code in flavor 1 and 2, but not in flavor 3?
Comment: I want to have two flavors only both sharing same code but need to add some files in production one. what should be the best way to do it.
Comment: This is why you put in `main` all the code that will be shared. You refactor your code so that only the parts that reference your added files (the code that differs between staging and production) is in the `staging` and `production` folders. Then you add the extra files in `production`, which are only referenced by your production code. All the shared code stays in `main`.


Upgrading Drush 6 to Drush 9 on Centos 5 server

Question: I haven't updated drush in awhile and looking to update it to the latest. I'm not exactly sure how it was installed originally. But when I do a which drush, it shows it resides in /usr/bin/drush
When I do a drush dl drush - I only get the option to upgrade to 7.x only.
How can I update it to Drush 9?
Can I just do a git clone of the drush repo from: https://github.com/drush-ops/drush
Then do I just do a checkout of the drush 9 tag? But how do I make it the default drush application to run? Or do I just overwrite the file in /usr/bin/drush?
FYI: My linux server admin skills aren't up to par.
Comment: What version of PHP is on your server?  CentOS 5 only supports old versions, even with the IOS repos.  You may not be able to get a recent version of drush to work.
Comment: I just got the server guys to upgrade it to 5.5.23 -- would I run into any issues?
Answer: drush dl drush downloads the obsolete version of Drush from drupal.org. Drush was never intended to be used to download Drush via the pm-download command, even when it was hosted on drupal.org; the fact that this works is more of an anomaly or coincidence than design.
To update to a newer Drush, follow the usual instructions in the Drush documentation.  Since you already have Drush in usr/bin/drush, use this location instead of the location stipulated in the docs (usr/local/bin/drush).
wget http://files.drush.org/drush.phar
chmod +x drush.phar
sudo mv drush.phar /usr/bin/drush

The Drush at files.drush.org/drush.phar is always the most recent stable version of Drush. To download a specific version, visit https://github.com/drush-ops/drush/releases. There is a phar available with every release of Drush from version 8 and later.  You can, of course, replace your /usr/bin/drush at any time that you need to upgrade.
Comment: Probably the simplest way would be to symlink /usr/bin/php-cli to ~/bin/php, and make sure that ~/bin is in your $PATH ahead of /usr/bin when you're logged in to your shell.
Comment: Yes, good point. I have actually answered how to install Drush 8 here, missing that detail from the subject line. Drush 9 is, in fact the `master` branch of Drush. It was only recently forked, and is currently very similar to Drush 8 at the time of this writing. Folks will soon be in for a bumpy ride if they install it. Dev versions of Drush are generally usable (the maintainers all use HEAD of master for day-to-day work), but behavior can change without warning when you are on dev.
Comment: what if i wanted to update it in the future? do i do the same thing? thanks greg!
Comment: I'm actually getting a weird error after doing the upgrade like you said: http://prntscr.com/aygq6d --- when i run drush, it just says **X-Powered-By: PHP/5.5.28** did i download the wrong one?
Comment: Very weird, but it works when I'm not logged in as root. Any idea to why that is?
Comment: Symptom looks like you are running php-cgi instead of php-cli. Your $PATH is probably different as root. Probably best to always do php development as a non-root user anyway.
Comment: where would i make this change from cgi to cli? i checked php.ini and there's no reference to change that. sorry that my command line-fu isn't all that great. thanks greg!
Comment: nevermind i did a **which php** and then went to /usr/bin and saw that there was a **php-cli** and just replaced that with the **php** binary
Comment: Be careful about swapping out php binaries; you wouldn't want to use php-cli with your webserver.
Comment: =D ... just found that out the hard way.. yea my site just died because i did that. i switched it back and its working now. not sure how to make php-cli run as default when using drush.
Comment: I take Drush 9 is the master branch. Isn't a little too early to install it?


Recursion Draws

Question: See Above for description
However my code is adding circles to the array in incorrect colours:
I have a Color baseColor, which contains a variable int baseGreen. This int is reduced during each recursive call, with the intention of changing the type of green for each set of 3 circles.
If anyone is able to hazard a guess as to why this is happening I would be very grateful. Thanks.
Comment: Color simply follows your recursion path. With each size you first you go all the way to the left, then center, then right. Instead of tracking your color independently you may want to make it a function of `rad`.
Comment: As you reduce "rad" in each recursion, you just need to make a darker shade for your colour and pass that on. Just like you reduce "rad" by 1/3, you increase shade and use the new colour shade to make the 3 createCircles() call.
Comment: Cheers for the reply, could you please demonstrate how I should implement your suggestion.
Answer: tracking base color is unnecessary as you are passing it into your method.
this is a simple way of make the color progressively darker
<code>public void createCircles(int x, int y, int rad, Color parentColor){
    Circle myCircle = new Circle(x, y, rad, parentColor);
    ...
    if(!(rad<1)){
        ...
        Color myColor = parentColor.darker();
        createCircles(x - (2*rad), y, rad/3, myColor);
        createCircles(x, y, rad/3, myColor);
        createCircles(x + (2*rad), y, rad/3, myColor);
    }
}
</code>
Comment: Color myColor = parentColor;???? You should be calling darker() and create a new darker color to be used for the 3 callss to createCircles().
Comment: I have implemented it now (see above) but I still get an incorrect representation of the circles. Have I done it correctly?

Recursion Draws


What is the t-value of a linear regression as variance of residuals approaches $0$?

Question: I was just thinking about a linear regression situation where we assume each point $Y_i \sim \mathcal{N}(\beta x_i+c,\sigma^2)$ and all points are independent, what would the value of the t-statistic be when testing whether $\hat{\beta} = \beta$ as $\sigma \to 0$? I'm assuming we are using the formula
$$t = \frac{\hat{\beta} - \beta}{\text{S.E.}(\hat{\beta})}.$$
My confusion is that $\hat{\beta} \to \beta$ and $\text{S.E.}(\hat{\beta}) \to 0$.
Comment: if standard error of the regression approach to zero and all OLS assumptions are meet both, numerator and denominator, approach to zero. Now the t-stat should said us that the null hypotesis cannot be rejected ... so I suspect that the nominator tend to zero faster than the denominator ... and t-stat approach to zero. However this is just an euristic reasonong ... formal proof is needed.
Comment: What about if $\beta = 0?$
Comment: NB: Your title does not reflect the question.  In the question, the *error* variance shrinks to zero, not the residual variance.  The latter is a property of any set of data -- it depends on what the $Y_i$ happen to be and on how $\beta$ and $c$ are estimated -- while the former, as stated, as a parameter in the model, $\sigma^2,$ and governs the data *generation* process.
Answer: This is a little tricky because we need to consider what $\sigma\to 0$ might mean.  One possible interpretation is that a set of values $x_i$ of the explanatory variable are fixed, along with the parameters $\beta$ and $c.$  Do we treat the errors as random variables or as also being fixed?  Here I analyze the latter case because it is straightforward and instructive, but because it also requires new formulas (because the errors are no longer random variables, which precludes applying standard results expressed in terms of their means and variances).

Let's get the algebra out of the way first.
Plan of analysis
If the errors $\varepsilon_i$ are treated as fixed (so that varying $\sigma$ -- which we allow to be zero or even negative -- merely rescales them), then the $(x,y)$ data can be expressed as a collection of ordered pairs
$$(x_i, y_i) = (x_i,\ \alpha + \beta x_i + \sigma\varepsilon_i),\quad i = 1,2,\ldots, n$$
(where I have written "$\alpha$" for "$c$" to keep the notation consistent.) In this context, the only variable is $\sigma$ and we may consider the t-statistic in the question as a function of $\sigma$ alone, written $t(\sigma).$  The immediate objective is to obtain a formula for $t(\sigma)$ that we can analyze.  This will be done first by finding a formula for its numerator and then a formula for its denominator.
Preliminary simplifications
Without any loss of generality we may proceed as always and re-express the explanatory variable by centering it at zero and fixing its variance.  It's simplest (using vector notation $x = (x_1,x_2,\cdots, x_n)$ and $\,\cdot\,$ for the vector dot product) to set
$$1 = |x|^2 = x\cdot x = \sum_{i=1}^n x_i^2.$$
The numerator
It is well known -- and extensively documented here on CV -- that the slope estimate is
$$\hat\beta = x\cdot (y - \bar y) = \beta + \sigma x\cdot (\varepsilon - \bar\varepsilon)$$
with $\bar y$ the mean of the $y$ values and $\bar\varepsilon$ the mean of the errors $\varepsilon_i.$
The denominator
The residuals consequently are
$$e_i = y_i - \hat y_i = \sigma(\varepsilon_i - \bar\varepsilon - x\cdot(\varepsilon - \bar \varepsilon)x_i).$$
Writing $z_i = \varepsilon_i - \bar\varepsilon - x\cdot(\varepsilon - \bar\varepsilon)x_i$ for the coefficient of $\sigma,$ the usual (unbiased least squares) estimator of the standard error of $\hat\beta$ (assuming $n\gt 2$) is
$$\widehat{\operatorname{SE}}(\hat\beta)^2 = \frac{1}{n-2}|e|^2 = \frac{|z|^2}{n-2}\,\sigma^2.$$

Analysis of the Question
With that algebra done, consider testing $H_0:\beta = \beta_0$ against the alternative $H_A:\beta \ne \beta_0$ with the usual t test.  It has $n-2$ degrees of freedom (which does not change when $\sigma$ is varied) and the t statistic is
$$t(\sigma) = \frac{\hat\beta - \beta_0}{\sqrt{\widehat{\operatorname{SE}}(\hat\beta)^2}} = \sqrt{n-2}\left(\frac{\beta - \beta_0 + \sigma x\cdot(\varepsilon-\bar\varepsilon)}{|z|}\right)\frac{1}{\sigma} = A + \frac{B}{\sigma},$$
with $A$ proportional to $x\cdot(\varepsilon-\bar\varepsilon)$ and $B$ proportional to $\beta-\beta_0.$
Answer
This has three possible behaviors:

For testing any hypothesis where $\beta\ne \beta_0,$ the t statistic is asymptotic to $\sigma^{-1}.$  This guarantees that as $\sigma$ shrinks, the t statistic eventually becomes significant, no matter what level of significance is chosen.

If we happen to postulate the correct value $\beta_0=\beta,$ then $t(\sigma)$ is constant:

The constant is zero when $A=0;$ that is, the vectors (not random variables!) $x$ and $\varepsilon - \bar\varepsilon$ are orthogonal.  The test will never reject $H_0.$

Otherwise, if $|A|$ is sufficiently great, $H_0$ can be rejected (and it is rejected no matter what value $\sigma$ might have).  This occurs because the residuals $\varepsilon_i$ are not truly orthogonal to the $x_i,$ creating an irreducible discrepancy between the data pairs and the ideal linear model.
Comment: @whuber Thanks, so these guesses 2 and 3 where okay :-) I will continue reading your nice exposition... so may be more questions follow. Best regards.
Comment: If errors are considered rvs, and $E[\epsilon|X]=0$, something like your answer "2a" is the relevant?
Comment: @markowitz When errors are analyzed as RVs, the standard analysis applies and shows the t statistic has a Student t distribution under the null hypothesis and a non-central t distribution under the alternate hypothesis.
Comment: I known, and probably the asker too, but this do not answer to the question. Indeed the asker have the standard analysis in mind I suppose.
Comment: Moreover if error and explicative variables are non random even the response variable is not random. I such a situation it is not clear to me the role of hypothesis testing.
Comment: @markowitz "Randomness" is primarily a modeling construct: a stance taken by the analyst to understand and interpret data.  Plenty of regressions are performed with good effect on deterministic, non-random data.
Comment: Regression is a concept with discuss meaning. Sometimes explicative variables are considered as not random but I never seen regression and test used with non random errors and, so, without randomness at all.
Comment: @whuber I would like to understand what you did, and it's a bit hard... sorry. I have a few, probably basic, questions (1) I guess you use symbol e for estimated error terms, and the Greek epsilon for the true (unknown) errors? (2) The mean of the true epsilons does not have to be 0, I guess, unlike the mean of the estimated e terms. Is that correct? (3) the estimated e terms are uncorrelated with x, but the epsilons could be correlated. Is that correct?
Comment: @BenP No need to guess: I name and define both the $\varepsilon_i$ and $e_i.$  (2) is correct and is one of the main complications.  Even when we model the errors as *iid* Normal variables, there is still no chance that their mean is $0;$ whereas *by construction* the mean of the errors $e_i$ is zero.  The only possible meaning of "uncorrelated" in (3) in this formulation is that $(x-\bar x)\cdot(e-\bar e)=0$ (true by construction) and $(x-\bar x)\cdot(\varepsilon-\bar\varepsilon)=0,$ which is not necessarily true (and indeed has zero probability with the *iid* Normal assumption).
Answer: If think we have the same problem here: what happens if we test $H_0: \mu=0$ when $\sigma$ approaches zero?
Let's assume that true value of $\mu$ in the population is $1$, and the true value of $\sigma$ is "small", say, $0.1$. Since we know the value of $\sigma$, we can use the $z$-test instead of $t$, but that doesn't change a lot. Also assume we have a sample from this population of, say, 4 cases, with mean value 0.8 (or whatever value close to the true value 1 of $\mu$ in the population, because $\sigma$ is so small). We could now calculate the value of the test statistic $z$ under $H_0$:
$\Large z = \frac{0.8 - 0}{\frac{0.1}{\sqrt4}} = 16$
If we would not know the true value of $\sigma$ we would estimate it by the sample standard deviation, and that would be a small value too, because the true $\sigma$ happens to be so small. So again we end up with a "huge" $t$ value.
No matter how close the true value of $\mu$ under the alternative hypothesis (which we assumed to be 1 above) is to $0$ (the value under $H_0$), the situation will be similar if we choose $\sigma$ arbitrarily small. Each time we will have: the smaller $\sigma$ is, the more extreme (positive/negative) our $t$ value will be, for any true value of $\mu$ under the alternative hypothesis.
Comment: Sorry markowitz, did not notice that you meant this.... Then my answer is irrelevant indeed.
Comment: It seems me that your arguments are bad focused. The relevant case is where the value under the null hypothesis is exactly the true one. Otherwise indeterminate form do not appear and the result is trivial.


Selecionar o dataframe com maior número de linhas em uma lista R

Question: Olá,
Estou desenhando um loop e em um determinado momento preciso selecionar o dataframe com maior número de linhas dentro de uma lista.
Exemplo:
<code>df1 <- data.frame(a = 1:15)
df2 <- data.frame(b = 1:35)
df3 <- data.frame(c = 1:105)
lista <- list(df1, df2, df3)

# resultado esperado lista[[3]]
</code>
De alguma forma, eu queria que eu pudesse dizer "retorne-me o elemento da lista com maior nrow() .
Agradeço pela ajuda!
Comment: A outra possibilidade é calcular número de linhas no interior do loop. Algo assim: fora do loop: vec <- numeric(). Dentro do loop: vec[i] <- nrow(df1); list(df1, df2, df3)[[which.max(vec)]]
Answer: Consegui encontrar uma resposta que não é ideal mas serve para os meus propósitos.
<code>#contando o número de linhas de cada dfs:
cnt <- sapply(lista, nrow)
# Agora atribuindo a um DF final:
df_final <- data.frame(lista[which.max(cnt)])
</code>
Comment: Nota: `lista[[which.max(cnt)]]` é suficiente. Usa `'[['` em vez de `'['` para extrair o *elemento* da lista dado por `which.max`, que é o df pretendido. A outra forma extrai uma *sub-lista* e é por isso que é necessário usar `data.frame()` depois.


What is the significance of the slope of the tangent line of a function? Why is the derivative so important?

Question: As I finished calc 1. I can use the product rule and chain rule and resolve integrals. But I feel like its too mechanical for my taste. I know the procedure and I execute on paper without really understanding or experiencing the "ahaa moment".
For example, when I was learning geometry in elementary school, the "ahaa moment" for me was when I had to move furniture in my room and needed to find areas of stuff. I'm trying to find the equivalent application of the derivative and integral as I learn calculus. Could someone demystify this?
Thank you in advance.
Comment: There aren't many elementary applications of calculus (unlike geometry). On the other hand, calculus is the foundation of optimization problems. This is probably the main kind of problem you'll be concerned with if you're an economist or an engineer.
Comment: Learn about Mean Value Theorem, and/or optimization, and it'll become much more interesting :)
Answer: A slope is a rate of change.  If a car moves at 30 miles per hour, and you graph its distance traveled as a function of time, the slope of that graph is 30 miles per hour.
Isaac Newton was the first person ever to show that the laws of nature that govern objects we see every day here on Earth are the same as the laws of nature that govern things in the heavens: planets, moons, comets (including the planet Earth as a whole).
In order to do that he had to think about the rates at which they move as a function of their locations.
Rates of change also occur in the following way: Newton asked himself whether the gravitational pull of the earth on the moon or other orbiting object is the same as if the whole mass of the earth were concentrated at the center.  (The bottom line, after much effort, turns out to be "yes".)  So how do you find the sum of the infinitely many infinitely small quantities involved?  The answer is that you ask how fast that sum changes as progressively more of the earth is taken into account.  This is not a rate of physical motion as time passes, but is something else.
Unfortunately far too much of the conventional mathematics curriculum is designed to prepare students for later courses, in such a way that you find out the motivations only if you take certain later courses that most of the students will never take.  It leaves students not understanding the whole thing.  Honest education does not do that.  A few professors here and there are working on calculus courses that are in that respect honest.  At least two professors at Macalester College have been working on that, and at various other places that I can't name right now.
Comment: I am not trying to sound critical of you personally, but I think it is a sad commentary on what "Calc 1" is like in your school that you managed to complete that course without learning that *velocity* is the derivative of *position*.  I'm sure it's not your fault, but come on -- that is the most fundamental idea in Calculus; it literally is what motivates the entire subject.
Comment: WOAHHH. That's sort of magical. I don't know how that's possible though. I mean we have the time and we have the distance, how can we get the rate at which we were traveling at some historical time x?? That does not seem possible.
Comment: You don't just have the total time and the total distance; rather you have the distance traveled so far at _every_ moment in some time interval.
Comment: I studied business. They never taught physics. Basically they taught how to find derivatives. with respect to one variable, then it went on to partial derivatives, then rieman sum and integrals. And some garbage at the end on differential equations that I did not understand much. Actually this was wayy to mechanical of a course. I wish more time was spent explaining the Why's rather than the Hows.
Comment: Could you break down how I would graph the distance traveled as a function of time? Does that mean, time is on the x axis and on the y axis there is distance? So are you saying the slope is the speed at which I was traveling at time x?
Comment: Yes, to both questions.
Comment: So from time a to time b I can figure out the distance traveled between those 2 points. Thats simple right, just take the difference from the Y axis `f(b) - f(a)`. But what I'm really trying to understand is the slope. The slope is the rate at which I was going at a certain point right?
Comment: The slope of the curve at a point is that speed at one particular time.  That's the derivative.
Comment: @mweiss : Calculus is much like that in most schools: zillions of students who are known not to be capable of learning calculus are pushed into the course.  They bring in tuition money. The course gets taught as just a bunch of algorithms. The reason so many the students are not capable of properly learning it is that they've learned the prerequisite courses as merely a bunch of algorithms. If they work hard and get straight "A"s in those dumb algorithmic courses, they feel that they are who calculus was intended for.
Comment: At any rate, what differential calculus is about is rates of change.  That teachers let students get through the first semester without hearing that is malpractice.
Comment: @mweiss I think you underestimate the ability of a math course to be taught without context.
Comment: I don't understand the big deal about calculus. Why would I want to know the rate of change?
Comment: @Michael Hardy : So what school did _you_ go to that taught it correctly (presumably)?
Comment: @TazMan : My answer gives you _some_ of the reasons why people would want to know about rates of change.  The reason for inclusion of calculus in a liberal education for students who don't have a pre-identified need for it is so that they can find out about one of humanity's great intellectual, cultural, and esthetic achievements. If the course is made to consist of teaching students to chant "en ex to the en minus one", as so often happens, then of course it won't achieve that purpose.
Answer: The derivative might just be the most important thing in mathematics. In physics, if the function that gives the motion of a particle with respect to time is defined as $x(t)$, then the derivative of this function $$x'(t)=v(t)$$ gives the velocity of the particle at time $t$. Also, the derivative of the function $v(t)$, or $$v'(t)=a(t)$$ gives the acceleration of the particle. Even Newton's famous law $F=ma$ can be rewritten as the derivative of the momentum with respect to time, or $$\Sigma{F}=\frac{dp}{dt}.$$ Also, the power exerted by a force is equal to the derivative of the work with respect to time $$P=\frac{dW}{dt}.$$
In fluid mechanics, the definition of pressure is given as the derivative of the force with respect to the area that the force is acting upon, or $$p=\frac{dF}{dA}.$$ In physics the list goes on and on, there would be no physics with calculus. The derivative can also be applied inside of mathematics, given the gradient of any curve, which is useful, and the second derivative giving information about concavity and points of inflection.
Basically, it is really important, and if you go into the sciences or engineering as well as studying mathematics, you will notice the derivative, and all other aspects of calculus.
Comment: Your answer starts by claiming that "The derivative might just be the most important thing in mathematics" but what you actually explain is why the derivative might just be the most important thing in physics.
Comment: What is pedantic about that? Mathematics and physics are kind of different things.
Comment: @MitchKnight I don't think I was being pedantic. Mathematics is a subject in its own right, not just a tool for physicists. The technique that is most important for physicists may or may not be the most important part of mathematics as a whole (if such a thing even exists).
Comment: ehhh, I kinda know or read the stuff you mentioned.. Its super important in the sciences. But I need an intuitive understanding in real layman terms. What you explained about physics and acceleration/pressure is still wayyy to abstract for me. What about an everyday example that I can relate to?
Comment: Fair enough. Basically, calculus is used when studying quantities that are changing. The rate at which something changes, which is the derivative, is very important in the sciences. It is an abstract concept at first, but the more you study it the more you will understand it, and be amazed by its power.
Comment: How about try not to think of it as _only_ to distances, for example, typing rate (number of letters you type every second); plot it into graph with x as the time in second, and y as the number of letters you typed.
Comment: True. You could also say that rate at which a population increases is proportional to the population, such that $dP/dt=kP$.
Comment: Perhaps I should have said the 'most applicable thing in mathematics.' Being hugely pedantic is not necessary for such an opinion based question as this though.
Answer: There are two other ways to think of the derivative:

as the "instantaneous rate of change" of the function -- that is, how much it is changing at one particular moment were it viewed as a function of time. Namely, the rate of change of a quantity over an interval is
$$\mathrm{rate\ of\ change} = \frac{\mathrm{change\ in\ quantity}}{\mathrm{interval\ over\ which\ change\ occurs}}$$
or, in symbols,
$$R = \frac{\Delta f}{\Delta x}$$.
Then the derivative is the limiting value of this rate when $\Delta x \rightarrow 0$, that is, in the "ideal" case where the interval is a single instant of time. We denote this by $f'(x)$ or $\frac{df}{dx}$, the latter calling to mind the ratio above.
as a "best linear approximation" of the function. That is, the derivative tells you what the linear function is which is "closest" to the function at a given point in that every other linear function will have a worse error for points near the point of differentiation. This is what the tangent line represents -- note that it too is really a function. If you've done a little linear algebra, you might have heard of a "linear transformation", which on the real numbers is a function of the form $g(x) = ax$. You can think of this as finding the linear transformation (the $a$-value, more precisely), translated to be relative to the point at which you differentiate, which best approximates the deforming action of the function on a small piece of the real number line about the point at which you take the derivative. Since the linear transformation shown can be thought of geometrically as a "stretch" or "scaling" (that's what it means when you multiply a real number by another real number -- you scale one number by another), you can also think of the derivative as telling you how much the function "stretches" or "scales" a small piece of the real number line about the point of differentiation. This is actually a good concept to keep in mind for when you get to more advanced forms of math, where generalizations of the derivative to more exotic kinds of spaces than the Real Numbers will appear, and it is this sense in which it is used.

Usually in physics, one is most often interested in interpretation 1), whereas in more advanced forms of math, one may be more interested in interpretation 2).
Comment: Thank you. So when I take the derivative of a function, why am I reducing it? whats the reason for that? For example the derivative of, `3x^5 + 4x` is `15x^4 +4`. What does this derived `15x^4 + 4` give us? It gives us the a linear line, not a curve? why?
Comment: @TazMan: The derivative gives you the linear approximation _at the point_ by giving the number which, when it acts via multiplication, approximates the behavior of the function near that point. In particular, the translated function $f(x + x_0) - f(x_0)$, which is just $f$ recentered so the point of interest $(x_0, f(x_0))$ is at $(0, 0)$, behaves like the linear map $f'(x_0) x$ for small $x$ (which, in untranslated coordinates, means $x$ close to $x_0$). The linear approximation's variation from point to point need not be linear.
Comment: And of course, the graph of that linear approximation is just the tangent line, and that's the connection between the two. The tangent line is the best linear approximation and conversely.
Comment: So for your specific example, $15x_0^4 + 4$ is the value $f'(x_0)$ which multiplies $x$ to produce the linear function $(15x_0^4 + 4)x$ which approximates the behavior of $f$ close to the point $x_0$ (when appropriately translated). There is such a linear map associated with every point $x_0$, giving how the function behaves close to that point.
Comment: In translated coordinates, you can write $T_{x_0}(x) = (15x_0^4 + 4)(x - x_0) + (3x_0^5 + 4x_0) = f'(x_0)(x - x_0) + f(x_0)$, which is centered about $x_0$ and is the equation for the tangent line.
Comment: I'm not getting this. The explanations are getting too mechanical again. Do I need to revisit graphing? How would you explain what a derivative is or the big deal behind it to an algebra 1 or 2 student?
Comment: Isn't basic algebra a bit too early to get into wading into calculus??? But if I had to, I'd probably start by taking a graph of something, say, $y = x^2$, and then imagine "zooming in" on one point on the graph, and have them notice the more you "zoom in", the more the "curviness" goes away and it looks like a line, then asking what this line is, which means the "best approximation by a line" in that no matter how much we zoom in to the central point, the curve is never seen to separate from it, only to resemble it more and more, or, the line the function most resembles when you zoom closely.
Comment: So since we already know the central point which the line passes through, the only missing information to determine this "best fit line" is the slope.
Comment: Then for the "deform" explanation -- if they are at a point (and this seems to go past basic algebra! Sheesh!!!) where they can get that a function can be applied to a set of points, and so that we can imagine it as deforming a set, one could have them see how the function acts on small line segments centered at the point of interest, and see that as you shrink the segment down small enough, the images are approximately centered about the image of the interest point and the ratio of their length to the original segment approaches a constant.
Comment: Then show that this constant is the same as the slope obtained for the line by pointing to the equation of a line and the geometric fact that a _real number multiplication is a scaling_.
Answer: Taking your example of the furniture in the room we can think of the integral as the area under the curve. We divide the area up into small blocks and fit them in there like the furniture. Consider the integral
$$
\int_0^1 x^2 dx = {1 \over 3}
$$
we can think of this as the area beneath this graph.

If we were to grind up the unit square so we could fit small pieces of it into this area we could fit $1\over3$ of a piece.
Answer: I think you'll enjoy this example. :)
Remember how to calculate the mean of a list of $n$ numbers?
Of course you do, it's almost an insult to ask: you just add them all up, and divide by $n$.
But why is this the "right" thing to do?! You probably don't know. Well, here's why.

Say you have this list of numbers: $1$, $2$, $7$, $10$
Let's say we want to find the "center" of all of these numbers. How could you go about doing this?
Well, obviously, anything outside the range $1$ to $10$ isn't the "center" by any reasonable definition.
But, then, what's the center? Well, let's call $\mu$ the "center". What properties should $\mu$ satisfy?
Ideally, it should be as close to all the numbers as possible, as a whole.
Let's see what happens if we take the distance of each number with $\mu$, square it, and add it up:
$$d_2(\mu) = |\mu - 1|^2 + |\mu - 2|^2 + |\mu - 7|^2 + |\mu - 10|^2$$
Since the absolute values don't affect the squaring operation, we can remove them:
$$d_2(\mu) = (\mu - 1)^2 + (\mu - 2)^2 + (\mu - 7)^2 + (\mu - 10)^2$$
What happens if we find the $\mu$ that minimizes $d_2$? Well, we find the root of its derivative $d_2'$:
$$
\begin{align*}
d_2'(\mu)
= 0 &= 2(\mu - 1) + 2(\mu - 2) + 2(\mu - 7) + 2(\mu - 10)  \\
  0 &= \mu - 1 + \mu - 2 + \mu - 7 + \mu - 10  \\
  4\mu &= 1 + 2 + 7 + 10  \\
\implies\ \ \ \ \ \   \mu &= (1 + 2 + 7 + 10) \div 4
\end{align*}
$$
Hey look, the mean $\mu$ is the minimizer of the total squared deviation from our list!

Now you may wonder: why did we use squared deviation? Why not just absolute deviation?
Well, let's try that instead:
$$
\begin{align*}
d_1(m) &= |m - 1| + |m - 2| + |m - 7| + |m - 10|
\end{align*}
$$
Now take the derivative (thanks to @Ian's comment below for the suggestion on the compact notation). Let $\mathrm{sgn}(x)$ be the signum function (equivalently, $\mathrm{sgn}(x) = |x| / x$):
$$
\begin{align*}
d_1'(m) &= \mathrm{sgn}(m - 1) + \mathrm{sgn}(m - 2) + \mathrm{sgn}(m - 7) + \mathrm{sgn}(m - 10) = 0
\end{align*}
$$
Remember that $\mathrm{sgn}$ can be either $-1$, $0$, or $1$.
Does does the $m$ that satisfies this sound familiar?
It should: any $m$ that satisfies this equation is is a median of this list!
(You may have been taught that the mean of $2$ and $7$ is "the median". In fact, that's arbitrary and there is no reason to choose $5$ as the median. In reality, if you had to choose a single number, it should be $\approx 4.85$ (I think that's 34/7), and I'll leave it as an exercise for you to figure out why.)

We see that the mean and median are very intimately related -- they are both measures of dispersion. And using the derivative, we can prove why their formulas are correct! (And if we didn't know how to calculate the mean, the derivative would tell us.)
Bonus points: if you replace the exponent with $0$ instead of $1$ or $2$, you will get back the mode as well!
Comment: You didn't differentiate your absolute values in the $d'_1$ line. Doing so actually makes it clearer that you get a median: you get $\text{sign}(m-1) + \text{sign}(m-2) + \text{sign}(m-7) + \text{sign}(m-10)$. Any root of this has two of these numbers positive and two negative, i.e. is between 2 and 7.
Comment: @Ian: Ooh, yeah I totally missed that, sorry. I also totally forgot I could use $\mathrm{sgn}$ for the notation, that's a handy notation. Thanks, I'll update that.
Comment: @Downvoter: Care to comment?
Answer: Imagine you would like to recreate some smooth curve you have gotten (perhaps a sine curve ), but you are only allowed to use small straight line components. This is actually a very common task; I would imagine computers do this all the time. The shorter line segments you use, the 'closer' you are to actually recreate the actual curve. You can see this by imagining your recreation of the sine curve with small straight lines will get less 'pointy' the shorter you make the straight line segments. Imagine you would use infinitely smaller and smaller straight line bits to rebuild this curve, then your recreation would be indistinguishable from the curve you were given.
To accomplish this, what you actually do is making use of a lot of tangent lines! (Remember that the tangent is always a straight line.) So you are actually using the derivative for this. So in this sense the derivative actually recreates the curve you are given. (And it's also a bit cool that you can build something as 'non-straight' as a sine curve with straight lines.)
Answer: The differential is the slope or the rate of change.
On a roller-coaster:

Your velocity is the rate of change of position.
Your acceleration is the rate of change of your velocity.
Your jerk is the rate of change of your acceleration.
Your jounce is the rate of change of your jerk.
Comment: so is it safe to say that if I get the derivative of the derivative of the derivative of velocity I can reach to jerk? The equation keeps getting smaller, how does the graph change?
Comment: @TazMan - Remember that derivative of `sin` is `cos` and vice-versa so not everything diminishes to zero like polynomials do.
Comment: What is this diminishing. Whats the big deal behind it? Are all derivatives the slope of a tangent line? The tangent line must be straight right? So the equation of the line can never be more complex than y = mx + b..
Comment: @TazMan - In the case of polynomials yes all derivatives diminish inevitably because d/dx x^n = x^(n-1) (more or less) but that is a feature of polynomials. And yes, the derivative is the slope of the tangent which **is** the rate of change but the world is not all polynomials. There are curves that do not decay to nothing as you differentiate - there are also some that behave in very unusual ways but the core of my answer is the insight that the differential is the rate of change which is exactly the equation for the slope at any point.
Answer: (in addition to OldCurmudgeon)
If a roller-coaster is too wild for you, consider a merry go round with constant rotation around $(0, 0)$.
You can notice by differentiating x(t) and y(t) twice that acceleration is always towards the rotation-axis and if you differentiate two more times, you'll see that the jounce-vector is a positive constant multiple of the position vector.
Answer: First, don't be fooled by how derivatives are introduced in looking at slopes.  This is an artifact of how functions are introduced by graphing them.  A function is just a black box that takes in an input number and spits out an output number.  I cannot tell you how many people I've run into who think the derivative is the slope of a tangent line or that the integral is the area under a curve.  These are applications of derivatives and integrals, not fundamental definitions.
From a purely mathematical perspective, consider a Taylor series expansion:  in a neighborhood around a value $a$, the behavior of a function $f(x)$ could be well approximated by looking at the derivative:
$$f(x) \approx f(a) + (x-a) f'(a) + O([x-a]^2)$$
Such an expansion is at the heart of, for example, the small angle approximation: you can approximate the sine of an angle by the value of the angle itself, which simplifies problems in many applications, including optics.
The integral gives us a way to generalize weighted sums on a discrete number of points or objects to a continuously weighted sum on a continuous interval.  Consider, for instance, the notion of assigning probabilities to events and then performing a weighted sum to get the expected value.  The integral allows us to assign a probability density to an interval and to integrate that density, weighted by the value function, in an analogous way to the discrete case.
Comment: THis is really what I'm looking for. Could you explain why taking a derivative that results in "reducing" a function (as I understand it) results in a better approximation? is that what derivative is all about? getting an approximation?
Comment: It's about looking at how sensitive the function is to changes in the input.  That's why you can use the derivative to generate an estimate through Taylor series: if the change in the input is quite small, then everything else becomes insignificant compared to the derivative. - Finally, do note that how sensitive a function is to changes in its input may vary with different inputs. This emphasizes that the derivative itself can often be thought of as a function in its own right.
Answer: An application, which if applied world wide on all roads, would make it impossible to go over the speed limit and go unnoticed.
If you place sensors with timers that correctly identify passing cars throughout every stretch of road spaced 1km apart and the worldwide speed limit is now 50 km/h = 50 km/3600 seconds, a car going at top legal speed (50km/h) would take 1/50th of an hour = 3600seconds/50 = 72 seconds to cross adjacent sensors.
If a car takes less than 72 seconds to cross adjacent sensors, then the car MUST have gone over the speed limit at some point between the sensors. This conclusion comes from the fact that we have a mapping between time and distance, which allows us to make accurate (in my example not exact) deductions about the collected information.
If it still isn't clear enough, I will demonstrate how exactly the program coordinating the sensors would go:
<code>var max_speed=50
Sensor A:Car[x] Passes at Time Stamp 1:15:15PM
Sensor B:Car[x] Passes at Time Stamp 1:16:10PM
//average* speed=difference in distance/difference in time
//[f(x2)-f(x1)]/[x2-x1]=1km/55seconds
//1km/55seconds][60seconds/1min][60min/1h]=[3600/55]km/h=65.45km/h
var Car[x].speed=[1/Date(1:16:10)-Date(1:15:15)][3600]=65.45/h
65km/h>50km/h = EMIT SPEEEDING TICKET FOR Car[x]
</code>
*average speed: you might actually go at various instantaneous speeds throughout continuous length of road (even if you put it on cruise control).


Calling classes through applet

Question: Hello I am newbie to Applets and i need help in understanding something.
So I created an applet in eclipse that calls another class file and its methods when the button on the applet is clicked.
public class mainApplet extends JApplet {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;

private int x;
private int y;
private int result;
public mainApplet() {

    textField = new JTextField();
    textField.setColumns(10);
    textField_1 = new JTextField();
    textField_1.setColumns(10);
    textField_2 = new JTextField();
    textField_2.setColumns(10);

    JButton btnCalculate = new JButton("Calculate");
    final JCheckBox ChckbxADD= new JCheckBox("Add");
    final JCheckBox chckbxLaunch = new JCheckBox("Launch  Browser");

    GroupLayout groupLayout = new GroupLayout(getContentPane());
    groupLayout.setHorizontalGroup(
        groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayout.createSequentialGroup()
                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                    .addGroup(groupLayout.createSequentialGroup()
                        .addGap(49)
                        .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addGap(26)
                        .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addGroup(groupLayout.createSequentialGroup()
                        .addGap(89)
                        .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
                            .addComponent(btnCalculate)
                            .addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                            .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                .addComponent(ChckbxADD)
                                .addComponent(chckbxLaunch)))))
                .addContainerGap(203, Short.MAX_VALUE))
    );
    groupLayout.setVerticalGroup(
        groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayout.createSequentialGroup()
                .addGap(48)
                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                    .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(18)
                .addComponent(ChckbxADD)
                .addGap(3)
                .addComponent(chckbxLaunch)
                .addGap(20)
                .addComponent(btnCalculate)
                .addGap(28)
                .addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addContainerGap(74, Short.MAX_VALUE))
    );
    getContentPane().setLayout(groupLayout);

    btnCalculate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Functions func = new Functions();

            if (ChckbxADD.isSelected()){
                x=Integer.parseInt(textField.getText());
                y=Integer.parseInt(textField_1.getText());
                result=func.addition(x, y);
                textField_2.setText(String.valueOf(result));

            }
            if(chckbxLaunch.isSelected()){
                func.Launch();

            }

        }
    });

}

}
This works when I run it through eclipse. I exported the class files along with the applet file in a jar (Calc.jar). Then, I used the following simple html to call the applet. This html is a local file.

     <APPLET CODE="mainApplet.class" archive="Calc.jar" WIDTH="800" HEIGHT="500">
     </APPLET>

The applet is in MainApplet class and it calls on a Functions class.
   public class Functions {

        public void Launch(){

WebDriver driver= new FirefoxDriver();
driver.get("http://www.google.com");

}

public int addition(int x, int y){

    int result;
    result=x + y;
    return result;

}

}
When the applet is launched in the browser and the "Launch Browser" checkbox is checked and the button is clicked, a firefox window should open and launch google.com.  In eclipse, this happens perfectly. But when the applet is embedded in the local site, nothing happens when the "Launch Browser" checkbox is checked and the button is clicked. I have another function that is used on applet ( addition), and that works as designed. The user can input two number in two Jtextfields and the checkbox for "add" is checked and when the button is clicked, the result is displayed on another jtextfield on the applet. This works fine but the other function doesnt work.
UPDATE:
The following is the exception in the console:
Exception in thread "AWT-EventQueue-2" java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
    at mainApplet$1.actionPerformed(mainApplet.java:75)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.WebDriver
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 36 more

Thanks in advance for any help.
Comment: The applet element is completely invalid.  What is your question?
Comment: My question: how can I use the other classes that are within the jar. The applet uses a class by calling it when the button is clicked. However, when i embedded the applet within a webpage, the applet showed up but nothing happens when i click the button.
Comment: What is the output seen in the [Java Console](http://www.java.com/en/download/help/javaconsole.xml)?  What is the (new, validated) HTML?  What is the name of the Jar containing the classes that must be called on button click?  What is the link to the web page?
Comment: I think My problem is that I am using external jars that are being used in the applet. However I am not calling them correctly through my HTML.
Comment: *"I think.."*  Good luck with that. You are not answering my questions so I can be of no further help.  I don't know why you bothered to ask other people in the first place.
Comment: I had answered your questions by updating my post. Not sure if you saw that. When I exported the jar file, I had made sure all of the resources were in the jar. I didnt know that I have to specifically call the selenium jars in my HTML again. I am not sure how to call the selenium webdriver jars in my HTML. Sry if I sound like complete newbie but I am just trying to learn. So if you dont want to help, you dont need to. Thanks
Comment: OK - did not notice the edit.  What is reported in the [Java Console](http://www.java.com/en/download/help/javaconsole.xml) when run in a web page?  I expect it will show something related to security - e.g. an `AccessControlException`.
Comment: Hey Thanks for responding again..I get the following error in the console:  Exception in thread "AWT-EventQueue-2" java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
 at mainApplet$1.actionPerformed(mainApplet.java:75)
Comment: I have added the console output in the post right now.
Comment: Change `archive="Calc.jar"` to `archive="Calc.jar,x.jar"` where `x.jar` is the name of the Jar containing the `WebDriver` class.
Comment: Hey thanks! That worked. Only works with IE though. Firefox throws ExceptionInInitializerError FirefoxBinary error but that is no biggie. Thanks again!
Answer:

What is reported in the Java Console when run in a web page? I expect it will show something related to security - e.g. an AccessControlException.

I get the following error in the console:

Exception in thread "AWT-EventQueue-2" java.lang.NoClassDefFoundError:

Change:
archive="Calc.jar"

to:
archive="Calc.jar,x.jar"

..where x.jar is the name of the Jar containing the WebDriver class.

Calling classes through applet


Getting the sizeOf(a flatbuffers Table)

Question: I am using Flatbuffers with C++. I would like to create an array of bytes in a struct that is the size of the generated table (I am sending the contents as a payload for a NanoMSG message).
How does one do a sizeof(table)?
<code>#include "pnt_generated.h"

struct packetStruct {
    Topics topic;
    int payloadSize;
    uint8_t payload[sizeof(pnt)];
};
</code>
does not work directly.
Comment: Perhaps this has some info on that https://groups.google.com/forum/#!topic/flatbuffers/7wuLsfjI3u8
Comment: In C++ you cannot declare variable size arrays (a FlatBuffer is not a fixed size known ahead of time).
Note that you can create size prefixed buffers in FlatBuffers. So rather than trying to wrap a FlatBuffer in your own struct, you can use FlatBuffers for all of it.
Comment: @Aardappel I need to wrap it in a packet, since I am using a variant of ZeroMQ to publish it on the net, and the first bytes of the packet are the channel/topic. The rest is the payload which is Flatbuffers.
Comment: can reserve a std::vector instead of array..
 struct packet {  Topics topic; int pSize;  std::vector payload(sizeof(pnt)); }
Comment: That does not help one get a contiguous memory block with the channel topic as the first bytes
Comment: Well it looks like no one has a better Idea for me to use a fixed size #define PayloadMax 256, then declary payload as uint_t[PayloadMax] and check in the builder if I exceed the size I don't expect bigger than 256, I don't think this will be a problem. And I am only sending the actuall size (int payloadsize) so what can get hurt?
Answer: You can get the size of your payload from the bufferbuilder:
<code>
    flatbuffers::FlatBufferBuilder builder(1024);
    auto l = CreateLogEvent(builder, builder.CreateString("INFO"), builder.CreateString("main.c"), builder.CreateString("Test Log Entry"));
    FinishLogEventBuffer(builder, l);
    auto ptr = builder.GetBufferPointer();
    auto size = builder.GetSize();
</code>
Answer: Since it seems that Flatbuffers dynamically sets the size (in my case of the payload). And no one has a better idea, I am creating a fix sized payload in the struct, and then checking to see if I exceed that:
<code>#define PayloadMax 256
#include "pnt_generated.h"

struct packetStruct {
    Topics topic;
    int payloadSize;
    uint8_t payload[PayloadMax];
};
</code>
Answer: There is a hidden feature in flatbuffers (prefixSize): https://flatbuffers.dev/class_flat_buffers_1_1_flat_buffer_builder.html#a425ab2bd13a0e4331a7190ec2d17c3b2
Or you might just use a different protocol.

Getting the sizeOf(a flatbuffers Table)


Field must be inside reduxForm() when using symlinked module

Question: I am having issues with redux-form when developing locally with an npm linked module. I have created an Input component which I intend to use across multiple applications, and so have placed it inside an npm package. In my main application I wrap a component with reduxForm() and then import the Input component in to that wrapped component. The Input component initialises the Field from redux-form.
If I import the Input component from anywhere within my project it works perfectly. Similarly, if I install the package to my node_modules and import it from there it also works perfectly. However, as soon as I import it through a symlink (using npm link) it complains with the following error: Uncaught Error: Field must be inside a component decorated with reduxForm()
This is strange, it appears to me from the stack trace that it is in fact decorated with reduxForm(). I am also running Redux Dev Tools and can see the form has been initialised in state exactly as I expect it to... So the form is there for sure.
Stack trace:
react-dom.development.js:17882
The above error occurred in the <Field> component:
    in Field (created by Context.Consumer)
    in Hoc (created by Field)
    in Field (created by FieldComponent)
    in div (created by Index)
    in Index (created by FieldComponent)
    in FieldComponent (created by Connect(FieldComponent))
    in Connect(FieldComponent)
    in div
    in Col
    in div
    in Row
    in form
    in div (created by Index)
    in Index
    in EditProfileView
    in EditProfile
    in Form(EditProfile)
    in Connect(Form(EditProfile))
    in ReduxForm
    in Hoc
    in ReduxForm
    in Connect(ReduxForm)
    in div
    in Col
    in div
    in Row
    in ContactView
    in Contact
    in Connect(Contact)
    in Route
    in Switch (created by FlatSwitch)
    in FlatSwitch (created by App)
    in Switch (created by FlatSwitch)
    in FlatSwitch (created by App)
    in div (created by Col)
    in Col (created by AppView)
    in div (created by Row)
    in Row (created by AppView)
    in div (created by Container)
    in Container (created by AppView)
    in div (created by AppView)
    in AppView (created by App)
    in App (created by Connect(App))
    in Connect(App) (created by Route)
    in Route (created by withRouter(Connect(App)))
    in withRouter(Connect(App)) (created by App)
    in Auth (created by Connect(Auth))
    in Connect(Auth) (created by Route)
    in Route (created by withRouter(Connect(Auth)))
    in withRouter(Connect(Auth)) (created by App)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by App)
    in App
    in Provider

Considering this error is only occurring when importing through a symlink I am to assume this may be something to do with the webpack set up. Here are some extracts from my webpack config (the relevant parts I believe):
{
    resolve: {
        symlinks: true,
        extensions: ['.jsx', '.js'],
        alias: {
            core: '/Users/MyUser/Projects/@AAG/core',
        },
    },
    module: {
        rules: [
            {
                test: /\.(jsx|js)$/,
                include: [
                    '/Users/MyUser/Projects/Hub/src',
                    '/Users/MyUser/Projects/@AAG/core',
                ],
                exclude: [
                    /mapbox-gl/,
                ],
                loader: 'babel-loader',
                ...
            }
        }
    }
}

So you can see that it is set up to transpile from the correct symlinked directory. And in fact it works fine as babel is managing to transpile all of the JSX and all other features of my website (I am importing quite a bit from the core alias). redux-form is my only bug at this point.
So the form I have created (EditProfileView from the stack trace) imports the Input component as follows:
import { Input } from 'core/components/Form';

The code for this as as follows:
const Input = field(InputField);
export { Input };

import { connect } from 'react-redux';
import { Field } from 'redux-form';
export function field(Component) {
    const FieldComponent = (props) => {
        ...
        return (
            <div className={`${className} ${block ? s.block : s.inline}`}>
                <Field component={Component} {...props} />

        );
    };
    function mapStateToProps(state) {
        return { theme: state.theme };
    }
    return connect(mapStateToProps)(FieldComponent);
}

And then the InputField component does some styling and such and returns a simple input.
I hope all this helps. I have tried to give as much information as possible to help debug this because I really cannot figure out why this is happening. Everything else through the symlink works perfectly, and without the symlink it also works perfectly. I have been looking at this for a long time now and am out of ideas.
Any help would be greatly appreciated.
Thanks!
Comment: I fixed this in the end by just importing the `Field` component and injecting the `Input` component inside the project itself. It's not quite as clean but it works once again with the symlink. If anyone could provide a reason for this bug I would be interested to know.
Answer: Steps

connect to reduxform (to use decorator you have to setup your babel or refer simple redux Form)
The field which is imported from redux-form must be used inside the form.

thats it, try the following steps.
import { Input } from 'core/components/Form';
    The code for this as as follows:

    const Input = field(InputField);
    export { Input };
    import { connect } from 'react-redux';
    import { Field, reduxForm } from 'redux-form';

    @reduxForm ({
     form: 'nameOfForm'
    })
    export function field(Component) {
        const FieldComponent = (props) => {
            ...
            return (
                <div className={`${className} ${block ? s.block : s.inline}`}>
                   <form>
                    <Field component={Component} {...props} />
                   </form>

            );
        };
        function mapStateToProps(state) {
            return { theme: state.theme };
        }
        return connect(mapStateToProps)(FieldComponent);
    }

Comment: Unfortunately this does not work :( First of all it would complain that only a class could be decorated, so i went about it like this: `export function field(Component) {
 @reduxForm ({ form: 'nameOfForm' })
 class FieldComponent extends React.Component {`. However it still complains that the class is not decorated with `reduxForm`. This behaviour is very strange. I think it has to be something to do with the symlink. As said, if i copy this code and import it from the project it works fine...


difference between acf() from {stats} and Acf() from {forecast}

Question: When I execute both functions on the same vector, I get slightly different graphs. I think I know what is happening but I want to confirm. acf() shows the spike at lag 0 which is 1 naturally, this makes the rest of the graph look much smaller. Acf() in contrast does not show the spike at lag 0 and starts at lag 1. Am I right in my assumptions?
Answer: The difference is actually explained in the forecast package manual:

The functions improve the acf, pacf and ccf functions. The main
  differences are that Acf does not plot a spike at lag 0 when
  type=="correlation" (which is redundant) and the horizontal axes show
  lags in time units rather than seasonal units.


Taxonomy terms from multiple vocabs on a single line

Question: I migrated from Drupal 6 to Drupal 7 and used the same theme, now the "post tags" (taxonomy terms from multiple vocabularies) aren't displayed on the same line as shown below.

How to get these into a single line.
Answer: This change in my style.css did the trick :
.node .taxonomy,
.node .field-type-taxonomy-term-reference {
  font-size: 0.8em;
  line-height: 100%;
  display: inline;
  /* padding-left: 1.5em; */
}


How to click on multiple dropdown & select same values from all dropdown in cypress

Question: I am able to click on all dropdowns but am not able to select values from them one by one.
cy.xpath('/html/body/app-root/div/mat-sidenav-container/mat-sidenav-content/app-configurable-product-management/form/div[2]/mat-card/mat-card-content/app-configurable-product-inventory/form/div/div/div/div')
            .each($row => {
                //Click on drop down
                cy.wrap($row).find(':nth-child(4) > .common-form-field-width > .mat-form-field-wrapper > .mat-form-field-flex > .mat-form-field-infix').click({timeout: 2000, force:true})
                //Select same values from all dropdown (Not working)
                cy.contains('In Stock').click({timeout: 2000, force:true})
                cy.wait(2000)
            })

Comment: You've set the timeout to 2000 ms, but usually it's 4000 ms - did you mean to increase it?
Comment: It could be the selector used doesn't match all dropdowns. DOM info of your dropdowns would help.
Answer: It's working now...
cy.xpath('/html/body/app-root/div/mat-sidenav-container/mat-sidenav-content/app-configurable-product-management/form/div[2]/mat-card/mat-card-content/app-configurable-product-inventory/form/div/div/div/div')
                .each($row => {
                    cy.wrap($row).find('mat-select').then((sel) => {
                        cy.wrap(sel).click()
                    })
                    cy.get('mat-option[value="IN"]').click()
                    cy.wait(2000)
                })


3ware raid controller, unit unusable, several degraded disks

Question: I was switching the disk drives in my server, running RAID 6 on 5 disks on a 3ware 9650SE controller, for newer disks and have run into a problem.
The two first disks went fine, I took out one disk and inserted a new one, let the array rebuild and repeated for disk 2.
When booting after switching the 3. disk I noticed two where wmissing, not just the one, so I did not ask the controller to rebuild, but shut it off and investigated.
One of the remaining disks had a bad power connector, so I took out that disk and put in the one I had just taken out.
When booting again booth of the disks originally being a part of the array shows as #degraded"
The two disks that was synced in are ok and the las swapped disk is "spare".
With 2 of 5 degraded and one missing I can't rebuild.
Why are the two disks marked as degraded and whan, if anything, can I do to get them online again?
Both disks are ok according to SMART...
Please help.
Answer: Trash the RAID set, rebuild it from scratch and restore from backups.
Comment: There has been written absolutely nothing to the disks after the last time the array was operational, so the data is there, but there's no way to force the controller to rebuild?

This IS the backup and it takes a looooong time to start it from scratch, again, so I would very much like to find an alternative.

Hardware controllers :sigh: I have never lost an array with mdadm...


solving $\frac{1}{\sqrt{2\pi}} \int_{-\infty}^{\infty} \frac{e^{ikx}dk}{b^2+k^2}$

Question: Can someone explain to me how to solve this integral?
I didn't understand the method how to approach it in the class:
$$\frac{1}{\sqrt{2\pi}} \int_{-\infty}^{\infty} \frac{e^{ikx}dk}{b^2+k^2}$$
Is there any identity that i should know about?
Thanks
Comment: noticed that it's $dk$ not $dx$
Comment: You might find help here http://math.stackexchange.com/questions/545348/what-is-the-value-of-int-infty-infty-frace-ixx2-4-dx?noredirect=1&lq=1
Answer: If you were to solve
$$
                -f''+b^2f = \sqrt{2\pi}\delta
$$
for a function $f\in L^2$, where $\delta$ is the Dirac delta, then you would end up with the equation
$$
                k^2\hat{f}(k)+b^2\hat{f}(k)=1 \\
                   \hat{f}(k)=\frac{1}{k^2+b^2} \\
             f(x)= \frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}\hat{f}(k)e^{ikx}dx=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}\frac{e^{ikx}}{k^2+b^2}dk,
$$
which is the desired integral.
The differential equation is solved by
$$
                       f(x)=Ce^{-b|x|},
$$
where the discontinuity in $(-f')$ is chosen to have a jump discontinuity of $\sqrt{2\pi}$, so that the derivataive of $-f'$ will produce $\sqrt{2\pi}\delta$. So, $C$ must be chosen such that
$$
    -\sqrt{2\pi}=f'(0+)-f'(0-)=(-b)C-(b)C=-2bC \implies C=\frac{\sqrt{2\pi}}{2b}
$$
So the expected solution is
$$
                  f(x) = \frac{\sqrt{2\pi}}{2b}e^{-b|x|}.
$$
To check this,
$$
       \hat{f}(k)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}\frac{\sqrt{2\pi}}{2b}e^{-b|x|}e^{ikx}dx \\
    =\frac{1}{2b}\left(\int_{-\infty}^{0}e^{bx}e^{ikx}dx+\int_{0}^{\infty}e^{-bx}e^{ikx}dx\right) \\
    = \frac{1}{2b}\left(\frac{1}{b+ik}-\frac{1}{-b+ik}\right) \\
    = \frac{1}{k^2+b^2}.
$$
This implies
$$
      \frac{\sqrt{2\pi}}{2b}e^{-b|x|}=  f(x) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}\hat{f}(k)e^{ikx}dx = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}\frac{1}{k^2+b^2}e^{ikx}dk,
$$
which evaluates your integral.