Is it secure to share an access token via HTML5 messaging API between various iframes?

Question: I have a main website that embeds 3 other websites via iframes (legacy systems providing various functionalities with a user interface). Currently the user has to authenticate with each of the system despite that they are all using the same authorization server. In order to make it user-friendly I was thinking to share the access token across the various iframes using the HTML5 messaging API and I was wondering whether this approach is viable from a security point of view?
Comment: There's a standard solution to this problem, which is to implement SSO with OpenID/OAuth protocol. You might want to either use existing libraries that implements these protocols or read their code for ideas on how you can design yours.
Answer: The postMessage API  is designed for cross domain communication as part of the Cross Origin Resource Sharing mechanism.
The Window.postMessage() method, introduced in HTML5, allows JavaScript code running on different origins to communicate with each other in a bidirectional manner. This API can be used for communication between an iframe and its parent document. Similarly, it can be used by an HTML page and a child window to exchange messages, such as an embedded third-party video notifying its parent frame when the user pauses the video.
The classical rules of security also apply to applications using postMessage(). You are planning to use this method for sharing authentication information which is perfectly fine if you you follow basic input validation rules while implementation.

Never broadcast your auth tokens: Your scenario contains multiple different parties who need to have access to a common token. you might be tempted to broadcast the authentication information so that all the iframes get access to it. This may result in unauthorized access to your tokens. Hence the postMessage() call should always specify the target origin.

Always validate message origin:  You need to validate that the message has been received from a valid and expected origin. Only after origin validation you should proceed with using the message in the application logic. Imagine a case where your app is iframed by a malicious domain. If you do not validate the origin of the message it may result in script injection.

Additionally, depending on your trust relationship with the authorization server, you may want to validate the token itself once the sender origin is validated.
For a more detailed analysis of postMessage() API security along with a few example code snippets, refer to Mcafee's Blog
Comment: @WashingtonGuedes Fixed it. It has been years and it seems they moved the company blog.
Answer: You can read about the rules that modern browsers follow on cookie and domain access control: RFC6265IFrames for many reasons are not recommended (Like SEO, google indexing, Security,...).  The new version of browsers with default cookie domain configuration are 99% secure in this subject. However, the most security risks in IFrame (and browsers) history were about CSRF and XSS. So if you protect your sites by CSRF tokens and XSS filtering methods + Correct cookie domain configuration, even with a vulnerable browser it's approximately safe to use IFrame.
Comment: This question is likely about the postMessage API and has nothing to do with cookies.


Testing without SRS as a fresher tester?

Question: I am new to testing field and from a non-technical background how should I report bugs without SRS (Software Requirements Specification)?
Answer: Even without a formal document, there are always requirements. You just have to work harder to find them.
You can talk to people and ask, then document what you heard. And there are some requirements ("must not crash", "must be consistent with a prior version of the application") that are usually implied.
see: http://www.allthingsquality.com/2010/04/there-are-always-requirements.html
Answer: With any application you are testing you need to learn the system. How is it used and how it generates revenue. Requirements come from that.
Who is using the system. What are the persona's and what is important for them. Understanding the users and their roles is key to see if something is a possible defect in their eyes.
Reporting defects should include the following info:

Step by step reproduction (containing enough details for a developer to reproduce the issue)
Actual result (what is the end-result of the steps, this is the thing that is possibly wrong)
Expected result (the result the persona would expect instead of the actual result. This makes it easier for developers or product managers to verify you understand the requirement and if the defect is valid or not.)

When you are new to a system it seems advisable to communicate a lot with the different roles users, managers and developers to understand what is happening and why.
Instead of just blindly creating bug-reports I would talk to the people and ask them if they think you have indeed found an issue or requirement that is wrongly implemented. This until you are confident with the requirements of the system. Getting a lot of reports rejected is not fun and or helpful.
As I am confronted with a new product to test. I always start with quality interviews with the roles. Asking them what they expect from the system, but also explaining the three different types of software quality. With the goal to understand where the product currently stands and what the greatest gaps are in the quality process. If needed you could start creating formal requirement documents, but question yourself if alternatives like automated tests could be an better idea to safeguard these features.
Answer: My opinion is communication. To communicate with developer, customer, business analyst and so on. Communicate with customer to get:

Better domain understanding ,Better acceptance tests, Better
  end-to-end tests

And communicate with developers to get:

Better Test Automation code, Better Unit Tests

And communicate with business analyst to get:

Better domain understanding Better acceptance tests
Answer: Without SRS try to identify the business work flow on the system.
Based on that report bugs.
Always try to identify work follow of the system .
Talk to a BA,PM,clients and finally to the developer.
Answer: I have this same issue lately, testing without SRS or the SRS lack of details.
I'll share my to-do list when meet this situation:
1.Know your client or at least think as a normal user that will use the App.
Make a list about what most user do with this App.
2.Ask myself about Why I want to make this App?, how people use this App?, Is it good enough for me?, etc. And from this question I make a simple SRS, or I prefer to called it "my own standard".
3.Without SRS or the SRS lack of details, it means it will be a lot more bugs to catch, since QA define the App's standard it self, so the testing process will get more rough, to avoid miss the deadline, test it as soon as possible.
4.And if the 3 to-do list above still doesn't meet user requirements, it means get ready for Change Requirement and a lot of Overtime.
-When there is no standard, try to make one-
Answer: This is how I would normally approach.

Talk to the developers : For me this is the starting point. This will give me an idea of what requirements they used and importantly access to the system design.
Cross checking with the business/users on the discussions with developers : This will be the base for my testing. Discussions with the business/users will definitely help in defining and refining the requirements. Document the findings (at least email ) and get the consent from the team and the business. the requirements will not be a functional requirement spec, but at least you'll have some requirements to work with from a business perspective.
Exploring : with the little understanding you have on the system, it's time to explore. There'll be lot of questions. But having questions will help understanding the requirements properly. At least it'll start a discussion among the key stakeholders which eventually refine the requirements.
Refer the Defects : I usually refer both open and closed defects. More often than not, you can find the fine tuned requirements within the comment threads on defects.

key word here is, ask lot of questions.
Hope this helps.


How to truncate the lines of a file?

Question: I need to truncate the lines in a file to 24 characters, to feed to a small dot-matrix printer. How can I do this? I use doom emacs.
Answer: From the shell:
cut -c1-24 FILE

In Emacs, interactively:
M-x replace-regexp RET ^\(.\{24\}\).+ RET \1 RET
Answer: phils has answered your question, but i wonder if you didn't mean that you wanted to limit the line lengths of a given file so that they'd all print within the constraint of your printer, rather than cutting your lines off.
if that is so, you need to set the fill-column to a value small enough, and then fill (wrap) your text, which limits your line lengths to the fill-column's value:
use set-fill-column (C-x f in vanilla emacs) to set a value for it.
then fill (wrap) your text with e.g. fill-region or fill-paragraph. to wrap a whole file you can just select whole buffer with mark-whole-buffer (C-x h in vanilla emacs) then run fill-region.

How to truncate the lines of a file?


Rounded edges in picturebox C#

Question: How to round edges in picturebox control. I Want to get angles like ellipse have but i dont know how to do it. I Use C#. Thanks!
Answer: putting 1 Picture box on the form and write this code
also you can change the the minus number beside of Width and Height to get best result
 System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
            gp.AddEllipse(0, 0, pictureBox1.Width - 3, pictureBox1.Height - 3);
            Region rg = new Region(gp);
            pictureBox1.Region = rg;

Comment: Thank you, this is a great solution for the amount of syntax necessary.  I haven't tested how much resources this draws but I like it as is for now. Also, nice picture :P
Answer: Yes, no problem, you can give a control an arbitrary shape with its Region property.  Add a new class to your project and paste the code shown below.  Compile.  Drop the new control from the top of the toolbox onto your form.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

class OvalPictureBox : PictureBox {
    public OvalPictureBox() {
        this.BackColor = Color.DarkGray;
    }
    protected override void OnResize(EventArgs e) {
        base.OnResize(e);
        using (var gp = new GraphicsPath()) {
            gp.AddEllipse(new Rectangle(0, 0, this.Width-1, this.Height-1));
            this.Region = new Region(gp);
        }
    }
}

Comment: Ahh, thanks for this! It really gives an image of the possibilities you have when you extend an class. And how easy it is to get a modified component in your toolbox. :)
Answer: Round edges as in round corners?
If so check out http://social.msdn.microsoft.com/forums/en-US/winforms/thread/603084bb-1aae-45d1-84ae-8544386d58fd
Rectangle r = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
int d = 50;
gp.AddArc(r.X, r.Y, d, d, 180, 90);
gp.AddArc(r.X + r.Width - d, r.Y, d, d, 270, 90);
gp.AddArc(r.X + r.Width - d, r.Y + r.Height - d, d, d, 0, 90);
gp.AddArc(r.X, r.Y + r.Height - d, d, d, 90, 90);
pictureBox1.Region = new Region(gp);

Answer: Thank you, Hans. But I also need a smooth look. I did some research on this subject, but I could not find a solution. Then I tried to do it myself and found the solution below. Maybe someone else needs it.
protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (GraphicsPath gp = new GraphicsPath())
        {
            gp.AddEllipse(0, 0, this.Width - 1, this.Height - 1);
            Region = new Region(gp);
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.DrawEllipse(new Pen(new SolidBrush(this.BackColor), 1), 0, 0, this.Width - 1, this.Height - 1);
        }
    }

Rounded edges in picturebox C#


Does "Erase All Data" feature on iPhone disable "Find my Phone"?

