Why do brain cells use shuttles that pass electrons from NADH to FAD?

Question: Brain cells are cells require one of the highest amount of energy of any cell of body. So why do they use a shuttle which will transfer electrons from NADH produced in glycolysis to FAD(and there by reduce the no of ATP that can be made ) ?
Comment: @WYSIWYG she is correct. Her question refers to the glycerol phosphate shuttle which is more prominent than the malate asparate shuttle in brain and muscle cells.
Comment: @SatwikPasani.. Sorry, I didnt know about it so thanks for letting me know. I did a quick check and I could only find [this article](http://www.ncbi.nlm.nih.gov/pubmed/16368075) on G3P shuttle and brain; I couldnt access it right now but the abstract says that G3P shuttle is minimal in neurons and almost zero in astrocytes.
Comment: I looked at that WYSIWYG's abstract and it doesn't explain the poster's main concern, namely that moving a hydride via NAD has a different energy yield than moving one via FAD. Won't it be irrelevant if the reducing equivalent enters the mitochondrion via glycerol phosphate shuttle vs malate aspartate shuttle?
Comment: No that doesn't happen. are you sure ?
Comment: @WYSIWYG Actually, as is already mentioned in the reference abstract you cited, it is not very clear what the distribution of these shuttles is. But the extract refers to pharmaceutical determination studies only. Earlier biochemical studies showed high G3P shuttle prominence in muscles and neuronal tissues but has always been under active controversy. My information was older but Your reference is quite recent and may have solved the issue, but for me it's behind a paywall.
Answer: In the absence of unanimous consensus and sources regarding the actual distribution of these shuttles,(wikipedia favours G3P shuttle abundance) let me try to explain the cause if the glycerol-phosphate shuttle is assumed to be prominent in brain cells. Several possible reasons might lead to this:-
1) The existing metabolic pathways are all intertwined to form a complex metabolic net. This means that invariably, the intermediates of any pathway are the products or intermediates of several other pathways. Therefore, the G3P shuttles require Glycerol-phosphate and Glycerol-phosphate dehydrogenase (I and II) which might be naturally abundant in brain owing to its use in strict lipid metabolic control in nervous tissue. This means that tapping the already high G3P for use as a shuttle compared to synthesising and operating a distinct metabolic shuttle is more profitable. Furthermore, operating Malate aspartate shuttle migh require intermediates whose high concentrations (required to maintain the shuttle) might negatively interfere with existing metabolic pathways like protein synthesis and regulation.
2) This shuttle has much faster operation time than Malate-Aspartate shuttle and hence is very useful in shuttling reducing equivalents fast in muscles and brain. Compared to the malate aspartate shuttle, it is shorter and hence faster and less prone to cessation due to unavailable intermediates or enzymatic disruption. Due to several enzymes working in Malate-aspartate shuttle, it has a narrower pH and temperature optima than the G3P shuttle which is shorter and depends on lesser intermediates, and hence is less prone to disruption.
3)The last and the most far-fetched (but relevant)reason is that the loss of one ATP may not cause much of a problem because of already high respiratory rate, high Oxygen delivery to brain and ability of the body to quickly transfer available energy sources to brain at the cost of other parts, at times of energy stress. This means that replacing the shuttle with a more energetically conserving one may not have a strong driving force for evolution to operate on, and therefore the presence of G3P may be because of something like phylogenetic inertia, that is, the prevalence of an ancestral character just because it is neutral and does not influence the fitness in a considerable manner. Therefore, the ancestral G3P shuttle would just not have been replaced here but this is very unlikely as G3P shuttle is prominent in 2 very high energy-demanding organs, muscles and brain.
Except the last outrageously far-fetched reason, all other reasons should be enough to explain its prominent presence (if it is true) in brain tissues.
Answer: Looking at this question, which has resurfaced after five years, I was not really convinced by any of the possibilities suggested in the answer from @stochastic13, commendable attempt though it is. It happens that I have just been consulting the section on these shuttles in Berg, Tymozcko and Stryer where the following is written:

When cytosolic NADH transported by the glycerol 3-phosphate shuttle is oxidized by the respiratory chain, 1.5 rather than 2.5 ATP are formed. The yield is lower because FAD rather than NAD+ is the electron acceptor in mitochondrial glycerol 3-phosphate dehydrogenase. The use of FAD enables electrons from cytosolic NADH to be transported into mitochondria against an NADH concentration gradient. The price of this transport is one molecule of ATP per two electrons. This glycerol 3-phosphate shuttle is especially prominent in muscle and enables it to sustain a very high rate of oxidative phosphorylation.

I know little about brain metabolism, but if the demand for energy in brain is higher than in other tissues (as stated in the question) then the above would seem to provide the explanation: the greater production of ATP by oxidative phosphorylation possible when NADH entry into the mitochondria is independent of its internal concentration more than offsets the price in ATP of that entry.


How to know which IPv6 interface will be chosen by the router?

Question: I would like to know how does the kernel decide through which interface it sends data to some IPv6 address, how is the calculation done based on the routing table information: destination, gateway and netmask?
Comment: In a router, the route selection works the same way for IPv6 as it does for IPv4.
Answer: That would be RFC 6724. From the abstract of that specification:

This document describes two algorithms, one for source address selection and one for destination address selection.  The algorithms specify default behavior for all Internet Protocol version 6 (IPv6) implementations.  They do not override choices made by applications or upper-layer protocols, nor do they preclude the development of more advanced mechanisms for address selection.  The two algorithms share a common context, including an optional mechanism for allowing administrators to provide policy that can override the default behavior.  In dual-stack implementations, the destination address selection algorithm can consider both IPv4 and IPv6 addresses -- depending on the available source addresses, the algorithm might prefer IPv6 addresses over IPv4 addresses, or vice versa.

It's quite a extensive algorithm, so I won't try to replicate its contents here. The link provided above is very stable and will not disappear :)  Feel free to ask questions in the comments and I'll try to clarify the answer if something is not clear!


Undo restoring from backup on iPhone

Question: I accidentally deleted a downloaded book from iCloud and wanted to restore the book to my phone. So I restored my phone to the last time I synced my phone. In doing so, I have lost all my Apple Watch activity rings data. Is there any way to undo that restore, and bring my phone back to before I restored it? I don't even care about the book anymore. I just want my old activity rings back.
Answer: Unless you have a backup you made of the data you wish to restore, no, the data is lost.

Undo restoring from backup on iPhone


Unable to access webmin?

Question: I'm unable to access webmin via web or com. I've changed the port, and I'm thinking it's the firewall that is closing it. What code is needed to change and give access to the port?
Answer: First, reset the port to 10000 for Webmin by editing /etc/webmin/miniserv.conf putting 10000 in the port and listen fields. Save the changes. You should now be able to access Webmin through the standard web address.
Go into the Webmin Configuration page and add the new port you want to access through in the "Listen on IP's and ports:" section; leave the standard port 10000 open for now - you can add a second port in the settings. Make sure the "Open new ports in firewall" box is checked. Save the changes and try accessing Webmin through the new port. If that works, you can remove the port 10000 entry and use the new port.
If you are going to be accessing Webmin from outside of your LAN, make sure to add a port forwarding rule in your router for the new port.
Answer: If I remember correctly, webmin uses port 10000. If you're running webmin on localhost you would have to enter the address localhost:10000 in the address bar of the browser.
If you are accessing a different computer you switch out localhost with that computer's IP address. If you have to open up a port in the firewall, I'm guessing it's port 10000.
Comment: I change the Webmin Port so its not 10000. It will not launch from com or browser. That's why I was asking for the command to open iptables so I could allow accesss if it's closed.

Unable to access webmin?


Why $ \langle \mathcal{R}_{\Omega}\,X\,,\mathcal{R}_{\Omega}\,X\rangle \ge \langle X\,,\mathcal{R}_{\Omega}\,X\rangle $?

Question: Let $\{w_{a}\}_{a=1}^{n^2}$ be an orthonormal basis for a matrix. Assume we pick $m$ elements of this basis uniformly at random. $\Omega$ denotes the set of randomly chosen basis. With that, in matrix completion, the following restriction operator can be defined
$$
\mathcal{R}_{\Omega}(X) = \sum_{\alpha\in \Omega} \langle X\,,w_{\alpha} \rangle w_{\alpha}
$$
In the paper https://arxiv.org/abs/0910.1879, the following inequality is used
$$
\langle \mathcal{R}_{\Omega}\,X\,,\mathcal{R}_{\Omega}\,X\rangle \ge \langle X\,,\mathcal{R}_{\Omega}\,X\rangle
$$
If $R_{\Omega}$ is a projection operator, the inequality becomes an equality. In general, I don't know why the inequality holds true. Is there some inequality involving $\langle X\,, \mathcal{A} X\rangle$ and $\langle X\,,\mathcal{A}^{*}\mathcal{A}X\rangle$? I will appreciate any hints or suggestions.
Comment: a vector is best correlated with itself.
Answer: Since I figured this out, I thought I will share it in case somebody runs into the same thing. For an orthonormal basis, this turns out to be actually easy. For general operator basis, things are delicate.
Vectorize $X$ and the basis $w_{\alpha}$ and rewrite the restriction operator as
$$
\mathcal{R}_{\Omega}\,x = WW^{T}x
$$
where $W$ is a matrix whose columns are the chosen basis vectors. With that, the left
side inequality can be written as
$$
x^TW(W^{T}W)W^{T}x = \sum_{i} diag(W^TW)_{i} b_i ^{2}
$$
where $b = W^{T}x$.
Now, if the sampling is with replacement, the matrix $W^TW$ is not identity. But it is a diagonal matrix where the diagonal entries tell us how many times a given basis vector is sampled. Now consider the right hand side of the inequality
$$
x^TWW^Tx = \sum_{i} b_i^2
$$
Now comparing the two sides, we see that the left inequality is greater since the diagonals of $W^TW$ are always greater than $1$(by construction). The equality holds if one changes the sampling condition, namely assume that a given basis vector is chosen only once i.e $W^TW=I$


Where does 1000 Amps save game progress?

Question: In what location on the filesystem does 1000 Amps store your progress through the game when you save in game?
Answer: Open this folder:
%appdata%\Macromedia\Flash Player\#SharedObjects\

You will find one randomly named folder, open it. From there:
localhost\program files\steam\steamapps\common\1000 amps\1000AmpsReWin.exe\

