How to get more than 100mA from a USB port

Question: I heard that the current limit for a USB port is 100mA. However, I also heard that some devices can get up to 1.8A from a port. How do you get past the 100mA limit?
Comment: @Kortuk - A computer *should* not do it.  Some probably can, though.
Comment: @Kortuk, Technically speaking, "*Systems that obtain operating power externally, either AC or DC, must supply at least five unit loads to each port.*" - Section 7.2.1, USB 2.0 Specifications. Note, "at least" 100mA x 5 = 500mA. There is no upper limit.
Comment: I added a long post trying to explain what goes into each group. If you need 1.8A the short answer is that a computer will not do it.
Comment: @reemrevnivek, this was discussed down below, every computer I have used will **not** deliver 1.8A. I have used a couple that would even shutoff the port if there was too capacitive of a load and you violate the input rush current.
Comment: Related: [What is the ideal way to handle data pins D+ and D- on a USB power adapter to be compatible with fast charging on devices?](https://electronics.stackexchange.com/questions/123172/what-is-the-ideal-way-to-handle-data-pins-d-and-d-on-a-usb-power-adapter-to-be)
Comment: Putting this in the comments because it's not a guarantee, but I've designed a few "dumb" devices that hook into USB power ports, and I've only rarely seen ports that won't supply 500mA to an unenumerated device. As per the standard, this shouldn't happen, but real-world implementations and standards are often not quite the same.
Comment: Related: https://electronics.stackexchange.com/q/532928/142
Answer: I think I can attempt to clear this up.
USB-100mA
USB by default will deliver 100mA of current (it is 500mW power because we know it is 5v, right?) to a device. This is the most you can pull from a USB hub that does not have its own power supply, as they never offer more than 4 ports and keep a greedy 100mA for themselves.
Some computers that are cheaply built will use an bus-powered hub(all of your USB connections share the same 500mA source and the electronics acting as a hub use that source also) internally to increase the number of USB ports and to save a small amount of money. This can be frustrating, but you can always be guaranteed 100mA.
USB-500mA
When a device is connected it goes through enumeration. This is not a trivial process and can be seen in detail on Jan Axelson's site. As you can see this is a long process, but a chip from a company like FTDI will handle the hard part for you. They discuss enumeration in one of their app notes.
Near the end of enumeration you setup device parameters. Very specifically the configuration descriptors. If you look on this website they will show you all of the different pieces that can be set. It shows that you can get right up to 500mA of power requested. This is what you can expect from a computer. You can get FTDI chips to handle this for you, which is nice, as you only have to treat the chip as a serial line.
USB-1.8A
This is where things get interesting. You can purchase a charger that does outlet to USB at the store. This is a USB charging port. your computer does not supply these, and your device must be able to recognize it.
First, to get the best information about USB, you sometimes have to bite the bullet and go to the people whom write the spec. I found great information about the USB charging spec here. The link on the page that is useful is the link for battery charging. This link seems to be tied to revision number, so I have linked both in case the revision is updated people can still access the information.
Now, what does this mean. if you open up the batt_charging PDF and jump to chapter three they go into charging ports. Specifically 3.2.1 explains how this is gone about. Now they keep it very technical, but the key point is simple. A USB charging port places a termination resistance between D+ and D-. I would like to copy out the chapter that explains it, but it is a secured PDF and I cannot copy it out without retyping it.
Summing it up
You may pull 100mA from a computer port. You may pull 500mA after enumeration and setting the correct configuration. Computers vary their enforcement, as many others have said, but most I have had experience with will try to stop you. If you violate this, you may also damage a poorly design computer (Davr is spot on there, this is poor practice). You may pull up to 1.8A from a charging port, but this is a rare case where the port tells you something. You have to check for this and when it is verified you may do it. This is the same as buying a wall adapter, but you get to use a USB cable and USB port.
Why use the charging spec? So that when my phone dies, my charger charges it quickly, but if I do not have my charger I may pull power from a computer, while using the same hardware port to communicate files and information with my computer.
Please let me know if there is anything I can add.
Comment: @TonyStewart, it is my understanding that by spec until enumeration is complete you can only be guaranteed 100mA. The fact that it is common for a device to allow 500mA does not mean I would want to design my devices to immediately trust 500mA is available, I would instead design to wait for enumeration to complete. I am open to learning that I can do otherwise though. Many of my links that I have given list that as a requirement of the standard.
Comment: The document you linked to specifies a resistance of "maximum 200 Ohms", which is basically a description of a short.
Comment: @GustavoLitovsky This has been discussed in detail, this probably varies by computer maker but I have seen multiple that enforce such a rule and do you really want to explain to a customer your product is not working because of their computer?
Comment: Although in theory one should not pull more than 100mA unless you've enumerated, this limitation is rarely enforced in practice. I've seen only one laptop that did this. 99% of devices I've seen provide 500mA at least and likely more, no enumeration needed.
Comment: For Apple products, things are a bit more complicated: http://www.ladyada.net/make/mintyboost/icharge.html
Comment: @Kortuk: You have to take into account that adding chips that enumerate is a large expense in some cases, so for many it didn't make sense for a long time.
Comment: @clabacchio I clarified. I mean bus powered. they literally have an unpowered USB hub inside them to give you your ports, this means that none of your USB ports can deliver more then 100mA as they are really all ports on an unpowered USB hub.
Comment: @AndreKR your Apple products charging link is broken.  Here's a working one: http://learn.adafruit.com/minty-boost/icharging
Comment: related-  https://superuser.com/questions/690074/what-is-the-power-output-of-a-usb-port
Comment: The "termination resistance" of a dumb charger is really just a short.
Comment: @andreKR, this is not always true, but yes, often people hard short it.
Comment: @AndreKR, I believe it has to be a measurable resistance if you want an IPhone to use it, that is how iPhones originally had their own separate chargers.
Comment: @andreKR, yeah, apple does make your life easy...
Comment: Kortek, I challenge your statement " USB by default will deliver 100mA "  If the USB HUB if designed for 500mA per hub it  has no default limit per port it will deliver all as needed and available. So each port can consume the max but all the ports shared by that hub must not exceed the same max. limit defined in the above screenshot.  So **there is no default 100mA limit** unless by hardware design, that hub is a legacy 10yr old design when peripherals all consumed < 100mA.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/3418/discussion-between-kortuk-and-tony-stewart)
Comment: @GustavoLitovsky Yes, I realize the associated cost, it just seemed worthwhile to explain what the spec demands. You could edit in a section explaining what the computer side must do and why it can be skipped, sounds like fun to me, but for now I think this explains what your device must do to get power pretty thoroughly.
Comment: *Some computers that are cheaply built will use an bus powered hub internally* is there a typo or just I can't understand? Shouldn't it be "USB" instead of "bus"?
Comment: This answer contains misleading information, and better be corrected (due to high traffic). Any normal USB **HOST** port must be capable to supply 500 mA of current, See Section 7.2.1 of USB 2.0 specs, or  Section 11.4.1 of USB 3.1 specs. So any non-USB gadgets can use 500 mA (or 900 mA on USB 3.0) without much hesitation. The 100 mA non-enumerated limit must be obeyed by **USB DEVICES**, so the limit is not applicable outside USB framework. The rare exceptions form 500 mA limit are small **battery-powered USB hosts**, who can limit themself to 100 mA per port.
Comment: "It shows that you can get right up to 500mA of power requested. This is what you can expect from a computer."  And if the computer (hypothetically) refuses?
Answer: You can negotiate for 500mA with one of the FTDI USB chips, here's a forum post that talks about it. If you use some other chip, you still need something that can speak the USB protocol and tell the PC that it wants 500mA. Please don't violate the USB spec, your device might work fine for some people, but then it wont work for others, and you risk causing damage to poorly designed PC's.
Answer: The theoretical current limit on a bus-powered USB port (the kind in your computer) is 100mA, negotiable up to 500mA. In practice, you probably won't  get as much from the ports on your computer. If you use a self-powered USB hub however, you should be able to get 500mA from every port on the HUB. So if your HUB has 4 ports, you can get 4 * 500mA = 2A.
Beware: make sure your HUB comes with a decent power adapter. Some hubs come with a 1A adapter, because manufacturers think it's an unrealistic scenario for users to draw 500mA from EVERY port.
Check out this wiki article:
http://en.wikipedia.org/wiki/USB_hub#Power
Comment: Small correction: limit is 500 mA for USB 2.0 (load unit is 100 mA and maximum is 5 load units). On USB 3.0, load unit is 150 mA and maximum is 6 load units, so that's 900 mA. Computers usually do not support 1.8 A. You could get that much by placing a resistor between data wires (to signalize that device is only using power and not transmitting data) and use USB cell phone charger or similar device dumb power source.
Comment: @Kevin - yes, you have to negotiate the 500mA even when you re using a self powered hub.  How else would the end device know how much it is allowed to draw from the port.  It cannot tell until the enumeration process is complete whether the socket that it is connected to can supply the requested current.
Comment: Do self-powered hubs require you to negotiate to higher current levels?   I'll have to go home and take mine apart to see what the circuit is...
Comment: @Ian - Yeah, I understand that the spec would work that way, but my (now 1-year-old) investigation of two self-powered hubs I have indicates that the PSU circuit (or rather, the switch in the barrel jack) makes the power available to the device regardless of whether the device negotiates or not.  Seems like a cost-effective and reasonable deviation from spec to me.
Answer: As far as I know, no one actually bothers to include current limiting in the USB host, so devices are really on the honor system not to draw more than they are allowed.  I've seen a lot of devices that claim one power but actually draw a lot more, and I've never seen them shut down or anything.  On a desktop, at least, I assume the ports are capable of more than 500 mA.
So if you're making a product that will be used by others, read the USB spec and learn how to negotiate with the computer to draw up to 500 mA.  If you're just doing a one-off and you know for some reason that the port is capable of 1.8A, then just draw it.

In reality, many electronics manufacturers still do not strictly adhere to the USB 2.0 specification by not implementing these current limits in the USB ports that they provide. Some (read: most) USB ports allow 100mA regardless of enumeration and continued activity; some ports even offer 500mA irrespective of the required power negotiation. - Maxim