Question: I have the "Erase All Data after 10 failed passcode attempts" feature turned on on my iPhone 4S. I also have the "Find my Phone" app installed. If my iPhone was stolen, and the thief triggered the "Erase All Data" feature after failing to unlock the phone, would it erase the "Find my phone" app meaning I couldn't locate it through iCloud?
Comment: see also this question: http://apple.stackexchange.com/questions/34861/if-i-remote-wipe-my-iphone-can-i-still-locate-it-remotely
Answer: The 'Find My iPhone' app on the iPhone itself does nothing to affect the ability to locate/remote message/remote wipe the iPhone itself. The 'Find My iPhone' app is a client to simplify the functions of doing so for other devices.
In order to actually use those features on the iPhone itself MUST be configured via Settings: Location Services > (down at the bottom) Find My iPhone. Only by enabling that will you actually be able to locate your phone via another iOS device, or at icloud.com;
Comment: Yes, I'm aware that if you're on your iPhone you can "remotely lock", "send a message", or "remote wipe" the iPhone while you're on it via the app, but my point is that the Find My iPhone app is a client, and the actual server/security settings are what I listed in the answer itself.
Answer: Yes. Enabling this option is both risky and safe. On one hand, you risk losing your phone/data forever, but on the other hand that individual will not be able to access your data or use your phone. It's your call, but I'd recommend leaving it off so you at least have a chance at getting it back. You can always wipe out your phone remotely with Find my iPhone without having that option enabled.
Comment: I disagree. It is not "always possible to wipe the iPhone remotely". If the bad guy who's stolen the phone disables WiFi and takes out the SIM card, find my iPhone will NOT work. If you have no passcode all your data (maybe company data as well) be accesible. If you had a passcode but without erasing phone data after X tries and you only use a 4 digits code, the attacker could just bruteforce your code. This is especially bad for confident company data.
Comment: @cyphorious I agree with this post on the basis of my recent experience of being mugged in Sao Paulo. It's been several weeks and the device never reconnected to iCloud, and my remote erase never succeeded.
Answer: Yes. Unfortunately, Find my iPhone isn't a fail-safe system. It's also disabled if someone else erases all your data, through iTunes for example. Additionally, if a SIM card other than your own is put into the phone, the handset can only locate itself via wi-fi, and not through the third party networks SIM.


Why did they name the show Russian Doll?

Question: Watched Russian Doll recently and it was enjoyable but really made me wonder about the title. Like what does the show have to do with Russian dolls? Even the poster used it:
Comment: I don't _think_ it's a spoiler but just in case I'll mark it as one (apparently I don't now how to do that for comments, so stop reading now if you're avoiding spoilers):

>! In one of the loops, she finds a matryoshkas in with her childhood toys.
Answer: The Hollywood Reporter spoke with Natasha Lyonne in January 2019 and explains:

Poehler came up with the title as a literal idea of what the protagonist would represent. In those early days of brainstorming Russian Doll, Nadia was conceived as someone who "has an external presentation that we all put out into the world and, once you take the deep dive, has this whole other person working in there," Lyonne explains. "The idea that we had come up with was choose your own adventure style, where you could make a choice to try every person out at a party, but who would still be stuck with themselves at the end. And that's the person you were really going to have to look at."

(Amy Poehler co-created the TV-series.)
A Russian (or Matryoshka) doll according to wikipedia:

A set of matryoshkas consists of a wooden figure, which separates, top from bottom, to reveal a smaller figure of the same sort inside, which has, in turn, another figure inside of it, and so on.
Comment: @Cœur but that's not the Russian doll part. Where are the layers there? It's the emotional and interpersonal layers breaking down on each "respawn" that is more important
Comment: Your answer is eluding the blatant pitch: [_The series follows a woman who repeatedly dies and relives the same night in an ongoing loop._](https://en.wikipedia.org/wiki/Russian_Doll_%28TV_series%29)
Comment: I believe, at one point in the show, another character actually says "She's still inside you", referring to the main character's mother.  That's seems to me, to be a direct call back to the title.
Answer: It's a double (triple?) entendre.
First, the character is of Russian heritage.  And in particular, a Russian Jew.
This also summons up Winston Churchill's famous line,

I cannot forecast to you the action of Russia. It is a riddle, wrapped in a mystery, inside an enigma...

Which may aim to evoke the Russian Matryoshka doll.
It's even more complicated for Russian Jews. That is relevant because of the very heavy Jewish topicality and symbolism in the show, that the character is Russian, and that the actress, Natasha Lyonne, has deep Jewish heritage.
Then there is the direct symbolism of the Russian Matryoshka doll, as that pertains to the constant deaths and rebirths. And particularly, as the character slowly by trial and error, uncovers the layers of her personality, ego, and the way she presents herself to the world.
The character also does her makeup in near comical extremes, in a "dollish" sort of way.
Comment: Where does she do her makeup in a comical way? I recently saw the series, and never i think did her makeup stand out or was attention drawn to it.
Comment: @Joachim It's more that she's 'over the top' character. She's uniquely a charter that seems to have no qualms about physically standing out, she's not physically or verbally a modest character, but yet clearly she's over compensating for her hidden humanity. I think her make-up and hair argumentively goes along with that. But to the Answer, she begins her journey that's about her mother and ex's daughter by wanting to learn the Heritage of Jewish building her friend, whose throwing the party, lives in. She in that moment denies her "Jewish" heritage by not being a practicing Jew...
Comment: This seems to go with and/or be the subtext about her mother's problems. There's potential for a second season, but I don't know if we really got underneath her problems with her mother, or if we just blew the lid off so to speak? I don't know if the second season would delve deeper here or introduce something newer, but it's possible it's just the beginning!
Comment: I think that's looking too hard for meaning that's not there. Nadia indeed comes across as an individualistic character. And, yes, her sarcasm, cynicism and self-destructive nature indicate a lack of self-value, but nowhere does she seem to want to compensate outwardly for her apparent apathy - I think it is only insinuated that her behaviour is directly linked to her (unwittingly) abusive mother - she in fact seems to care remarkably little about the way people perceive her.


how to use SOP ICs on Breadboard?

Question: I have a project, But the required IC is available in my home is in SOP design. How do I use SOP ICs on breadboard?
Comment: Possible Duplicate of http://electronics.stackexchange.com/questions/8000/how-to-use-multiple-terminal-surface-mount-chips-in-amateur-project and http://electronics.stackexchange.com/questions/21635/prototyping-with-smd-components/21639#21639
Answer: You could use an adapter board.  Futurlec have a broad selection of them, and - by far - the cheapest prices I've seen.  Theirs tend to be less than a dollar, where a corresponding part from Sparkfun or Digikey could be > $5.00.
http://www.futurlec.com/SMD_Adapters.shtml
Answer: There are two obvious solutions: The cheap and the not so cheap.
The cheap solution is to solder wires directly to the IC and then connect the wires to a breadboard. The downside of that is primarily physical: The IC won't stay securely attached to the breadboard, the wires may develop intermittent faults. I don't think that the wires themselves will be a bigger problem to the signals going through them compared to the breadboard itself. Then there's also the problem of soldering appropriate wires to the IC and then connecting them to the breadboard. Another option which I've seen is to solder the wires to a pin header and then insert the pins into a breadboard, but this is also very fragile.
The other option is to use a SOP to DIP adapter. They have a small PCB on which you solder the device. The PCB will also have holes spaced like a DIP component to which you solder pins and then just insert the adapter into a breadboard. Here's an example of such adapter.
Answer: The wires-to-a-header method can be made more robust if you solder the header pins into a piece of copper-ringed-perfboard, for example making a module that is perhaps 800 mils wide with the small IC perched (glue is possible but probably not needed) in the middle.
Making a toner-transfer PCB to breakout the pins is another viable "need it today" option.  If the pin count is low, you can avoid drilling any holes by breaking it out to a single row and "surface mounting" a 100-mil header on the edge of the board.
Obviously the pre-made breakout PCBs or carriers are the best solution - if you have one on hand, or can get one in a reasonable amount of time without paying several times the value of the item in shipping fees.

how to use SOP ICs on Breadboard?


File deletion bypassing trash on OS Mavericks

Question: Deleting files in finder is now permanently deleting the files (i.e. basically doing  rm filename) and is not moving the items to trash. How do I fix this behavior? I like being able to undo my deletes.
Answer: Check what the permissions and owner for ~/.Trash/ are:
$ ls -led ~/.Trash
drwxr-xr-x  39 lauri  staff  1326 Apr 17 02:49 /Users/lauri/.Trash

If the owner is root, run sudo chown $USER ~/.Trash. If the permissions are for example dr-xr-xr-x instead of drwxr-xr-x, run chmod 755 ~/.Trash.
Comment: The permissions were all right, so this didn't actually solve my question. It turns out that in the end, a good old "windows solution" reboot was all that was needed. Nevertheless, thank you for the heads up. I didn't think to check the permissions.


android new task and activity stack issue

Question:
I have my launcher activity (A) set to "singleTop".
Now there is something in notification bar. User clicks on it. So I start activity in receiver with
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
So A's onNewIntent is invoked and I start activity C based on extras in intent.
User go back to A(back key)  and to other activity D. And then home key.
Now when I long press home. And relaunch my application and step 3 repeats. and user goes to C. where actually user should have gone to D
Answer: Somehow , when you press Long home and restart the activity , the extras parameters are lost.Only the data parameter is preserved.
Answer: Add android:launchMode="singleInstance" in Activity D (in the menifest file). And then check the app behaviour.


How much would you need to remember to store bitcoins in your head?

Question: Suppose I had a gigantic sum of bitcoins and wanted to store them in my brain's memory instead of any physical form. How much data would I need to be able to remember? I understand I'd have to transfer it all to one address - would I need to remember both its private and public key, or can the public one be calculated based on the private key?
Answer: This is called a brain wallet. You need to remember only the generator for the private key, which can be anything you choose. You just have to remember something (anything) that is complicated enough that other people could not guess it, even if given trillions of guesses.
This is actually surprisingly complicated. If you write the passphrase down, it's not really a brain wallet anymore. If you don't, and you forget any bit of it and cannot precisely remember it, your funds are lost. If you make it simple enough to ensure you can remember it, the risk that someone else will find it is high. Lastly, the tools you use to convert the passphrase to a Bitcoin address can be flawed or sabotaged.
Comment: I'd like to stress the importance of the risk that someone else can find it. As opposed to normal password-guesses, where you are rate-limited or shut out after some failed tries, here you are exposing yourself to an unlimited attack by the whole world, forever. If you didn't generate the passphrase by a computer or dice, it's probably not random enough (even though it is long, and looks non-random).
Comment: What if I decide to just remember a random key? Wouldn't that theoretically be as secure as storing the key on the HDD?
Comment: @d33tah So long as the key had at least 70 bits of equivalent entropy, you should be okay. But it's pretty hard to remember 13 random characters. Give it a try -- `yXi2ano5SXJ8D`.
Comment: I think that if you store a million dollars there, you have quite a good incentive.


Enabling PHP pdo_odbc extension on a Mac OSX

Question: I am trying to get the pdo_odbc extension for PHP enabled on my Mac which is running PHP 5.3  Here is what i did to try to get it to work:

I installed UnixODBC with brew
$ brew install unixodbc

Downloaded the source for PHP 5.3.8. In the terminal I navigated to the pdo_odbc folder. Then did the following.
$ phpize
$ ./configure --with-pdo-odbc=unixODBC
$ make

There was an error.
/Users/todd/Downloads/php-5.3.8/ext/pdo_odbc/pdo_odbc.c:43: error: 'ZEND_MOD_END' undeclared here (not in a function)
/Users/todd/Downloads/php-5.3.8/ext/pdo_odbc/pdo_odbc.c: In function 'zm_startup_pdo_odbc':
/Users/todd/Downloads/php-5.3.8/ext/pdo_odbc/pdo_odbc.c:135: warning: cast to pointer from integer of different size

Based on some blogs I replaced ZEND_MOD_END with {NULL,NUll, NULL} and ran make again. This time it complied.
Then I ran "sudo make install"
and that installed the extension in the right place. I modifed php.ini to enable it. And it shows up in phpInfo()

So far so good.  But when I start running simple tests I get errors about every other try
php(20048,0x7fff796f1960) malloc: *** mmap(size=2977160837258543104) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
terminate called throwing an exceptionAbort trap: 6

This was thrown, when i tried to execute this code:
<?php

   $dsn = 'odbc:Driver={FileMaker ODBC};Server=localhost;Database=CalDAV;';
   $pdo = new PDO($dsn, "odbc", "odbc");

   $sql = "SELECT * From Users Where id = 2";
   $r = $pdo->query($sql);
   print_r($r->fetch(PDO::FETCH_ASSOC));

   $sql = "SELECT * From Users Where id = ?";
   $stmt = $pdo->prepare($sql);
   $stmt->execute(array(2));
   print_r($stmt->fetch(PDO::FETCH_ASSOC));

?>

this line causes the exception.
$stmt->execute(array(2));

Does anyone have any experience getting pdo_odbc to work on the Mac.  I would really like to get this extension working. Suggestions ?
Comment: not sure if there is a brew equivalent but I just ran "sudo port install php5-odbc" and it installed easily.
Comment: Looks like there's a bug in the PDO_ODBC extension: https://bugs.php.net/bug.php?id=52942

My guess is a bad `malloc()` call to allocate memory that's already been allocated.
Comment: Kevin, I am pretty sure that php5-odbc is just old non PDO ODBC extension.  I am trying to get the PDO-ODBC extension going on the mac.
Answer: Perhaps worth noting that Apple chose iODBC (over UnixODBC) for Mac OS X and bundled it in starting with Jaguar (10.2).  You should get the latest update from the iodbc.org site, because Apple has never kept up with the official project patches.  I recommend installing both the Frameworks and such, and applying the separate patches to the Apple-bundled headers and dylibs.
Past malloc issues associated with UnixODBC have been resolved by shifting to iODBC.  I do not know that this will be the case for you, but it seems a small investment to try.
(ObDisclaimer: I work for OpenLink Software; we maintain and support the iODBC project. I personally gain nothing from your pursuing this option.)
Answer: Have you checked your php.ini (or equivalent) to see if your 'memory_limit' setting is high enough?
Error 12 appears to be related to memory exhaustion, but I'm not sure if it's related to a run-away loop in the tests you are running, or simply too many very large allocations. Check what a phpinfo() dump says about your current 'memory_limit' setting and then up it to see if that corrects the error.
See also: http://www.php.net/manual/en/ini.core.php#ini.memory-limit
Answer: I personally prefer MacPorts, although I think most folks prefer Fink. The easiest way to get more feature-complete versions of standard unix packages for OSX is to use either MacPorts or Fink.
Locate the php.ini file on your Mac (/etc/php.ini)
Replace all instances of /var/mysql/mysql.sock to /tmp/mysql.sock
Save the file and restart Apache.

Answer: I'm using VirtualBox with a Ubuntu Server Distro on my MacBook.
Since I've noticed that one OSX update can ruin your configuration.

VirtualBox (20GB VDI)
Ubuntu Linux-Server (with an host-only adapter)
LAMP (Apache, MySQL & PHP)
Samba (To manage my web-projects)

Works great for development and you don't need to worry about dependencies being ported properly!


Coaxial passive amplification

Question: I have a passive UHF antenna, with a 1:2 splitter close to it, short run for tv1 is about 5 meters, long run for tv2 is about 15. I have 4 digital channels on my grid, and tv2 does not receive enough signal on one of them. Question is can it be improved with an inline amp(passive)?
Comment: place your amp before the splitter.
Comment: The first question to ask is does it work direct wired without the splitter?  If the answer is yes then an amplifier before the splitter should help.  A splitter normally drops signal by 7.5db
Comment: Did you ever get this working? If so, please give a check-mark to the answer that helped you the most, or write up your own answer explaining what you did to get it fixed and give yourself a check mark. That will help others with this kind of problem know that this has a resolution and is a good place to look for their answer
Answer: Will an inline amp improve your signal? Yes a amplifier will boost the signal that is available. With that said there has to be enough signal to amplify. In the past I have found many DIY connections that were not made with the correct type of coax or connectors. Each connection has some power loss measured in DB mis matching the impedance of an antenna to the type of coax can reduce the signal to a level that can not be recovered. A matching network may be needed from the antenna to the coax to reduce the losses. The amplifier should be prior to the splitter and the splitter should be the type for the frequency range (UHF) you are targeting. The last item to watch is splices each splice has some power loss. 3db of loss cuts the power in 1/2. Remember that a splitter will reduce the signal. More expensive splitters usually have a lower loss (check the splitter it may be a 60/40 or 70/30 not 50/50 as you would expect these are very inexpensive to build and you may be able to flip the splitter and both tv's might work). There are amplifiers that have multiple outlets and will run on a 9V battery for over a year but these devices are harder to find now since the demand has decreased over the last 10 years. One last note getting the highest gain amp is not always the best deal a 15db amp with a low noise may do better than a 30+ db amp with a higher noise level.

Coaxial passive amplification


How to get the closest "visible" object from my "player"?

Question: I'm using Unity 3d and i have to accomplish the following task: get the closest "visible" object to my player in forward direction.
It is a sort of radar.
I don't know where to start.
Any advice is welcomed.
Thanks
Comment: what will you do when the object returned is always the ground you're standing on ? this problem needs restrictions to work well enough, like objects only smaller than the player... filter/layers (only living entities?..)
Answer: You can use the dot product trick to get a list of instances actually visible by the player (thus lying inside the camera frustum), and check for the distance from your camera object to get the closest one.
First, you can test a certain number of instances so that their distance is low enough for them to be considered "near" the camera (or the player). Instead of testing every object, which can be overkill for your game performance, you can consider a volume around the camera (a sphere, for example) and test only object inside this space partition. The number of instances to work with is now lower, and more tests can be performed.
In mathematics, the dot product of two vectors gives as result a scalar number, which represents the projection of vector v1 upon vector v2. The length of projection depends on the cosine function of the angle between the two vectors. We can see it the other way: given two vectors, if their dot product is a value k, then their mutual orientation in the space (or plane, or any n-dimensional system) is such that the angle between them has a cosine value cos(θ) = k. So, the angle is θ = arccos(k).
If your camera has a FOV angle ranges from -β to β, assuming angle 0° is in front of the camera and that the frustum is just a cone, if θ is either lower than -β or greater than β, your object is out of sight.

This said, you consider two vectors, A and B. Vector A is the relative position of an object, and B is the "front" vector of the camera. If the dot product of A and B is lower than or equal to the cosine of β, such object is potentially visible to the player. Otherwise, its position is away from the sight cone.
The final step is to search the list of remaining objects to find the one whose distance is lowest among all. Here's your closest, visible object to focus your attention on!
To sum up: consider a list of candidate object, so that every object is closer than a certain distance from camera. Help comes from space volume instead of checking every single instance. Then, compute dot product of those instances, to get a list of only instances lying in front of the camera. Finally, look for the closest one.
Answer: Assuming that you're making a 3D game, you can use Physics.OverlapSphere to get a an array of Colliders that are within a certain range of the player. To check if the object is "visible" to the player, you could simply call Physics.Raycast in the direction of the object(s) returned by OverlapSphere and check if nothing that isn't the object you're checking for blocks the raycast. Here's a code example:
public class RadarController : MonoBehaviour
{
    public int RadarRadius;
    public string DetectableObjectTag;

    public void CheckForVisibleObjects()
    {
        Collider[] objectColliders = Physics.SphereOverlap(this.transform.position, this.RadarRadius);
        for(int index = 0; index <= objectColliders.Length - 1; index++)
        {
            GameObject colliderObject = objectColliders[index].gameObject;
            if(colliderObject.tag == this.DetectableObjectTag)
            {
                RaycastHit hit;
                bool hitOccurred = Physics.Raycast(this.transform.position, colliderObject.transform.position.normalized, out hit);
                if(hitOccurred && hit.gameObject.tag == this.DetectableObjectTag)
                {
                    // Do whatever you need to do with the resulting information
                    // here if the condition succeeds.
                }
            }
        }
    }

    public void Update()
    {
        this.CheckForVisibleObjects();
    }
}

Disclaimer: I am not able to check and see if this code works properly, or if it performs at an ideal rate. If there is an issue, just mention it and I'll see what I can do.
Comment: @omouse Added a code example.
Comment: code example would be amazing to have; or a link to a code example in a tutorial?
Comment: that maybe fine for an indie game with low standards. but rigorously, visibility is not solved by one raycast. Also about efficiency, there surely is a better algo using directly the physics partitioning structures.
Answer: Typically, to get the closest object from the player, you do something like this (generic pseudo-code):
var listOfObjects = getAllObjects()
var closestObject = null
var distanceSquareOfClosest = infinite

for otherObject in listOfObjets:
  if otherObject != this:
    var distanceSquareOfThisObject = (otherObject.position - this.position).lengthSquare()
    if distanceSquareOfThisObject < distanceSquareOfClosest:
      distanceSquareOfClosest = distanceSquareOfThisObject
      closestObject = otherObject

I don't know how it's done in Unity, but I would assume there is something that lets you get all the objects, and there would be a way for you to check if they're visible or not. You'd modify the if otherObject != this to something like if otherObject != this && otherObject.isVisible.
To find all the game objects, you can take a look here.
Comment: I don't think the OP means visible as in not invisible but visible to the player. E.g. not hiding behind a wall. Probably hoping for some sort of ray casting implementation.
Comment: @RichardTingle Yeah; a simple google search revealed tons of resource to do that though..
Answer: As mentioned in the comments you probably want a Raycast.
An example of how to implement a forward-facing raycast in a Fixed Update cycle is spelled out exactly in the Unity Scripting API Documentation here. This will return true if the raycast strikes a collider in front of whatever object you attach the script to.
From the documentation above:
using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    void FixedUpdate()
    {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);

        if (Physics.Raycast(transform.position, fwd, 10))
            print("There is something in front of the object!");
    }
}