...has your booty.
Comment: Note: on a 64-bit system, it'll be `localhost\program files (x86)\steam\...`. Also, if Steam is installed somewhere other than Program Files (eg. on a separate partition), then it'l be `localhost\steam\...`.
Answer: These are all the possible save game locations:

Windows:%APPDATA%\Macromedia\Flash Player\#SharedObjects\{random}\localhost\games\Desura\Common\1000-amps\1000AmpsReWin.exe
macOS (OS X): ~/Library/Application Support/Brandon Brizzi/1000 Amps/
Steam: <path-to-game>/save
Steam Play (Linux): <Steam-folder>/steamapps/compatdata/205690/pfx/


Policy to maintain cleanliness

Question: In countries where littering is a problem and the regulations and rules alone cannot give the desired effect due to vary high population,large surface area,etc.. ,will it be effective if the government starts buying garbage on a price per kg basis?
(This money spent can be compensated by reducing the number of sanitary workers and other departments if this method proves effective)
Answer: How effective it will be in the end depends on how the policy is shaped and enforced exactly.
Buying garbage is in fact the same as subsidizing people to pick-up the garbage. In theory, by setting the subsidy at the appropriate level (where the marginal damage of an additional kg of litter on the street equals the marginal cost of picking up that garbarge and handing it in) one would achieve the "optimal amount of litering".
I do see a problem though,especially for the longer term. If people get paid for handing in their garbage, there are no incentives to reduce the overall amount of garbage, in fact people might be tempted to buy products that come with extra packaging so they can cash in on the garbage.
I think a better solution in the long term would be a tax on material that is likely to end-up on the streets.
Comment: By 'buying the garbage', I didn't mean to cut the taxes. In fact ,the money paid for the garbage will come from the taxes on packaging and other materials. So by buying the garbage back with the tax money collected from companies, people will be intended to hand over more garbage at the right place and the companies will try to reduce the packaging. Moeover, sanitary workers or any firm involved will be better motivated(more garbage handed over results in more money).

Policy to maintain cleanliness


Chains of ganglia on each side of the nerve cord belongs to the spinal cord

Question: One of my textbook says this: "A double chain of ganglia on each side of the nerve cord belongs to the spinal cord."
But the diagrams I saw on internet depict only one dorsal root ganglion.
I am unclear which is wrong my textbook or the diagram.
Answer: There are only single dorsal root ganglia on each side of the spinal cord, within the dorsal (sensory) root of the spinal nerves.  If it is specifically referring to dorsal root spinal ganglia, the textbook is presumably describing the bilateral anatomy as a 'double chain'.
In addition, the dorsal root ganglia develop in the embryo from neural crest cells, as opposed to neural tube cells. Thus, the spinal ganglia can be considered grey matter of the spinal cord that is translocated to the periphery: that is, they 'belong to the spinal cord'.
Alternatively, the textbook may be referring to the Sympathetic Chain of Ganglia, a 'double chain' whose two components lie either side of the vertebral column and spinal cord, and consist of nerve fibres emanating from its ventral roots.  Any decent textbook of Anatomy should be pretty clear about this.
For your interest, 'Wikipedia' describes the latter in part as follows:
Sympathetic Chain Ganglia.
The bilaterally symmetric sympathetic chain ganglia, also called the paravertebral ganglia, are located just ventral and lateral to the spinal cord. The chain extends from the upper neck down to the coccyx, forming the unpaired coccygeal ganglion. Each ganglion within this chain is either cervical, thoracic, lumbar, or sacral. Preganglionic nerves from the spinal cord synapse at one of the chain ganglia, and the postganglionic fiber extends to an effector, a visceral organ in the thoracic cavity, abdominal cavity, or pelvic cavity.
There are usually 22–23 pairs of these ganglia (which is interesting number in view of chromosomal numbers): 3 in the cervical region (cervical ganglia), 11 in the thoracic region (including the stellate cervicothoracic ganglia), 4 in the lumbar region and 4–5 in the sacral region, collectively known as the 'Sympathetic Trunk'.

I hope this helps to clarify things in an area which is clearly problematic to describe without a precise anatomical diagram.
Comment: Can someone please explain the down-vote: is the answer incorrect or incomplete?  And voting like that without explanation is akin to assaulting someone on a public street for no apparent reason.  Very cowardly.  State your case sir.


Account creation in private testnet vs mainnet

Question: When we setup geth private testnet, we define one genesis file. Suppose after mining 100 blocks I want to create one more account. In this case I will update the alloc key of genesis file with new account address. When I will restart the geth node, a new blockchain will be started because genesis file has been changed. So my question is "What happened when someone create the new account on livenet (mainnet)." Because a new blockchain is not started there. Correct me if I am wrong in any concept. Thanks in advance.
Answer: The accounts in the genesis file are a initialization to define the blockchain parameters, it is not the way used to create accounts ( in genesis file you define some account with some balances in a private chaine just to help you starting sending/receiving ethers). you could use a genesis file without any account.
to create a new account you use the ethereum's clients eth,geth..
for example : geth account new this has no relation with the genesis file.
read about account managment : https://github.com/ethereum/go-ethereum/wiki/Managing-your-accounts
Comment: Thanks a lot !!! Just one more question. Can Account created using personal.newAccount() be updated using 'geth account update'?
Comment: yes just add the account addresse


What is that change in tune called?

Question: I was listening to this song here.
At 3:49 I find there is something change in tune or tempo,
What is that transformation called? Is there any english term for this?
Answer: Instead of letting the song to end in the tonic (Fm) as it seems, the song chromatically ascends to the dominant (C) and recaps the hook (AbBbC Db Bb) in C as (CDE FD).
I didn't hear any tempo change but since the diminuendo phrase ends on a long note and the hook comes back vigorously through a subito glissando, it has the feeling of returning to the original tempo (tempo primo).
To create the effect, you just need to interrupt an ending with the chorus.  To accentuate it, set it in a contrasting key.
Comment: I would say the key change is done without modulation and that's the intentional effect.  But I think Chris is right, the term has a broader sense in popular music.
Answer: This is called a modulation, or more informally (as David indicated) a "key change."  It repeats some or all of the song as transposed to a new key.  It is very common in some styles of music (for instance, gospel music), and usually is used to add excitement or interest to a repeated section.  Some songs only have one, but others have multiple modulations.  This can result in a melody line far outside the original vocal range, so it requires either a limited original range for the original melody, or a singer with a particularly wide range.  Even in the case that the overall tempo doesn't change, modulation to a higher key literally results in a faster pace for the vibrations composing the individual notes.
In modern popular music modulations are most common near the end, usually travel a single whole step higher (at a time), typically repeat the chorus, and rarely return to the original key.  In classical music, on the other hand, modulations were common in the middle, were generally in the dominant or subdominant modes (a fifth or fourth up or down) or in the relative minor (three half steps down), often featured a new melody, and typically returned to the original key.
See this link for some good examples in popular music: Can You Take Me Higher?
...and here's how Bach did it: Bach Double Concerto

What is that change in tune called?


Why wavefunction becomes exponentially smaller during quantum tunneling?

Question: I am interested in quantum tunneling and I am wondering why the wavefunction of a particle would becomes smaller so that there is a slight possibility of finding it at the other side of a big energy barrier? Is there any interaction otherwise how can the wavefunction knows there is a barrier?
Comment: I mean, the presence of a potential barrier is what _defines_ an interaction between the object and some container, so... yes?
Comment: Do you want a "why" answer other than the fact that that's the solution of the Schrodinger equation? Do you want it at a lower mathematical level than that?
Answer: Wavefunctions are solutions of quantum mechanical  differential equations, with given boundary conditions for the problem at hand, i.e. tunneling:

Is there any interaction otherwise how can the wavefunction knows there is a barrier?

The boundary condition of a barrier defines the wavefunction by construction. It has been found that experiments validate this model and its predictions.
Comment: This answer does not really address the OP question directly.  Where have they misunderstood "interaction"?  What about the case when there are no boundary conditions, e.g. a smooth potential hump?
Answer: The classic step barrier is the easiest to solve but the general behavior holds for other functions.  The comment addresses the physics of your question, i.e. "the presence of a potential barrier is what defines an interaction".  This is the same for classical mechanics.  One could ask, "How does the earth know to move in an ellipse when gravity is there, is there an interaction"?
Specific details come from the math.  Schrodinger's equation is set up in each interval of the x-axis (assuming a 1-dim problem) with the appropriate value of V(x) in each region.  If the total energy is greater than the barrier there will be a modification of the wavelength in the region of the barrier.  If the total energy of the particle is less than the barrier then the wave number will become imaginary, cancelling the imaginary factor, i, in the exponential leading to a decaying solution.  If the barrier continues to exist for all space after it is encountered the decay will eventually cause the wave function to vanish, this is the phenomenon of penetration.  If the barrier is finite in extent then the particle will make it out the other side, tunneling.  It is fairly easy to derive the exact solution for this case since the potential is constant, they are exp(+ikx) and exp(-ikx), with appropriate boundary conditions.
Comment: So what's wrong with this answer?
Comment: Nothing wrong, it is a correct description of the mathematical model of tunneling.


Are there plans to get ATI stream SDK working properly on BSD?

Question: I have BSD functioning exactly as I would like for workstations/laptops.  I'm looking at getting in to OpenCL applications and would prefer to use BSD with fglrx or some workaround to get opencl working without doubling to cost to get Nvidia cards.  There were plans to get USB passthrough vbox OSE working on BSD for a while and I waited it out.  Great stuff btw.  I'm wondering about opencl on ATI.  I can't seem to find a definitive answer anywhere.
Answer: Since ATI and AMD does not even published binary drivers for FreeBSD, I doubt that they would do that for ATI Stream SDK.
Comment: Thanks.  I had just noticed that you could get some opencl support for nvidia through linux abstraction and the binary driver, so I thought I would ask.


C++ program to generate mnemonic seed, view/spend keys and wallet address?

Question: Is there a simple C++ program to generate a mnemonic seed, view/spend keys and a wallet address? The reason I am asking this is because I am working on an iPhone product and I require this to integrate Monero in Swift and Xcode. If you have a better solution please let me know.
Comment: src/wallet/wallet2.cpp, one of the generate functions.
Comment: Can't you just use the official C++ monero repo?
Comment: I am not good at C++ so I am not certain which ones I should use.
Answer: XMR is a bit clunky, but should get you rolling. Also look at http://moneroexamples.github.io/spendkey/.


Could Danzo use Kotoamatsukami on Sasuke to fight Tobi?