My Samsung phone requests a MaxPower of 2 mA, but then draws ~250 mA no matter what it's plugged into.
Comment: I have actually found the opposite. Almost every computer I have used will disable the USB port if too much power is drawn. They don't necessarily do it based off how much you have requested, but they do have a max current that once hit will notify the OS and shut off the port. Windows will even pop up a message notifying the user that this has happened. In my experience it takes a reboot of the computer for the port to be re-enabled.
Comment: On my laptop, a dead (shorted) USB device caused all devices on the bus to shut down, but removing the malfunctioning device seem to fixed the problem. Linux dmesg mentioned overcurrent shut down.
Comment: @Kellenjb - I've seen this behavior as well, but usually only on laptops where power consumption is a concern.  Further, while the computer monitors the power consumption, it often doesn't actually shut the port power off, it just uses the USB control channel to tell the device to power down.  They often have polyfuses in line to prevent huge power consumption, but those are often 1A or greater.  So one can still pull a significant amount of current from the port, though windows might complain about it.
Comment: On my Macbook pro, I can draw 500mA without even asking, without ill effects.  Same with the powered hubs coming from the Dell desktops at my school (and my powered hub for my laptop).  Neither computer issues a warning message of any kind.
Comment: We have some 6 year old Dell desktops used in a student lab. We have had students all of the time pull too much current and have the USB port shut down until a restart occurs.
Comment: I've seen the message in Windows, too, but only from a current spike, not continuous draw.  The USB spec has restrictions on both.
Comment: I have seen this from both. current spikes and overcurrent. Current spike detection seems to vary by computer pretty heavily, but overdrawing current has made most every computer i have used turn it off.
Comment: My behavior may be because I was using name brand computers.
Comment: what hardware were you using when you did that?
Answer: I  that it differs from motherboard supplier how good the power supply for the USB is. Some cheap B-brand manufacturers may just link the +5V of the power supply down to the USB port.  Some better ones may actually include the whole package for overcurrent protection etc.
I got a sweex 4-port (el-cheapo, costed me like 10 euro's) USB hub so I don't have to get under the desk all the time for an USB connection. This sweex port clearly doesn't have any protection. I have smoked shorted MOSFET with it once, which its rated current was 3A.
Anyway, my point I want to make is that no matter what your project is, you probably will not want to get over 500mA of current drawn from a USB port. As a one off, maybe.. if you want to risk blowing it up on your own behalf. Certainly not for anyone else.
I'd like to think that the power provided by USB is mainly to make it possible to have communication with the real device. You might feature an isolation circuit to give better protection for USB hosts. I'd certainly not take USB as a universal 5V power supply, because adapters can do that much better (and in the long-term probably cheaper).
Answer: Adding to the excellent advice from Kortuk:

You should really use a powered hub or a "USB charger" for debugging since you do not want to fry your computer by accidentally shorting something.
All computers I had pleasure with do not bother with limiting current draw below 500mA. (with or without enumeration)
Comment: jpc I agree, but your age is showing....USB was just avail when Win98 was out, and everyone was self powered, just needed hub power to do negotiations with drivers.
Comment: I guess you are right: my interest in USB started around the time Igor Češko released his software based AVR USB implementation in 2003. At that time USB 2.0 was already available.
Answer: The most voted up answer contains misleading information, and better be corrected (due to high traffic).
Any normal USB HOST port must be capable to supply 500 mA of current, See Section 7.2.1 of USB 2.0 specs, or Section 11.4.1 of USB 3.1 specs.
The USB 2.0 specs says, page 171:

"Systems that obtain operating power externally, either AC or DC, must
  supply at least five unit loads to each port. Such ports are called
  high-power ports."

Note the language, "at least". So any non-USB gadgets can use 500 mA (or 900 mA on USB 3.0) without much hesitation.
The 100 mA non-enumerated limit must be obeyed by USB DEVICES, so the limit is not applicable outside USB framework. The rare exceptions form 500 mA limit are small battery-powered USB hosts, who can limit themselves to 100 mA per port.
Comment: An externally powered port should supply 500mA (think PC, or a hub with a wall wart).  The quote from p.171 deals with such externally powered ports.  A bus-powered port has to supply only 100mA.  Enforcement of these rule varies from one design to another, as has been already mentioned in the answers.
Comment: @NickAlexeev, this is true, in USB2 framework the concept of power balancing did not exist. So  the 100 mA per port from a bus-powered hub is true. The 100mA limit is very inconvenient from user standpoint. That's why bus-powered hubs do not exist in marketplace. To be useful, these hubs supply fake information that they are "self-powered". So all these discussions about 100 mA limit  are inconsequential.
Comment: There should be some hesitation when drawing more than 100mA. You can't consume more current until *after* enumeration is complete and the host has sent a SET_CONFIGURATION setup packet identifying the configuration index (and associated bMaxPower) it has chosen.
Answer: You can't draw 1.8A from the PC's USB directly. However if you need the high current and connected to the PC at the same time, consider investing in a hub that have it's own supply from the mains.
Comment: Yes you can. USB specifications don't impose an upper limit on how much a port can supply. See Section 7.2.1 of USB Specifications. It is up to designer of USB **HOST** system to decide. A USB device, however, has no rights to take more than 500/900mA; this device will be non-compliant, technically illegal.
Answer: The above 100 mA current upto 500 mA can be negotiated by the device driver.
However some devices may not get configured properly at boot time if your BIOS has an option titled: "Enable legacy storage" under USB settings. If this setting is off - you may find yourself re-plugging the device after booting up, in case if it does not work properly.
Only with this setting on, if present, the BIOS will provide a current greater than some minimum value, I think 100 mA.
A brute force method may be to get a two male USB to one female USB cable for extra power. CAUTION: may have electrical / power draw safety issues.
Answer: Mr 404notFound,
Sorry to say you cannot increase the limit in a USB device. It is limited by design.
Some early hubs were limited to 100mA, now all hubs are 500mA and with USB3 ports 900mA is available.
Good news is you can find out what your ports are rated for. If older than 5 yrs some may be 100mA, but newer than that, I doubt it.
If running Windows...
go to >Device Manager > hardware > USB Hub (pick any) > property (rt mouse)> power

I hope this helps!! sorry about the fuzzy image.. this is a Mac .. you can see 500mA per port and the device connected = 0mA
It has a built in current meter, what it doesn't do is make it easy for you to identify which physical hub and port it is referring to. I found moving a mouse to each port the easiest way to identify, but my learned colleagues may know a faster way.
BTW All the USB hubs are protected by automatic resettable polyfuses from short circuits. But I have seen at least one motherboard with blown electrolytic caps near the USB ports due to current surges, detected with the traditional popcorn bulging lid.
Comment: Fuzzy image because it's a Mac???
Comment: If just resizing makes it that fuzzy you really need a decent image processing software! :-/
Comment: Most cheap USB hubs I dealt with do not have any over-current protection (neither polyfuses nor series transistors).
Comment: Hey have you seen the USB spec? Their images are just as fuzzy as mine.  See Figure 19-3 for example on Device Mgr. I agree thats why I said expensive program.. ( please not Gimp) .. Thats why I love Irfanview owned by Corel now. instant anything including adobe addons.
Comment: Yes I captured a high resolution image remotely on a Win7 tower and resized onto a low resolution Mac Air and enlarging turned out fuzzy, If you needed more resolution, I could have matched pixel resolution on this Mac by disabling autoscale, but that was hindsight and it wasnt essential. Beside it left some thinking why/how I was using a Mac to report about Windows Current monitoring features. The whole process took 1 minute. Besides with Windows 3rd party Apps I can easily see dpi and xy image sizes and edit. On OSX you need an expensive program to do it or use primitive Preview.


U.S. Bank ATM cards and credit card acceptance in Russia 2015,

Question: Do ATM cards extracting money from US banks work in Russia? Will I have a problem using credit cards that are on US banks in Russia?
Comment: What do you mean? What network does your card belong to (visa, MasterCard, Maestro, or else)? As far as I know cash machines provide cash on that criteria only, regardless of the country the card was issued
Answer: If you show up in Russia and start using your debit card at ATM's there's a possibility that your bank's detection program may flag it up for analysis.  This would happen if using a Russian ATM is outside of your standard usage pattern.
At that point, the bank will start trying to call your mobile or send you email asking you to contact them, and if they cannot reach you then yes, they might put a block on your card.
To avoid something like that, you can send your bank a notification email along the lines of...

I expect to be in Stavropol during 20 July - 23 July and in Tver on 24
  July - 26 July.  I will be using local ATM's to replenish my pocket
  money and please honour withdrawals up to USD 200 per day.  My mobile number is... and my email is...

Some banks (like HSBC) even have a form you can fill out online.
Other than that, there is no cause for thinking that a debit card issued by a Fed regulated bank would not work in Russia.  I don't use American Express at ATM's, but can attest that Visa and Mastercard debit cards work in the cities I mentioned above along with Moscow and Peter.
To help canonicalise this answer, the same would hold true for FCA regulated banks and ECB supervised banks.
Comment: Can only add that you should rely only on two main types of cards: Visa & Mastercard. Other ones, such as American Express or something like that, can be a problem as they not so widely accepted even in big cities..
Comment: Minor note: my experience with US banks is that you can't send them an email: there is no email address set up to receive account specific inquiries (partly because there is no good way to authenticate them). You'll have to use either an online form or the telephone (number should be on your card). Also, it seems that some banks no longer accept this sort of travel notification at all.


Nikon telephoto zoom ring turns but Lens won't extend

Question: Nikon telephoto lens zoom ring turns but will not extend lens but will retract it if I manually extend the lens!
What is causing this and is it something that I can fix myself?
Answer:
is it something that I can fix myself?

The answer to that is almost certainly "if you have to ask the question, the answer is no". For a bit more detail, have a look at this teardown of a zoom lens by Lens Rentals - if that looks like the kind of thing you'd be happy to try, you might get lucky and be able to spot an obvious problem in the lens which you can fix. If like the vast majority of us that looks incredibly scary, then no, you definitely can't fix it.
Assuming you're not going to fix it yourself, you have two options:

Get it repaired by a professional
Junk it and get a new lens

Expect to pay at least a few hundred dollars for a repair; unless it's under warranty or is a top of the range lens, it's almost certainly not worth it.
Comment: @FreeMan You're assuming it's a cheap lens. A high end lens would be worth paying to have fixed. Tear it down first and most repair shops won't even attempt to fix it. If they do, they'll charge twice as much. Not to mention that one can do a lot of damage to things like flexes and position sensors (touch them with your uncovered finger and they're usually toast) without even realizing it.
Comment: Step 437: Drop all the bits in a bin & buy a new lens. ;) Boy, but that's complex.
Comment: Honestly, if the expectation is that the lens will be replaced, may as well tear into it to see if you can fix it. It won't end up any _more_ broken than it already is, you'll learn something in the process, and you may just end up being able to fix it after all!
Comment: @MichaelC that's why I said "If the expectation is to _replace_ the lens..." If you're going to have it serviced professionally, then your point is very true.
Comment: @Tetsujin But at least you don't have that nagging feeling that it might still be salvageable.  You know where you are standing now.  And the bits and pieces won't get you a restraining order.  And you learnt a lesson.

Nikon telephoto zoom ring turns but Lens won’t extend


Is there software available to benchmark networking equipment?

Question: Is there software, or a utility, available on Ubuntu that I could use to benchmark (performance test) traffic and throughput on networking equipment (specifically Cisco switches or routers)?
Comment: what sort of hardware? what sort of test? (max connections/sec, 450 byte tcp, jumbo frame udp, etc?)
Answer: For general throughput testing, I've used iperf (sudo apt-get install iperf).
You start a server on one machine (using iperf -s) and run the client on another machine on the other side of the network. You get a throughput like so:
oli@bert:~$ iperf -c tim
------------------------------------------------------------
Client connecting to tim, TCP port 5001
TCP window size: 16.0 KByte (default)
------------------------------------------------------------
[  3] local 192.168.0.4 port 39402 connected with 192.168.0.5 port 5001
[ ID] Interval       Transfer     Bandwidth
[  3]  0.0-10.0 sec  1.04 GBytes    895 Mbits/sec

Answer: hdparm -t /dev/disk can be a good indicator as well, if you mount any of the drives on a server on the other side of the device. comparison between local disk speed on the server and disk speed from a client over the network can be a good indicator.


Is there a way to view edges in weight paint mode?

Question: It would make the process a bit easier I am aware of face-select mode but I don't like the way that works. I would like to be able to weight paint across all faces as I normally would without either weight or vertex selection but with my edges more visible. I am aware of wireframe mode but... obviously that does not give you the visual cues you need for weight painting.
Comment: Have you tried enabling the [wireframe overlay](https://i.stack.imgur.com/mVuNS.png)?
Comment: I forgot that option but that was exactly what I needed. Thanks.
Answer: You can enable the Wireframe Option (under Geometry) in the Viewport Overlays while in weight paint mode.
Answer: The accepted answer works, but the Wireframe option remains visible both in weight paint and object mode. This means it adds a wireframe overlay for every visible object in your scene. The Show Wire option performs the same function as Wireframe, but it is only visible on objects in weight paint mode.
While in weight paint mode, you'll find Weight Paint options immediately below the Geometry section of the Viewport Overlays menu. Show Wire is at the bottom of this section.
Comment: Show Wire does have the stange property that any face currently selected in edit mode will *not* show wires in weight paint mode. I haven't found a use for this, but it's worth being aware of.


Maxwell's Demon as a heat source on memory erasure

Question: The paradox of Maxwell's Demon, consisting of a box a gas, separated in two compartments, with a door, are initially both sides in thermal equilibrium hence at maxim entropy. By the action of an imaginary being, a Demon, who is able to observe the directions and speeds of each individual particle in each compartment at each moment, is able to open the door between the two side in the right moment, resulting in more faster particles gathered on one side, and more slower particles gathered on the other side, in this way a temperature difference produced between the two sides, no longer in thermal equilibrium, meaning the entropy of the system decreased (also the Universe's total entropy). As the Demon having a finite amount memory, after a while it is forced to erase the information accumulated during his action, but according to Lanadauer's principle, which states that, the erasure of information is an irreversible, physically heat dissipating process. This released heat increases the environment's (also the total entropy of the Universe) entropy, balancing out the entropy decrease created by the Demon, thus the Second law is claimed to be preserved, and the paradox resolved. The problem is that, in this way, the Demon (his memory) on erasure becomes a heat source itself, possibly available to do useful work with it, in this way invalidating the resolution to the paradox. So, the question is, how the total entropy still increases, and how the Second law is preserved, if the Demon's memory -on erasure- is a heat source itself, good to do useful work with it? Is this long enough now? I expect answers then.
Answer:
possibly available to do useful work with it, in this way invalidating the resolution to the paradox

The issue with the initial premise lies here (as I noted on your previous question that you deleted and reposted—please don't do that, as it discards discussion that some might find useful).
The Second Law prohibits total entropy from being destroyed.
Suppose the Demon is used as the hot reservoir in a heat engine. Then we have two phenomena occurring:

The Demon reduces local entropy in the box, but this is argued to be acceptable because entropy is generated elsewhere from erasing information.

The Demon loses entropy from being used as a hot reservoir, but this is acceptable because the entropy of an associated cold reservoir is increased by at least the same amount, as with any heat engine. (This is cleverly done in the usual manner by removing entropy $\frac{q}{T_\mathrm{hot}}$ from the hot reservoir and depositing at least as much entropy as $\frac{q-w}{T_\mathrm{cold}}$ in the cold reservoir, allowing work output $w$.)

The two phenomena can be uncoupled. If there is no Second Law problem with either individually, there is no problem with them used together in series. Therefore, it's not clear why any explanation would be invalidated.
Answer: You mention "[Landauer]'s principle, which states that, the erasure of information is an irreversible, physically heat dissipating process", and jump to the conclusion that erasure is therefore a source of heat. This isn't what Landauer's principle is saying. It means that the demon has to find an external source of heat and dissipate it in the environment in order to perform the erasure.
However, it's not a good explanation of the Maxwell's demon argument. For this, consider the classic case of a demon separating hot and cold molecules, using an abacus for data storage.

The demon measures the temperature of each gas molecule, and reduces the $2^n$ states of the well-mixed gas to $1$ state. At the same time, he transforms the $1$ state of an empty memory store to the $2^n$ possible states of a full one.
Now we can see that the demon is faced with exactly the same problem when it comes to erasing the memory store. The beads of the abacus are divided into two groups representing 'hot' and 'cold'. In order to erase the data, the demon has to measure the state of each one so it knows how to perform the transformation to the 'empty' state. All we have done is moved the problem, not solved it.
This is where Landauer's principle comes from - erasure of a data store is exactly the same sort of problem as separating a mix of hot and cold molecules, and thus requires an external source of entropy increase to perform the erasure, such as heat dissipation. Thus, Landauer's principle assumes the demon's impossibility, and assumes the standard thermodynamic formula for heat engines to calculate an amount of energy to dissipate.
Comment: Could you please explain your comment that the filled-out abacus has $2^n$ states. Surely the beads aren't thermalized—that would make a very poor abacus. They sit in place after being set. Why doesn't the abacus then continue to have one state (not counting its material entropy; perhaps we could assume that it's arbitrarily cold)?
Answer: Thanks for your answer @Chemomecanics & Nullius In Verba. Second, sorry for my english, my phrasing can be imperfect.
I think it is my mistake I forgot to mention one very important, but officially accepted fact: only memory erasure requires energy investment, memory write doesn't!
Correct me if I understand wrongly the Second Law of Thermodynamics, this is how I understand it:
"It is impossible to create an engine which working in cycle, results in no other than the extraction of heat energy without at least the same amount of external energy invested first."
The Demon does exactly this: without any energy investment is able to extract heat energy, because memory write has no cost. This is the paradox in short.
The solution is, that yes yes, the Demon can extract without any energy investment, but when he needs to erase his memory, he needs to use at least the same amount of energy as he extracted, so he needs to use the energy he extracted to do the erasure.
In short, in this way the problem is solved, no net energy is gained for no investment.
However let's notice a cyclic energy flow is created either way, without any energy investment, and what prevents me to insert a heat engine to extract some energy, and do dome external useful work with it?
Because when the Demon does the memory erasure, uses the energy extracted, so the energy flows through his memory back to the box-system.
The Demon's memory becomes a heat source (the hot body) and the box-system becomes the cold body, actually becoming a possible energy-extraction point.
Do you observe that the energy-neccessity-to-erase of the Demon is actually redundant?
Here are some presentations about the cycle:
<code>      Box
      / ^
     /   \
    /     \
   /       \ <--- Possible energy extraction point
  /         \
 /           \
V             \
</code>
Ext.energy-------->Demon
storage

Since here I suppose to write an answer, then my answer would be that Landauer's principle is wrong, memory write and erasure has the same cost, a Demon would be able to do this action.
The classical thermodynamic Second Law was formulated, at a time when the atomic composition of the matter was still under heavy debate, many even rejected, and gases (and heat) was considered as "indivisible bodies", to which the original formulation of the Second Law what I wrote above was true.
Science moved on, atoms were proven, thermodynamics haven't: physicists still today cling convulsively to the impossibility of extraction of the internal energy of the gases at no cost, because that would be something "too good to be true perpetuum mobile". To cut short, -here I can't explain in short-, to this adds the deep confusion between physical and informational entropy.
The reason I opened this question is, if anyone could find a reason, what I haven't thought of, why the Demon's memory on erasure cannot be used as a heat source for energy extraction. I think it was never intended to ... by definition the heat generated on erasure is "waste heat" which supposed to be considered as lost in the environment (to increase back the global entropy), but one can argue why not to use it, since it can be considered coming from a source, the Demon's memory.


How to stop Ubuntu tracking process?

Question: As far as I know Ubuntu is using a process to track user usages and maybe personal information, some like google and other websites use cookies to provide you with "more suitable add". Can someone tell the name of the process and how to stop it ?
Answer: Go to
System Settings -> Security & Privacy -> Diagnostics -> Uncheck Send Occasional system information to Canonical
I believe what you are referring to is(Zeitgeist) a feature of Ubuntu for you.  It isn't for advertising purposes.  It is to display information to you about recent files, log events, and other things you may find useful and display some of that information to you when searching in the dash. Some of this information can be shared and you can decide what is ok to share by using the answer from @DnrDevil.  Be aware that this information also has benefits for you as well in the Dash.
Ubuntu does have services for monitoring systems like Landscape that is intended for Enterprise usage, or for a savy individual with many Ubuntu systems and not really for Canonical/Ubuntu Community.
I think what you may be confused about is Canonical having included in the dash "Online Search Results" which are sometimes linked to Amazon links with their affiliate code.  Not exactly tracking your usage of the desktop though.  This will be removed from what I have heard in 16.04 the next LTS.
Although if you don't have a need for this you can turn it all off easily.  You can also easily remove it as well.
You can remove landscape if you never plan to use it.  I haven't removed any of these things as I usually just disable them though so make sure you research doing that.
To understand privacy here is a great resource - http://www.ubuntu.com/legal/terms-and-policies/privacy-policy
To disable and move Zeitgeist - Disabling Zeitgeist
Also if any Scopes in the Dash bother you, you can always disable ALL of them.  Just right click on the dash plugin while browsing the dash applications tab.  Then click Disable.
Answer: Depending what version of Ubuntu you are on.
Go to Settings-> Security and Privacy-> Files & Applications. Turn this setting off. A few more setting are in there as well like "gather information and send to partners".

How to stop Ubuntu tracking process?


Clash of clan confused

Question: Okay so can I link another account to my other account? My brother is playing and I'm afraid of erasing it because he is level 85 and he'd kill me. Not really. But I made my own Apple id and deleted and reinstalled the app but it did nothing. I want to make my own base. So can I link another device without loosing the base on the other? I really need answers!
Answer: If your brother is connected through GameCenter, signing out will not cause any loss of game progress as long as he can sign back in later. Sign out of GameCenter account and sign into yours then try and launch the game.

Clash of clan confused


Can Outer Space be used for Waste Disposal?

Question: If harmful toxic, nuclear and other wastes are dangerous if improperly disposed on Earth, can't they be launched into space? If a large, tightly bound mass of waste were to be propelled into outer space, according to the law of Inertia, it would never stop going forward, unless obstructed by something. Also, the chances of it running into a space shuttle are almost zero. So can wastes be launched into space? If not, what are the demerits of such a practice? Or has such a project already been undertaken?
Comment: This reminds me of a Futurama episode.
Comment: Short answer. Launching something into space that doesn't crash back eventually: hard. Digging a hole deep enough to never worry again: trivial.
Answer:
Disposal in outer space
The objective of this option is to remove the radioactive waste from the Earth, for all time, by ejecting it into outer space. The waste would be packaged so that it would be likely to remain intact under most conceivable accident scenarios. A rocket or space shuttle would be used to launch the packaged waste into space. There are several ultimate destinations for the waste which have been considered, including directing it into the Sun.
The high cost means that such a method of waste disposal could only be appropriate for separated high-level waste (HLW) or spent fuel (i.e. long-lived highly radioactive material that is relatively small in volume). The question was investigated in the United States by NASA in the late 1970s and early 1980s. Because of the high cost of this option and the safety aspects associated with the risk of launch failure, this option was abandoned.
Today only radioisotope thermal generators (TRGs) containing a few kilograms of Pu-238 are launched by NASA (see information page on Nuclear Reactors for Space).

World Nuclear Asscociation ("The World Nuclear Association is the international organization that promotes nuclear energy and supports the many companies that comprise the global nuclear industry.")
Comment: The fact that they mention "directing it into the Sun" says a lot, considering it is harder to throw something into the Sun than to send it on an escape trajectory out of the Solar System.
Comment: @ChrisWhite They mention "_including_ directing it into the Sun". So, I'm not so sure about "says a lot". But, otherwise, that's a very good point.
Answer: In principle you can shoot anything into space. Economically, it will never be affordable, but how about energetically.
The earth escape velocity is about $v_e=11.2 km/s$. This means, that per unit mass, to get something to outer space, you need at least the following amount of energy
$$ \frac{E_{kinetic}}{m}=\frac{1}{2}v_e^2 = 63 \frac{MJ}{kg} $$
Now it is interesting to look at energy density per unit volume of certain fuels. The nuclear material itself contains in the order of a million times more energy, so energetically it is very well possible. The only downside, is that you need fuels that you can just burn down. And of course, the financial and safety aspects are not included.


Is this proper use of jQuery?

Question: I have created a tabbed display with html/css.  I simply want to use jQuery to toggle the tabs/classes.  It works perfectly but I want to make sure I'm using jQuery properly.
Here's the html structure + jQuery:

Tab1

Tab2

This is tab 1 content

This is tab 2 content

 $("#tab1").click(function() {
           $("#tabcontent > div").hide();
           $("#tab1content").show();
           $("#tabs > li a").removeClass().addClass("inactivetab");
           $("#tab1").removeClass().addClass("activetab");
       });

The jQuery you see for tab1 is repeated for each tab.
Answer: You should use a more generic approach in defining the behavior for the tabs:
$('#tabs a').click(function(){
    $("#tabcontent > div").hide();
    $("#"+this.id+"content").show();
    $("#tabs > li a").removeClass().addClass("inactivetab");
    $(this).removeClass().addClass("activetab");
});

With this code, it is possible to add other tabs without the need to add new JavaScript code. The information in the id attribute of the a tag is used to determine the content panel to display.
Answer: You don't need to repeat the code for each tab.  Instead, write one function that applies to all tabs (finding the parent and child nodes using jQuery selections) and bind that single function to the click handlers for tabs (you'll need a new class to identify which elements are tabs).
Answer: The jQuery you see for tab1 is repeated for each tab.

I'd rather go with generic solution. Use "tab" class for all tabs, write a click handler for that. Use $(this) to reference what was clicked on.
Comment: And use href="#yourTab" (which makes a lot more sense then linking to the top of the page)
Answer: You ought to be able to write a single function, which can be called for each tab.  Or, you can do something like this:
$("#tab1, #tab2").click(function() {
  var tab = $(this);
  var tabContent = $('#' + tab.attr('id') + 'content');
  // etc.
});

Answer: The jQuery looks ok, but you could generalize it to work with n number of tabs.
Also, adding a class for inactive tabs is probably redundant as if a tab does not have the active class, then it can be considered inactive.
Answer: or you could just use the tabs function in jQuery UI:
$("#tabs").tabs();

Answer: You're on the right track I wouldn't recommend coding commands for each tab click. JQuery UI has a tab feature http://jqueryui.com/demos/tabs/ that could give you some ideas or for use too.
Answer: also might be useful to check out the toggle effect.

Is this proper use of jQuery?


about visa entry and exit

Question: im a indian citizen. i am holding a schengen visa through portugal. due to some circumstances i am not visiting portugal now and visiting other schengen countries like Germany and Hungary. would that be a problem at immigration?
Answer: Once you get the Schengen visa, you can enter and leave the Schengen region from any of the member states. The border guards just ensure than you have all the right documents to be in the region. For Indian citizens, this mostly means the passport, visa and sometimes medical insurance.

about visa entry and exit


In F1 why does the checkered flag appear when the driver has not finished and is further down in position?

Question: Why does a driver in (say) 13 place have a checkered flag but positions 4-12 have no flag yet?
Comment: Can you give more details of when you saw this? The most likely situation is that those drivers have been lapped.
Answer: The reason for that is simple.
The race is over for any car crossing the finish line line after the winner and they cross the line in the order of cars on the track, which isn't necessarily the order on the scoreboard due to lapping of slow cars.
For example, if a slower car was lapped and is now between the first and second placed cars they will finish the race "together". The winner sees the chequered flag and so do all the following cars, regardless of how many laps they're behind. They will not be able to unlap those laps anymore and get ranked accordingly.
Answer: This link on the BBC to Formula 1 Flags explains that the chequered flag is show to the race winner and every car behind them. The race is complete for those cars once the chequered flag is shown to them.
Answer: Please refer to the image below. Consider that the brown line is the checkered flag. Then the car P1 position will have checkered flag sign along with P2 driver. This also involves for P13 car behind the P1 and P2 car because the car P13 and so on has been out-lapped by the leader. Hence, the driver will finish the race behind the leader but being outlapped.
Notice that P11 and P12 car has been pass the brown line but for them, it still not counted as 'finish' because the checkered flag that indicates the finish race will raise when the P1 driver has finish all the laps. So, when P11 and P12 drivers cross the brown line, the leader P1 still not touch the brown line that indicates the race has been finished.


Installing TinyOS on recent version of Ubuntu

Question: I am following this tutorial to install TinyOS but when I run sudo apt-get install tinyos it says unable to locate package. I have tried all distributions.
Answer: From the TinyOS tutorial at your link:

Supported distributions are (hardy, intrepid, jaunty, karmic)

All of these Ubuntu releases are end of life and are no longer supported by updates. You are using Ubuntu 14.04 which is not supported by the TinyOS package repository that is shown in the tutorial at your link.
Instead I followed the instructions from Automatic installation - TinyOS Wiki to install TinyOS in Ubuntu 14.04 (it also works in Ubuntu 16.04).
Install TinyOS in Ubuntu 14.04 and 16.04

Visit TinyOS (TinyProd) Debian Development Repository and follow these instructions:

Tell apt about the TinyProd Signing Key.
wget -O - http://tinyprod.net/repos/debian/tinyprod.key | sudo apt-key add -

Add the two new lines to /etc/apt/sources.list.d/tinyprod-debian.list:
sudo -s
cd /etc/apt/sources.list.d
echo "deb http://tinyprod.net/repos/debian wheezy main" >> tinyprod-debian.list
echo "deb http://tinyprod.net/repos/debian msp430-46 main" >> tinyprod-debian.list

Install the new packages:
sudo apt-get update
sudo apt-get install nesc tinyos-tools

I didn't install either msp430-46 or avr-tinyos at this step, in case you want to install them later after you have tested your TinyOS installation.

Get the code from the TinyOS release repository:
wget http://github.com/tinyos/tinyos-release/archive/tinyos-2_1_2.tar.gz
tar xf tinyos-2_1_2.tar.gz

This will extract the actual TinyOS code in a folder named tinyos-release-tinyos-2_1_2 inside the directory the command was issued. Feel free to rename this folder to tinyos-main.
You will need to add some environment variables to your shell. The following file includes the necessary ones. Substitute the placeholder  with the path where you chose to place the code in the previous section (full path recommended).
# Here we setup the environment
# variables needed by the tinyos
# make system

export TOSROOT="<local-tinyos-path>"
export TOSDIR="$TOSROOT/tos"
export CLASSPATH=$CLASSPATH:$TOSROOT/support/sdk/java
export MAKERULES="$TOSROOT/support/make/Makerules"
export PYTHONPATH=$PYTHONPATH:$TOSROOT/support/sdk/python

echo "setting up TinyOS on source path $TOSROOT"

Suppose you named this file tinyos.env. There are now at least two possibilities to have these variables accessible in your shell:

Place it as root user in /etc/profile.d/
Place it in <local-tinyos-path> and add the following line to your .bashrc
source <local-tinyos-path>/tinyos.env

After the TinyOS installation is finished, you can check if it is successful by executing some of these commands:
tos-bsl                 tos-ident-flags         tos-serial-debug
tos-build-deluge-image  tos-install-jni         tos-set-symbols
tos-channelgen          tos-locate-jre          tos-storage-at45db
tos-check-env           tos-mote-key            tos-storage-pxa27xp30
tos-decode-flid         tos-mviz                tos-storage-stm25p
tos-deluge              tos-ramsize             tos-write-buildinfo
tos-dump.py             tos-serial-configure    tos-write-image

Comment: Be careful if you install msp430-46 in Ubuntu 16.04 and later releases. For further information see this question: [Error while installing for TinyOS](https://askubuntu.com/questions/948570/error-while-installing-for-tinyos).
Answer: I happened to have the same issue and I solved it in the following way.

I downloaded the tinyos package form their github repo
tiny-os-main.
I extracted it to my Desktop (you can extract it wherever you want and note down the path).
I then installed tinyos-tools from apt using apt-get install tinyos-tools.
I then followed the 3rd instruction form the link Automatic Installation - TinyOS Wiki to setup the environment. The "local-tinyos-path" is the path you noted down in step 2.

Btw I am using Ubuntu 14.04.
Hope this helps.
Comment: Before the above procedure, I first setup my machine with toolchain from [link](https://github.com/contiki-os/contiki/wiki/Setup-contiki-toolchain-in-ubuntu-13.04).
Answer: Install TinyOS on Ubuntu 18.04
You don't need to download source for TinyOS, these command would do that:
% sudo apt-get update
% sudo apt-get install tinyos-tools bison flex graphviz
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  ca-certificates-java default-jre default-jre-headless fonts-dejavu-extra java-common libatk-wrapper-java libatk-wrapper-java-jni libjama-java libpcsclite1 nescc
  openjdk-11-jre openjdk-11-jre-headless tinyos-source uisp
Suggested packages:
  default-java-plugin libjama-java-doc pcscd gcc-avr gcc-msp430 libnss-mdns fonts-ipafont-gothic fonts-ipafont-mincho fonts-wqy-microhei | fonts-wqy-zenhei fonts-indic
The following NEW packages will be installed:
  ca-certificates-java default-jre default-jre-headless fonts-dejavu-extra java-common libatk-wrapper-java libatk-wrapper-java-jni libjama-java libpcsclite1 nescc
  openjdk-11-jre openjdk-11-jre-headless tinyos-source tinyos-tools uisp
0 upgraded, 15 newly installed, 0 to remove and 0 not upgraded.
Need to get 53.2 MB of archives.
After this operation, 233 MB of additional disk space will be used.
Do you want to continue? [Y/n]y

The above commands install Java, nescc (v1.3.5), tinyos-source (v2.1.2), and tinyos-tools (v.1.4.2).
The source code for TinyOS will be placed in /usr/src/tinyos.
After installing these, you will need to add some enviroment variables to your shell by:
source /etc/profile.d/tinyos.sh

Or to add these enviroment variables automatically, type:
printf 'source /etc/profile.d/tinyos.sh\n' | tee -a "$HOME/.bash_profile"

Next, check the installation with:
tos-check-env

Finally, change owner of TinyOS source:
% printenv TOSROOT
/usr/src/tinyos
% sudo chown -R "$USER". "$TOSROOT"

Useful links

Wiki page: http://tinyos.stanford.edu/tinyos-wiki/index.php/Main_Page
FAQ : http://tinyos.stanford.edu/tinyos-wiki/index.php/FAQ
Overview: http://tinyos.stanford.edu/tinyos-wiki/index.php/TinyOS_Overview
Installation on Ubuntu 16: Installing TinyOS on recent version of Ubuntu
[Obsolete] Installation from unofficial repo: http://tinyprod.net/repos/debian/
Answer: That will happen if the package
name is typed incorrectly , you can
double check package name in the
software center or install from there .
The terminal is case sensitive for
some operations , use lower case for
installing packages. sudo apt- get
install name.
It may depend which repository
those packages are in and whether
those repositories are enabled. I am
no expert on apt - get, but if you list
which packages you are looking for ,
someone may be able to help.


Netgear GS724T static IP assignment

Question: I have a Netgear GS724T smart switch. I'm not sure if this can be done, but I want to assign a static IP address to each of the 24 ports on the switch so that any device connected to a particular port will always have the same IP address. Is that possible and if yes, please help me to configure it.
Comment: That is a layer-2 switch, so you do not assign layer-3 addresses to the interfaces. Also, assigning addresses to the switch interface has nothing to do with what address a device connected to the interface gets. A host will either be statically configured, or it will be configured by DHCP from a DHCP server.
Comment: Did any answer help you? If so, you should accept the answer so that the question doesn't keep popping up forever, looking for an answer. Alternatively, you can provide and accept your own answer.
Answer: No! You can't do that, as the comment from Ron shows.
You have to configure static IPs on your PCs or you have to configure your DHCP Server. The keyword for your DHCP Server ist "MAC Reservation".
Depending on your DHCP Server you will find suitable instruction via google.

Netgear GS724T static IP assignment


Parallelogram OPQR is such that OP=[-7,24] and OR=[-8,-1] determine the acute angle between the diagonals OQ and RP.

Question: I'm just really stuck on this question I only found the magnitude of OP = 25 and RP=√65
Answer: Hint: Determine the vectors representing OQ and RP, then take the Dot product of them using the $2$ different standard definitions (with one involving the angle between the vectors), and then compare these $2$ results. I trust you can finish the rest yourself.


Why doesn't Join a Conference show up under my Gmail account in Trillian?

Question: I read that Trillian supports the XMPP Conference feature and there is supposed to be a "Join a Conference" option when I click my account icon.  But when I click my Gmail icon, I don't see it.  I thought Gmail Talk supports XMPP.  Why doesn't it show up?
Answer: You have to create a separate XMPP account in the Trillian account manager, with the same Gmail email address and password.  Then, click the V (XMPP icon) then Join a Conference.
Even though Gmail Talk uses XMPP, Trillian does not expose this functionality through a "Gmail" account.


Adding an .exe to default path without adding the directory

Question: For example, I want to add notepad++ to my PATH, however the directory also contains uninstall.exe and several other files/executables and I don't want them to "pollute" my path. Can I just add the one notepad++.exe?
Answer: You can add a batch script to a directory that is in your path, that looks something like this:
@echo off

:: Notepad++ execution

if [%1]==[-h] goto :HELP
if [%1]==[--help] goto :HELP
if [%1]==[/?] goto :HELP
goto :START

:START
start "" /i "%ProgramFiles(x86)%\notepad++\notepad++.exe" %*
goto :EOF

:HELP
echo -------------------------------
echo Notepad++ Command Argument Help
echo -------------------------------
echo Usage :
echo.
echo notepad++ [--help] [-multiInst] [-noPlugins] [-lLanguage] [-nLineNumber] [-cColumnNumber] [-xPos] [-yPos] [-nosession] [-notabbar] [-ro] [-systemtray] [-loadingTime] [fullFilePathName]
echo.
echo     --help : This help message
echo     -multiInst : Launch another Notepad++ instance
echo     -noPlugins : Launch Notepad++ without loading any plugin
echo     -l : Launch Notepad++ by applying indicated language to the file to open
echo     -n : Launch Notepad++ by scrolling indicated line on the file to open
echo     -c : Launch Notepad++ on scrolling indicated column on the file to open
echo     -x : Launch Notepad++ by indicating its left side position on the screen
echo     -y : Launch Notepad++ by indicating its top position on the screen
echo     -nosession : Launch Notepad++ without any session
echo     -notabbar : Launch Notepad++ without tabbar
echo     -ro : Launch Notepad++ and make the file to open read only
echo     -systemtray : Launch Notepad++ directly in system tray
echo     -loadingTime : Display Notepad++ loading time
echo     -alwaysOnTop : Make Notepad++ always on top
echo     fullFilePathName : file name to open (absolute or relative path name)
echo.
goto :EOF

:EOF

You can name it notepad++.cmd.  The help section allows you to easily get information on the switches.
I put all such scripts and command line programs in a directory which is added to %PATH%:
C:\Users\Public\Command\
...and that directory is synced to all computers and virtual machines.
Answer: Create a batch file with contents like the following:
@"C:\Program Files\Git\bin\git.exe" %*

This should be saved as a .bat file, such as git.bat in a directory that's in your PATH.
@ suppresses echoing the command to the invoking shell. The quotations "" prevent white space being interpreted as argument delimiters. %* pastes any arguments to the batch file, to the quoted executable instead.
You can now invoke the executable using the part of the batch file name before .bat. In my case, git.
References:

Adding Python to Windows path using a small batch file
Adding Python to Windows path using a small batch file - forum thread
Comment: For many programs that will hang up CMD until you close it.  You need to use `start` to avoid that, as shown in my answer.
Comment: @paradroid: Thanks, but it's standard terminal behaviour to remain attached to the parent unless asked. The user should do `start git` rather than have it done for them. The batch script would act better if it `exec`d into the requested process but this isn't possible on Windows: http://serverfault.com/questions/315077/is-there-a-windows-cmd-equivalent-of-unix-shells-exec. I could prepend `call` but it would be pedantic and mostly pointless.
Answer: Drag a shortcut to notepad++.exe to C:\Windows\System32.

Alternatively, as suggested by @Synetech inc., you could place your shortcuts in a separate directory (e.g. C:\Shortcuts), and then add that directory to %PATH%:
setx PATH "%PATH%;C:\Shortcuts"

As some of the comments indicate, this only works from the Run dialog. In order to get the shortcuts to launch from a command prompt, you need to add the shortcut extension (.LNK) to your PATHEXT environment variable.
setx PATHEXT %pathext%;.LNK

References:
How can I start applications easily with the Run dialog box?
Comment: This only works when invoking from the `Run As` dialog, it didn't work from the command prompt.
Comment: This doesn't work. By default (I'm dragging git.exe), "git - Shortcut", renaming this to combinations of "git.exe", "git", "git.cmd" etc. has no effect. It won't acknowledge the shortcut.
Comment: This is the preferred solution (as opposed to a batch file); create a shortcut to it in a (different) directory in the path—don't pollute Windows' directories! I have a folder specifically for this purpose called `Shortcuts`.
Comment: That's the wrong syntax for `setx`.  You do not use an equals sign, and IIRC, you need to enclose the whole path in quotes, if the current `%PATH%` has spaces in it (which it will).
Comment: And doesn't `SETX` use tildes for variables instead of percents to avoid expanding them? I know that some env-var setting tool does…
Comment: @Synetech: No, it doesn't. You could use bangs when using `SETLOCAL ENABLEDELAYEDEXPANSION` when you do not want percents expanded in a batch file though.
Comment: Well something does, maybe `setenv` or something (though I'm pretty sure it was a version of `setx`); I'll check my drive. Ah, I thought so; it was indeed an [older version of SETX](http://www.codeproject.com/Messages/1808287/Adding-Environment-Variables-to-Variables.aspx).
Comment: @Synetech: `setx /?` says that you can still use tildes (they do get expanded), but I never noticed that before, and I'm sure that the syntax has not changed since the version in the `Windows Server 2003 Resource Kit` (which is probably the same version now included as standard).
Comment: Well there you go; multiple ways to suit the situation. (Though frankly, I find that using the command-line always results in a *potential* for problems due to escaping no matter what escape character you choose (eg you can't have strings that contain '%' and/or '!' and/or '~', etc.) It just can't be like say, C++ strings where you can create *any* string, including ones that contain the escape character.)
Answer: Just create a symbolic link using mklink in a folder in the Path.
e.g. (in Administrator command prompt)
mklink "C:\Users\Me\Documents\Paths\np.exe" "C:\Program Files (x86)\Notepad++\notepad++.exe"

Answer: The App Paths registry key does exactly this: set the path to notepad++.exe to "\program files\..." and you'll be able to launch it from Start-Run, cmd, ... just like any executable from a directory in %PATH%.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths

Reference: https://stackoverflow.com/questions/4822400/register-an-exe-so-you-can-run-it-from-any-command-line-in-windows
Comment: This will not make it executable from cmd - only from start-run, or in cmd you have to prefix it with "start" as in "start myapp.exe"
Comment: The Command Prompt this, agreed, lacks the ability to recognize this variable. PowerShell does recognize it. This solution, more importantly, only applies to the directory, and hence, off topic.
Answer: I didn't like any of the solutions presented here, so I tried something else.

Install link shell extension (more info here)
Create a folder somewhere to store all your shortcuts like Marteen suggests and add it to your %PATH%. I created C:\Shortcuts and used Rapid Environment Editor to add it to my PATH.
Right-click the file you want to add to your path (in Explorer) and click "Pick Link Source"
Right-click in folder you just created and click Drop As > Symbolink Link.
Rename the symbolink link if you want.

That's it. You should be able to access your program via the command-line now. If you just added the new folder to your PATH, you will have to restart cmd.exe or Cmder or ConEmu or whatever it is you use. After that, you can add new programs without restarting.


Can I get viruses from compiling C# code?

Question: I have found a tool that requires me to compile it with Visual Studio. I am not sure if I can do it without the risk of malicious software being installed during the compiling process. Is that possible? Or would only the resulting exe file be malicious?
Comment: That would depend if VS had a vulnerability that could be exploited when compiling.
Comment: Not even that, project files can execute arbitrary code, that's a feature not a bug.
Comment: seems like it could overwrite a file that's already loaded on startup.  I've seen a few compiler type exploits mentioned on this site I think.  The bigger threat is when you run it though.  Whenever you're dealing with other people's code (who you don't know) there's a possibility of infection.  I've also seen an exploit that hides code from view.  (It's a unicode character that switches from left-to-right to right-to-left... so if the IDE is vulnerable it won't show the code when reviewing.)
Answer: From compiling C# code manually with the compiler, it would take an exploit in the compiler to do more than produce object files and error messages... Not impossible, but not likely either.
However, if you use a Visual Studio project file, a Makefile or any other build tool, you should very carefully review it as they all can execute arbitrary commands, so infecting you with a virus or worse is relatively easy.


Simplify Boolean Algebra Expression

Question: The problem is to simplify:
$$ xz+\bar{x}y+zy $$
I have an answer key that says the answer is:
$$ xz + \bar{x}y $$
I have no idea how they got this expression, though. The first thing I tried was to find the dual. Setting the original expression equal to some variable c, I got
$$ \bar{c} = \bar{x}\bar{y} + \bar{z}x + \bar{z}\bar{y} $$
This, however, doesn't simplify anything. Taking the dual of this only gets me the original expression again. How do I get the $ zy $ term to drop out?
Answer: You can get the $zy$ term to drop out by conjoining it with $\,1 = x + \bar x\,$ first, and then distributing $zy=yz$ over $x + \bar x$.
Then, by "reverse" distribution (twice) you collect common factors (there will be two terms with $xz$, and two terms with $\bar xy$). Doing this makes nice things happen:
$$\begin{align} xz+\bar{x}y+zy
& = xz+\bar xy + (1)zy \\ \\
& = xz + \bar xy + (x + \bar x)yz\\ \\
& = xz + \bar xy + xyz + \bar x y z\\ \\
& = xz(1 + y) + \bar xy(1 + z)\\ \\
& = xz(1) + \bar xy(1)\\ \\
& = xz + \bar xy
\end{align}$$
Comment: Interesting. This doesn't seem like an obvious thing to do. I suppose something like this would just be a consequence of pattern recognition. Does this come up often?
Comment: It comes up here and there. You're right that it isn't, initially, intuitive. In some cases, using this "trick" is a bit more intuitive, but as with most things, it becomes more intuitive with practice. Once you see it a few times, and understand why it works, plus actively look for situations to apply it, it will stick with you.
Answer:
solution
$xz + x'y + yz = xz(1+y) +  x'y(1+z) + zy\\
              =xz + xzy + x'y + x'yz + zy\\
              =xz + zy(x + x') + x'y + yz\\
              =xz + 2yz + x'y$

on comparing LHS and RHS , we get
$$\Rightarrow yz=0
\Rightarrow xz + x'y + yz = xz + x'y$$

Simplify Boolean Algebra Expression


The "Oblivion prophecy"

Question: There are known prophecies for Nerevarine and the Dragonborn. Is there any prophecy for the guy in Oblivion known as the Champion of Cyrodiil or the Hero of Kvatch?
Answer: Yes there was, the Prophecy of Alduin's return and the Dovankin predicted the Oblivion Crisis as you can see it on Alduin's Wall, you can read more about the translation of the wall here
Not only does it predict the Oblivion Crisis and Alduin's return but it predicted the events of Arena, Daggerfall and Morrowind and even the start of the Civil War in Skyrim. the Wall was made long before them by the Akaviri and, as per most prophecies, came from an Elder Scroll.
Of course the prophecy of the Oblivion Crisis wouldn't be a step-by-step guide like "a prisoner is going to receive the amulet of kings, find the last heir at Kvatch, stop Mehrunes Dagon's Mythic Dawn and the heir is going to sacrifice himself and the Amulet of Kings to become an avatar of Akatosh", no it's going to be obscured in riddles and metaphors which wont become clear until the time actually comes
Answer: Yes.
The prophecy is told to you during the very opening. The Emperor tells you of his dreams, where he foresaw the Siege of Bruma. During his escape, he tells you that you're the person he saw in his dreams, which is why he gave you the Amulet of Kings in the first place
In Skyrim they etch the prophecy into a wall, but the prophecy in Oblivion is not recorded anywhere. Only The Emperor has ever seen it, and he never told anyone about it

The "Oblivion prophecy"


What is the effect of a flat mirror's surface flatness as a function of beam wavelength

Question: Mirror surface flatness is specified as a multiple of $\lambda$, where $\lambda$ is the wavelength at which the surface flatness was tested, and is typically $\sim 632\ nm$. A $4\lambda$ surface flatness beam might not work so well in certain applications with a $632\ nm$ beam. Would the effect of surface flatness increase or decrease when using the same mirror with a long wavelength beam (eg. hundreds of $\mu m$)?
Comment: Take a look at this link https://www.edmundoptics.com/knowledge-center/application-notes/optics/effects-of-laser-mirror-surface-flatness/
Answer: Most lenses and mirrors are carefully designed and manufactured to a shape that captures light that left a point and brings it back to another point, as in this example. This is a camera with lenses, but telescope mirrors and bathroom mirrors do a similar job.

The image is from http://camera-wiki.org/wiki/Lens
If the shape is wrong, some rays will go to the wrong place and the image will be blurred instead of a sharp point.
Lens and mirror design is done by ray tracing. Given the position and angle that an incoming ray strikes a lens or mirror, it is possible to calculate the angle at which it leaves. And therefore the position and angle at the next lens or mirror.
Lens design software can calculate light from multiple points, at multiple wavelengths. For zoom lenses, it must consider multiple lens separations. It is a difficult job to choose shapes that bring all of these to sharp focus.
But light is only approximately described by ray tracing. Light is a wave. You can't bring it to a perfect point focus. You can't make the focal spot smaller than a wavelength. The wave properties of light are calculated as the effect of diffraction in lens design.
So if lenses and mirrors make the rays come to an almost perfect spot that is about the size of the spot from diffraction, that is good enough. The system is said to be diffraction limited, which is as good as you can get.
Lens design software can also calculate how the focal spot is affected if a surface radius is slightly wrong. Typically if the error is big enough that the surface is misplaced by a wavelength of light or so, the rays are misdirected enough to create a focal spot that is bigger than diffraction limited. The software can calculate the exact sensitivity of the focal spot size to errors in each surface.

For visible light, if requires tight tolerances to manufacture an object where the surface shape is correct within a wavelength.
$CO_2$ lasers operate at $10.6 \mu m$ in the far infrared, about $40$ times the wavelength of visible light. Tolerances are considerably looser there, because diffraction limited spots are $40$ times bigger.


The Western Wall

Question: Is the "Western Wall" a part of the temple wall that Jesus said would Not have one stone left upon another and if so was he referring ahead to a later time because the chapter is about the end of the age. Therefore, Jesus may have been referring to a time yet to come when the Western Wall would have every stone no longer upon another stone?
Comment: No, the Western Wall is part of the wall to the temple courtyard, but not part of the temple. The Romans completely destroyed the temple in Jerusalem.
Comment: Welcome and thanks for a good question. For modern people, it seems as if that wall is a very important part of the old temple (pre-70 A.D.) but as two people have now pointed out, it never was part of the Temple. Realising that it only became important 150 years ago via Muslim encouragement changes the common perception significantly! What we see on TV gives a misleading impression as to the role of that wall!
Answer: During the life of Jesus, and up until A.D. 70, the Temple and the Sacred Enclosure were surrounded by the Soreg Boundary, beyond which non-Jews were not allowed.  The Temple included the Sanctuary, the Priests' Court, the Israel Court, the Women's Court, the Nazirites' Court and the Lepers' Court.  The Temple did not include the Western Wall.
Titus, the Roman general, led four legions to besiege Jerusalem and then to burn down the temple. In A.D. 70, after the Temple was burned, the gold in the temple melted in the fire and ran down into the cracks between the stones. The Roman soldiers took the temple apart, stone by stone, searching for the gold, thus fulfilling Jesus' prophecy in Matthew 24:1-3.

As Jesus was leaving the Temple grounds, his disciples pointed out to him the various Temple buildings.  But he responded, "Do you see all these buildings?  I tell you the truth, they will be completely demolished. Not one stone will be left on top of another!" (Matthew 24:2 NLT)
Some of his disciples began talking about the majestic stonework of the Temple and the memorial decorations on the walls [of the Temple].  But Jesus said, "The time is coming when all these things will be completely demolished.  Not one stone will be left on top of another!"  (Luke 21:5-6)

The Temple Mount, where Herod's temple stood, is now home to the Islamic mosque the Dome of the Rock. The Western Wall stands to the southwest of the mosque and north of an Islamic museum.  It was part of the structure of the Temple Mount but was not part of the Temple Wall.  Here is a short extract from an article that talks about the history and the significance of the Western Wall:

When the Romans razed the Temple, they left one outer wall standing. They probably would have destroyed that wall as well, but it must have seemed too insignificant to them since it was not part of the Temple itself, just a retaining wall surrounding the Temple Mount. It held no special significance, according to F.M. Loewenberg, until the 16th century when Sultan Suleyman I (the Magnificent) ended nearly 300 years of Mamluk rule and established the Ottoman Empire. Suleyman restored Jerusalem's city walls in 1536 and encouraged Jews who had been expelled from Spain and Portugal to settle in the city.
Loewenberg concludes:  ...there is no ancient Jewish tradition that designates the Western Wall as a sacred site. Instead, it was designated as a place of prayer less than five hundred years ago by a Muslim ruler. It took more than three centuries for the wall to attract the Jewish masses and, only in the last 150 years, has it become Judaism's most sacred site. Yet, even if this place was not intrinsically holy (let alone as holy as the Temple Mount), or even if it had not been so designated by Suleyman the Great, it has become sanctified over time as Jews have increasingly utilized it for prayer.  Source:  https://www.jewishvirtuallibrary.org/history-and-overivew-of-the-western-wall

In Matthew 24, Jesus' disciples asked him: "What will be the sign of your coming and of the end of the age?" (Matthew 24:3).  What follows is the Olivet Discourse, Jesus' summary of end times' events as they relate to Israel. This destruction of Jerusalem was but a foreshadowing of what is yet to come.  In the Olivet Discourse, the second half of the tribulation is described in Matthew 24:9-14. More information here: https://www.gotquestions.org/Olivet-discourse.html
Yes, the "end of the age" points ahead in time to when Christ Jesus returns and establishes his kingdom, but this will be a global event.  It will affect all the nations of the Earth, and not just one nation.  Neither will it be restricted to Jerusalem.

The Western Wall


How can I my homing missile avoid walls (2D)?

Question: Okay, I have the homing missile implemented. It will follow the player, but I want it to avoid the walls. I tried out A* but I want to make my own. I need some help plzz.
Comment: You can also look into "local avoidance".
Comment: What unwanted behavior did you observe from using the industry-standard A* algorithm, that you want to improve upon with your own version? We need to clearly understand what needs to be different about solutions we offer here.
Answer: fo me, I am using raycast to create nodes and then use a* algorithm to calculate path.
But I am just create some iteration of path since game environment will changed every frame. Here's how I create nodes:

cast a ray (Physics.raycast) from missile to target, if there's a obstacle get hit point of raycast (usually it's a return value of raycast method).
add missile pos & hitpoint pos divide by 3/4 or 4/8 or whatever it's up to u.
we got a node by execute step 2.
we can repeat step 1 & 2 but this time, we start from the node and we cast some degree to the left or right (the degree is up to u).
5.let's said you cast to the left first, since this cast is not to target, just decide how long you want to cast.
6.same as step 1 & 2. but this time we not cast a ray anymore, just switch it to right direction from first node we've got from step 3. and do the same thing as left in step 5.
now you have 3 nodes! now all you have to do is compare the last two nodes (left & right) because they are branched from the first node, compare who is closest to the target.
8.let's said the result of comparison between left and right nodes is second nodes
now missile will move to first node and then second nodes

important to note:
1. as this method is not generate path nodes from start to end, missile can't arrive to the target if they reach dead end like maze environment. But I like this method because it's like realistic missile and low cost performance.
2. you can improve it by increase branch nodes per turn.


What "thing" enables Speculative Execution to actually work?

Question: I have been learning recently about the inner workings of a CPU, how machine code is executed and how data moves around between registers using the bus.  Now I'm reading about Speculative Execution and I can't wrap my brain around what "thing" is actually deciding to process instructions in a different order (ahead of time).  It seems like there must exist some type of intermediary component sitting between where the instructions are coming from (in memory) and the CPU that is performing the calculations.  This "thing" obviously is reading ahead and deciding to feed commands that may not be needed, and I assume it also somehow knows which results to discard when necessary.  What is this "thing" called that actually enables Speculative Execution to function at all?  Is it inside the CPU, or outside, for example in the "chipset" (a whole 'nother thing I need to read about).
Comment: That's more a computer science question. Obviously there is some logic that gathers data based on how software is behaving and has both branches of a jump executing intermediate results in a pipeline and in the end ignores the instructions of the wrong path.
Comment: William Johnson (RIP) wrote the book. https://vlsiweb.stanford.edu/people/alum/pdf/8906_MikeJohnson_SuperScalar_Processor_Design.pdf
Comment: That's a broad category. It's not a single idea, but an ever-growing collection of them. So it is hard to tell you what enables "it" since there isn't a single "it" to enable. Also, often it is a matter for a compiler tool (see the Ph.D. thesis on the Bulldog Compiler, for example.) So this isn't just the sole territory of hardware. It often includes software. In the compiler case, you can imagine the compiler "seeing" some floating point computations to make *after* an IF statement that can be pulled up before the IF, since the hardware has extra functional units available for it. Like that.
Answer: Speculative execution isn't really about any particular "thing" which is responsible for the speculating, but is a consequence of the core microarchitecture as a whole, with a few pieces of hardware which are necessary, but not sufficient on their own.
Some (but not all) of the other necessary conditions are:

Superscalar microarchitecture
Any (even trivial) branch prediction
A way of deferring visible effects until after the branch is successfully resolved
A way of discarding speculative instructions resulting from incorrect predictions

Note that these are not just "things" or "behaviors", but really a superposition of both - e.g. "a way of deferring" requires both registers and buffers to record deferred effects, and the behavior to actually store into that buffer and use it to defer those effects.
Let's walk through an example on a hypothetical (vaguely defined) microarchitecture. In some ways, it's inspired by Skylake (there's a great diagram here that you should take a look at), but in other ways I'll handwave away a lot of the components (e.g. the L1I cache/instruction queue/decoder/uOp fusion/microcoder are all bundled together as "decoding an instruction", even though the real Skylake has immense complexity to make decoding work as well as possible).
In a superscalar processor core, multiple instructions are in flight at the same time, even though the actual machine code gives them in a linear order. As long as an instruction's inputs don't depend on still-pending outputs, and there's a free execution unit capable of handling that type of instruction, it can execute freely. If an instruction depends on a not-yet-ready result, it will stall until the inbound dependency can be forwarded, which happens as soon as that result is ready.
In the pseudocode below:
  load [r1] -> r2;
  sub r2, r7 -> r2;

the load operation may take a while (e.g. due to an L1 cache miss, or because r1 is not ready). This means that the result of r2 is delayed. However, a superscalar processor will still decode the subtraction, and assign it to one of the execution ports capable of executing an integer subtraction.
At that point, the execution will stall, until the load is complete and the value of r2 is available. At that point, the load/store unit will transmit the value of r2 (e.g. via the Common Data Bus), and the integer unit assigned to our subtraction can snoop that value after which it can begin executing - that is, the decode, assignment to a functional unit, and fetch of r7 have already been done, and we were only waiting for r2.
In the case of speculative execution, this goes even further - an instruction to branch may depend on a condition which is not yet evaluated. For example, in the following assembly pseudocode, the branch instruction has a dependency on the immediately preceding instructions, and has immediately useful work following it:
  load [r1] -> r2;
  sub r2, r7 -> r2;
  branch-if-zero r2 -> some_label;
  add r4, #4 -> r5;
  store r1 -> [r5];
...
some_label:
  mov #0 -> r0;
  ret;

Now consider the branch predictor (a piece of hardware, which can be as simple as a hardcoded static prediction1, an intermediate design like a history buffer, or as complex as a neural branch predictor). Suppose that this predictor decides that the branch is likely not taken. This means that we expect the next instruction after the branch is add r4, #4 -> r5.
As the processor decodes this branch, the value of r2 is not ready yet (the load and sub are still in-flight, and the load could take a long time on a cache miss). Stalling the processor would waste precious time if the branch was indeed not taken, so the next instruction (the add) is issued and allowed to execute (either as part of a single pipeline, or by being mapped to a free execution unit in scoreboarding/Tomasulo Algorithm). The following instruction (the store) can also begin to execute, but cannot be committed yet. The effects of the two speculative instructions may be recorded in a processor-internal buffer, but the store cannot be allowed to hit main memory yet, and the store to r4 cannot overwrite the old value yet.
As soon as r2 is known, the branch outcome is known. If the branch was not taken, as predicted, then we saved some time by executing speculatively. The store (which we placed into the reorder buffer) can now be fully retired and the instructions' visible effects allowed to occur.
Let's suppose that the branch prediction was wrong. In that case, the store to r4 and the store to main memory must be discarded. The effects of the speculative instructions are never made visible2, and the processor resumes operation along the desired path, having paid a time penalty for the misprediction since it spent time doing useless work until the branch result was known.
Here's an example considering real x86 assembly.
Supposing I have the following code (also available in this interactive demo) and use gcc 8.43, -O3:
// use stride to avoid extracting REP MOVSB
void copy_with_stride(char* dst, char* src, long srcStride) {
    do {
        asm volatile("# LLVM-MCA-BEGIN");
        *dst = *src;
        src += srcStride;
        dst++;
    } while (*src);
    asm volatile("# LLVM-MCA-END");
}

I get the following assembly at -O3:
copy_with_stride(char*, char*, long):
.L2:
        movzx   eax, BYTE PTR [rsi]
        add     rsi, rdx
        add     rdi, 1
        mov     BYTE PTR [rdi-1], al
        cmp     BYTE PTR [rsi], 0
        jne     .L2
        ret

and I can pass it to llvm-mca to get the following timeline view showing four iterations of the loop (24 instructions) over 14 clock cycles. Each line is an instruction, and from left to right you can see it be Decoded, wait to start executing (=), execute*, finish Execution, maybe stall waiting for retirement (-), and then be Retired.
llvm-mca -timeline -iterations=4 -instruction-info=false -resource-pressure=true -dispatch-stats=true -mcpu=skylake

// snip

Timeline view:
                    0123
Index     0123456789

[0,0]     DeeeeeER  .  .   movzx    eax, byte ptr [rsi]
[0,1]     DeE----R  .  .   add  rsi, rdx
[0,2]     DeE----R  .  .   add  rdi, 1
[0,3]     D=====eER .  .   mov  byte ptr [rdi - 1], al
[0,4]     D=eeeeeeER.  .   cmp  byte ptr [rsi], 0
[0,5]     .D======eER  .   jne  .L2
[1,0]     .DeeeeeE--R  .   movzx    eax, byte ptr [rsi]
[1,1]     .DeE------R  .   add  rsi, rdx
[1,2]     .DeE------R  .   add  rdi, 1
[1,3]     .D=====eE-R  .   mov  byte ptr [rdi - 1], al
[1,4]     . DeeeeeeER  .   cmp  byte ptr [rsi], 0
[1,5]     . D======eER .   jne  .L2
[2,0]     . DeeeeeE--R .   movzx    eax, byte ptr [rsi]
[2,1]     . DeE------R .   add  rsi, rdx
[2,2]     . DeE------R .   add  rdi, 1
[2,3]     .  D====eE-R .   mov  byte ptr [rdi - 1], al
[2,4]     .  DeeeeeeER .   cmp  byte ptr [rsi], 0
[2,5]     .  D======eER.   jne  .L2
[3,0]     .  DeeeeeE--R.   movzx    eax, byte ptr [rsi]
[3,1]     .  DeE------R.   add  rsi, rdx
[3,2]     .   DeE-----R.   add  rdi, 1
[3,3]     .   D====eE-R.   mov  byte ptr [rdi - 1], al
[3,4]     .   DeeeeeeER.   cmp  byte ptr [rsi], 0
[3,5]     .   D======eER   jne  .L2

You can see how deeply speculative and superscalar our real-world CPU actually is; by the time we finish decoding the fourth iteration of our loop, we haven't even retired the first iteration, even if every memory access got a cache hit and finished quickly! This means that we could very well have three or four iterations of our function executing speculatively, with their retirement (and hence visible effects) deferred until the branches ahead of them are resolved.
1 An example of hardcoded prediction is to assume that branches backwards are taken (since they're likely to be loops that execute a bunch of times), while branches forward are not taken (they may be error handlers or early returns).
2 Sometimes, the results are made subtly visible. For example, a mispredicted speculative load might lead to effects in the CPU cache even though the result isn't permitted to update the actual CPU register being speculatively loaded to. Although the program state is still unchanged, the speculative load can still be detected through subtle differences in timing between cache hits and misses or other subtle observations, forming the basis for microarchitectural data sampling attacks like Spectre and Meltdown.
3 Newer versions of GCC and Clang generate separate specializations for stride == 1 (with inc) and stride != 1 (with add), since the stride == 1 case can get slightly better throughput when considered over a long loop. This makes the assembly and llvm-mca output a bit messy, so I use an older version to ensure that a single loop is created instead.
Comment: @user1850479 Somewhat tangential since it's not *prediction* or speculative in the same sense, but CUDA cores used to (and still may) execute both sides of an if/else if it diverges within a warp (group of 32 threads), discarding the effects of one or the other branch depending on the thread.  In this case I think the benefit was *simplifying* decoding circuitry and allowing more of it to be shared across a warp.
Comment: If enough execution units *are* available, is it usual to simply execute all (e.g. 2) versions of a branch to be able to continue without delay? Or is that prohibitive in terms of power ?
Comment: @tobalt I'm not certain, to be honest, since I haven't designed a fully superscalar core of my own. (My focus is usually analog these days) I'm certain that the major CPU fabricators have considered it, but their rationale for not speculating both branches is probably not public. My *guess* is that you end up bottlenecked at the L1I cache/decoder with trying to decode twice the instruction stream at the same time, while branch prediction and just evaluating the predicted branch can be pretty good for the most commonly seen branch patterns.
Comment: Furthermore, in the example I gave with the short loop, you can have four or more branches in the pipeline so I guess you'd need to handle the exponentially expanding complexity, having more machinery to tag each possible path through the branches, possibly dealing with paths that converge again, etc
Comment: @tobalt Since prediction is generally extremely accurate, it is usually not worth the (potentially large) increase in power consumption and resource contention for calculations that will most likely not be required and will be discarded.  You're better off using that power budget to clock the CPU higher or to have more advanced prediction logic.  I have seen papers that discuss executing both sides of a branch, but off hand I cannot think of hardware that does (although it probably exists).


Image plane visibility after camera movement

Question: I added an image as plane B z=0. Then I added another image as plane X z=0. X is above B as I wanted, X uses B as background image. But when I walk/navigate the camera, X would disappear. Increasing z value slightly doesn't seem to work, I had to increase the value quite drastically, which makes it very messy. Is there a proper way to keep X always above B, after I move the camera ? Thanks !
Comment: Make the Z position of X fractionally more than zero. It sounds as if you've got 'Z-fighting' happening at the moment where Blender can't decide which image to display because they're both in the same position.
Comment: Thanks for the reply! Yes I didn't mention I tried that, but a slight change doesn't seem to work. e.g. z=2, it has to be quite substential. like z=10. But hat makes it quite messy especially with a lot of objects around.
Answer: OK I think the issue is the camera x,y rotation. For a 2D image plane, that's not needed. (obviously when you do a camera walk with the mouse, it will invariably rotate slightly)
I just needed to lock the rotation and it's fine.


Sharing memory between two processes

Question: I want to share memory between two processes. One way I know is to mmap a shared file. However, I don't want to use a shared file, I want an anonymous mapping in the memory. How can I do that.
Answer: shm_open is your friend. You can unmap the shared region by using shm_unlink.
Answer: Shared memory is what you want: http://en.wikipedia.org/wiki/Shared_memory
Since you're on linux, here you go: http://www.kernel.org/doc/man-pages/online/pages/man7/shm_overview.7.html
Answer: You can put your mmap'd file in the directory /dev/shm, which is mounted in most Linux systems as a tmpfs (that is, a memory-based filesystem).
Or your can mount your own tmpfs somewhere else in the directory tree (if you want other options).
Answer: shm_get is a good starting point, but you also need to read up about semaphores for mutual exclusion so that memory does not get corrupted.
Answer: Remember that on a NUMA system, if cores are on separate nodes they will access the memory at different speeds unless you pick a NUMA node which is equidistant from the cores.

Sharing memory between two processes


jBoss 4.0.2 deploying same WAR multiple times causes jBoss to crash because of PermGem/Out-of-Memory Errors

Question: I develop web applications and I use jBoss 4.0.2 and when I have redeployed my WAR several times with eclipse, jBoss will crash because it runs out of memory. And when I have to install new version to production enviroment, it will consume production servers memory, so that means I have to stop jBoss to prevent redeploying eat memory from customers server. Is there any work around for this problem?
Answer: Basically, no. Because of the way the JBoss classloaders work, each deployment will use up a chunk of PermGen that will not be released even if the application is undeployed.
You can mitigate the symptoms by ramping up the PermGen memory pool size to several hundred megs (or even gigs), which makes the problem easier to live with. I've also found that reducing the usage of static fields in your code (especially static fields that refer to large objects) reduces the impact on PermGen.
Ideally, I would not use hot deployment in production, but rather shut the server down, replace the WAR/EAR, then restart it.
Answer: I'm not sure it's linked, but I suspect it is - JBoss is not J2EE compliant as far as implementing application separation as it comes out of the box.
As it comes, there is one classloader into which all classes are put and thus it is not possible to unload classes and therefore you are going to have this problem. You can configure jboss to be more J2EE compliant in this respect.
Are you getting the "out of memory Permgen" or are you getting regular out of memory?
I also made progress by connecting JProfiler up to it and checking memory usage with this.
I ended up simply restarting Jboss all the time - didn't take up too much time.
Answer: Try this (which applies to Sun's Java):
-XX:+UseConcMarkSweepGC
-XX:+CMSPermGenSweepingEnabled
-XX:+CMSClassUnloadingEnabled
-XX:MaxPermSize=128m
CMS can actually GC the permanent generation heap (the heap where your classes are).  Setting MaxPermSize is unnecessary, but the default is low for an application server.


Is there any significance to "Inc." vs "Corp."?

Question: Oregon requires corporation names to include "Incorporated," "Corporation," "Limited," or an abbreviation of one of those. Is there any reason why a business owner might pick one over the others, other than simply preferring one of the names? E.g. does it matter if Bob's construction business is Bob's Construction Inc. or Bob's Construction Corp.?
Answer:
Is there any significance to "Inc." vs "Corp."?
does it matter if Bob's construction business is Bob's Construction
Inc. or Bob's Construction Corp.?

No.
"Inc." is an abbreviation for "incorporated" and "corp." is an abbreviation for "corporation" which are really just different grammatical variations of the same word.
Limited is a term that can include both limited liability companies and corporations in some contexts, so this is less desirable if you want to make clear that you are a corporation rather than a limited liability company. Making the distinction between a limited liability company and a corporation is desirable because a 1099 has to be issued for payments to an LLC but not for payments to a corporation.
The word "company" is even broader and can be used to refer to any business firm regardless of its form of organization.
Comment: @Someone Yes it is.
Comment: @BruceWayne A corporation is incorporated. That which is incorporated, is a corporation.
Comment: Thank you! So it's best to stick with "Corp" or "Inc", but which of those is just based on which I like better?
Comment: Legally there's no difference between a company that's "incorporated" and one that's a "corporation"? Not even regarding say tax law?
Comment: LLC's that are corporations for tax purposes don't get 1099s.
Answer: "Inc." or "Corp." or "Co.", etc. are required to be part of the name of the corporation under the law of the state in which the corporation is incorporated. It's a part of the legal name of the corporation. The purpose is to inform anyone dealing with the corporation that it is a corporation and not an individual person.
Comment: You have answered neither the title nor body of the question. They are asking if there is a difference between the designations that might cause a company to choose one over the other, not whether or not they need to have one in the name at all.


Manuscript status changed from Review in progress to Ready for review

Question: After two months the status of the manuscript under review changed from review in progres to ready for review. I dont understand is my paper yet to be reviewed? Dont know the workflow of River Valley Review.
Answer: Just a guess, but a reviewer may have backed out so they are back to square 1. Probably no reflection on the paper. It may also been that the editor wasn't satisfied with the review he/she got so started over. Reviewers get busy just like authors.
Another possibility is that the editor got back inconsistent reviews.
Be advised that dealing with publishers can be very frustrating. Not the finest aspect of the academic life.