After that, to return the object you strike with your raycast, you use a Raycast.Hit to get the transform of whatever you're hitting. We do this because the transform has a variable of gameObject. SO:
        using UnityEngine;

public class ExampleClass : MonoBehaviour
{

public GameObject storedGameObject; //create a bucket to store the game object in when we find it

    void FixedUpdate()
    {
    RaycastHit hit; //define the raycasthit

        Vector3 fwd = transform.TransformDirection(Vector3.forward); //define the forward Vector3

        if (Physics.Raycast(transform.position, fwd, hit)) //use the current transform position to start, shoot outward "fwd", and return a RaycastHit
            {
            storedGameObject = hit.transform.gameObject; //set the bucket to the value of the target's transform.gameobject
        }
    }
}

Full disclosure: I'm at work and can't test this code, but it should be approximately what you need.


How to create a new BibDesk export template

Question: Where do I find the current "Minimal BibTex" template for exporting a library? I want to (a) create a new version that includes URLs and DOIs, (b) name it "MinPlus BibTex", and (c) save it to wherever it needs to be saved so that it appears on the Mac, BibDesk File/Export... menu.
Comment: @jon This is a question specifically about BibDesk and its ability to export into various formats.
Comment: @AlanMunn -- Ah, yes. I think my eyes subconsciously skip over words referring to things I never use.... I'd still avoid spaces in filenames, however.
Answer: You can't edit the Minimal BiBTeX template directly, but you can make your own template and then choose that when you export or copy items.
To do this, create a plain text file with minimal-URL.txt with the following content:
<$publications>
@<$pubType/>{<$citeKey/>,
<$requiredFields>
    <$name/> = <$bibTeXString/>,
</$requiredFields>
<$optionalFields.@nonEmpty>
    <$name/> = <$bibTeXString/>,
</$optionalFields.@nonEmpty>
<$fields.url?>
    URL = {<$fields.url/>},
</$fields.url?>
<$fields.doi?>
    DOI = {<$fields.doi/>}
</$fields.doi?>
}
</$publications>

Save this in ~/Library/Application Support/BibDesk/Templates (to get to this folder when you save you can type Command-G at the file save dialogue box and it will allow you to enter the entire path.)
Now in your BibDesk preferences, go to the Templates panel, and click on the + to add a new template file.  Choose .txt as the file type.  You should see the following:

Double click to choose the file, and then navigate to ~/Library/Application Support/BibDesk/Templates and choose your minimal-URL.txt file.
Now your template is available.  If you just want to use it occasionally, for individual items or groups of items,  you can always access it via the Edit menu -> Copy As -> Template -> minimal-URL.
If you want to use that as your default action for copying bib items, then you can set that in the Citation panel of the Preferences: choose Template and then pick your minimal-URL template.
It will also be available in the File -> Export menu as a possible output format:
Comment: Alan, This is a very complete answer to my question. Many thanks!


Asking user to select file in Python Script tool using parameter?

Question: In a custom toolbox you can make a parameter and ask user for input where he can type something and used as arcpy.GetParameterAsText(0) in the script in the toolbox. This is good if you want to use address of a folder but what if needs to select a csv file?
One way would be:

User types the folder path and the script will add + file.csv

Example code:
import arcpy
import pandas as pd
file = arcpy.GetParameterAsText(0)
df = pd.read_csv(file)

In this case the user will be asked to select a path when using the toolbox.
To do this he just copies the path of the folder the csv is. Then he must add manually to the path the: ex. \pop2012.csv.
Answer: The answer is to select file in parameters in the properties of the toolbox. Then it enables you to select a file.


Google Earth API fails to load placemark with custom icon

Question: At one point I was able to load custom placemark icons into the Google Earth JavaScript API; however, sometime in the last few months, something has changed.
If I add a marker in the google domain it seems to work... but if I use another icon from the internet it fails.
I followed the instructions from the documentation and I still get nothing.
<code>// Define a custom icon.
var icon = earth.createIcon('');
icon.setHref('http://www.jcsda.noaa.gov/images/arrowDown.jpg');
var style = earth.createStyle(''); //create a new style
style.getIconStyle().setIcon(icon); //apply the icon to the style
placemark.setStyleSelector(style); //apply the style to the placemark
</code>
For the sake of clarity I have made a fiddle illustrating the problem.
Any thoughts on where I am going wrong?
UPDATE
Last night when I made the fiddle the icon failed to load... this morning when I checked it has spontaneously started working for some icons.
Interestingly, it's still not working in my application.
I am using an Apache web server and I have some security in place (using .htaccess file) requiring a username and password... this has been active for months, but could it now be prevent Google Earth from accessing the icons even though I am logged in?
Answer: Is your page https is could be a browser mixed content http/https issue


R: build custom installer for windows

Question: I am building a custom R installer, following the instruction in "R Installation and Administration" I've installed the latest Rtools212.exe and Inno Setup.
After successfully running tar --no-same-owner -xf R-2.12.1.tar.gz
I've then run make all recommended from R_HOME\src\gnuwin32 and it runs ok until I get the following message:
building package 'base'

cannot create /tmp/R860644: directory nonexistent

mv: cannot stat '/tmp/R860644': No such file or directory

make[3]: ***[mkR] Error 1

make[2]: ***[all] Error 2

make[1]: ***[R] Error 1

make: ***[all] Error 2

After checking the instruction, I thought it was about the environment variable TMPDIR not being set properly. So I tried two options:

create c:\tmp folder
add TMPDIR to the windows environment variable and set the value as c:\DDDD (an existing folder). I then checked the value of TMPDIR in R console by typing Sys.getenv("TMPDIR"), and the change was confirmed.

To my surprise, however, I still got the same error. It looks like: 1. the make commander can not find the default /tmp, which is actually existing; 2. the change of TMPDIR has not been recognized in this occasion, the make commander still try to find the default directory, rather than the changed one.
I also searched online for this problem, and from what I can find, I have done what people had suggested, so now I am stuck.
Can anyone give me some suggestions? Any help appreciated.
Regards,
Shu
Answer: well, I just found a solution for my question,
I typed in "set TMPDIR=c:/DDDD" in the command window, and this time no error has been presented.
But I still wonder why my initial tryouts did not work.

R: build custom installer for windows


Is this method safe or recommended for moving a /home directory?

Question: I have my linux install on a small disk. I want to put the home directory on a different hard-drive. I was thinking of using this and then this. Would this work? Is there a better way? Should I just move the entire thing to the new harddrive? The first article describes how to put your home directory into a new partition. The second one describes how to move a partition to a new hard drive.
Comment: Please explain what you want to do in a bit more detail. I don't want to have to read two long external pages to understand what you're asking
Comment: I'd recommend [fsarchiver](http://www.fsarchiver.org/Main_Page) for copying the data across, rather than rsync and dd or whatever is recommended in those links.
Answer: Here's the real easy way.

Log out and log in as root.  Not su or anything else.  You don't need a GUI to do this, either.  Just make sure all your normal /home/whoever users are logged out.

Create a new partition, and mount it on (e.g.) /mnt/tmp.

cp -a /home/ /mnt/tmp/.  You can actually leave the stuff that's in home there for a while until you are happy all this went smoothly.  When you mount the new partition there, the stuff in /home will become inaccessible until you umount it, but it will be safe and sound until you delete it (see REMEMBER below).

Remount the partition. I.e., umount /mnt/tmp, mount /dev/mypartition /home.

You can now try logging back in as a regular user; everything should work.  As mentioned in one of your links, you may want to remove gvfs related stuff from your new $HOME first.  If all this works, add a line to /etc/fstab to make it automatic at boot; first you need the UUID of the newpartition (blkid /dev/mypartition).
UUID=theuuidyougotfromblkid /home  ext4 defaults 0 2

This presumes that the partition is ext4 and there isn't another 2 in the last column.  If so make it 3 or whatever.
REMEMBER
The stuff you copied from /home is still there "underneath" the mount point, meaning you can't access as it as long as the new partition is mounted there.  You can leave it as long as you want (note: it WILL NOT parallel changes made in the new home, it will remain as it was), but beware it will still be taking up space on that original partition, so at some point you will want to (logged out, as root) umount /home and delete the stuff underneath.
Comment: You don't need to `unmount` /home to get to the stuff underneath. You can bind mount `/` to another location and access it there. eg - `mount -o bind / /mnt/root; rm -rf /mnt/root/home`.


MySQL Monitoring - Cloud Instances - No System Access