Question: Just when they stab each other there was clear eye contact. Danzo could have used it on Sasuke and make him fight Tobi, right?
Comment: For reference, I believe this question is referring to scenes from the Danzo vs. Sasuke fight in Naruto Shippuden episode 211, or Naruto manga chapter 480.
Answer: Danzo had just used the Kotaamatsukami at the Five Kage Summit, and I believe that the eye needed some time to regain the power, that's why he asks his subordinates to fight Tobi first. Then while fighting Sasuke he uses the other Sharingan (located in his arm)... He basically wanted to use the Kotoamatsukami against Tobi, because he was the main guy to be controlled.
Comment: Danzo states that even with Hashirama's cells, it can't be used more than once a day
Answer: Realistically speaking, Danzo still has to wait until he uses Kotoamatsukami again. But hypothetically, this wouldn't have much of a benefit. First off, during the fight Sasuke spammed the HECK out of his MS' abilities. Tobi even stated it himself. So, if Danzo used Kotoamatsukami, his only hope will be Sasuke's strong visual prowess. Which would probably be on the verge on blindness after a few attacks. Not to mention that Tobi has a way to counter pretty much all of Sasuke's MS abilities. So if he used Kotoamatsukami, it'd be kinda useless and would have to wait another time because he used it to try to kill someone who had no interest in his battle, but only Shisui's eye. Hope my answers reasonable. :)


How to fix the bone influencing other meshes

Question: I have boned a laptop and when I moved the bone for the screen, it goes fine, but a vertice on the laptop goes up or down all the time when i move the bone for the screen. How can I fix it though? I looked at it to see if there were any weight paint at that area but no.
Answer: In Edit mode, select the vertex, open the N panel, you'll see if the vertex is part of a vertex group it is not supposed to be part of, you can remove if from this group if you press the X button.

Blue doesn't mean the selected bone or group has no influence on these vertices, it might be a very low influence, to check the real zero influence in Weight Paint mode you need to display the Zero Weight option of the Viewport Overlays.


Why do the faces in my model become checkered when rendering?

Question: Could anyone help identify my setup error when rendering using cycles.  The model looks fine in the viewport shading window, but when pushed to the render tool it seems to introduce checkered faces.  This is after I've attached all the texture mapping outputted from substance painter.
Answer: My blunder.  Even though duplicated objects were hidden in my layer control, they still showed in the render.  deleted them and issue has been resolved!


How to add a calculated column which shows the modified date/time of an attachment?

Question: I have a list where each item has an attachment (or in some cases 2 attachments). I would like to add a "Last modified" column in a view which shows the date/time of the last attachment modification. I do not want to show the date/time of the record its self - only the attachment(s). How can I accomplish this?
Answer: There isn't anyway to do this in the UI or SharePoint Designer.  You would need to create a custom Visual Studio solution.  A couple things you could do in Visual Studio: 1) create a Visual Studio workflow that runs each time the item is edited to get the information, or 2) create a list event receiver that accomplishes the same thing.


What is the term used to describe the number of times a pointer can be dereferenced?

Question: For example, which term completes the sentence "p has 5 ____" in order to describe a situation like int *****p?
Comment: "Levels of indirection". (See https://en.wikipedia.org/wiki/Fundamental_theorem_of_software_engineering)
Comment: Why do you need a specific term? If, for example, in some documentation, you write "p can be dereferenced 5 times" or "p can be dereferenced over 5 levels" does not make a huge difference in length or clarity".
Answer: Levels.

A pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer.
A pointer is generally initialized as:
datatype *variable name;
This above declaration is a single pointer but there can be more than this. This is called levels of pointers. According to ANSI C, each compiler must have at least 12 levels of pointers. This means we can use 12 * symbols with a variable name.
Level Of Pointers in C/C++:
Level of pointers or say chain can go up to N level depending upon the memory size. If you want to create a pointer of level-5, you need to precede the pointer variable name by 5 asterisks(*) at the time of declaration.
How many levels of pointers can we have in C/C++ - geeksforgeeks.org

See also

C++ Pointers: Number of levels of Indirection, and
ANSI C allows for up to 12 levels of pointers. Why would you ever use more than 3 or 4 levels?

Just to be clear, this 12 thing they keep going on about is just counting how many *'s you can use in one go. But you can stick it in a loop and dereference as many times as you like.  Well, so long as the value you find there never sends you outside of addressable memory.
Comment: The term "level" isn't wrong, but to use it for the OPs case, one would still have to write "we can dereference this pointer over 5 levels". And for this, I don't see any benefits in comparison to "we can dereference this pointer 5 times". Saying "this pointer has 5 levels", however, is probably not clearly telling anyone what was meant.
Comment: Well 'level' alone is a shortcut and is not sufficient, and geeksforgeeks is not really autoritative. 'Level of indirection' would be more accurate and less ambiguous imho.
Comment: @Christophe adding "indirection" is as redundant as adding "dereference". Also, I'm showing usage. I don't recognize anyone as having authority here. It's called what it's called. That's how language works.


How do i replace an apple ID on a used iPhone 4?

Question: I have given my dad my old iPhone 4, and I bought a new 4S. He put a new sim card in and used the phone but now 'his' contacts have appeared on my new iPhone i.e. the old phone retains my apple id.
How can I 'erase' my apple id from the old iPhone and reinstate it with my Dads apple id ?
Answer: Important to note that there are two apple IDs that can be linked to phone.   One for App Store purchases and one for ICloud.   Just remove account from iCloud menu and settings and add the account to new phone.  Best to make an Itunes backup of old device before you do that.
If you want to clear phone going to your dad can also Erase all Content and Settings in Reset option of the General Settings menu.  (After backup and checking that everything you need is on new phone)
Answer: First: clear your dad's iPhone from your AppleID.
Second: login into your AppleID and remove the iPhone 4 from your devices list
Third: create a new AppleID from this link: https://appleid.apple.com/account
More info : http://support.apple.com/kb/ht2731
Lastly: set created new AppleID on your dad's iPhone 4


Pogo pins for RF?

Question: Are pogo pins (e.g. this one) suited for 1 GHz?
Comment: CPU sockets use pins (not sure if pogo). A lot of them are IO..So HF is possible
Comment: Is this for an RF application or a digital one at 1 GHz?  And note that almost all RF applications/interfaces even into the multi-GHz range are really single ended.
Comment: I see no showstopper. But consider that GHz is always differential, i.e. it can be only considered together with the return conductor. So at a minimum you need 2 such pins. But it could be difficult to control the line impedance with pins. Ideally the manufacturer provides impedance ratings for certain pin types at certain distances.
Comment: Not digital, analog. I need to pass through this fast pulses with a spectrum between 200 MHz and 1-2 GHz. The source of such pulses is a small silicon device, and the idea is to connect it straight to the input of an integrated RF amplifier using one of these pogo pins. So the distance between the source and the amp would be about 3-5 millimeters.
Comment: Do you know of any application? For example, I know some Apple connectors use pogo pins but I cannot find if this is for DC power only, or also high speed data.
Comment: @SteveSh single-ended still needs two conductors at RF. With differential I just wanted to emphasize this fact. Both conductors must be laid out with well defined spacing.
Comment: @user171780 - I would look for a pogo pin that's characterized at the frequencies, 200 MHz - 2 GHz that you're concerned about.  S parameters are what you're looking for.
Answer: I use similar short smt pogo pins for 30db RF amplifier test at 894.75MHz working very well, make sure UUT (Unit Under Test) is well grounded.
Without prior RF knowledge our first design used longer touch type, vs solder on, pogo pins and ended up with bad values and over running current. At the recommendation from our customer we redesigned with the shortest SMT pins we could find and works very well. Simple input Vcc and inject a signal/read gain using Rhode and Schwarz ZVH8 in S21 mode with 30dB attenuation on port 2(Cal>Other>Normalization, so we read back actual value). Of course alternative equipment can be used.
Good Luck!

Pogo pins for RF?


Can electrons be converted into photons?

Question: In cathode ray tube electrons hit a fluorescent screen. Then photons are emitted. But where did electrons go after they hit the screen?
Comment: Into the screen material, then to ground. The photons come from energy deposited by the electron as it is slowed to a stop in the screen.
Comment: Conservation of charge forbids the conversion of an electron into a photon.
Comment: There is a grid at the front of the screen that collects electrons, and keeps the screen from building up a large negative charge.  These electrons are pulled away from the screen by associated circuitry.
Comment: @BenCrowell Why not present that as an answer.
Comment: You can run your hand past the front of a recently turned off CRT and feel the static electricity.
Answer: The way that these cathode ray tubes work is through the attraction of negative electrons to the positive anode.  The focussing anode accelerator accelerates the electrons to the phosphor in which the incident energy is absorbed and then transferred to the photons which emit the beams of light.

The electrons themselves are absorbed into the phosphor screen. Residual electrons scatter randomly and eventually end up but collected again by the anode and sent back to the circuits electrical ground.


oil for cooking eggs

Question: I want to cook eggs and I want to know the amount of oil that I have to add for 4 eggs.
The eggs' weight is about 75-80gr.
Comment: How are you cooking them? What kind of pan? Most people don't measure for something like this; usually it takes a thin coating, and if they stick, it wasn't enough. But it depends!
Comment: This question is meaningless without details; it's possible to cook eggs without *any* oil. Closing.
Answer: Assuming you are talking about fried eggs, use a non-stick pan, and use just enough fat to coat the pan. If you're using an oil, don't measure, just use a few drops, and make sure to spread it thinly on the pan. You could also use cooking spray. The key is having a really, really slick non-stick pan. No pan with any kind of texture will do.
For scrambled, the same is true, but I'd suggest using butter, and just a little more than you need. For 4 eggs, I'd use about a teaspoon of butter. Of course, I also add whipping cream to my scrambled, do it over a double-boiler, and often finish with a small amount of melted butter on top as it is. Here, you want to really keep the eggs moving to keep from sticking.
If you're talking about another cooking method, please be a little more specific.
Answer: if you are using olive oil, use little. Perhaps a half spoon, at any rate enough to grease all the bottom of the pan but not enough to make a puddle. If you use too much it will make bubbles at the edges of your eggs and spatter everywhere, but mostly on your hands and shirt.
Answer: Where frying eggs is concerned, an important element, almost as essential as how much oil you use, is that the pan is heated and the oil is at the right temperature. Be sure to heat the pan and oil to a point where (1) the oil becomes very fluid and there is just a negligible amount on the bottom of the pan to swirl around freely and (2) the oil should spit if you flick some water in it.
I have a 12" anodyzed pan and it only needs about two teaspoons vegetable oil. If it's the kind of thing that concerns you, I find you can get away with less when you use peanut or sesame oil.

oil for cooking eggs


what's the meaning of ぎじゅつしゃ?

Question: There's s hotel resident asking the receptionist that the AC doesn't work .
so the worker told him
"スイッチをぎじゅつしゃ押してください"
I don't know what's the meaning of "ぎじゅつしゃ" here ?
Comment: The sentence is likely be in a instruction book for an air conditioner made in China. Making no sense to me. Could you get back to the original source?
Comment: Ah, may be not '押してください' but '呼んでください' isn't it?
Answer: ぎじゅつしゃ is in kanji 技術者, which means 'engineers' in general.
In this case most sufficient translation would be technical service or electricians.
And the original sentence would be

スイッチのぎじゅつしゃを呼んでください。

Call the electricians for the switch, please.
Then, the sentence makes a little sense.
Anyway get back and check with the source.

what's the meaning of ぎじゅつしゃ?


Semantics and implementation of side effects

Question: From a practical point of view, how do functional languages with formally specified semantics (like ML) handle side effects like printing? I'm aware of things like the IO monad in Haskell but I'm interested in how the actual primitives are encoded and implemented. Thanks in advance.
Comment: I'm not sure to understand the question. You want to know how printing is implemented? What do you mean by side effect. I searched it online and don't get much result.
Comment: I don't have a computer science background. I actually found the answer to my question. I think by side effect you mean something like the following (from wikipedia):  an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides returning a value.
Comment: Actually, I answer mostly questions about operating-systems and the interface between operating-systems and programming languages so this is a good question of interest for me.
Answer: Monads in Haskell serve two purposes.
A monad that is defined within Haskell is really a simulation of some computational effect in terms of pure (side-effect free) computation. After all, Haskell is a pure language.
The second use of monads in Haskell, as well as in programming language semantics, and many other languages, is to model external or primitive computational effects. Such effects cannot be defined within the language itself. They necessarily come from some external environment (hardware, operating system, virtual machine).
In Haskell the monad that gives access to external effects is IO. This is why the main program has the type IO () – so that it can actually interact with the external world through computational effects.
Under the hood, the Haskell compiler compiles pure code, including user-defined monads, to machine code that behaves equivalently to the pure code (with respect to a formal semantics). But it takes special care of code of type IO by compiling things like putStr to actual system calls that trigger real I/O (I am over-simplifying a bit, but you get the point).
The ML-family of languages differ from Haskell because they do not separate so cleanly the pure & effectful computations. In such "impure" languages, all computations happen in a single IO-style monad that gives access to all external effects (I/O, mutable memory, exceptions) all the time. And the fact that this is the case is not recorded in types. Thus, an ML computation of type int would really be something like IO Int in Haskell.
Of course, the programmer is free to define their own monads in ML to simulate various computational effects, just like in Haskell, but this is a bit irrelevant here.
You ask how the effects are specified in the formal semantics. There are several ways of doing it (transition semantics, algebraic semantics, abstract interpretation), and I am not sure that describing them here would serve a purpose. Please ask for further references if you'd like to know the details.
The important thing to understand is the relationship between the formal semantics, which is the mathematical model of computational effects, and the actual implementation by the language compiler, which converts source code to machine code that triggers computational effects by using the available hardware, possibly via some system calls. We want the mathematical model and the compiled code to match, i.e., the compiler should be correct with respect to the formal semantics.
Comment: As I said, there are several formalisms for reasoning about external effects. A recent one (apologies for self-promotion) is [Runners in action](https://arxiv.org/abs/1910.11629). It's got monads for extermal computation, but also programming concepts for virtualization and OS-style access to external effects.
Comment: I am afraid "pure language with IO capability" is a bit of an oxymoron, since IO makes it impure. But Haskell and ML are both polymorphic $\lambda$-calculi with IO.
Comment: If I understand correctly, Haskell handles side effects by building up a control flow graph (in the same fashion as `data Expr = ... | ...`) and the interpretation executes it in a meta-theoretic level, and IO is simply encapsulating the monadic structure of the abstract "graph"?
Comment: It's not clear from your question what are you asking. Are you asking how precisely Haskell and ML actually compile effectful code, or how computational effects are specified in formal semantics?
Comment: Phrases such "the interpretation executes it in a meta-theoretic level" do not mean a whole lot to me. Maybe try to explain precisely what you would like to know, in concrete terms.
Comment: I'd say my question is about the meaning of correctness in this situation, what calculus can one use to reason about the correctness of the external effects if the external environment is fundamentally impure? Thanks.
Comment: For the practical side, I'm also interested to know how one might extend the implementation of pure languages such as polymorphic lambda calculus to a pure language with IO capability.
Answer:
From a practical point of view, how do functional languages with formally specified semantics (like ML) handle side effects like printing? I'm aware of things like the IO monad in Haskell but I'm interested in how the actual primitives are encoded and implemented.

It is strange to lump ML and Haskell together in this question. Unlike Haskell, ML is not a functional language in the sense that you seem to be using the term here.
ML handles side-effects in exactly the same way that C or Java or almost any mainstream programming language does: it doesn't. It ignores them.
This is in contrast to Haskell, where side-effects are not possible at all. There are no ways to express side-effects in the Haskell 2010 language and there are no ways to express side-effects using the Haskell 2010 standard library.
Okay. There is a big asterisk attached to that paragraph.
First off, there are actually functions like System.IO.Unsafe.unsafePerformIO which allow you to use unrestricted side-effects. Note, however, that this function is explicitly placed in the System.IO.Unsafe module, and also note that it is not part of the Haskell 2010 Specification. So, there is already a double warning sign around it: first, you have the fact that it is a non-portable implementation-specific extension to the standard, and then you have the word "unsafe" in the module name.
These functions are considered to be "escape hatches" for emergency use by very experienced programmers working on performance-sensitive core libraries, they are not considered to be part of the normal toolset of a Haskell programmer.
In other words, using these functions is considered to be outside the realm of Haskell; whenever you use them, you leave all the protections and guarantees of Haskell behind.
Secondly, of course, there is the System.IO module, which is part of Haskell 2010. This is how you can perform I/O (the most general form of side-effects) in Haskell. Except, technically, you are not performing I/O using the System.IO module. What you are doing is describing purely-functional I/O Actions, and returning these Actions to the runtime.
The runtime then contains an impure evaluator for those Actions. So, the trick that Haskell uses, is that the programmer never performs side-effects. The programmer only describes the side-effects to the runtime, and the runtime then performs those side-effects … but the runtime is not considered to be inside the realm of Haskell and therefore is not bound by the restrictions of Haskell.
How the runtime performs those side-effects is considered to be irrelevant. That is what programming, in the end, is all about: abstraction and reuse. As long as I get a description of how to use some "thing", I don't need to know how that "thing" works internally … in fact, ideally, it should be impossible for me to figure out how that "thing" works internally (IOW it should be impossible to break an abstraction boundary).
Now, of course, most Haskell implementations are open source, so we can just check. E.g. GHC implements the I/O runtime at least partially in C and calls out to the Operating System's I/O routines. (In fact, GHC contains multiple different implementations of the I/O subsystem for e.g. POSIX vs. Windows or single- vs. multi-threaded Runtime System.) Other Haskell implementations are allowed to implement I/O differently. For example, I am assuming that the (now defunct) Haskell.NET did not implement I/O in C but in C#; similarly, I am assuming that the (now defunct) Jaskell did not implement I/O in C but in Java. I assume GHCJS implements I/O in ECMAScript.
In short, most Haskell implementations view the graph of I/O Actions generated by the IO monad as instructions to some form of abstract machine … in other words, they view them as a language, and they deal with them the way you deal with any other language: you either compile it to a language you know how to interpret, or you interpret it directly.


What are the alleged reasons for emergence?

Question: What are the alleged reasons for emergence? What explains emergence, what are the philosophical explanations for emergence? Does it indicate that there's gap in our knowledge, does it indicate that it's something that occurs regardless of whether we know everything or not, is it caused by something else than the lack of knowledge?
Comment: Have you read through [the SEP article on emergent properties](https://plato.stanford.edu/entries/properties-emergent/)?
Comment: Our policy is one question per question and general information questions are better addressed by reading encyclopedias. This sites takes more specific and pointed questions.
Answer: Emergence is a general concept and it seems you're concerned with it as a specific philosophical position regarding natural or social phenomena which is termed as Emergentism usually employed in philosophy of mind and related living creatures, self-organising systems, and complex systems:

Other varieties see mind or consciousness as specifically and anomalously requiring emergentist explanation, and therefore constitute a family of positions in the philosophy of mind. Douglas Hofstadter summarises this view as "the soul is more than the sum of its parts". A number of philosophers have offered the argument that qualia constitute the hard problem of consciousness, and resist reductive explanation in a way that all other phenomena do not.

Intermediate positions are possible: for instance, some emergentists hold that emergence is neither universal nor restricted to consciousness, but applies to (for instance) living creatures, or self-organising systems, or complex systems.

As for the root cause of such mysterious emergence, it mainly has three candidates:

Some philosophers hold that emergent properties causally interact with more fundamental levels, an idea known as downward causation.

Others maintain that higher-order properties simply supervene over lower levels without direct causal interaction.

All the cases so far discussed have been synchronic, i.e. the emergent property exists simultaneously with its basis. Yet another variation operates diachronically. Emergentists of this type believe that genuinely novel properties can come into being, without being accountable in terms of the preceding history of the universe.

Of course emergentism strives to be compatible with physicalism and the wiki reference also mentions it should not be considered as anti-reductionsm.
Answer: I'm not sure this will answer all your questions, but it might help.
Let's look at water as an example. As a molecule, it does not possess viscosity because that is a collective property of very large numbers of water molecules in close proximity to one another. You can therefore argue that viscosity is an emergent property of water molecules.
Similarly, a single water molecule possesses no surface tension- and neither do a large collection of molecules in close proximity to one another. However, if you furnish a water-air interface, then surface tension becomes manifest. It is emergent, in the sense that the collective behavior of a large number of individual molecules possesses a property that a single molecule does not.
Can a single water molecule experience gravity waves? Certainly not. Can a large collection of molecules in close proximity to one another experience gravity waves? No. If we provide a water-air interface? Still no- but if we add gravity, the answer becomes yes, and we get crashing surf. Same comments apply.
Comment: As Devil's advocate, couldn't one argue that since viscosity is a property of large assemblages of water molecules and not of individuals, that when we say "the viscosity of water" we are equivocating the word water;. We DON'T mean water molecules, but rather large assemblages of same. A grain of sand does not possess "sand dune-ness," but a sand dune is not an emergent property of sand. (Unless you want to argue that it is). Rather, sand is called by one name, and a pile of desert sand is called by another. If we said that "water dunes" have viscosity, the mysterious emergence would vanish.
Comment: ps -- In other words it's a problem of semantics, not of some (IMO) murky aspect of nature called emergence. There's only emergence because we use language that doesn't make the proper distinctions among things, collections of things, and even collections of things in particular contexts. For example a pile of sand on a construction site is not a dune. The same pile in the desert is a dune. The sand didn't change, the semantic context did. Nature didn't turn a pile into a dune, language did.
Comment: @user4894 That is a good point, thus I did upvote. The problem is that this does not fit well with reductionist ontology. If there are properties of systems that cannot exhaustively be explained by their components, they seem to have existence of their own in a non-trivial sense.
Comment: Your point's good too. I can't help thinking that nature doesn't have sand grains or sand dunes. It has quarks and atoms and such. Humans, due to our own limited powers of perception, see things at this intermediate level of rocks and apples and mountains, so we give these things names. Then we get confused and ask, How did these quarks turn into mountains? There's no mountain-ness in a quark. The question is an illusion. Nature doesn't name things quarks or mountains, we do. I can't help thinking emergence is a flawed concept due to how we use language.
Comment: Did you catch the linked discussion that preceded this? https://philosophy.stackexchange.com/questions/81417/whats-the-opposite-of-emergence/81429#81429
Comment: @PhilipKlöcking: I don't see reductionism or emergentism as ontologies, but as *modes of explanation*. It is not that quarks are 'more real' than atoms, but that they allow a model to work in more cases, to have invariant components that can for instance work at high speeds and fields, back to the big bang, as well as fit our everyday states. Strong emergence is properties *that can't be explained* by constituents. But scientists generally only consider weak emergence.
Answer: We had a relevant discussion here: Have philosophers speculated on how chaotic forces meeting together can result in order?
I would describe it as a kind of overlay of rules of thumb, where we find structures or units that are in some way persistent. This is fundamentally a kind of symmetry: for instance a cell has a persistence of order across time that the equivalent 'dead' molecules would not. To characterise living matter, we can define it as creating disorder to maintain order, ie 'eating', or harvesting the Gibbs free energy.
Complexity, which emergent behaviour is a subset of, occurs in systems that are between high order, and high disorder. A butterfly flapping it's wings can create a hurricane on the other side of the world because of sensitivity to initial conditions - a frozen world or one on fire would be far less likely to do that, than our warm wet world.
But it's us that makes a conceptual group of phenomena, that sees it as having emergent properties belonging to it, or an identity. It's a shorthand, to support computational traction, where fundamental dynamics can be neglected. For more on that, see: Is the idea of a causal chain physical (or even scientific)?


Unit testing for quantum programs?

Question: Does unit testing on real quantum computers make sense as any observation in the quantum system can cause the system to loose its superposition state?
Comment: I don't know about unit tests
- the probabilistic nature of quantum computers makes it hard to create deterministic tests.
 but you could verify if the circuit is correct in the mathematical sense.
Answer: From what I know, no testing framework exists yet for quantum computing. I searched approximately one year ago for one and did not find anything.
But this does not mean you can't test!
Below are the methods I ended up using when I saw that no specialised testing framework for quantum computing was out there in the wild.
Unitary simulation
This method can only be used for small circuits. It uses $2^{2n + 8 + 1}$ octets of memory, $n$ being the number of qubits used by the circuit. With 8Go of RAM, you can use this method up to $\approx 11$ qubits. A computer with 32Go of RAM can go up to $\approx 12$ qubits.
1. Circuits given by unitary matrices (no ancilla)
Imagine that some quantum algorithm requires me to implement the operation $e^{-iZ\otimes F t}$ for $Z$ Pauli $\sigma_z$ gate and $F$ a known Hermitian matrix.
I implemented this gate with a quantum circuit $C$ that does not need any ancilla qubit and I now want to check that my implementation implements correctly (maybe up to a given error) $e^{-iZ\otimes Ft}$. As the quantum circuit $C$ is assumed to act on a small number of qubits (remember, circuits are assumed small in this section), I can use a little linear algebra to compute the unitary matrix that $C$ implements.
Hopefully, some frameworks already implement the linear algebra part. For example qiskit has a unitary simulator.
The final test code would look like this in pseudo-code (as it is not specialised to one testing framework nor to one quantum computing framework):
import numpy

qubit_number = 5
absolute_error_tol = 1e-3
relative_error_tol = 1e-3

qcirc = get_quantum_circuit(qubit_number)
implemented_unitary = unitary_simulator(qcirc).get_unitary()
expected_unitary = numpy.zeros((2**qubit_number, 2**qubit_number),
                               dtype=numpy.complex)

assert numpy.allclose(
    implemented_unitary,
    expected_unitary,
    atol=absolute_error_tol,
    rtol=relative_error_tol
)

2. Circuit given by unitary matrices (with ancillas)
To test quantum circuits that require ancilla qubits, you should "separate" the ancillas from the meaningful qubits.
Here I assume that all the ancillas are pushed to the end, i.e. the last qubits are all ancillas. For example: $\vert x \rangle \vert v(x) \rangle \vert a \rangle$. If it is not the case, you will need to change the indexing of the example program at the end of this section according to your quantum register layout.
Now that there are ancillas we have something else to check: are all the ancillas returned to $\vert 0 \rangle$ at the end of my quantum circuit? In other words, the action of my quantum circuit on the ancillas must be the identity matrix.
The pseudo-code for this kind of quantum circuits:
import numpy

qubit_number = 5
ancillas_number = 3
absolute_error_tol = 1e-3
relative_error_tol = 1e-3

qcirc = get_quantum_circuit(qubit_number, ancillas_number)
implemented_unitary = unitary_simulator(qcirc).get_unitary()
expected_unitary = numpy.zeros((2**qubit_number, 2**qubit_number),
                               dtype=numpy.complex)

# The implemented_unitary is a matrix of size
# (2**(qubit_number + ancillas_number), 2**(qubit_number + ancillas_number))
# whereas the expected_unitary is of size
# (2**(qubit_number), 2**(qubit_number)). In order to compare the
# 2 matrices, we should "upgrade" the expected_unitary with identity matrices.
expected_unitary = numpy.kron(expected_unitary, numpy.identity(2**ancillas_number))

assert numpy.allclose(
    implemented_unitary,
    expected_unitary,
    atol=absolute_error_tol,
    rtol=relative_error_tol
)

Statevector simulation
For simulable circuits. It uses $2^{n + 4 + 1}$ octets of memory, $n$ being the number of qubits used by the circuit. With 8Go of RAM you can use this method up to $\approx 27$ qubits. A computer with 32Go of RAM can go up to $\approx 29$ qubis. Qiskit's online simulator ibmq_qasm_simulator can go up to $32$ qubits.
1. Circuit given by unitary matrix that use a lot of ancillas
The unitary matrix simulation method is usefull, but cannot be used for medium-sized and large quantum circuits because of its large memory footprint.
When the tested quantum circuit has a lot of "garbage" qubits (i.e. ancillas), a little trick can allow us to test it, even if the quantum circuit needs $n + a > 20$ qubits (where $a$ is the number of ancilla qubits and $n$ is the number of "interesting" qubits, i.e. the total number of qubits minus the number of ancillas).
The trick is the following: as ancilla qubits should be given in the $\vert 0 \rangle$ state and returned to the same state, the input space of your quantum circuit is reduced from $2^{n+a}$ (the number of input states possible when counting the ancilla qubits) to $2^{n}$ (the number of input states really possible as ancillas should always be given in $\vert 0 \rangle$).
This means that if $n$ is sufficiently small, you can simulate the action of your quantum circuit on all the $2^n$ possible input states, and verify that the output state is correct (ancillas back to $\vert 0 \rangle$, "interesting" qubits in the expected state, ...).
To compute the expected state of your $n$ "interesting" qubits, you have 2 ways:

Construct the unitary matrix of size $\left( 2^n, 2^n \right)$ that represent the expected evolution performed by your quantum circuit and apply it to the input quantum state.
Compute "by hand" the expected output quantum state.

For this kind of test, here is the pseudo code.
import numpy

qubit_number = 5
ancillas_number = 3
absolute_error_tol = 1e-3
relative_error_tol = 1e-3

qcirc = get_quantum_circuit(qubit_number, ancillas_number)

# The unitary matrix that your circuit should implement.
# Replace initialisation with your unitary matrix.
reduced_evolution = numpy.zeros((2**qubit_number, 2**qubit_number),
                                dtype=numpy.complex)

for state in range(2**qubit_number):
    # If state = 10 (base 10), do:
    # 10 -> 8+2 -> 1010 (base 2) -> |1010> -> vector of size 16 with zeros everywhere
    #                                         except in the 10th entry where there is a 1.
    qstate = integer_state_to_vector(state)
    expected_qstate = reduced_evolution @ qstate # matrix-vector multiplication

    computed_qstate = simulate(qcirc, input_state=qstate).get_statevector()
    # The compute_qstate is a vector of 2^{qubit_number + ancillas_number} complex values.
    # It should be the tensor product between expected_qstate and |0...0> (ancilla qubits
    # should be reverted to |0> at the end).
    ancilla_state_full_zero = numpy.zeros((2**ancilla_state, ), dtype=numpy.complex)
    ancilla_state_full_zero[0] = 1.0

    assert numpy.allclose(
        numpy.kron(expected_qstate, ancilla_state_full_zero),
        computed_qstate,
        atol=absolute_error_tol,
        rtol=relative_error_tol,
    )

Footnote: I think I missed some things, I will come back to this answer as soon as I have more time. Do not hesitate to ask me questions if something is not explained enough.
Answer: You can read Microsoft Guide on Q# unit testing:

As with classical programming, it is essential to be able to check
that quantum programs act as intended, and to be able to diagnose
incorrect behavior. Unlike classical programming, though, observing
the state of a quantum system and tracking the behavior of a quantum
program is not always easy. In this section, we cover the tools
offered by the Quantum Development Kit for testing and debugging
quantum programs. Unit Tests
One common approach to testing classical programs is to write small
programs called unit tests, which run code in a library and compare
its output to some expected output. For example, you can ensure that
Square(2) returns 4 since you know a priori that 2^2=4.
Q# supports creating unit tests for quantum programs, and which can
run as tests within the xUnit unit testing framework.

More at: https://docs.microsoft.com/en-us/azure/quantum/user-guide/testing-debugging
Answer: IBM offers online access to their quantum computer to test quantum programs. Here is the link: https://www.ibm.com/quantum-computing/technology/experience. You can use the portal to check your programs by running them on an actual quantum computer.
Comment: Hello and welcome to Quantum Computing Stack Exchange! Could you expand upon this answer? A link, along with details about how this specifically answers the question, would help this answer be more thorough.

Unit testing for quantum programs?


Suit Yourself (paper puzzle)

Question: For the occasion of my husband's 13th/52nd birthday the other day I created a few (somewhat) thematic puzzles. Most don't necessarily translate, but one was a pencil-and-paper puzzle I think folks here would get a kick out of. As typical for this sort of puzzle, the answer is a word or short phrase. Enjoy!
Comment: How on earth did you construct this? Not to mention, come up with the idea...
Comment: @KlaymenDK The idea was the easy part; it being a 52nd (ish) birthday, playing cards naturally suggested themselves, and the suits are a topic with a nice amount of semantic weight to them. Finding enough phrases was a matter of plumbing some pop culture and then doing a little bit of digging using Qat for the stragglers. As Gareth suggests, construction was also pretty straightforward; I don't want to say too much here to avoid spoiling anyone else, but I'll see if I can write something up sometime soon...
Comment: @KlaymenDK The idea's a very nice one, but the construction doesn't seem very difficult to me once you've had the idea. (This isn't a criticism; there's not that much relationship between how hard a puzzle is to make and how satisfying it is to solve. This was a fun one.)
Comment: @StevenStadnicki You may remember me from another time and place. I knew you as a Tilbury House resident, though only indirectly through someone else. Greetings from the wayback machine. :). Very clever puzzle, by the way.
Answer: I think the answer is

 SERGEANT PEPPER'S LONELY HEARTS CLUB BAND.

Here's a perfectly clear explanation:

What? Not perfectly clear? Oh, OK then.

 Each clue leads to a word, name, etc. containing SPADE(S), HEART(S), DIAMOND(S) or CLUB(S). In some cases (e.g., THE ART OF NOISE, HEARTHSTONE) it's slightly non-obviously hidden. This is found somewhere in the grid, with a gap where the suit name occurs. The letters in those gaps -- as is hinted at by the fact that each of these letters occurs in a row and column labelled by the appropriate suit, as shown by the horizontal and vertical lines in my beautiful diagram -- are the things we need, and read top to bottom they spell out BILLY SHEARS BAND.

I thought that was the intended answer, but OP indicated in comments that another step is wanted. Well,

 in the Beatles album Sergeant Pepper's Lonely Hearts Club Band (note the suits!) "Billy Shears" is apparently the leader of the band. So perhaps that band is the intended answer here -- though I'm not sure it quite qualifies as a short phrase.
Comment: Very close! But your answer is a final clue itself...
Comment: Nice work. I was trying to use letters suit-indexed into the words, not the gaps. No wonder it wasn't spelling anything (and why some didn't have letters). :)
Comment: Oh, there's meant to be another step? Well, rot13(gurer vf na npghny onaq pnyyrq Gur Ovyyl Furnef Onaq) but rot13(ur'f nyfb vzcyvrq gb or gur yrnqre bs Fretrnag Crccre'f Ybaryl Urnegf Pyho Onaq). That of course rot13(pbagnvaf URNEGF naq PYHO); is it rot13(FCYUPO) we're looking for?
Comment: That seems likely enough to be what you have in mind that I've put it into the answer.
Comment: That's the last step, indeed! Well done.