Question: Are there any MySQL monitoring suites/tools built to use on systems such as Amazon RDS where you do not have system access?  Looking for something beyond custom tools (nagios, zenoss, ganglia, hyperic) and more like MySQL Enterprise Monitor, MONyog, and DBTuna.
Comment: What kind of monitoring are you trying to get?  Very little is beyond nagios, xenoss, etc... plugin capabilities.  If you could give ups a hint about the type of statistics you're trying to collect, that would be very helpful.
Answer: You could try MONyog MySQL Monitor and Advisor from http://www.webyog.com.
Comment: No. That requires system access as I stated in my question.
Answer: You could try appfirst with a mysql plugin.  It's easy to do.  You don't need nagios, but you get to use any of the nagios plugins.  Lots of rich tools for mysql.
Comment: Looks to require a collector.
Answer: Two that I can recommend most are Percona's PMM and Shattered Silicon's SSM (fork of PMM v1). Both support monitoring of remote database systems, and SSM has a few features that make it slightly better at monitoring RDS instances because it supports query data extraction from RDS via slow log.
PMM only supports query data extraction from performance_schema, which unfortunately doesn't cover information about queries that run as prepared statements, which can be quite a crippling drawback depending on how the application implements it's query execution.
Disclosure: I work with the maintainers of the SSM fork of PMM1


What is a good collection of alcohol to keep around for someone who doesn't drink?

Question: I don't drink alcohol at all, but I'd like to keep some kind of selection around to offer to guests who do. I'm not looking to fully stock a bar, but at least a few different options that can accommodate a variety of tastes and also not require prompt consumption.
Comment: We've had questions pop up about specific types of alcohol for people who don't drink, for instance - good starter beers. Whereas this question just seems to have way too many variables and possible answers. In short, you'd probably need to know your likely guests, and what their tastes were.
Comment: I voted to close. This is far too broad and also subjective. There are a huge number of possible answers, and some of them may be good for some people, not for others.
Comment: Fair enough. I can understand the vagueness although I also don't know how to make my question more specific.
Answer: The kinds of alcohol you'd want can differ depending on the occasion or type of hosting you'll be doing. If a friend helps you move a couch, for example, it would not be unexpected to offer them a beer afterward as a thank you.
Wine can be offered but is probably more acceptable in the evenings or with a specific meal. One bottle of white and one of red should be sufficient. Chardonnay is probably a safe bet for white wine and a Merlot or Cabernet Sauvignon for red, but your guests' individual tastes can obviously differ.
Liquor like vodka or whiskey can be used to make a variety of cocktails (again, during or after dinner are commonplace) and for guests who want to party these can easily be used for shots as well. Many people have preferences towards specific brands, but if you buy a $20-30 bottle you won't have many guests turn it down just over the name.
Comment: As far as I'm aware the liquor can be stored indefinitely. Most beers will last a minimum of 6 months if stored in a cool place, and much longer if kept refrigerated (obviously opened beers would need to be discarded if not consumed). Wine can also be kept for months/ years, but once opened probably should be finished or disposed of within a week.
Comment: It's probably worth saying something about how long each of these drinks can be kept.


Is the facial hair of Tolkien's dwarves unshaveable?

Question: By which I mean that they could not be shaven, due to some sort of magic on them. Or are they simply omnipresent, but not magically protected?
Comment: All Men have hair yet it's not uncuttable... flawed logic
Comment: IS there any reason to believe it would be unshaveable?
Comment: Because all dwarves have them...it seems to be part of their nature, almost.
Answer: Per The History of Middle Earth Vol. 11

The Naugrim were ever, as they still remain, short and squat in
stature; they were deep-breasted, strong in the arm, and stout in the
leg, and their beards were long. Indeed this strangeness they have
that no Man nor Elf has ever seen a beardless Dwarf - unless he were
shaven in mockery, and would then be more like to die of shame than of
many other hurts that to us would seem more deadly.

It's not clear how this fact is known, but that a dwarf can be shaved (if under duress) is evident.

Their beards can also be burned by dragonfire.

"The few of us [dwarves] that were well outside sat and wept in hiding, and
cursed Smaug; and there we were unexpectedly joined by my father and
my grandfather with singed beards. They looked very grim but they said
very little.
The Hobbit, or There and Back Again
Comment: Well, maybe they still would have had part of their beard, like the mustache, goatee, or sideburns. But I see that this answer is probably quite correct, so I thank you for it.
Answer: It doesn't say shaving particularly, in the sense of removing all traces, but at least at the time of Bilbo's adventure Dwarven facial hair was cuttable.
From The Hobbit, chapter 8, "Flies and Spiders":

Somehow or other Fili was got on to the branch, and then he did his
best to help the hobbit, although he was feeling very sick and ill
from spider-poison, and from hanging most of the night and the next
day wound round and round with only his nose to breathe through. It
took him ages to get the beastly stuff out of his eyes and eyebrows,
and as for his beard, he had to cut most of it off.


A Lattice that is not a Complete Lattice

Question: I was studying about Complete Lattices from the text book J.P. Tremblay.
The definition of a complete lattice is that each of its non empty subsets should have a least upper bound and greatest lower bound. By this definition every finite lattice should be complete. But what about Infinite Lattices? Is there an Infinite Lattice which is not Complete. So far I couldn't come up with an example or prove that there are no such case.
Answer: The set $\mathbb Q$ of all rational numbers, with the usual linear order, is an infinite distributive lattice which is not complete. For example, $\mathbb Q$ itself has neither a least upper bound nor a greatest lower bound in $\mathbb Q$; neither does the bounded nonempty set $\{x\in\mathbb Q:x^2\lt2\}.$
Answer: Consider the lattice of finite subsets of $\Bbb N$. Since the union and intersection of two finite subsets is again finite, this is indeed a lattice. But the set $A=\{\{0\},\{0,1\},\{0,1,2\},\dots\}$ has no upper bound in the lattice. Of course $\Bbb N$ is an upper bound of $A$ in $\mathcal P(\Bbb N)$, the powerset of $\Bbb N$.
Comment: This set is also a very important example in set theory that pertains to some theorems about infinite sets either having an infinite totally unordered subset or containing an infinite chain (linear order).
Answer: The partially ordered set $(\mathbb R, \leqslant)$ of real numbers is a lattice, but not a complete lattice. Note that the subset $S = (0,\infty)$ does not have a supremum in $\mathbb R$.


salesforce api calls for connected app

Question: I've a connected app in salesforce and I'm using bulk api for downloading xml files but for updates I'm using getupdate rest call, salesforce documentation says that there's a limit of api calls per day. My question is does that limit apply to my connected app or each client? My connected app uses oauth2 for client authentication and api calls
Answer: Each Salesforce org has a limit on the total number of API calls per day for that org. It is not specific to your connected app or client.
The number of allowed API calls varies depending on the Salesforce edition and the counts of each type of license, but you can approximate it as 15,000 + (15,000 * the number of Salesforce Platform licenses). The total is capped at 1,000,000 for Enterprise and Professional editions, but uncapped for Unlimited and Performance edition. You can find the full nuance of the calculation at API Request Limits and Allocations.
Note that the limit is not for a calendar day. Like many Salesforce org-wide limits, it's a rolling 24 hour period. It does not reset at midnight. This means that if you exceed the limit, recovery may not be instantaneous depending on the distribution of limits consumption across the 24 hour window.
You should also note that there are a number of limits specific to the Bulk API, including a cap of 10,000 batches per rolling 24 hour period.
Comment: Good answer, but to avoid confusion, I edited your answer a bit. An *instance* is an entire pod (e.g. na1) and is composed of many organizations. Users work in an *organization* (often abbreviated to just org).
Comment: To be honest, I've often used the words interchangeably. Appreciate the clarification!
Comment: Yes, for a typical customer, instance and org would be synonymous, but it's important when you hear official communication from salesforce.com, since an org-wide problem is much less severe than an instance-wide problem. Salesforce.com tries pretty hard to keep those terms discrete for that reason.

salesforce api calls for connected app


Difference between variables in jQuery