Suit Yourself (paper puzzle)


Expected absolute deviation greater than standard Laplace

Question: Could there exist a distribution, other than standard Laplace (probability density of the form $1/2e^{-|x|}$), on $\mathbb{R}$ such that $E[x]=0,E[|x|]=1$ and that
\begin{equation*}
E[|x-a|] \geq |a|+e^{-|a|}
\end{equation*}
for all $a \in \mathbb{R}$?
Answer: Consider a ReflectedGamma($b$, $c$) distribution (also known as a double Gamma distribution) with pdf $f(x)$:
$$f(x) = \frac{ |x|^{c-1} \space e^{-|x|/b}}{ 2 \space \Gamma (c) \space \space b^c} \quad \quad \text{for } x \in \mathbb{R}  $$
... but where the usual Gamma parameters $b$ and $c$ are chosen such that $b = \frac{1}{c}$. By this construction, the first two conditions are satisfied for all values of parameter $c$, namely that:

$E\big[X \big] = 0$

$E\big[\space|X| \space\big] = 1$

When $c = 1$, we obtain the special case of the standard Laplace distribution that is the reference subject of this question.
The following diagram plots our constructed ReflectedGamma pdf for different values of parameter $c$ (including the reference case of the Laplace when $c = 1$). Of note is the changing shape when $c < 1$ or $c > 1$:

Entering the pdf as:

... we can find $E\big[ |X-a| \big]$ as:

where I am using the Expect function from the mathStatica package for Mathematica.
The following plot compares:

the derived expectation $E\big[ |X-a| \big]$ for our ReflectedGamma($c$) distribution (ORANGE curve) when $c <1$  (here with $c = \frac{1}{10}$)

with the required lower bound $|a|+e^{-|a|}$ (BLUE curve) relating to the standard Laplace $(c=1)$:

As per the diagram (and numerically checked), $E\big[ |X-a| \big]$ for the ReflectedGamma (orange) EXCEEDS the Laplace lower bound for all real values of $a$, when parameter $c < 1$.
The answer is thus: YES - there do exist distributions (other than standard Laplace) that satisfy the required properties.
Formal Proof
The simplest counterexample I have found is from the family of Reflected Lomax distributions:
$$f(x) = \frac{1}{(1+|x|)^3} \quad \quad \text{for } x \in \mathbb{R}  $$
for which $E\big[ |X-a| \big] = |a|+\frac{1}{1+|a|}$. Assuming $a > 0$ without loss of generality (due to symmetry), we then have to prove that:
$$a+\frac{1}{1+a} \geq a + e^{-a}$$
or equivalently that $e^a \geq 1+a$ where the latter is a well-known exponential inequality. All done.
Comment: @SushantVijayan The density in `In[1]:=` is  $\dfrac{c^c}{2 \Gamma(c)}|x|^{c-1} e^{-c|x|}$ with $0< c \le 1$, and is your Laplace distribution when $c=1$
Comment: @SushantVijayan Strictly speaking *leptokursis* is really about the tails of the distribution. Even so, in your Laplace distribution (with variance $2$) almost $1\%$ of the distribution is in the interval $[-0.01,0.01]$.  With $c=\frac1{10}$ (despite variance increasing to $11$) more than half the distribution is in the interval $[-0.01,0.01]$, so it becomes more concentrated around the mean.  Meanwhile  in your Laplace distribution about $0.67\%$ of the distribution is above $5$ or below $-5$ while with $c=\frac{1}{10}$ about $5.86\%$ is that extreme, showing the heavier tails.
Comment: @SushantVijayan I have added a formal proof.
Comment: Thanks for the answer. Could you write out the double gamma density and the expected absolute deviation from a in Latex. I haven't used mathematica so am unable to quite get the expression. Do you think you could turn this into a formal proof?
Comment: It has a mean of $0$ and average absolute deviation of $1$ as requested, but has a variance of $1+\frac1c$  and becomes extremely leptokurtic as $c \to 0^+$
Comment: @Henry doesn't leptokurtic mean it becomes more concentrated around the mean than normal? In that case shouldn't this distribution be the opposite?


Using MPMoviePlayerViewController in SDK 3.2 for iPad

Question: I've developed an iPhone app that has been running MPMoviePlayer (pre 3.2 SDK) with no problems.  I know this is a newbie question, but how do I get a movie to play in the new MPMoviePlayerViewController.  I am only getting audio and wish to learn the new view controller.  I've ported my whole app over to iPad and everything else works fine except for video.  Could someone please show an example using the movie view controller?  Any help would be appreciated.
Thanks,
Comment: refer to http://www.devx.com/wireless/Article/44642/1954
Answer: NSURL* videoURL = [NSURL URLWithString:url];
MPMoviePlayerController   moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
[moviePlayer prepareToPlay];
[moviePlayer play];
//For viewing partially.....
[moviePlayer.view setFrame:CGRectMake(50, 200, (self.view.frame.size.width)-100 , 400)];
moviePlayer.view.backgroundColor = [UIColor grayColor];
[self.view addSubview:moviePlayer.view];

Comment: it works fine for all why don't for me...it plays only audio no visuals are there
Answer: You need to use MPMoviePlayerViewController, not MPMoviePlayerController.  Search the docs for MPMoviePlayerViewController.
Answer: Try this in your view controller:
MPMoviePlayerViewController* theMoviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
[self presentMoviePlayerViewControllerAnimated:theMoviePlayer];

This should get you started but check the MPMoviePlayerViewController Class Reference for detailed info.
Answer: change  this line:
MPMoviePlayerController  moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];

to
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];

you need the *
Answer: I've struggled all over the place with this - Apple's own MoviePlayer sample code doesn't play video, only audio.  It actually took me ages to figure out that it was playing audio because the sample airplane video they supply has NO AUDIO TRACK!!!  (So I click the button and get absolutely nothing.)
Thanks for all the suggestions here.  I finally found https://developer.apple.com/library/ios/#qa/qa2010/qa1240.html
and even that is an obscure-ish fix.
This works: in initAndPlayMovie after [mp release]:
[[self.moviePlayer view] setFrame:[window bounds]];// size to fit parent view exactly
[window addSubview:[self.moviePlayer view]];

Bon voyage and happy flying :)
Answer: I am pretty sure that its broken in simulator at present !  I get same behavior (no video but hear audio) with latest sdk and their own MPMoviePlayer sample code with Apples own video that Will play in iPad simulator using safari...   So bottom line video plays on simulator-ipad inside of Safari but Not from an app using MpMoviePlayer class.  Bug or feature, you decide. (I think its just broken).  release notes for this version have lots of changes going on in MPMoviePlayer class...


What are some good ICA packages for physiological data, like MEG?