Question: Can anyone tell me what is the difference between variables $variable and $.Variable in jQuery? For examle:
$x='3';
$.y(parseInt($(this).val())

Answer: The first one ($x) is a variable (that in this case is assigned a value of the string 3. The second one is a function call to the function y(), which is assumably a jquery extension function. In your example this function gets an argument that contains the some integer coming from the value of something that is referenced by $(this).
Note that $x could just as easily have been var x = '3'. The assignment in your example is actually a bit weird because the $ prefix usually indicates that the variable is holding some jQuery selector result.
Answer: $var is just a convention to tell that the var holds a jQuery wrapped DOM selection, e.g.:
var $form = $('#yourForm');

$.function on the other hand means that you are calling some "static" function of jQuery library, e.g. $.each(), without performing any DOM selection.
Answer: In JavaScript, you can have variable names contain the character $.  If you create a new HTML document with a script tag, you can just do:
var $test = 10;
console.log($test);

And it will log 10 to the console.
jQuery uses the $ variable as a shorthand to itself, and any jQuery functions/extensions are available off of that object.  The following might make it more clear:
// Assume you have already loaded jQuery
$ == jQuery; // true!
$.test = 10; // Assign a random property to the "jQuery Object"
console.log($.test); // print out "10"

Now, in the case of your example, $.y(), somebody has extended jQuery by adding a method named y, which can be accessed as $.y().  In many cases, as a way of keeping track of object types, if you have a variable that is a reference to a jQuery object, you prepend the variable name with dollarSign:
var header = document.getElementById("header"); //without jQuery
var $header = $("#header"); // with jQuery

The above is not a rule, and is just a convention that many people follow to keep their code clear.

Difference between variables in jQuery


What's the difference between road bike disc brake wheels /cyclosross wheels?

Question: What's the difference between road bike disc wheels /cyclocross disc wheels?
Answer: Cyclocoss will tend to be wider to accommodate the wider tires used in cyclocross.  And tend to be sturdier.  Are you buying the wheels for a road or cyclocross?
Comment: I added sturdier but not always the case.  Depends on the quality of the wheel.
Answer: The real difference to look for is the axle width and connection method. A "standard" road bike has a 130mm/10mm rear axle and 100mm/9mm front axle that
both use a standard quick release.
If a set of wheels matches those dimensions and has disk brake compatible hubs, then any difference between road/cyclocross disk will only be in the various
details of the build and rim width/depth.
However, many of the newer road/cyclocross bikes with disk brakes are using different axle widths and connection methods. Often the rear hub axle is 135mm/10mm, and many CX bikes are now coming with through axle mounts. These
kinds of specs were previously only found on mountain bikes.
Many hub manufacturers ( especially on the pricy end ) now provide exchangable
caps to allow you to switch between connection styles. But before you spring
for those fancy carbon wheels, you should verify that the axle widths/styles
match your current bike.
Answer: Road wheels will be more likely to be more aero with aero bladed spokes, and possibly 4 less of them. Deeper section rims are more common on road wheels than cx wheels too out on the start lines.


I-Adjective nominalization

Question: For 面白い, why is the noun form commonly 面白 instead of 面白さ?  Isn't さ supposed to be the way to take i-adjectives and make them nouns?
Comment: Hmm, are you sure about the "_commonly_" thing? How about cite a source for that? Also 面白さ, not *面白いさ.
Comment: I'm not entirely sure, but I am basing it off Jisho marking 面白 common and 面白さ is not marked common.  Is it true that 面白 is the noun form of 面白い because it is labeled as a noun or verb acting prenominally?
Comment: Just because two words are nouns based on the same concept doesn't mean they share the same exact meaning. There's a difference between "Interestingness" as a concept related to the word interesting and "interestingness" indicating "the degree to which something is interesting." Maybe the disctinction is subtle in English (and ignore the fact that we don't say "interestingness" very much), but Japanese divides them more clearly.
Comment: @Leebo That's a very interesting example! Funny you should mention "interesting" because someone just asked me if there's any difference between "interest" and "interesting points/things/quality" as nouns (or rather NPs) in "a story full interest/interesting things" and "that adds interest/interesting things to the story"
Answer: There is no usage, as far as I know in the modern Standard Japanese, of 面白【おもしろ】 itself as a noun.
面白さ is a true noun deriving from the adjective 面白い. It means "fun" or "interestingness".
面白 is just a form 面白い minus conjugable い. It is called "adjective stem" (形容詞語幹) in the Japanese grammar, that does not work as noun; actually not able to become a word, but only makes a non-final affix of a word that carries the meaning, mostly you see in a way like "permadeath" or "instakill". (In this case often written in hiragana or katakana to mark a vernacular vibe.)

おもしろ動画 "lolvideo" → funny(-est) video
おもしろ装置 "loldevice" → funny (and often useless) machine

Of course there are also more conventional words made with it, including 面白おかしい "fun-o-hilarious; sidesplitting", 面白がる "find amused", and aforementioned 面白さ.

I-Adjective nominalization


Accidently renamed system/xbin to system/xbi

Question: So i accidently renamed xbin in /system to xbi. I can't get root anymore because su is stored there and it won't work in xbi. I get a 'Connection to ui timed out' every time i try do './su'. If it helps i'm on a Samsung S4 Mini or a GT-I9195T.
Answer: Someone will probably want an answer so here are the steps I performed:
I managed to get twrp running on it with odin. (I got odin from odindownload.com, gone to twrp.me/Devices), found my device, grabbed the .tar and started odin.
I then clicked the 'AP' button and selected the .tar file. I connected the phone and pressed start. Booted into recovery by holding the
Vol up + Home +  Power key buttons.
Finally I hopped in a terminal and finally cd system;mv xbi xbin.


iMovie 10 Project Lost

Question: I created a new iMovie 10 project and there was no option to associate it with an event when I created it, which there is when I create one now. I have not updated iMovie since I created the project. After working on the project for a day, I quit iMovie and opened it back up. The project was missing. How do I get it back?
Answer: Make sure that it shows nothing over here:  under today's date or the title that you have given it. If there is indeed nothing, then try File > Update Projects and Events. If it still doesn't show up, then your only hope is that you have a time machine and that you backed it up.
Just asking, what version of iMovie are you using?
Comment: I have already done this and nothing works. I know that the files of the project that was lost were saved in the wrong place in the iMovie library and were unable to load after iMovie was quit. I am using iMovie 10.0.2
Answer: I had the same problem and this fixed it. File ==> Update Projects and Events

iMovie 10 Project Lost


DNS resolution on OpenVPN server

Question: I am running virtual server with Windows Server 2012 R2 for RDS purpose mostly. OpenVPN server is installed on this host as well. Firewall is configured in a way that RDP connections could only be made from VPN network. But now to access RDP users have to type server's VPN ip (like 10.8.0.1), instead of using friendly DNS name (I have a domain registered). What would be the simplest way to bind a hostname to this ip? Changing host's file on each client machine is obviously not an option. Thanks in advance.
Answer: How you handle DNS on VPN setups can get pretty complicated.
The question Wesley linked is generally good for redirected gateway setup where all traffic is being sent over the VPN, or minimally you accept that all DNS resolution will be handled by the server published by the VPN connection.
Another really simple option you could use is simply create a DNS record in your public zone that has the private IP address you want to use.  Almost no DNS servers do any kind of filtering on the record values.  So you can publish the private records.
If your clients are all Windows another option you could do is setup a rule in the name resolution policy table.  This is a Windows 7+ feature, that permits you to set different DNS servers per domain.  Using a command like below dould make any request for the *.example.org records be redirected to the defined name servers.  But all other domains would continue to be resolved by whatever the client had configured.
<code># add rule via Powershell
$Rule = @{
    'Namespace'   = '.example.org'
    'Comment'     = 'example domain'
    'NameServers' = ('10.8.0.1', '10.8.0.2')
}
Add-DnsClientNrptRule @Rule
</code>
Comment: Ehhh, I've always shied away from private IP addresses in public DNS, which is why I didn't suggest it. People way smarter than me seem to have established that it's not really bad: http://serverfault.com/questions/4458/private-ip-address-in-public-dns So I defer to you and other Smarter-Than-Wesley people. :D
Comment: I just included it for completeness, I didn't really mean to suggest it was good idea.  You probably should use alternatives if you can, but it is one of those things I have seen people do when the alternatives were just too complex or couldn't be made to work given the combination of clients that must be supported.

DNS resolution on OpenVPN server


control per app internet (non-rooted) while using actual VPN?

Question: I am trying all sorts of (non-root) security software that allows me to block internet for apps. so far every one needs some kind of fake VPN to gain access to traffic, I guess so no root is needed. I can't have this since I use an actual VPN which gets turned off if I use any of these security apps. is there no way to block internet for apps while using my VPN?
Comment: Does this answer your question? [How to use a firewall AND a VPN?](https://android.stackexchange.com/questions/182341/how-to-use-a-firewall-and-a-vpn)
Comment: Hardly possible without root. You can run VPN inside VPN but I don't think any Android app would be offering that out of box. You need to configure that manually and that won't be possible without root. It needs messing with routing tables etc.
Answer: This is possible since Android 8 (when Block connections without VPN feature was added), also you will have to use VPN app which supports Per-App VPN (which is supported since Android 5.0?) e.g. OpenVPN for Android from F-Droid or Google Play.
Assuming you use OpenVPN for Android:

System settings → VPN → tap button with gear icon on the right side of OpenVPN for Android → enable both Always-on VPN and Block connections without VPN.
OpenVPN for Android → tap button with pencil icon on desired profile → swipe to ALLOWED APPS tab → select apps you want to exclude from using VPN → return to main screen → re/connect to VPN using this profile

This was tested on MIUI device, but I think should be pretty much the same on majority of devices (except those whose manufacturers removed or hid Android's default functionality from ROM (like Huawei from EMUI)). Also per app internet control access is built-in by default in MIUI.
Answer: I don't think it's possible as per this answer: In Android 6, how to deny an app permission to access the network?. To summarise the network permission is classified as 'normal' so it is automatically granted and can't be removed. However you can try to revoke the INTERNET permission using adb.
adb shell pm revoke com.name.app android.permission.INTERNET
I'm 99% sure it won't work, but can't test right now, on mobile. Unfortunately that means a VPN firewall or root + iptables firewall are your only options.
Comment: Only permissions with `dangerous` [protection level](https://developer.android.com/guide/topics/permissions/overview#normal-dangerous) can be revoked.
Answer: You can try NetGuard, the non-root firewall for Android smartphones. It can help you in restricting the net usage per app.
Comment: this is also vpn based, I just tried it.
Comment: NetGuard also uses a local VPN. (https://i.stack.imgur.com/KacDS.jpg)
Comment: But this is the only option.
Comment: how is it an option if it has the exact same problem? plus is definitely not the only one that works that way. or am I missing something?


Whatsapp Online Status Inquiry

Question: This question might have already been answered so sorry in advance.
My question is: If I am using Whatsapp, it would obviously show me as online but what if I have the application open but my screen timed-out/turned-off, will it still show me as online? Or will it show as last seen (time before screen time-out)? Will it only show as online when I'm in the app actively using it, or will it show as online until I close it (go to home screen or close the app)?
Thank you.
Comment: I think it's when you're actively using the app, or when you briefly quite the app (using the home button)
Answer: WhatsApp will only show you as online when you're in the app. In fact - even if you reply to a message from in-notification, you still won't be shown as online.

Whatsapp Online Status Inquiry


How to place script in footer?

Question: I have a script I want to place in my site's footer. It's not actually a file, just a single line of code (the script source is located at an external URL).
So my question is, should I enqueue the script or just copy and paste it into the footer?
Comment: In this case it may not matter. Personally, I would enqueue it in the event that the script depends on another library, you can then set the dependencies for the script without worrying if it will load in the wrong order.
Answer: See wp_enqueue_script() and the $in_footer parameter it supports. Here's an example of how you'd do this from the functions.php file for your theme. Note the last argument is true, which inserts the script into the footer.
<?php
add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_script( 'my-script', '/path/to/script.js', [], null, true );
} );

Comment: So, to use the `wp_enqueue_script` function I would need to either first register the script using `wp_register_script()` or link to it in the `wp_enqueue_script` function? In that case the answer given by @Jack Johansson might be the better option.
Comment: You don't need to register it first, that's just a formality for the sake of plugins. If it's just a file for your site, you can literally copy/paste the example snippet and change the first two parameters; i.e., change `my-script` to a handle that matches your script, and the second parameter should be a URL or absolute file path leading to the script.
Comment: To clarify, if you 'register' a script, it allows that script to be enqueued and dequeued later; e.g., by a theme or by plugins. So it's better, yes. However, if this is for a site-specific script there's really no need. Just enqueue.
Comment: The `$src` variable in the `wp_enqueue_script` function is optional so if you don't link to the script in the `wp_enqueue_script` function you would need to have previously registered the script. As mentioned in my question, the script is just a single line of code so I'm thinking the answer given by @Jack Johansson might make more sense in this context.
Answer: If you want to output a single line of javascript, you might not need to put it in a js file and go through enqueuing it and stuff. Simply output it by using the wp_footer() action hook:
add_action('wp_footer','print_my_script');
function print_my_script(){
    echo '';
}

However, this is good just for small scripts. For larger script and js files, use wp_enqueue_script() instead.

How to place script in footer?


Why hedge when one can simply reduce the position size?

Question: Often, I would read about traders/investors hedging their position in case things do not go their way. I find this strange. If one were unsure, then wouldn't it be better to simply reduce the position size instead of taking on an opposite position?
Comment: Don't forget that you often hear about hedging in the futures market, and the agent hedging may be a company trying to guarantee itself a certain price (high *or* low) for a commodity in the future. They may not *have* a position in the commodity at the moment.
Answer: Sometimes you may want to be in a position long term but are worried about short term volatility and the price going against you in that period. You don't want to sell and re-buy back later as this may trigger a capital gain. Plus you don't know the extent of the price drop or when it will start recovering, so an alternative is to hedge against any potential short term weakness in prices but still reap the long term gains without triggering any intermittent capital gains.
Comment: The only thing I might add is that you might hedge because it is costly to get out of and back into the investment.  Sometimes that's because of fees, other times taxes as you mention.
Comment: Yes if you have a full-fee broker it can become quite expensive.
Answer: A lot of hedges use a lot less capital than the core position uses, while still retaining the ability to reduce or eliminate losses. The core position is still being able to gain nearly as much as it could unhedged. If one simply reduced the core position size, then they really wouldn't be able to gain as much on their capital.
Think of hedges are insurance premiums, you pay a small amount to gain big in the case of an adverse scenario.
Answer: Say I have a portfolio of 50 well chosen stocks. Stocks that are 'guaranteed' to beat the market. But I think the entire market is in trouble. I place a short position on the S&P index. I'm right, the market drops, my 50, not as much, but they did go down. I was better off doing it this way than to sell my positions.
I also would have a tough time telling my shareholders why I just went to all cash. But this way I still add value.


is left brachiochephalic vein and left pulmonary artery is same?

Question: I am reading about ligamentum arteriosum which connects the left pulmonary artery and descending aorta. But I am seeing that if any figure shows left brachiochephalic vein it does not show left pulmonary artery (and vice versa). Are they both the same?
Comment: Veins are not the same as arteries. A non-capillary blood vessel is either one or the other, not both.
Comment: Please include references for those figures or add those figures to your question. Plus, as MattDMo said, veins cannot be simultaneously labelled as arteries. I guess the figures are intended to show veins and arteries separately (and not in the same picture). In any case that cannot be verified unless you show us the figures.
Comment: They are structurally and functionally distinct. The left brachiocephalic vein joins the superior vena cava which returns deoxygenated blood to the right side of the heart. Deoxygenated blood is pumped OUT of the right heart and travels to the left lung via the left pulmonary artery.

The two don't always appear in the same image because many anatomical images remove structures that aren't the area of focus for clarity. However a quick google image search reveals several pictures that illustrate the distinct positions of both.
Answer: No, they are not the same.  The left brachiocephalic vein receives de-oxygenated blood from the left subclavian vein (draining the left arm) and the left internal jugular vein (draining the brain and parts of the face).  The brachiocephalic vein then joins with the superior vena cava which flows into the right atrium.
The left pulmonary artery carries the deoxygenated blood that has just passed through the right atrium and ventricle, through the pulmonary trunk to the left lung for oxygenation.
In the foetal circulation, the ductus arteroisus (before it closes into the ligamentum arteriosum) allows blood to bypass the lungs, which are not oxygenated in the uterus!
Please see this diagram (which shows the foetal circulation including PDA for you).  The left brachiocephalic vein is circled in yellow, whilst the left pulmonary artery is circled in green.

Image from public domain edition of Gray's.


Is There a Sparse Representation for Noise?

Question: Is there sparse representation for stationary noise and nonstationary noise?
How can I learn dictionary for each noise class?
(my mean of noise is noises with which speech signals are often contaminated such as white gaussian noise, car noise, babble noise, impulsive noise....)
Comment: In particular, white Gaussian noise is not sparse.
Comment: my mean of noise is noises with which speech signals are often contaminated such as white gaussian noise, car noise, babble noise, impulsive noise....
Comment: @beni that is crucial information and **must** become part of your question by editing it!
Comment: what type of noise you mean? do you assume something like 60Hz power line noise?
Comment: @beni, Could you please mark my answer?
Answer: The question of the existence of a sparse basis of noise is closely related to the question of the effective dimensionality of the noise subspace.
First, it is important to realise that noise is a process, and not a signal. You can think of a full characterisation of any kind of noise by means of a function $p: S \to \mathbb{R}^+_0 $ that maps a signal $s$ to a probability $p(s)$ of finding that signal as the realisation of the noise process. This description is fully general and more useful than it may appear at first sight.
The ensemble of all possible noise signals $s$ together with their respective probability $p(s)$ is a very unhandy object to deal with mathematically. Finding a more practical description that still contains relevant information is possible.
Consider the orthogonal projector $P_s$ onto a signal $s$. This projector is a non-negative symmetric operator on the signal space.
If we have a fairly and sufficiently densely sampled set of possible signals $\{s_i:i\in\mathbb{N}\}$ with their respective probabilities $p(s_i)$, then the weighted convex sum of the projectors onto these sample signals $$E:=\frac{\sum_i p(s_i) P_{s_i}}{\sum_i p(s_i)\cdot\mathrm{trace}\left(\sum_i P_{s_i}\right)}$$ is also a non-negative symmetric operator on the signal space. (Note that this ad-hoc construction becomes somewhat more involved if done rigorously, but then would require a bit of measure theory on the signal space.)
The operator $E$ has some interesting properties. It's relatively straight forward to see, that its trace is bounded by $0$ from below and $1$ from above. The upper bound is attained exactly if $p(s)\equiv \mathrm{const}$. The trace of $E$ has an interesting interpretation as the effective relative dimensionality of the noise subspace $S_N$:
$$\mathrm{trace}\left(E\right)\approx\frac{\mathrm{dim\,S_N}}{\mathrm{dim}\,S}$$
What is more, an orthogonal basis of the noise subspace can be derived from $E$ in form of its Eigenspectrum. If you sort the Eigenvectors of $E$ in order of their descending Eigenvalue and take the first $\mathrm{dim}\,S_N\approx\mathrm{ceil}\left(\mathrm{dim}\,S \cdot \mathrm{trace}(E) \right)$ vectors, you should have a basis that spans your noise subspace reasonably well.
So, how do we find $E$ in practice? Let us assume you have a noise generator that produces a single output signal. It is reasonable to assume that for such a noise generator, each received output signal is approximately equally likely. Therefore, generating an ensemble of noise signals with this generator samples the noise subspace evenly and with constant probability. The rest of the signal space has a probability of 0 and is not sampled. However, we do need a set of signals that sample the entire signal space to apply the definition of $E$ from above. Let us call the samples of the signal space that we do not take $\{ \bar{s}_j \}$ and the constant probability of those $s_i$ that we do take just $p$. Then the definition becomes
$$E=\frac{\sum_i p\,P_{s_i}+\sum_j 0\,P_{\bar{s}_j}}{\left(\sum_i p + \sum_j 0\right)\cdot\mathrm{trace}\left(\sum_i P_{s_i}+\sum_j P_{\bar{s}_j}\right)}$$
which simplifies to
$$E=\frac{\sum_i P_{s_i}}{\mathrm{trace}\left(\sum_i P_{s_i} \right) + \mathrm{trace}\left(\sum_j P_{\bar{s}_j} \right)}$$
We are stuck here, because don't know $\mathrm{trace}\left(\sum_j P_{\bar{s}_j} \right)$ and estimating it would require the dimensionality of the noise subspace, which we are trying to find. However, we can look at the operator
$$E'=\frac{\sum_i P_{s_i}}{\mathrm{trace}\left(\sum_i P_{s_i} \right)}$$ which is has the same Eigenstructure as $E$ up to scaling. Because of the assumptions we have made, the Eigenvalues of $E'$ associated with the Eigenvectors outside of the noise subspace are all 0. Because the trace of $E'$ equals $1$, the Eigenvalues associated with the Eigenvectors inside of the noise subspace approximately equal $\frac{1}{\mathrm{dim}\,S_N}$. So doing an Eigendecomposition of $E'$ will result in an orthogonal basis of the noise subspace and give a natural separation between the noise subspace and its orthogonal complement.
Numerically constructing $E'$ requires a bit of memory and summing of the projectors onto the generated signals. The following Eigendecomposition can be computationally challenging, but should be doable for reasonably sized signal vectors.
Comment: Hello, would you happen to know of a formalization of [this idea](https://i.stack.imgur.com/sJwzC.png)? I'm unsure it's mine to begin with, I saw something at least very similar on a site I can no longer find. Sines are very specific constructions and I've never been fully content with how their physical applicability is justified.
Comment: @OverLordGoldDragon the method you describe in the link is the series expansion approach to first order ODEs. So you're solving $f''=-f$ with initial conditions.
Comment: Right, I just meant having a physical interpretation associated with said expansion, at every step of derivation. I've not explored every angle of it though, from both math and physical side.
Comment: Y'know, non-newbies could also use vote support. I would if was here earlier, even if I was clueless of your writing, just to offset bs. Granted, as a mathy-mcmather you might find my content crap. (If so, I'm curious to know, without taking offense.)
Answer: Let's think about it in a different way - Generate Noise from a Dictionary.
Let's create a Dictionary $ A \in \mathbb{R}^{m \times n} $ where each of its rows is normalized (Has Euclidean Norm of $ 1 $) and generated by a Gaussian Random Vector.
Now, let's create $ N $ random vector $ {\left\{ {r}_{i} \right\}}_{i = 1}^{N} $ by:
$$ {r}_{i} = A {g}_{i} $$
Where $ {g}_{i} $ are random vectors $ {g}_{i} \in \mathbb{R}^{n} $ with only $ k \ll n $ non zero elements (Let's say they are pre defined and deterministic otherwise we'll have to deal with multiplication of random variables).
Now, the output vectors are valid Gaussian Random Variables and given enough of them and some properties of $ A $ you'd be able to build a Dictionary which they are sparse with relation to it.
Yet it means the dictionary is random by itself and next time when you get new set of random data it won't be able to represent it correctly (It doesn't generalize).
While the above is not rigorous (It means to develop some intuition, not analytic analysis) it tells you why when we deal with finite amount of data it can be done but for noise as in general it won't work.


Expresso Store - Show product price with TAX and Shipping costs

Question: I wonder if there is a way to do this without using any modules. I can't seem to figure this out. I just want the regular_price + tax + shipping.
Answer: Shipping is calculated on a per-order basis, so you can't show what the shipping cost on an individual item is (once products are added to the cart, you can calculate the shipping for the whole order).
To display prices inclusive of tax, open Settings > Taxes and click on your tax rate, then click "included in price". You can then enter product prices inclusive of tax in the control panel, and these will also be displayed on your website's front end.


Local truncation error of given implicit 1-step scheme

Question: I'm given the 1-step implicit scheme $$y_{n+1} = y_n + \frac{h}{6}[4f(t_n, y_n) + 2f(t_{n+1}, y_{n+1}) + hf'(t_n, y_n)],$$
where $y'(t) = f(t, y)$, and I'm seeking the scheme's local truncation error. I've been able to use a Taylor series to get that
$$e_n(h) = hy'(t_{n+1}) - \frac{h^2}{2}y''(t_{n+1}) + O(h^3) - \frac{2h}{3}f(t_n, y(t_n)) + \frac{h}{3}f(t_{n+1}, y(t_{n+1})) + \frac{h^2}{6}f'(t_n, y(t_n))$$,
but I'm having trouble understanding what the $f(t_n, y(t_n))$ terms even represent. If $f(t, y) = y'(t),$ how can the expression $f(t_n, y(t_n))$ make much sense?
Answer: You insert the exact solution on both sides so that $y'(t_{n+1})=f(t_{n+1},y(t_{n+1}))$ and $y''(t_{n})=f'(t_{n},y(t_{n}))$. Thus
\begin{align}
O(h^{p+1})=g(h)&=-y(t+h)+y(t)+\frac{h}{6}[4y'(t)+2y'(t+h)+hy''(t)]\\
&=\left[y(t)+\frac{2h}3y'(t)\right]-\left[y(t+h)-\frac{h}3y'(t+h)\right]+\frac{h^2}6y''(t)
\end{align}
Then compute derivatives until the last is generally not zero for $h=0$.
\begin{align}
g'(h)&=\left[\frac{2}3y'(t)\right]-\left[\frac23y'(t+h)-\frac{h}3y''(t+h)\right]+\frac{h}3y''(t)\\
g''(h)&=-\left[\frac13y''(t+h)-\frac{h}3y'''(t+h)\right]+\frac{1}3y''(t)\\
g'''(h)&=-\left[-\frac{h}3y^{(4)}(t+h)\right]\\
\end{align}
Thus $g(h)=O(h^4)$ and $p=3$ as order of the method.


Interesting Question on Ants

Question: A horizontal stick is one metre long. Fifty ants are placed in random positions on the stick, pointing in random directions. The ants crawl head first along the stick, moving at one metre per minute. If an ant reaches the end of the stick, it falls off. If two ants meet, they both change direction. How long do you have to wait to be sure that all the ants have fallen off the stick?
Comment: @TimSeguine your quibble could be answered by 10 seconds' thought about what either of the options you put forward would imply for the question.
Comment: Dunno if it counts as duplicate, but the same question exists on [puzzling.stackexchange](http://puzzling.stackexchange.com/questions/1784/maximum-time-for-ants-to-fall-off-stick)
Comment: Is it a one dimensional stick, or a topological cylinder? "Random directions" seems like confusing wording if it is one-dimensional.
Comment: @jwg If you think so. I only posted that because I came to the "right" conclusion after reading the question, then the accepted answer in their entirety 3 times. If you consider that clarity, then we have most likely have different definitions of clarity. It seems to me that this was the source of some of the initial confusion people were having with the accepted answer.
Answer: One minute at most. Imagine that ants "go through" each other. Whether the ants bounce off each other or walk past each other without changing direction has the same end effect: we have two ants approaching each other, then they meet, then they diverge from each other with that same speed of $1\text{m}/\text{min}$. So just assume that they do not bounce, but instead they keep walking the same direction, so it will take at most $1$ minute before they all fall off the edge.
Judging from the comments, it seems people disagree with the above argument, or have difficulty following/understanding it, so I offer a different interpretation. Say each ant carries a piece of paper with a written number on it. (You may call that piece of paper a baton, think of a relay race.)  At the beginning all ants are numbered (from $1$ to $n$), and each ant holds a piece of paper with its own number on it. When two ants meet, they exchange their pieces of paper, and then bounce from each other. Note that while ants change direction when they bounce, the pieces of paper do not change direction. Thus these pieces of paper go with constant speed and direction $1 \text{m}/\text{min}$, so all the pieces of paper would fall off the stick in less than a minute. But, if there are no pieces of paper left on the stick, there are no ants either.
Just a comment on the first approach (when you could think ants pass by each other, instead of bouncing). Imagine that all ants look alike so much that you can't really tell them from each other. So two ants meet and bounce. But how could you tell, if you can't tell which ant is which? Perhaps you thought they bounced, but in reality each continued in its path without changing direction, passing by each other, and you do not know which is the case since these ants look so identical that you can't tell what exactly happened. Say ant A was going to the right towards ant B, and ant B was going to the left towards ant A. They meet and at the next moment you see them diverging from each other but you can't tell which ant is ant A and which ant is ant B. Perhaps the ant that now goes to the left is ant A, perhaps it is ant B. If it is ant A then they must have bounced, but if it is ant B then they must have passed next to each other without changing direction. But, it doesn't matter, since the "end result" is the same: immediately after they meet, we have two ants diverging from each other whether they bounced or they passed by each other. So assume now you have a different problem, in which ants do not bounce, but instead pass by each other (so each ant just keeps going, without changing direction). Clearly in this version of the problem all ants clear the stick in at most one minute. But, if you can't tell ants from each other, then you can't tell the two problems from each other either, so the answer to your original problem is at most a minute.
Since you put forward the name of Einstein in one of the comments, I feel entitled to involve physics in my answer. If the ants are particles, then they bounce from each other. But, if the ants are waves, then they "go through" each other, or pass next to each other. So, does light consist of particles, or waves, was Newton right (with his corpuscular theory of light), or was Huygens right (with his wave theory of light), and how is it that both theories are right?
Comment: @AndreiRykhalski If we assume that the ants take negligible amount of time to turn and move in the other direction, it will take at most one minute. This is because there will be *some* ant out of those 49 ants that is at the forefront. This will crash into the one ant that is coming from the other direction, and then all of them will be moving in one direction after which they all fall down.
Comment: If you have 1 ant looking forward in the beginning of the stick and 49 looking backward somewhere in the end, then the first ant will stay on the stick for at least 100 minutes.
Comment: @AndreiRykhalski all ants are moving...you can not keep rest of 48 ants fixed.
Comment: @adijo: one will always be going in the other direction (until it falls off). Collisions are irrelevant: you might as well assume that they pass right through each other - the effect is the same.
Comment: so this stupid sounding solution is - we don't know if the ant took the turn or not ? i mean you set the rules, lets force them to take turns - i don't really understand anything here.
Answer: This should help arrive at the answer.  Let's first consider the shortest amount of time you'd have to wait. Assuming the ants were evenly distributed, and each ant faced the nearest edge, you'd have to wait 30 seconds.  This is because the farthest an ant would have to walk is 50cm.
Now this should help see what the longest path an ant would need to walk is.  Assume an ant starts at Edge A and faces Edge B.  If this ant walks all the way to Edge B (which takes one minute), you can be sure that there are no ants behind this ant.  Now let's say this ant bumps into something right at Edge B and has to turn around.  We now know that the ant will fall off Edge A after one minute.  So this ant walked two minutes and we know the ruler is empty.  The problem here is that when this ant gets to Edge B there's nothing to bump into because all of the ants have already fallen off at Edge B.  We know this because if any were going the opposite direction, this ant would have bumped into one beforehand.
If all of the ants are facing the same direction (a 2 in 2^50 chance), you'll see one ant walk the whole length of the ruler.  You know this takes one minute.  The question then becomes, what's the maximum distance an ant can walk if not all ants face the same direction.  In this scenario, if an ant starts at Edge A facing Edge B, this ant can only get as far as the middle of the ruler without bumping into another ant.  If the ant gets past the middle, that means all of the ants in front of it didn't turn around.  But we assumed at least one ant was going the opposite direction.  So assume the ant does get to the middle and bumps into another ant.  Because this ant started at Edge A, and made it to the middle, we know there are no ants behind it, so it has an unimpeded path back to Edge A.  This total journey takes half a meter twice, or one minute.
Finally, what about the ant it bumped into at the middle of the ruler?  There's no difference between that ant and the ant that started from Edge A.  That ant walks for one minute.
Comment: 30 sec is not really the shortest time, I think?! Consider an arrangement of ants just 1 mm apart, all facing the nearest end. It will take the last one much less than 30 sec to fall off. Otherwise, your analysis is correct.
Comment: @ysap I was assuming the ants were evenly distributed to try to make a point about how the ants move.  I should have mentioned what you say in your comment though.
Comment: i'm not smart enough to understand the first answer - but yours is bullcrap to be honest, who said they are evenly distributed ? an ant facing the edge will fall in 0 seconds ?

Interesting Question on Ants