Question: EEGLab doesn't work well due to the data being from a Neuromag MEG. Any thoughts for alternatives?
Comment: looks like BINICA (which is underneath Fieldtrip and EEGlab) is available, although the source code is very old
Answer: Fieldtrip implements ICA from EEGLab and works well with Neuromag (so far).

FieldTrip is the Matlab software toolbox for MEG and EEG analysis that is being developed at the Centre for Cognitive Neuroimaging of the Donders Institute for Brain, Cognition and Behaviour together with collaborating institutes. The development of FieldTrip is currently supported by funding from the BrainGain and the Human Connectome projects. The FieldTrip software is released as open source under the GNU general public license.
The software includes algorithms for simple and advanced analysis of MEG, EEG, and invasive electrophysiological data, such as time-frequency analysis, source reconstruction using dipoles, distributed sources and beamformers and non-parametric statistical testing. It supports the data formats of all major MEG systems (CTF, Neuromag, BTi) and of the most popular EEG systems, and new formats can be added easily. FieldTrip contains high-level functions that you can use to construct your own analysis protocols in Matlab. Furthermore, it easily allows developers to incorporate low-level algorithms for new EEG/MEG analysis methods.


Trace of Hermitian Matrix

Question: please tell me where I am wrong in the following chain of reasoning
1. trace of a matrix isn't affected by unitary change of basis
2. therefore trace of hermitian matrix is the sum of eigenvalues
3. if $U=e^{iH}$ where $H$ is hermitian,  then $U$ is unitary
4. $\det U=e^{i\times Tr{H}}$
5. But $\det U=1$.
6. therefore $Tr(H) = 2n\pi$ which I think is false
Comment: Note that the trace of _any_ matrix is the sum of its eigenvalues. See here: https://math.stackexchange.com/questions/546155/proof-that-the-trace-of-a-matrix-is-the-sum-of-its-eigenvalues
Answer: An unitary does not necessarialy have $\det U = 1$, we can only say that $|\det U| = 1$, which implies $\mathrm{tr}\, H \in \mathbf R$, which is correct, due to the fact that all diagonal entries of $H$ are real.

Trace of Hermitian Matrix


What is the expression of electrostatic energy density in dielectric medium?

Question: I read in my book electrostatic energy density is $ \frac{1}{2} \epsilon_0 E^2$, where $\epsilon_0$ is permittivity of vacuum and $E$ Is electric field in that region. But I want to know whether it is equally valid in dielectric medium too or do we need to replace $\epsilon_0$ with $\epsilon_r×\epsilon_0$, where $\epsilon_r$ is dielectric constant of the medium?
Comment: Actually expression you have given, is of electric field density, so you have to multiply with volume for energy.
Answer: We have $\vec{\nabla}\phi=\vec{E}$ and $\vec{\nabla}\cdot\vec{D}=\rho$.
The energy change due to the addition of a tiny amount of charge (density) $d \rho$ is: $$d U_e=\displaystyle{\int_V \phi d \rho~dV=\int_V \phi \vec{\nabla}\cdot d\vec{D}~dV=\int_V (\vec{\nabla}\cdot(\phi d\vec{D})-d \vec{D}\cdot\vec{\nabla}\phi)~dV}$$
Then the total energy is: $\displaystyle{\int\ dU_e=\int_V\int_0^D(\vec{\nabla}\cdot(\phi d\vec{D})-d\vec{D}\cdot\vec{\nabla}\phi)~dV=\int_V\int_0^D\vec{\nabla}\cdot(\phi d\vec{D})-\int_V\int_0^Dd\vec{D}\cdot\vec{\nabla}\phi~dV}$.
The first term vanishes when we integrate over the entire space (as it does in a non-dielectric media) and the only thing left is: $\displaystyle{\int_V\int_0^Dd\vec{D}\cdot\vec{E}~dV}$. Now in a linear medium: $\vec{D}=\epsilon_0\epsilon_r\vec{E}$ so $d\vec{D}=\epsilon_0\epsilon_rd\vec{E}$.
Back at the energy: $U_e=\displaystyle{\epsilon_0\epsilon_r\int_V\int_0^Ed\vec{E}\cdot\vec{E}~dV=\epsilon_0\epsilon_r\int_V\int_0^Ed\vec{E}\cdot\vec{E}~dV=\dfrac{1}{2}\epsilon_0\epsilon_r\int_V\vec{E}\cdot\vec{E}~dV}$
So indeed, you're right the density is: $\dfrac{1}{2}\epsilon_0\epsilon_rE^2$.
Note here that $\rho$ is the density of free charges.
Comment: Your final result for the energy of the electric field in the presence of a linear dielectric is correct. However the starting point is wrong: there is no $1/2$ factor in front of your first integral for $U_e$ in term of charge density and potential. For a correct derivation, one has to start with the expression for the increment of electrostatic energy in term of the increment of free charge and eventually integrating over the increment of the resulting  $\bf D$ field from zero to its final value. If the relation between $\bf E$ and $\bf D$ is linear one gets your final formula
Comment: But, $\displaystyle{U_e=\frac{1}{2}\int_V\phi\rho~dV}$ being the energy needed to bring all charges from infinity to the place where they belong; doesn't that amount to the same thing as what you said? ie: starting with the expression for the increment of electrostatic energy in term of the increment of free charge. Or maybe you can't do that, because all charges are free?
Comment: Nevermind, I've understood my error. It's corrected, thanks!!


Is it possible to do a complete image backup of an Android device via USB connected to a Windows PC without the Android device being rooted?

Question: I recently purchased a Nexus 7 tablet from Google and I also have a Samsung Skyrocket from AT&T. Neither of the devices is rooted. I'm not too enthusiastic yet about rooting either of them, especially since it voids warranties and severely limits support options. Is there a way to obtain a complete image backup of either (or both) of these devices via the USB port on my Windows computer? If so, how? Thank you!
Comment: If you're on ICS or JB, `adb backup` might be the way to do this!
Comment: @t0mm13b that will not be an issue, cuz Nexus 7 is JellyBean originally.
Answer: Most articles I have encountered where people wish to undertake a complete image backup of their device requires root. However I have come across an article written in How-To Geek entitled "How To Create a Full Android Phone or Tablet Backup Without Rooting or Unlocking Your Device".
The Article will take you throught the steps of :

Installing the Android SDK
Device Setup
Testing ADB
Backing up your device
Restoring a Backup

http://www.howtogeek.com/125375/how-to-create-a-full-android-phone-or-tablet-backup-without-rooting-or-unlocking-your-device/
The article concludes by saying the complexity of using the Android SDK to create and restore backups is a bit much for the average user.
Answer: This might help:  [GUIDE] Full Phone Backup without Unlock or Root
Although it is talking about Galaxy Nexus, but this method is completely compatible with your Nexus 7.


What will happen if I change the checkpoint data from bitcoin source code and try to synchronize the blockchain?

Question: Suppose I have a fully synchronized Bitcoin node running on my local machine and I change its checkpoints data apart from its genesis block and recompile the code. Now what will happen when I try to run the daemon, having older block data residing inside .bitcoin folder.
Is this what orphan block is?
Answer: Once a checkpoint block has been verified, it is not checked again. Changing the checkpoints will therefore not have any effect unless a checkpoint is added that is at a higher height than what you have synced.
If you also change the genesis block, it will think that the  databases have been corrupted and so it will attempt to redownload the entire blockchain. When it does, it will find that all of the blocks are invalid (because you changed the genesis block) and then it will just do nothing as it is unable to sync what it believes to be a valid blockchain.

Is this what orphan block is?

No. Orphan blocks are something else entirely and unrelated.
Comment: The question is changing checkpoints and not the genesis block, so your reply doesn't seem to follow.
Comment: what is i changed one block lets say block no 100 on source code and recompile the code when i am already synchronised with current block number in bitcoin blockchain
Comment: Checkpoints are not checked when you are fully synced, so changing a checkpoint should not effect your node.
Comment: Your comment here contains the answer to the actual answer, and your answer doesn't. Could you perhaps fold your comment into your answer?
Answer: Assume the following example. You already have a fully sync'd bitcoin node and you then build a new wallet by changing a single line from here :
Change this:
{295000, uint256S("0x00000000000000004d9b4ef50f0f9d686fd69db2e03af35a100370c64632a983")},

to:
{295000, uint256S("0x01")},

Recompile the code into a new wallet and run it on your already sync'd blockchain, but you will notice zero differences from the original wallet. Checkpoints only have an effect on nodes that have not yet synced up to the block height specified by the checkpoint. Therefore, if you take your custom built wallet and try to use it to sync a new blockchain, it will error out when it gets to block 295000 with the following error: forked chain older than last checkpoint (height 295000).
Essentially checkpoints prevent forked chains from being seen as the longest chain, since they will not be able to pass this error validation. Only new nodes and nodes that have not yet synced up to the block height specified in the checkpoint are affected.
To answer your second question, orphaned blocks have nothing to do with checkpoints. An orphaned block is the result of having two (or more) miners solve the proof-of-work challenge at the same time. Since only one of the blocks can be valid, both miners that solved the POW challenge race to notify all of their peers about the new block they found and the network temporarily splits as a result of half of the network thinking Block A is correct and the other half thinking Block B is correct. These types of splits are typically corrected in the next block, but can sometimes span more than one block if the competing chains both continue to solve their POW challenges at the exact same time (very rare but it has happened). This is precisely the reason why many exchanges and other payment services require a certain amount of confirmations before a deposit is considered valid. The more confirmations a block has, the more likely that it is the one and only valid block at that height.


Determine minimum and maximum number of leaves on a complete tree

Question: I want to determine the minimum and maximum number of leaves of a complete tree(not necessarily a binary tree) of height $h$.
I already know how to find minimum($h+1$) and maximum($2^{h+1}-1$) number of nodes from the height, but what about leaves? Is there a way to determine them knowing nothing but height of the tree?
Comment: Let's recall the definitions. In an $m$-ary tree, each node has at most $m$ children. In a complete $m$-ary tree, each node (except the leaves) has $m$ children, the leaves have 0 children. In other words, asking what number of children is is very relevant to the question.
Comment: What do you means with complete? Is the number of children specified (you only mentioned not binary)?
Comment: @narekBojikian _In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible._. the number of children is not specified but you can assume a binary tree.
Comment: But what do you mean then with "not necessarily a binary"
Comment: That it can be any kind of m-ary tree, i.e. a ternary tree, a binary tree or anything else. The number of children is the irrelevant part of this problem.
Answer: Hint:

 Try the case $h=1$.  What's the minimum?  What's the maximum?
Answer: For a given height (h) in m-ary tree, you can calculate first the max/main number of nodes and then calculate the leaves according to each situation:

To calculate the max/min number of nodes in m-ary tree use the following equations:

Maximum number of nodes: $\frac{m^{h+1}-1} {m-1}$
Minimum number of nodes: $(mh)+1$

Now you would use the following equation to calculate and find the internal nodes (I) from vertices (n)

$I = \frac{n-1} m$

You would have Internal nodes (I), and vertices (n). So finally you would use the following equation to find the leaves (L)

$L = n - I$


Current/Voltage sensing for wheelchair battery using arduino

Question: I am working on a project that requires me to monitor the power consumption of wheelchairs across a spectrum of different activities. (electric wheelchairs batteries are 2x12V)
To do that I am going to measure current flow using a split core hall effect sensor (link: http://www.amazon.com/Loulensy-Current-Transmitter-Transformer-Output/dp/B00LMPP01Q/ref=sr_1_72?s=industrial&ie=UTF8&qid=1432039609&sr=1-72) luckily I have spoke with the company and they will be able to provide me with a sensor suitable for a 12V power supply, and the output voltage is o-5V so I can interface it with an adrduino. To measure the voltage I was thinking to simply use a voltage divider to drop the voltage from 12V to 5V so I can measure it directly with the arduino.
To power my sensor and my arduino I was thinking to use a Li-ion battery pack i found on ebay (http://www.ebay.co.uk/itm/Super-Rechargeable-Protable-Li-ion-Battery-DC-12V-6800mAh-Lithium-ion-EU-Plug-/351353498255).
As data logger I was thinking to ust the Arduino ethernet board with the slot for the SD card.
The question is can I connect my battery directly to the arduino power jack and then use the Vin pin to wire the arduino to the breadbord so I can get the right voltage for my sensor?
Considering that I am not an expert in electronics I am not sure my components are the right one and if someone could point out if I am making a mistake it would be really appreciated. Thanks!
Answer: You should use a voltage regulator or dc-dc converter to use the 12V batteries. Regulator will regulate the voltage from 12 to 5V. You can use it to power both the arduino and the sensor or you can use the arduino to power your sensor.
Answer: I am not familiar with Arduino, but i do know something that might be very important to your application. You must sample the voltage and the current at the very same moment, otherwise the power is not V*I. And you must filter both of them to leave any PWM currents higher than your bandwidth is. Otherwise you will get almost random power readings


Sum Two Customer Formula Fields

Question: Is there a way to sum the value from two custom formula fields into a separate formula field?  I am trying to set up a prospect score in Salesforce based on the customer's lead source.  Due to the large number of possible lead sources, I could not put this formula in one field (it exceeded the 5,000 character limit).  As a result I split the formula in two and put it in two separate fields.  Now, I would like to add them together.  However when I add put (Leadscore1__c + Leadscore2__c) in my new field, Salesforce still tells me that my formula is too long.  Is there a way to add the values of these two fields together?
Answer:
Is there a way to sum the value from two custom formula fields into a separate formula field?

Yes.
You can just create another Formula field and add the other Formula Fields as you would do with any other field.
E.g., if I have two Formula fields as:

Formula1__c
Formula2__c

I can always create another Formula field say Formula 3 and use the other two fields in my formula editor, something as below.
<code>Formula1__c + Formula2__c
</code>

For limits issue, I would imagine that your other two formula fields already are near to the limits and thus when you combine it in a new formula, you run into issues.
You may like to refer to the TIPS FOR REDUCING FORMULA SIZE in this documentation which explains with examples to reduce the formula compile time size.

To correct formula limit errors, move parts of the formula into one or more secondary formula fields, and reference those in your main
  formula. The secondary fields don't need to appear on the page layout.

And if everything fails:

If all else fails, use a workflow field update

The document explains on the approaches as how you can reduce either your formula size or can utilize a workflow field update here.
Comment: Unfortunately, not true if the two combined formulas exceed 5000 compiled characters. See the KB in my answer.
Comment: Didn't notice the limit part in the question. Making updates to refer that.
Answer: Including one formula into another increases the second one by the size of the first one. Therefore, if the two formulas summed together would be more than 5000 compiled characters, they can't be used in another formula field. The best you could do (besides optimizing your code) would be to use workflow rules or processes/flows to calculate the values into fields. For example, you could make a new number field, then set up a process that sets the value of that field to the sum of the two formula values. You'll want to set this field as read-only so that normal users understand it cannot be modified. You can read more about the situation and resolution in the help topic Formula Field exceeds maximum number of characters (KB 000005456).

Sum Two Customer Formula Fields


Bonding CSST to electrical ground system

Question: I had a licensed natural gas tech/plumber install a new branch line using CSST to a new fireplace.  When I am asked him about bonding it, he said he had never heard of that before.  From everything thing I've read, bonding seems necessary (to avoid damage to the CSST from lightning strike or otherwise stray electrical charge).  What I can't wrap my head around is this: If the gas line is bonded to the electrical panel (circuit breaker service entrance) which is bonded to the water supply from the street (just a lead pipe (yes, we still have lead here) that runs through the ground), how is this different from the gas pipe which already is a metal pipe running through the ground?  It seems that the gas pipe is already grounded by virtue of being buried.  If I put what seems like an additional ground on the gas pipe, don't I run the risk of other charges on the grounding system running through the gas pipe to discharge instead of the water pipe?
Comment: Natural gas distribution is often done with poly pipe -- it could easily be the case that the riser coming from the ground to your meter is metal (and is wrapped or painted, ie electrically insulated, to protect against corrosion) but it quickly transitions to plastic and thus provides no meaningful grounding.
Comment: Here is a [video](https://www.youtube.com/watch?v=7QiNMnDdXQ8) that shows what CSST looks like and how ground bonding would happen.  This is not an attempt to answer - just to explain more about what is being asked.
Answer: The pipe only needs to be bonded at 1 place, usually this is at the meter. If it is bonded there the entire system is attached to a grounding bond and would be legal.
The gas pipe is bonded to prevent it from becoming electrified by a short. It cannot be used as a grounding electrode but the grounding electrode system needs to be attached someplace after the gas meter. I would check there as that is where the bond is usually located.
If you have lead pipes I would want to drive supplemental ground rods and get rid of the lead pipes (I hope you don't drink the water). The reason to have a pair of additional driven grounding electrodes is a good idea for what happened to a tract of homes in my area. All the old pipe was removed and new non metallic pipe installed. A customer called because getting shocked. I discovered she had no ground and the pipe was plastic up to the house. Their utility did this to every home and the only grounding electrode was the water pipe. After installing a pair of rods she quit getting shocked. If that same case happened to you your gas pipe would end up being your electrode not safe and a code violation.
Comment: The gas meter is inside the house and wasn't bonded.  I ended up clamping the black metal pipe before the CSST and running a #6 into the grounding system on the circuit breaker panel.  The city is in the process of replacing all the lead pipes so in the near future, I'll have to drive in a grounding rod and move the grounding wire from the panel over to this.  Thanks for the help.
Answer: I wouldn't touch the CSST with a 10-foot pole.  It is thin-walled, and any clamping method would risk puncturing it.
I would ground the chassis of the appliance, just as I might any large metal appliance whether it ran on wood fuel or steam!
Comment: Indeed, the manufacturer only specifies grounding clamps for the fittings and says never to clamp to the actual pipe under any circumstances.


Using © on a website when I don't own all the copyright

Question: I'll keep this brief. Currently, I'm working on a website and wish to put "© 2017 [My Site]" in the footer, but a fair chunk of the content will essentially be owned by others. I don't expect to have any legal issues with this, but would like to credit them in the footer. Would I also add "© xxxx - xxxx [Company]" or something else? I don't want to be claiming that I own the companies in question.
Answer: The normal practice, which you see in copyright notices of many books, is to give a copyright notice with the primary author and date of the complete publication and then to have a series of statements about specific portions that are copyrighted by others such as "The Poem Violets Are Red, Roses Are Blue" used by permission from XYZ author, copyright XXXX. The preface to chapter 2 used by permission from XKTD author, copyright XXX. The preface to chapter 3 was published by ABC author, with copyright XXX and is now in the public domain. The preface to chapter 4 follows the diagram from Joe Smith, et al., "Big Charts Are Cool", 45 Nature 456 (2015) and is considered to be "fair use" under [statutory cite to copyright law].
A more abbreviated version might have a copyright notice and then say "no claim is made to the material appearing in quotation marks which is quoted as "fair use" for the educational and literary criticism purposes."
Of course, if you can't make a notice like one of these, you are probably violating copyright law by using a fair chunk of content owned by others.
A formal claim of fair use is not required to do so, of course, and a de facto fair use claim can be clear from context, such as citation to a source and quotation marks without a statement that the material is used by permission which is almost always a condition of a license or other permission to use someone else's copyrighted work.


Conversion of X, Y values to different coordinate system

Question: Is there a way to convert coordinate X, Y values in SQL Server from one type of coordinate system to another using SQL Transaction? Like NAD83 State Planes to WGS 1984. My objective is to use a single ArcGIS web map to analyze and show X, Y values that has different type of coordinate system. I plan to convert or transform first the coordinate values to a common type of coordinate system like WGS 1984 before saving them to geodatabase.
Comment: duplicate? http://gis.stackexchange.com/questions/2723/is-it-possible-to-reproject-spatial-data-using-sql-server
Answer: It would be easier to add lat/long fields to sql, then bring them into ArcMap as an X,Y Event projecting them as the state plane they are. Then Calculate Geometry as Decimal Degrees for the new Lat/Long fields.
Another option is just bring in ID, X, Y fields, as an X,Y, define as STateplane, then set Dataframe to 4326 (WGS-84) export the points out using dataframe projection, then bring them back into arcmap, use add X,Y tool, then bring into sql, join, and update.
Answer: FME Desktop has a transformer (tool if you want to call it that way) that does exactly what you want to do. It is called AttributeReprojector it reprojects the values without having to create geometries then extracting back the coordinates. You can download a fully functional 14 days demo license. On the other hand if you are using ArcGIS and you have the interoperability extension, which is FME as well you might me able to do the same if the transformer is enabled in the ArcGIS interop extension. FME is avaiable from Safe Software website www.safe.com .
I forgot to add that you can read and write SQL Server directly with FME of course.