The Art of Computer Programming, Vol 4, Fascicle 2 typo?

Question: At the bottom of page 5 is the phrase "changes k to k ⊕ (1j+1)2". Isn't 1 to any power still 1 even in binary? I'm thinking this must be a typo. I sent an email to Dr. Knuth to report this, but I don't expect to hear back for months. In the meantime, I'm trying to figure out what this is supposed to be.
Comment: Arcane: Yes, Dr. Knuth stopped using email on 1/1/90. But there's an address for reporting errors in taocp. His secretary prints the emails and gives them to him. http://www-cs-faculty.stanford.edu/~knuth/email.html
Comment: Voting to close as "not programming related." Hehe, I kid.
Comment: For those of us who don't have a copy in front of us, to figure out what it is supposed to be we need a little more info
Comment: I didn't think Dr. Knuth /used/ email...
Comment: Adrian: I'm presuming that only people who have the book will answer the question.
Answer: This can be resolved by using the convention that (...)2 represents a bitwise representation. (1j+1)2 then consists solely of j+1 ones, rather than referring to an exponentiation. You can see this convention explained more explicitly in TAOCP Volume 4 Fascicle 1 at page 8, for example:

If x is almost any nonzero 2-adic
  integer, we can write its bits in the
  form
x =
  (g01a10b)2
in other words, x consists of some
  arbitrary (but infinite) binary string
  g, followed by a 0, which is followed
  by a+1 ones and followed by b zeros,
  for some a >= 0 and b >= 0.

[I have substituted the symbol alpha by g to save encoding problems]
Going back to your original query;
k ⊕(1j+1)2 is equated with k ⊕ (2j+1 - 1)
implying that (1j+1)2 = (2j+1 - 1): this holds because the left-hand side is the integer whose significant bits are j+1 (contiguous) ones; the right-hand side is an exponentiation. For example, with j =3:
(14)2 = (1111)2 = (24 - 1)
Hope that helps.
Answer: A list of known typos can be found on the errata page:
http://www-cs-faculty.stanford.edu/~knuth/taocp.html
Your reported typo is not there. If it really is a typo, you might be eligible for a cash reward from Knuth himself.
Comment: He doesn't actually do the checks any more, because it exposes checking account etc.  now you get a certificate.  Hardly anyone cashed the checks anyway: http://www-cs-faculty.stanford.edu/~knuth/news08.html


How to create a route like "/x/{*path}/y" in ASP.NET routing?

Question: I have routes like "x/{*path}" where the path parameter is used by the controller to navigate a tree structure to end up with a resource which is served to the client.
I would now like to extend this scheme in an orthogonal fashion with other controllers that provide other "aspects" of the resource such as meta-data or a thumbnail. It should be possible to add these other controllers so that the main controller does not have to be aware of their existence. I was planning to use routes like "x/{*path}/y" to index these aspects but the routing system will not accept such paths.
I could use a constraint to only match my additional routes if the path parameter ends in "/y" for example but then the controller would have to be aware of the "extension" added to be able to remove it when parsing the path - this is not acceptable.
Am I forced to write my own Route?
thanks!
Answer: Two solutions:

Use x/y/{*path} instead.
Continue using x/{*path}, but when you read the path parameter, check for the /y and act accordingly


Is it possible for extraterrestrial plants to produce oxidants other than oxygen gas?

Question: Oxygen is a byproduct of photosynthesis because photosynthetic organisms on Earth use water as the electron donor. However, the first photosynthetic organism emerged from ocean where chloride is also abundant. Considering that the electrode potentials of chloride and water are quite close, is it just a coincidence that photosynthetic organisms oxidize water instead of chloride?
Although oxidation of chloride can produce dangerous byproducts like chlorine gas and hypochlorite, further oxidation can turn them into perchlorate which is quite stable. Is it possible for extraterrestrial plants to produce perchlorate salts instead of oxygen gas, while extraterrestrial animals ingest perchlorate instead of breathing oxygen gas? My question is not limited to perchlorate, but can be extended to other oxidants like nitrates, permanganate.
Comment: "*first photosynthetic organism emerged from ocean where chloride is also abundant*" Actually, at the time the first life arose, the ocean water contained very little salts of any sort, chloride based or not. It took a few billion years of continental erosion to accumulate the salt (and chlorine) that is in the ocean nowadays.
Comment: And what would be the corresponding class of structural and energy-storage compounds instead of carbohydrates?
Comment: The same. Plants oxidize chloride to produce carbohydrates, while animals use perchlorate to oxidize carbohydrates. So animals can obtain both fuel and oxidants via eating.
Answer: I see a major problem: oxygen appears in a lot of organic molecules which are interesting for life, like carbohydrates, proteins, lipids and so on. This thanks to its 2 valence electrons, allowing it to be used both in between a molecule or at its end, by binding either with two different atoms or with a single one.
Chlorine, on the other hand, has a single valence electron, meaning that it can bind only with a single atom, thus necessarily at the end of an atomic chain.
This is why some alternative oxidative paths use sulfur.
You can still try to have an hybrid chemistry using both chlorine and oxygen, but you would need an efficient way to prevent competition between the two species when it comes to chemical reactions.
Comment: On the one hand, fair. On the other hand, the H in CHON is hydrogen, which also has the same single-bond issue. (That being said, having two backbone atoms of different effective radii is helpful sometimes.)
Answer: Considering that the electrode potentials of chloride and water are quite close, is it just a coincidence that photosynthetic organisms oxidize water instead of chloride?
No, it's not a coincidence. Chloride may be abundant, but water is way more abundant. And the point of oxidizing the oxygen in water is to crack the hydrogens off of it; oxidizing chloride doesn't get you the same benefits, unless the environment is highly acidic. Otherwise, you don't get hydrogen, you get elemental sodium or calcium or potassium, and nobody wants that!
Now, you might get organisms producing chlorine for other reasons, which can be cool, but it doesn't make sense as a feedstock for basic photosynthesis.
At least, not in a world dominated by close-to-neutral water.
If you are willing to go more exotic with your alien biochemistry and handwave a world where most of the liquid is HCl instead of H2O, then it makes perfect sense. That's a little hard to arrange, but you can get a similar effect with a sulfuric acid ocean--which is exactly what you would get if you cooled down Venus. Chloride and fluoride salts are not stable in sulfuric acid solution, so you do actually end up with a lot of hydrochloric and hydrofluoric acid, and it's much more plausible that you could get organisms using HCl as their hydrogen source for photosynthesis.
Leaving chlorine and chlorates behind, though, other complex oxidizers are entirely plausible. Oxygen itself, for example, is extremely poisonous to anaerobic life. Early oxygenic photosynthesizers got away with producing it because they could eject it into the environment where it diluted enough to not kill them for long enough to evolve increased resistance to it (while killing off their competition at the same time). Given that things like nitrates and phosphates are biologically useful materials anyway, it is not much of a stretch at all to imagine that life on a different world might decide to deal with oxygen toxicity by immediately locking up any liberated oxygen into other compounds, rather than just letting it diffuse freely. Hal Clement's novel The Nitrogen Fix posits that this is in fact the more typical state; the alien in that book is native to a world where plants all produce nitrate, animals eat or drink it, and nothing needs to breathe, and only contacted Earth after an apocalyptic disaster converted all of the oxygen in our atmosphere into nitrate, leading to the near-extinction of pre-existing complex life; until then, the aliens didn't consider Earth to show any obvious chemical signatures of advanced life! And nitrate does seem like the most likely form for oxygen to be bound in, simply because nitrogen, like oxygen, is extremely common in the environment and in biomolecules. Manganese, sulfur, and phosphorus could be used as well, but when those run out in the environment, there will always be more nitrogen.
Of course, if you happen to have a lot of sulfur in the environment, then photosynthesizers may just stick with hydrogen sulfide as their hydrogen source indefinitely, producing elemental sulfur as a byproduct, which animals would have to eat. This would have the side effect of steadily converting CO2 into carbonyl sulfide (COS) as the hydrogens from hydrogen sulfide are transferred into oxygen from CO2 during photosynthesis, producing excess water, and then carbohydrates are oxidized by sulfur to produce H2S and COS instead of regenerating CO2. Plants would then have to adapt to using COS as their main inorganic carbon source rather than CO2 in order to close the cycle.
On a sufficiently hot would, animals could breathe the sulfur, but that is getting into even more extreme speculative alien biochemistry. Hal Clement wrote another novel, Iceworld, about sulfur-breathing aliens whose equivalent of water is molten copper chloride!
Comment: While I'm not sure I agree with all of that, it's very well thought out. +1
Answer: Other elements have their quirks.
You can use chlorine, but it is very prone to free radical chemistry - unwanted cyclic  reactions that go on and on.
You can use fluorine but except as the ion it is very prone to stick on carbon "like glue" and go nowhere.  PFAS compounds, "forever pollution".  Very tough to work with biochemically.
You can use bromine or iodine, but there is almost nowhere they would plausibly be common.
You can use nitrogen, but it pairs up into nitrogen gas in preference to any other state.  Nitrates want to be TNT or ANFO bombs.  You don't want an exploding planet (probably ... though it always does wow the tourists).  And we do use it already in our planet's biochemistry anyway.
You can use sulfur, but it's not a very strong oxidizing agent; also, we use it in our biochemistry at a fundamental level already.
Your idea of perchlorates is one of the best options (oxygen and chlorine).  AND they are actually present on Mars, so we know it's possible without life.  Unless there's life on Mars, that is...
Comment: I do love the vision of growing explosive compounds, as energetically unfavorable as that might be. https://en.wikipedia.org/wiki/Water_gel_explosive
Answer: Sodium metal could be your carbohydrate equivalent
Photosynthesis on Earth uses H2O and CO2 and energy.  Modern plants store light energy as chemical energy.  Plants strip the hydrogen from the H2O and store it on the CO2 forming carbohydrate.  The oxygen is released.  Later the plants (or heterotrophs like us) reclaim that chemical energy by grabbing some of the O2 it let loose and combining it back, regenerating the H2O and CO2 and releasing the energy into some chemistry.
Let us imagine your plants do electrolysis of NaCl aka salt.  Radiant energy is used to produce elemental sodium and chlorine.  Energy is stored as sodium metal in the plant - maybe stowed in some greasy hydrocarbons.  Chlorine gas is released.
The world has an atmosphere full of chlorine gas produced by photosynthesis just as ours has a lot of oxygen gas.  When the plant wants to reclaim the energy or something eats the plants, the sodium metal stores are reacted with ambient chlorine gas to regenerate salt.
Other salts could be treated similarly - for example magnesium or lithium chloride could also be electrolyzed to the metal and chlorine gas.  I could imagine plants might evolve an end run around herbivores by switching their metabolism to produce a metal that the herbivores could not use.
Can you builders grok a plant whose tissues are silvery crystals with a greasy sheen, seen dimly through the yellow haze?
Comment: "Energy is stored as sodium metal in the plant - maybe stowed in some greasy hydrocarbons." I doubt the laws of chemistry allow it - when it comes to structural building blocks, sodium is too mobile and reactive for its own good. It makes a perfect choice for neural and muscular impulse conductivity (with K, Ca, Mg) for this very reason. Maaaaybe... if those plants develop a humongous brain?
Comment: "chemotrophs that get energy from iron or sulfur" but they are unicellular and they don't bring these elements inside their cytoplasma - they just use them as donors or acceptors of electrons. I still think storing excess sodium (at higher than the body fluid concentration) is a step too far for a plausible biochemistry, sodium is too mobile and too willing to get rid of its outer electron to "convince" it to keep it until needed. The only mechanism to use it as energy storage is to create a strong concentration gradient of sodium ion (battery-like behavior, which is not _that_ trivial).
Comment: @AdrianColomitchi - this creature would not build anything from sodium metal.  It would have energy metabolism and anabolic pathways separate.   There is much precedent: chemotrophs that get energy from iron or sulfur do not build their bodies from the iron and sulfur.  Their bodies are made of proteins and fats like ours.   The proposed organisms would do energy with sodium and chlorine, but build their bodies with more tractable molecules.


Selecting an entity reference once

Question: I am working on this project, parking management system. I have the admin populating the parking slots available in the building. Then an anonymous user visits the site, puts their details and those of their car, and then in drop down selects a parking slot. The parking slots are an entity reference fetched from what the admin populated. How do I make the system dynamically populate this dropdown so that the user only sees the empty slots? Like after they book slot A, I want it to disappear so that the next person booking does not see it in the dropdown list of available slots. This is to avoid two or more people booking the same slot. The image below shows the drop down am talking about.
Answer: I guess the Parking slot 1, Parking slot 2, etc. are nodes or fieldable entities. Most likely those nodes (or entities) have a boolean field which indicates if the parking slot is reserved already. For the sake of this example,
I call it field_reserved.
In this case you need to implement in a custom module a hook_form_alter().
I am going to write a pseudo code.
function mymodule_form_alter($form, $form_state) {

  // Check if the form id is the id of your form.

  // Use entity query that selects the node ids  of the nodes that are reserved.

  //Store the result in some array (let's say reserved_slots array).

  // With a foreach loop, check each select option id against the reserved_slots array of ids.

  //If such option exists, unset it.
}

Hopefully this gives you some guidance.
If you need a complete snippet, you will have to provide more data about your setup, like machine name of the fields, etc.

Selecting an entity reference once


Ubuntu 15.04 installation process doesn't load the keyboard layout I gave

Question: Note: This behaviour has been seen on Ubuntu Server, but it should be the same with the Desktop version.
On Ubuntu 14.04 Server installation process, if you set the English language, but choose the FR keyboard layout, the FR keyboard layout is loaded for the rest of the installation.
I just installed Ubuntu 15.04 Server, and during the installation process, I did the same thing:

English language
FR keyboard layout

But the FR keyboard layout is not loaded.
I did it twice to be sure. The fun part is that except my password, all the input I had to give were mapped the same way in the FR/US layout, but when the computer started, bam, wrong password, because I typed it with the US layout during the installation.
Why does Ubuntu 15.04 Server decided not to load the given keyboard layout?
Answer: Could it be that you have bound something to super+space keyboard combination? This is as far as I know the default "switch layout" binding and may be the reason.
It's also possible that you got both layouts when installing which would be fixed by System settings -> Text entry
Just delete the US layout and you should be good to go.


Why do PC bus frequencies often end in multiples of 33MHz?

Question: It seems like there are a lot of frequencies for different system buses that end in 33 or 66MHz. Is there a particular reason for this?
Answer: Once you have one subsystem operating at a multiple of a particular crystal frequency, it's convenient to use the same basis crystal for generating other frequencies. This changes the line of inquiry to "what was the first use of 33MHz in computers?", which may be some 386 processors or the PCI bus.
It's possible that the first supply of 33MHz crystals was for some radio purpose, but googling is not suggesting a ready answer.
Comment: Quite likely it is..
Comment: This would suggest that either fsb133 is really 132 or 133.33333
Comment: crystals ar mainly used a a reference clocks are usually come from a PLL oscilatior, thus overclocking is just a mteer of sendin some commands over the system management bus.
Answer: The exact number is not 33.0000MHz, it is 2^25 Hz, in lower power CPUs, it is 2^15. It is easier to implement a power of 2 counter than other arbitrary number.
Edit:
After digging into the PCI spec and the 486 datasheets, I didn't find any hard requirement for clock accuracy. The PCI spec allows operation from DC to 33MHz and the 486 requires only 0.1% stability from its clock source.
Comment: Do you have a reference for that?
Comment: Multiply by 4, round up for marketing.
Comment: Oh, awesome! Where does the 25 come from then?
Comment: 2^15 is real, though rarely for CPUs per se, but for real-time clocks. 2^25Hz I have never seen, though Farnell certainly list 33.0000MHz crystals...
Comment: The clock source is usually a quarz crystal, and 33.0 MHz is a common frequency where cheap crystals are available.
Comment: How does that work for 133MHz FSB?


Good way to handle ability usage within a multiplayer game?

Question: I have written a client<>server based multiplayer game and have finished the basics (it's a flash client written in actionscript 3). The next step will be implementing a system which will allow me to easily add abilities to the game.
The problem here is that an ability can do so many things. Eg. player A uses ability "repair" on player B, the following will have to happen:

Player A sends message to server informing about the action
Player A is now showing a "repair casted" animation on its own ship
The server has to inform all players near that ship A now has the "repair casted" animation
The server has to increase the "health" of player B because it has been repaired by player A
The server has to inform all nearby players that player B now has a different health value
The server has to inform all nearby players that player B should show the "being repaired" animation

That's just an example, a lot of things have to happen for 1 simple ability. I could go into every object and add lines of code just for this spell. However, that would become a mess when I need to add a lot (~50) abilities. Also notice that some abilities do whole other things than others, some will have to show animations, some won't. Some will have to damage, some will have to increase statistics, etc.
So, how is such "ability system" usually handled both client and server side?
Answer: On client side never do a thing without the consent of the server. So client should only send the request of an ability and an optional target or some value. Also client should have to listen server for any commands. On the other hand, server should implement a function or classes (whatever you feel comfortable) to control ability actions. Whenever a client requests an ability to cast ability function should be called. As first task, function should check prerequisites. If they fail, client should be notified. Otherwise, a use repair ability ok signal should be passed to client. Then the function finds and send required commands to any nearby ships while updating their statuses. This method will guarantee that abilities cannot be abused by clients.
To understand it check the following, this is for illustration of the method, so dont tell me its not good to use so many ifs.
Client
function massRepair() {
    server.send("USE mass_repair;"); //no decisions in here
}

function recive(command, target) {
    if(command=="USE mass_repair OK")
        massRepairAnim.gotoAndPlay(0);

    if(command=="ANIM mass_repair") {
        massRepairAnim.setTarget(target);
        massRepairAnim.gotoAndPlay(0);
    }

    if(command==/SET ENERGY [0-9]/) {
         value=getValue(command);
         setEnergy(value);
    }

    if(command==/SET HEALTH [0-9]/) {
         value=getValue(command);
         setHealth(value);
    }

    if(command=="ANIM self_repair") {
        selfRepairAnim.gotoAndPlay(0);
    }

    if(command=="USE mass_repair FAIL NOENERGY") {
        display("Not enough energy to use the skill");
    }
}

somebutton.click=function() { massRepair(); }

Server
function userMassRepair(Ship owner) {
    if(owner.energy<30) {
        send(owner, "USE mass_repair FAIL NOENERGY");
        return false;
    }

    owner.energy-=30;
    send(owner, "SET ENERGY "+owner.energy); //every data sent is absolute
    send(owner, "USE mass_repair OK");

   foreach(ship in owner.shipsInRange(100)) {
        if(owner.ally(ship)) {
             ship.health+=10;
             ship.send("SET HEALTH " + ship.health);
             ship.send("ANIM mass_repair "+owner.position);
             ship.send("ANIM self_repair");
        }
   }
}

Answer: It looks like a lot of things, but it's really just a permutation of several standard components. Most actions will consist of changes to intrinsic properties and some cosmetics to be shown on the client, and there are only a handful of different ways to do those.
You need something like the following:

a standard way of sending actions to the server, which allows for convenient extraction of arbitrary parameters (as each action may have some very specific arguments)
a message type from server to clients to start playing a specified animation on a specified ship
a message type from server to clients increasing the health value on a ship

Then your server code for the action you mention looks like this pseudocode:
if (message.type == REPAIR)
{
    repairer = message.actor;
    repaired = message.target;

    // Insert verification code here to check that the 2 ships are close enough,
    // that the repairer is entitled to perform this action, etc

    // Verification has passed: do the work
    broadcastToAllClients(new Message(type=PLAY_ANIM, target=repairer, value=REPAIR_CASTED));
    broadcastToAllClients(new Message(type=CHANGE_PROPERTY, target=repaired, proerty=HEALTH, value=5)); // 5 is the amount
    broadcastToAllClients(new Message(type=PLAY_ANIM, target=repaired, value=BEING_REPAIRED));
}

That is very easy to extend to any number of actions, and will just require a few extra message types to accommodate the different things that can change or can be displayed.


How to restrict Front-End Editor on a page?

Question: I am working on a site where the user can do everything from the front end. I am using the plugin from scribu called front-end editor. My problem, is that I have a dashboard page with all the options for the user and I do not want the user to be able to edit it. How do I restrict a page from being able to be edited by Front-End Editor. I have read the wiki on github for it here https://github.com/scribu/wp-front-end-editor/wiki/Actions-and-filters and can't find anything about restricting pages. Only categories.
Answer: From the GitHub-Wiki
The 'front_end_editor_disable'-filter
Use this filter if you want to completely disable the plugin for certain URLs.
Callback arguments:
bool $disable: The current state. Default: false
You can use conditional tags: Conditionals tags return bool true/false, which means, if you want to disable it on a page, simply use is_page(), as it returns true for pages...
Disable FEE on pages, as a (mu)plugin.
<?php
/** Plugin Name: (#73660) Disable Front Page Editor on pages */
function wpse73660_disable_on_author_pages( $disable )
{
    return is_author();
}
add_filter( 'front_end_editor_disable', 'wpse73660_disable_on_author_pages' );

Comment: Hi Kaiser, how would this look like then if I wanted to disable on a page titled "dashboard"?
Comment: @Ryan Have you read into [the Codex and Conditional Tags](http://codex.wordpress.org/Conditional_Tags)? There's `is_page()` and it takes an argument...


Why usb with root filesystem is not mounting on boot bootcode.bin not working

Question: Hi I am making this thread because someone pointed that my previous was not specific enough.
I am trying to move my root filesystem to external usb on my raspberry zero v1.3. I have additional raspberry pi 1B+ which I use for debugging cause it has regular hdmi output. I followed a few tutorials on how to do it an here are the steps i took:
Creating PRIAMRY partition via fstab on dev/sda called dev/sda1, then i formated the partition":
sudo mke2fs -t ext4 -L my_data /dev/sda1
Next step was mounting the partition in /mnt folder and copying root files to /dev/sda1
sudo rsync -axv / /mnt
The last thing I was supposed to do was changing cmdline.txt so that root=PARTUUID coresponds to the PARTUUID of dev/sda1 and at the end of the file I added rootdelay. And just before the reboot i changed /etc/fstab so that now it should mount my partition at boot now it says:
PARTUUID=My dev/sda1 UUID            /       ext4    noatime,nodiratime,defaults     0 1
And still no luck. After the reboot it says "waiting for root device PARTUUID=******************".
This is my /etc/fstab:
proc            /proc           proc    defaults          0       0 PARTUUID=39c0b0b1-01  /boot           vfat    defaults          0       2 PARTUUID=735ad48f-8226-cd40-8405-77d27761a4e7  /               ext4    defaults,noatime  0       1
This is my /boot/cmdline.txt:
console=serial0,115200 console=tty1 root=PARTUUID=735ad48f-8226-cd40-8405-77d27761a4e7 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait modules-load=dwc2,g_ether rootdelay=5
I was trying different configurations like root=dev/sda1 in both cmdline.txt and fstab files.
I tried using several more usb drives, like SSD or HDD even few pendrives. Still no luck. It acts like root is not mounting. I thought it was because of raspberry undervoltage so i bought external power supply for my hdd disk. Nothing changed.
Then I came across this usb_boot script. It moves all of the files from sd to usb, and changes cmdline.txt so that it points to root on usb. According to the creator and official raspberry pi website all i need after moving boot and root partitions to usb is sd card formated to fat32 and bootcode.bin file on it. But when I insert sd card to raspberry zero or b+ with only bootcode.bin it acts like there is no sd card at all. It just dont boot no matter what. All I need is move root to usb because it is going to be read/write server and i need higher capacity and durability. Why the bootcode.bin does not work and why usb drive is not mounting on boot when I use boot from sd and root on usb? Please help it is getting really frustrating I have been trying to fix this for weeks.
Comment: `PARTUUID=735ad48f-8226-cd40-8405-77d27761a4e7` isn't a valid PARTUUID ... root will likely be `PARTUUID=39c0b0b1-02` - or use `UUID=735ad48f-8226-cd40-8405-77d27761a4e7` since that's the UUID of the root partition, not the PARTUUID
Answer: There are many things wrong with your Question, much detail missing.
There are 2 fundamental issues:-

735ad48f-8226-cd40-8405-77d27761a4e7 is NOT a PARTUUID
modules-load=dwc2,g_ether is incompatible with use of the USB for storage.

Frankly trying to use a Pi Zero with an external drive is a waste of time. You would be better to get a real Pi.
If you REALLY want to try boot the Pi, then use SD Card Copier to copy to the HDD, selecting the option to create a new PARTUUID, then edit cmdline.txt on the SD Card to use the PARTUUID of the copied HDD.


Correlation of a quadratic character with the Mobius function

Question: Let $p$ be a prime number and consider the sum $S(x)=\sum_{n\le x}\left(\frac{n}{p}\right)\mu(n)$. For how small an $x$ in terms of $p$ is it known that $S(x)=o(x)$?
I am especially interested in unconditional results.
Comment: Mobius randomness have gained much attention in the last couple of years (see Peter's notes in the IAS site), but your question is essentially equivalent to Dirichlet's theorem, and hence an effective version like you've asked for should follow from probably some effective proof of the PNT (with the L-function twisted by the quadratic character,  as done in Dirichlet's original proof).

Moreover you should quantify exactly the cancellation you want, little-o is an asymptotic term.
Comment: A quick computation showed that you will have $S(x) = o(x)$ whenever $x > \exp(C (\log p)^{10})$ with $C$ some large absolute constant. Is this the kind of result you are looking for? It seems to me that the power on the $\log p$ can be significantly improved (I have only used the simplest bounds).
Comment: In particular are you looking for *good* estimates, or just *any* estimates? If you are interested in *any* estimates (like the one I mention above) then I can post the proof...
Comment: Note that the mighty Generalized Riemann Hypothesis should give you the cancellation $o(x)$ whenever $x > C_{\varepsilon} p^{\varepsilon}$.
Comment: Thank you for your comments. Unfortunately it seems that for the application I had in mind any power of the logarithm bigger than $1+o(1)$ would be too big, but it is nevertheless interesting what is the smallest power one can obtain (unconditionally of course).
Answer: Wirsing's Theorem tells us that if $f$ is multiplicative and each $f(p)=-1,0 $ or $ 1$ then
$\sum_{n\leq x} f(n) = o(x)$ as  $\sum_{p\leq x} (1-f(p))/p \to \infty$ (and one cannot do much better). Moreover one can get an explicit upper bound:
$ \sum_{n\leq x} f(n) \ll x \exp( -.32\sum_{p\leq x} (1-f(p))/p)$.
In your case $f(n)=\mu(n)(n/p)$ so that
$\sum_{p\leq x} (1-f(p))/p = 1/p+ 2\sum_{q\leq x, (q/p)=1} 1/q $.
Therefore to get the bound $o(x)$ you need that a significant number of the $q\leq x$ satisfy $(q/p)=1$. So your question becomes: For what $x$ can we guarantee this?
Or, in other words, is it possible that $(q/p)=-1$ for "most" of the primes $\leq x$ (as may well be the case of one has a Siegel zero)?
If we use quadratic reciprocity, then $(q/p)=-1$ is equivalent to demanding $(p/q)=$ something fixed, and we can find such $p$ for which this holds  for all but one prime $q\ll \log p$, by Dirichlet's Theorem.  But then, by smooth number estimates, one knows that for almost all such $p$ one has $\sum_{n\leq x} \mu(n)(n/p) \gg \rho(A)x$ for $x=(\log p)^A$ (for each $A$).
So we have "proved" that for any fixed $A>0$, the estimate  $\sum_{n\leq x} \mu(n)(n/p) = o(x)$ does not hold uniformly for $x=(\log p)^A$.
The same ideas give, assuming GRH, that $\sum_{n\leq x} \mu(n)(n/p) = o(x)$ does   hold uniformly provided $\log x/\log\log p \to \infty$ as $p\to \infty$.
These ideas can   be found in my paper "Large Character Sums" with Soundararajan, though there we looked at character sums $\sum_{n\leq x} \chi(n)$; it should not take much to modify those ideas for this situation.
Answer: In general, we can take $x>\exp\{c_\epsilon p^\epsilon\}$ by the Prime Number Theorem for arithmetic progressions. More generally, one can use $L$-functions methods to relate $x$ to zero-free regions. In doing so it is hard to avoiding `losing logarithms'. The following elementary argument though, essentially due to Granville, does the job in an easier way.
Let $f$ be a completely multiplicative such that $|f(n)|\le1$ for all $n$ (so one can think that $f$ is a Dirichlet character), and assume that we know that
$$
\left|\sum_{n\le x} \Lambda(n)f(n) \right| \le Cx\cdot \frac{\log Q}{\log x} \tag{*}
$$
for all $x>Q$ (the size of $Q$ will depend on the available zero-free regions). Then we claim that $(*)$ holds for $\mu(n) f(n)$ too (with a different constant). Note that if suffices to show the result for $g(n)=\prod_{p^e\|n}(-f(p))^e$ (then one can use a convolution argument to pass to $f$). In order to show that $(*)$ holds with $g$ in place of $f\Lambda$, possibly with another constant $C'$ in place of $C$, we use induction, with the induction hypothesis being that
$$
\left|\sum_{n\le x} g(n) \right| \le C' x\cdot \frac{\log Q}{\log x} \tag{**}
$$
for all $x\le 2^m$. If $2^m\le Q$, this holds trivially (choosing $C'$ appropriately). Next, assume that $2^m>Q$ (and that $Q$ is large). Suppose also that that $(**)$ holds for $x\le 2^m$, and consider $x\in(2^m,2^{m+1}]$.Then
$$
\sum_{n\le x} g(n) \log n
  = \sum_{n\le x} g(n) \sum_{d|n} \Lambda(d)
  = \sum_{dm\le x} \Lambda(d) g(d)g(m) .
$$
We apply Dirichlet's hyperbola method:
\begin{align*}
\sum_{n\le x} g(n) \log n
  &= \sum_{m\le x^{1-\epsilon}} g(m)  \sum_{d\le x/m} g(d)\Lambda(d)
    + \sum_{1<d\le x^{\epsilon}} \Lambda(d) g(d) \sum_{x^{1-\epsilon}<m\le x/d} g(m) \\
&\ll \sum_{m\le x^{1-\epsilon}} \frac{Cx}{m}\cdot \frac{\log Q}{\epsilon \log x}
    + \sum_{d\le x^{\epsilon}} \Lambda(d) \frac{C'x}{d} \cdot \frac{\log Q}{\log x} \\
   &\ll \left( \frac{C}{\epsilon} + \epsilon C'\right) x\log Q
\end{align*}
Then applying partial summation and choosing $\epsilon$ and $C'$ appropriately completes the inductive step and thus the proof of $(**)$.
In the special case that $f(n)=(n/p)$, we know that
$$
\sum_{n\le x}\Lambda(n) \left(\frac{n}{p}\right)
= -\sum_{\substack{\rho=\beta+i\gamma\\L(\rho,(\cdot/p))=0,\,|\gamma|\le p}} \frac{x^{\rho}}{\rho} + O\left(xe^{-c\sqrt{\log x}}\right),
$$
(see e.g. eq (13), p. 120 in Davenport's book "Multiplicative Number Theory"). There is a $c>0$ such that the first sum has at most one summand with $\beta\ge1-c/\log p$, for which one then necessarily has that $\gamma=0$ (i.e. $\rho=\beta$ is a Siegel zero). The sum over the zeroes with $\beta\le 1-c/\log p$ can be shown to be $\ll x^{1-c'/\log q}$ for some absolute constant $c'>0$, using zero-density estimates (see e.g. equation (18.9) in p. 428 of the book "Analytic Number Theory" by Iwaniec and Kowalski). We conclude that
$$
\sum_{n\le x}\Lambda(n) \left(\frac{n}{p}\right)
= -\frac{x^{\beta}}{\beta} + O\left( x^{1-c'/\log p} + xe^{-c\sqrt{\log x}}\right) .
$$
So $(*)$ holds with $Q=1/(1-\beta)$ if $\beta$ exists and with $Q=p$ otherwise.
Comment: Thank you for your answer. Do you know what the known zero free regions imply for (*)?
Comment: @Alex: I added more explanations in the end to answer your question in more detail (and corrected some typos).


Dairy Farms in Wisconsin and Minnesota

Question: I'm looking to get a directory of Dairy Farms in Wisconsin and Minnesota and the approx. size of each farm in heads terms?
Any idea where can I get this info?
Answer: The Census of Agriculture, National Agricultural Statistics Service (NASS), and the ERS (Economic Research Service) branches of the USDA have most of the data you are looking for. However, I'm not sure if you can get down to the farm/number of heads level, although you should be able to get pretty close.
You can get a good feel for this here:
Ag Census Web Maps lets you mash them all up and get a better view (in my opinion). Here's a screenshot of Average Number of Cattle and Calves per 100 Acres of All Land in Farms: 2012
Lastly, try states agricultural services website; Wisconsin's has a directory
Comment: But this doesn't give me the directory of those farms, just aggregate figures.
Comment: the Wisconsin directory gives you exactly that. not to mention that i pointed out that i'm not sure if they give you such granular details in the usda data.

Dairy Farms in Wisconsin and Minnesota


Playing Trump in Rage

Question: If a player has two action cards and one trump card and trump hasn't been played yet, can they play their trump card or do they have to play an action card?
Answer: If you can follow suit, you must. Otherwise you can play any card you want.
In this situation, you can play any of your three cards. It doesn't matter whether anyone has played a trump or not unless it was the first suit that was played (trump was led) in which case you'd have to follow suit.
PDF of the rules

Playing Trump in Rage


Poincaré's inequality in Fourier space

Question: If $f\in C^{\infty}_c(\mathbb{R})$ is supported in the interval $[-R, R]$, then by means of the fundamental theorem of calculus one can show that
$$ \lVert f\rVert_{L^2(\mathbb{R})}\le 2R\left\lVert\frac{df}{dx}\right\rVert_{L^2(\mathbb{R})}.$$
Plancherel's theorem converts this inequality into the following:
$$ \tag{1}\left\lVert \widehat{f}\right\rVert_{L^2(\mathbb{R})} \le 2R\left\lVert \xi \widehat{f}(\xi)\right\rVert_{L^2_\xi(\mathbb{R})}.$$
Is there a way of proving (1) by working purely on the frequency space, avoiding the fundamental theorem of calculus? (I think that such a proof could be easily generalized to prove inqualities such as
$$\lVert \hat{f}\rVert_{L^2(\mathbb{R})}\le C_{R,s}\left\lVert \lvert \xi \rvert^s\widehat{f}(\xi)\right\rVert_{L^2_\xi(\mathbb{R})},$$
where $s>0$.)
Answer: As BaronVT notes, in order to do something in the frequency space, one has to translate the condition $\operatorname{supp}f\subseteq [-R,R]$ there. This is what the various uncertainty inequalities do. The classical Heisenberg-Pauli-Weyl uncertainty inequality
$$ \|x f(x)\|_{L^2}\, \| \xi \widehat f(\xi)\|_{L^2} \ge \frac{1}{4\pi}\|f\|_{L^2}^2\tag{HPW}$$
 immediately gives (1) because $\|xf(x)\|_{L^2}\le R\|f\|_{L^2}$ under your assumption. In order to handle fractional $s$ one needs a generalization of (HPW),
$$ \||x|^s f(x)\|_{L^2}\, \| |\xi|^s \widehat f(\xi)\|_{L^2} \ge C(s)\,\|f\|_{L^2}^2\tag{H}$$
Inequality (H) is a consequence of Hirschman's entropy inequality (proved here). Since  $\||x|^sf(x)\|_{L^2}\le R^s\|f\|_{L^2}$, it follows that
$$ \| |\xi|^s \widehat f(\xi)\|_{L^2} \ge C(s) R^{-s}\|f\|_{L^2}$$
as you wanted.
Comment: Thank you very much! This is exactly what I was looking for. I had a vague idea that (1) could be a consequence of some form of the uncertainty principle but I couldn't go any further than that.
Answer: Why only work in frequency space? The key fact is that, in physical space, the function is compactly supported, so you either have to translate that into a condition on $\widehat f$ you can work with, or just start from $f$ to begin with.
But, you can just iterate your first statement to get
$$
\lVert f \rVert \leq (2R)^s \left\lVert \frac{d^s f}{dx^s} \right\rVert
$$
so that $C_{R,s} = (2R)^s$.
Comment: The point is that $s$ is typically non integer.
Comment: If $s \in (k,k+1)$, you might be able to get this by comparing $|\xi|^s |\widehat{f}|$ to $|\xi|^{k+1} |\widehat{f}|$ and $|\xi|^k |\widehat{f}|$ for $|\xi| \leq 1$ and $|\xi| > 1$. Moreover, what does such an inequality demonstrate? As $s$ grows, so do $(2R)^s$ and $|\xi|^s |\widehat{f}|$ for $|\xi| > 1$. So, unless $\widehat f$ is concentrated around $0$, both quantities on the right hand side get larger as $s$ grows. I don't think this is the case though - compact support of $f$ will mean $\widehat{f}$ is entire, and has sub-exponential decay.
Comment: (if $\widehat{f}$ has exponential decay, this implies $f$ is analytic, which it can't be, since it's compactly supported)

Poincaré's inequality in Fourier space


Compiling PAR for Perl under Windows

Question: I've downloaded PAR from http://par.perl.org/wiki/Main_Page and compiled it after reading the README file. I've used dmake-4.12-20090907 instead of nmake ('cause 1.5 does not work) from http://search.cpan.org/dist/dmake/. No problems during the installing proccess (repeating the install proccess doesn't help farther, no warnings, just less text output), but there is no pp.exe or something similar.
I'm using Windows XP, all compilations were done on the c drive.
perl -v "This is perl 5, version 12, subversion 2 (v5.12.2) built for MSWin32-x86-multi-thread"
Comment: ActivePerl or Strawberry Perl?
Comment: Did you (try to) install PAR or PAR-Packer? I ask because pp(.exe) comes with PAR-Packer.
Answer: Check for the binary 'pp' under the location Perl\site\bin

Compiling PAR for Perl under Windows


Android : Network operations in Appwidget

Question: I'm developing a Android AppWidget for my application. For updating my appwidget I need to download data from network. But when I try to do that in onUpdate method, my appWidget is killed by Android system. I learnt that time consuming operations can't be done in receivers so I launched a service from onUpdate method and launched a thread from that. But still the problem persists.
Can anyone please let me know how to do network operations in Appwidget?
Answer: Delegate the download work to a service, probably an IntentService, possibly a WakefulIntentService depending on whether there is a risk that the device might fall asleep during the work itself.
Your AppWidgetProvider would just call startService() on your IntentService.
Your IntentService's onHandleIntent() method would do the work you presently have in onUpdate(), getting its own AppWidgetManager via the static getInstance() method. But, since onHandleIntent() is executed on a background thread, you can take as much time as you need. The IntentService will also automatically shut down once it is done with all outstanding work requests.
Comment: but how to combine that with use of RemoteViewsService? Should mentioned IntentService start RemoteViewsService after async operation is done?
Comment: @Malachiasz: "Should mentioned IntentService start RemoteViewsService after async operation is done?" -- no. `RemoteViewsService` will be automatically used by the app widget framework. You need to make sure that the `RemoteViewsService` is aware of whatever data changes were made by the `IntentService`, such as by the `IntentService` updating a database that the `RemoteViewsService` needs to pull from. There should be a way to get the app widget to then reload its views from the `RemoteViewsService`, though I have not researched this and do not know off the top of my head how it is done.


Can Ethernet II frame's Type be Layer1's or Layer4's protocol?

Question: The Ethernet II frame's Type field can be IPv4, ARP, so it can be Layer2 and Layer3's protocol.
This is a snapshot of frame captured by WireShark.

But I have a question, whether it can be other Layer's protocol? such as Layer1 or Layer4?
Answer: In theory, you could put anything you want.  But practically speaking, only certain types are defined.
IANA lists the defined ethertypes here.
Answer:
Can Ethernet II frame's Type be Layer1's or Layer4's protocol?

Neither. Ethernet II frames are layer-2 SDUs (a service data unit is the way data is packaged in that layer).
They most often carry (encapsulate) layer-3 SDUs (IP packets) which in turn often encapsulate layer-4 SDUs (TCP segments, UDP datagrams, ...) which in turn transport application-layer protocols.
Ethernet frames can also carry a multitude of other protocol payloads, including LLDP, STP BPDUs, or other layer-3 protocols (IPv6, IPX, NetBIOS, ...).
Layer 1 is the physical layer, defining physical transmission protocols like 1000BASE-T, and the cables, ports, ... that are used with it.
Answer:
But I have a question, whether it can be other Layer's protocol? such as Layer1 or Layer4?

First, as always, the network models (i.e. layers) are simply models for abstract concepts that help develop systems that are able to communicate with other systems. The Ethernet type field doesn't define or care about "layers." The purpose of the type field is so that the processes associated with removing the L2 headers from received data knows which process to hand the associated data off to next.
Think of it a bit as an apartment building. Your "L2 traffic" is received at the apartment building by address, but without some designation of which apartment it should go to, where does is go next? Sure, you could include a full name of the recipient, but a standardized number is more efficient. L2 doesn't care what sort of processing or delivery takes place once it is delivered to the correct apartment.
So, you could put in any value you want, but only certain types are defined and widely accepted.  This then begs the question of why you would want to put in a reference to a L1 or L4 protocol (assuming you mean a common L4 protocol such as TCP or UDP)? What would be the point?
There is no reason in modern networks that the L2 process would be removing the L2 headers and passing the associated data off to any L1 process. Things just don't work that way.
There is also no reason for a L2 process to hand off data directly to a L4 process such as TCP or UDP as they are written to expect the use of IP at L3. One could argue that the L2 data is passed directly to the application when certain protocols are in use (for instance STP, LLDP, etc), but again the L2 process doesn't care or need to know on which "layer" the next process is operating.


Streaming video from Android camera to server

Question: I've seen plenty of info about how to stream video from the server to an android device, but not much about the other way, ala Qik.  Could someone point me in the right direction here, or give me some advice on how to approach this?
Comment: I'd like to see an answer to this as well. Have you come up with anything yet?
Comment: I have a question related to this one that might be of interest to you as well. It's regarding pushing the video stream over 3g once you have video capture and container part done. http://bit.ly/vYpWGy
Comment: You can look into ffserver a component in ffmpeg.
Comment: Nope, gave up on streaming.  Just beating the MediaRecorder API into submission was tough enough.  You could check out the sipdroid code though, they seem to have gotten it working.
Comment: The Video code isn't in the Sipdroid source online though :(
Comment: I am also looking for a solution.. Found out one part Media Recorder API can be used to stream to server, Now what to do in the server.. Here is one of the  link http://www.mattakis.com/blog/kisg/20090708/broadcasting-video-with-android-without-writing-to-the-file-system
Comment: So, this is almost two years later, but this is still coming up in search results, so this could be useful to somebody: you can stream video from a Google Hangout.
Comment: Hi JCL, Can you give me some links which help me to stream video from the server to an android.
Comment: @JCL I want to stream video/ audio from url to an android device. Please prefer any link to get this. And Have a look into below link http://stackoverflow.com/questions/17268283/download-video-on-sdcard-from-url/17268343?noredirect=1#17268343
Answer: I have hosted an open-source project to enable Android phone to IP camera:
http://code.google.com/p/ipcamera-for-android
Raw video data is fetched from LocalSocket, and the MDAT MOOV of MP4 was checked first before streaming. The live video is packed in FLV format, and can be played via Flash video player with a build in web server :)
Comment: It gives me Errors.. like, java.lang.UnsatisfiedLinkError: Couldn't load teaonly: findLibrary returned null..

If anyone has solution then please share it. Thanks
Comment: @mpp: The app has NDK code. You can compile it yourself, or grab the .so files out of the apk that's in that Google Code project under "Downloads".
Comment: I'm also getting java.lang.UnsatisfiedLinkError error. Please briefly mention steps to remove that error.
Comment: For those not understanding the UnsatisfiedLinkError: you have to build the C code with the NDK. Simply put, run `ndk-build`. For more information, [read the NDK documentation](https://developer.android.com/tools/sdk/ndk/index.html#GetStarted).
Comment: why not upload the .so  file to libs folder
Comment: @pengwang Because its platform dependent you may have to compile it yourself
Comment: Here's a tip you can avoid the UnstatisfiedLinkError. Unpacking the ipcamera.apk, you'll find the two libs under lib/armeabi, put them into the source code project lib/armeabi. I've verified, it works.
Comment: If you are getting the NKD error, Google Android NKD, Download it and add it to your build path. Also in your project properties, (C/C++ build path) make sure it links to the correct nkd-build file (Put in your nkd-build absolute path if your unsure).
Comment: Flash is all but dead.
Comment: just gave you your hundredth UPVOTE.  hope it earned you a goldie badge.  great answer, tks for the share.
Comment: Does the app currently make it avaible to stream the android camera view to the webbrowser?
Answer: Took me some time, but I finally manage do make an app that does just that. Check out the google code page if you're interested: http://code.google.com/p/spydroid-ipcamera/
I added loads of comments in my code (mainly, look at CameraStreamer.java), so it should be pretty self-explanatory.
The hard part was actually to understand the RFC 3984 and implement a proper algorithm for the packetization process. (This algorithm actually turns the mpeg4/h.264 stream produced by the MediaRecorder into a nice rtp stream, according to the rfc)
Bye
Comment: Thanks a lot! Currently I cannot make it work right with h264.. and I can't change it to h263 (I have no clue of how to do that). anyway, thanks man!
Comment: I am using same but when it comes to stream on Android with rtsp, it says Video could not be played. I am using VideoView. Can you please help?
Comment: Works great (so far!) I'm using it to stream video from Glass (after a bit of work/editing/figuring out), but so far I can only get it to connect from a Windows based browser (Chrome) with the vlc plugin. VLC on Android/iPad or any other rtsp player won't pick up the stream (one of them looked good, but was trying to get a stream based on the device name, which this code returned as 0 and thus unfindable). Still, getting results after a day of coding thanks to you, so kudos!
Comment: @MacD Do you use the spydroid-ipcamera code (all the project or only some classes? Can you tell me?) or this library https://github.com/fyhertz/libstreaming for streaming in Google Glass? Thanks a lot!!
Comment: Hi could you explain how to implement this project in android studio I cannot make it run
Answer: I'm looking into this as well, and while I don't have a good solution for you I did manage to dig up SIPDroid's video code:
http://code.google.com/p/sipdroid/source/browse/trunk/src/org/sipdroid/sipua/ui/VideoCamera.java
Comment: What they have done over there is they stream using RTP packets to a server.Now the question is what is being done on the server? what does the trans-coding and how is it getting streamed
Comment: Nope.. I didn't go for the SIPDroid Approach, it was too complex.. I then did something with a MJPEGServer
Answer: I've built an open-source SDK called Kickflip to make streaming video from Android a painless experience.
The SDK demonstrates use of Android 4.3's MediaCodec API to direct the device hardware encoder's packets directly to FFmpeg for RTMP (with librtmp) or HLS streaming of H.264 / AAC. It also demonstrates realtime OpenGL Effects (titling, chroma key, fades) and background recording.
Thanks SO, and especially, fadden.
Comment: @dbro I try to learn about your service, but you require my login information before I can see your pricing. It's as if you guys are collecting email addresses. If that's not your intention, you should make pricing info available: the same way Parse and App Engine and many others have done.
Comment: can it stream to any HLS-capable client (not to your server only)?
Comment: Is it possible for a Video camera to send a video to Kickflip then it goes to android phone? If es which type of  Video Camera is suitable for this
Answer: Here is complete article about streaming android camera video to a webpage.
Android Streaming Live Camera Video to Web Page

Used libstreaming on android app
On server side Wowza Media Engine is used to decode the video stream
Finally jWplayer is used to play the video on a webpage.
Comment: This uses closed-source components. Any open-source alternatives?
Comment: You may use JavaCV for this I used it in my project to make live streaming from android device to wowza media server  also you can use https://github.com/begeekmyfriend/yasea
Comment: is libs streaming free?
Comment: can we use sound card device as input audio source and not mic in libstreaming.
Answer:
I am able to send the live camera video from mobile to my server.using this link
  see the link
Refer the above link.there is a sample application in that link. Just you need to set your service url in RecordActivity.class.

Example as:
 ffmpeg_link="rtmp://yourserveripaddress:1935/live/venkat";
we can able to send H263 and H264 type videos using that link.
Comment: I have used the code using the above link, but couldn't even able to start recording. getting an exception "No Video to Stream". Do you have any idea regarding this?
Comment: @AkhileshSk by using the above code u can send the live video through rtmp url to your server. it is not for recording purpose. if you want to record the video u need to record it at server side.
Comment: Hey @ Venkat is it possible to send a live video from a Camera to Android phone , do you have some code links , like using Youtube live etc
Comment: @LutaayaHuzaifahIdris yes its possible. I worked previously on this.
Comment: Hi @Venkat can you help me out with this, not able to find the RecordActivity.class file
Comment: hi venkat the above code is very old it is not building iam getting errors while building the code
Answer: Check Yasea library

Yasea is an Android streaming client. It encodes YUV and PCM data from
  camera and microphone to H.264/AAC, encapsulates in FLV and transmits
  over RTMP.

Feature:

Android mini API 16.
H.264/AAC hard encoding.
H.264 soft encoding.
RTMP streaming with state callback handler.
Portrait and landscape dynamic orientation.
Front and back cameras hot switch.
Recording to MP4 while streaming.
Answer: Mux (my company) has an open source android app that streams RTMP to a server, including setting up the camera and user interactions. It's built to stream to Mux's live streaming API but can easily stream to any RTMP entrypoint.
Answer: Depending by your budget, you can use a  Raspberry Pi Camera that can send images to a server. I add here two tutorials where you can find many more details:
This tutorial show you how to use a Raspberry Pi Camera and display images on Android device
This is the second tutorial where you can find a series of tutorial about real-time video streaming between camera and android device
Comment: out of the context


How can I store a GridView cell value to a session variable?

Question: How would I store the value of a GridView's selected rows to a session variable?
Answer: From the codebehind file you will want to use something like this to access the underlying data item (MyDataItem) from the selected row.
<code>MyDataItem item = (MyDataItem)GridView1.Rows[GridView1.SelectedIndex].DataItem;
Session["myItem"] = item;
</code>
Remember though, the gridview is already storing this data for you, so you may just want to access it from the GridView directly whenever you need it.
Answer: On a side note: can I stronly advise you NOT to use the session state.
Unless you are using it as a store where data is cached for the current user, which you can retrieve back at any time from e.g. a database.
If not, the "session" will come back and bite you. At some point there will be a user that leaves the browser open for longer time than your session lives (e.g. they get a telephone call, go out to lunch in a hurry, rush of to a meeting...). And when they return, they wish to complete what they are doing. And if you cannot restore all of your session data back at that point, you will either have to redirect your user to start over again (very annoying for your users), or you will have lost some information (very embarrasing), or the worst case, and most common case: your application will no longer work and crash (just plain: very bad).
It is a better approach to define small serializable objects that store your state (query parameters, selected items, etc) and use ASP.NET Viewstate to store that state across page requests. Note that most ASP.NET controls already use the viewstate to store their data. Then disable the Viewstate of your grids in the page, to vastly reduce the amount of data in your viewstate, and request the data upon each request (here it is safe to use the session or ASP.NET cache to improve performance of your application). You will have a much more robust and much more scalable application.
It is more work, but it will pay back very fast, and many times over.
Answer: ViewState only scope within one page. It's useful for postback problem, but not for cross-page problems. Session can handle both, but it has some limitations of security, lifetime, transmittion time... Depend on particular sittuation you can pick your right choice.


Are there any meta tags I can add to my website to make it more discoverable by search engines?

Question: I am quite a beginner at website design, and in fact so much of an amateur that I don't like paying for hosting/higher search engine results. Are there any meta's that will simply make my website a bit more discoverable by search engines? It is hosted on GitHub pages. I have gone through all the pages of the search and tried many different searches, but it is just not coming up.
Comment: Welcome to the site. We have a _frequently_ asked question [here](http://webmasters.stackexchange.com/questions/2/what-are-the-best-ways-to-increase-a-sites-position-in-google) that discusses the benefits of meta tags among other helpful SEO advice.
Comment: If search engines can read your `meta` elements, they must have discovered your site already. -- If you want to know if your site is indexed, search for `site:foo.example.com` (lists all indexed documents from foo.example.com).
Answer: To get your page into the search index of a search engine, you will need to let those engines know your website exists. This could be done by having other well known sites add links to your site or by adding your site manually through tools like google webmaster tools: https://www.google.com/webmasters/tools/
Once you site is know by the search engines, meta tags can help you to get your page higher in the search results. For this see the link on @dan's comment
Answer: There are some meta tags, which Google supported but it is not going to help to rank higher in search result.
For discovery Purpose I will suggest only two things.

Submit your site to Google Webmaster Tools
Create XML sitemap for your site and submit it to GWT.

Ranking Facts:
Google using 200+ Factors, to rank specific webpage, please don't search that signal list on Google, because those list are junk, those lists/case-studies are created by marketer with their assumption.
They don't know what's the difference between SEO and Ranking, for example, as I said, submit your site and sitemap to Google Webmaster Tools, so that is SEO process, but Google not using that in Search ranking.


Quality online tool to visualize my availbility in the simplest manner?

Question: OK, I may have overly complicated the title. But here is my issue.
I sometimes work alone, sometimes as a team of 3. Either way, I have to keep track of all time that has already been booked and time that is available for new tasks. Right now, I am keeping it all in my head (and each of us do the same). So when the client asks me for something urgent or when we can start work, I usually take a day to calculate and then come back and update him. But most time this does not prove to be accurate as the schedule changes (delays, unpredicted events, etc.) and when the client comes to me I have to tell him that I cannot work today but in X days.
So far, I did not have any negative consequences e.g. client left me in angry, but this is far from professional conduct.
So, I need quality, easy to use (not zillion steps and features) and most important easy to visualize (all my plan for 1 or more months on 1 screen for example, not 10 steps) online tool where I can track my work and available time.
You will say it's easy to reply, right?! For the last year, I have been using all kinds of tools proposed by this community or Internet, and each was not satisfactory. Either too many options or too complicated to enter schedule, or... and in the end I always keep my schedule in my head. I've tried tools like Google Calendar, Trello, Excel sheets, planner tools from MS Office pack, the real board on my wall, stickers, and even dozen online tools which names I cannot recall now.
So is there any such tool around or I have to create one (kidding on the later)? What tools to do you?
Note: 70% or more guys mention google calendar which IMHO is very uneasy to visualize. Maybe I am using it wrongly (being a developer I usually over-complicate things). If you think that Calendar is the right tool for me, then please show me some quality tutorial which will tell me how to use if effectively without complicating things.
Comment: This seems like it's more of a http://softwarerecs.stackexchange.com/ question
Comment: I can try there. I though to narrow it down as freelancers probably use such software.
Answer: Personally I've only used Google Calendar for many years; I have it in sync with my desktop PC, laptop, tablet and smartphone.
I can visualize the calendar by day, week or month and update it at any moment in around 10 seconds by any means. It is very easy and versatile to schedule my work, meetings, renewals, anniversaries, etc.
I don't think that you need a tutorial; just keep it simple and functional. No need to add 1000+ details; use it like a paper calendar you'd put post-it notes (or written notes) on. I hardly edit an event in the calendar; I only use the add and delete functions with very simple 2-3 word labels.
Answer: It sounds like you need a mix of project management and scheduling tools.
Perhaps you need something like PivotalTracker, that gives you a place to input time & effort estimates. Or perhaps you need something like Plan to help you assign tasks to time slots on a calendar.
Comment: Hi Katy, welcome to Freelancing.SE! Can you please [edit] to elabourate on how these tools would help in the OP's situation? Otherwise, this looks like it could point to a spammy-like answer. Thanks! If you have questions about this, please feel free to join us in [chat]
Answer: In a similar situation myself, I too tried many online tools, and all of them bar none were either over complicated, too biased in one direction (task management, project management, calendar scheduling or team sharing) that in the end I made my own. But even that became a headache quickly.
My solution was offline. Two white boards, this month and next month. I etched on a month outline (generalised) on each with a permanent marker, then used dry wipe pens to mark on when or what I was working on. I could book this month time in or next months time in. I could erase things easily, move things about easily enough, colour code stuff, and have as many notes, side diagrams, arrows etc as I needed on them. When the month ended, the current month was erased and labelled next month, and next months calendar became this months.
I even tried to replicate this online but could not replace the value of the freehand drawing over the calendar.
If you build a simple tool that can manage this stuff in a user friendly way online that will be fantastic. I never managed it. Google calendar is brilliant but not for this sort of generalized work planning. So for me the answer was offline, two white boards and some dry markers.
The obvious disadvantage was that it was only available in my office, but since I was in there every day, that was not a problem. When a customer called I could glance down and say, "The earliest I can do that is Thursday" or similar, nearly instantly. Then a quick note on that day, and get back to my work. No fuss, no mucking around, instant, free, flexible and fast.
Answer: I've used a tool called AccountSight. This software tool provides various features in to one. Check out their website at www.AccountSight.com.
There is a time tracking segment, which allows you and your other users to keep time efficiently and submit for review. They even have a time/stopwatch button which tracks the whole time precisely down to a second.
There's also a reporting section, and this is what you are looking for, I believe. It shows all the necessary data you need for quickly reviewing you company work, hours, employee work status, resources etc. You can filter your reports depending on various search filters.
Basically, this tool can help you calculate your hours and availability for your clients quickly, and do the same for your team members. All data is available and provided in real time, so you don't have to worry about making the wrong calculation.
The customer service representatives are very friendly and are always willing to work with you in order to provide the best contents. Their prices are reasonable. I would recommend it.
Comment: Most likely spam, see almost identical answer on different SE recently http://softwarerecs.stackexchange.com/questions/2/what-project-planning-software-includes-resource-leveling-and-is-cheaper-than-mi


Drill batteries for an electric mountain board

Question: I've been searching around for some rechargeable 36V battery packs and I can't seem to find one under $200. I found drill batteries are inexpensive and are 18V with 3AH. On top of that I wouldn't need to buy a charger. I could get 4 18V 3AH batteries for around $70. The only thing I'm worried about is that they might not be able to supply the amperage needed to the motors. They seem pretty powerful considering that the drill motors have pretty high torque. Do you think they can supply the amperage necessary to power the two 36V 190KV motors, or do drills just have a really good gearbox that creates most of the torque?
Comment: Drills do indeed have a good gearbox for the high torque setting.
Comment: A big problem is I don't know the chemistry of the drill batteries. A lot of them just say lithium.
Comment: You should probably figure out what your current demands are and getting a battery specced to do that.   You haven't really told us how much current you think you need. Frankly, your easiest path for something like this would be to find somebody who has done something similar and do what they did.
Comment: Look at the capacity (AH) rating for that 36V mountain board pack.  If it's significantly higher than 3AH, then even if your drill batteries *do* provide enough current, they won't do it for long.
Answer: Electric drill motors are geared down to give high torque at relatively low speeds.
You don't give a specification for your motors.  But it looks like they draw tens of amps (for example one listed on Amazon draws 24 to 65A.  Four battery packs wired in series/parallel only gives 36V 6AH.
Your batteries are only going to last a few minutes at that current, as they will be grossly overloaded.  There's also a risk they will overheat and catch fire.


The Meaning Of Haschen?

Question: With my slight knowledge of the German language (which isn't very advanced, I must admit!) I understand that the German translations for the English word "bunny" are "hase" and "haschen". Is that correct? Also, I would like to confirm whether or not haschen has any other meanings, other than bunny, that I should be aware of? Thank you in advance for any help!
Comment: Did you look it up in a dictionary? If so, you should write here what you found there. If not, why not?
Comment: Bunny (rabbit) is translated "Kaninchen", but hare is Hase or Häschen
Answer: Bunny would be Häschen, which is two syllables: Häs-chen. That's a common diminutive to Hase (hare), which might also get applied to animals which are actually Kaninchen (rabbit).
The way you spell it, you are not only turning the ä into an a (which has a very different sound), but massively changing the meaning. The verb haschen has sch [ʃ] as a single sound, so it's ha-schen. It's can be used as an outdated verb for catching or snatching something or someone, as in "die Kinder spielten Haschen" (the children were playing tag) or "die Polizei erhaschte den Täter auf frischer Tat" (the police caught the culprit red-handed). But as I said, that use is outdated, and these days the more likely meaning is the consumption of  Haschisch (hashish).
Answer: If you cannot type the ä, you have to write it ae, not a. The difference is significant for meaning. It's also a different vowel sound than a. The same for ö and ü.

Das Häschen (spoken Häs'chen) means (cute) little hare. And all the pet things you connect with it.
While haschen means to snatch and to smoke pot.
The two words cannot be mixed up in speech because of the glottal stop in Häschen and the different vowel sound.
Comment: There is a syllable boundary, but no glottal stop.
Comment: Glottal stop? Where?
Comment: Between s and ch.
Answer: You made two severe errors:

a ≠ ä
h ≠ H

What you wrote as »haschen« should be correctly »Häschen«, which is pronounced very different , and has a completely different meaning. (Both words, haschen and Häschen, exist in German.)

German has umlauts. This are three additional letters, that English (and most other languages) doesn't have. (There is a fourth additional letter, »ß«, which is a version of »s«, but this is not an umlaut and therefore not topic of this answer.) This letters are:

ä
ö
ü

Historically, they developed from a, o and u, and there are still connections between them (for example when inflecting verbs in different tenses, or creating plurals of nouns), but they are three distinct letters, with pronunciations that are very different from a, o and u.
It's like in English: If you replace a letter within a word by another letter, you either get a bunch of letters that is no longer an English word (sit → sut) or you get another word with a completely different meaning (bit → but).
And if you replace one of the letters a, o, u by it's umlaut-version ä, ö, ü, it's the same. Example:

zucken = to twitch
  zücken = to whip out

In German all nouns have to be written with an uppercase first letter. ALWAYS! No exceptions! All nouns, every time.
In internet you will see, that some people are too lazy to press the shift key every time they write a noun, so you will find evidence of nouns written in lower case, but this is not correct. It is an error.
There are even pairs of words (one of them a noun, the other one not), that have completely different meanings, and the only difference in their spelling is the capitalization of the first letter:

Rasen = lawn (noun)
  rasen = to race (verb)
Ungeheuer = monster (noun)
  ungeheuer = immense (adjective)

So, what you obviously did mean was:

Hase = rabbit, hare, bunny
  Häschen = little rabbit, little hare, little bunny

-chen is a diminutive suffix in German. If you add it to a noun, you turn the thing into a smaller version of what it was before. But if you do so, you very often have to omit a trailing e (if there is one), and you also very often have to replace a, o, and u by its umlaut version, which also changes pronunciation.
The pronunciations are:

Hase [ˈhaːzə]
Häschen [ˈhɛːsçən]

There is also a website, where you can listen to the pronunciations of Hase and Häschen.
Note, that the pronunciation of the first vowel is different ([a] vs. [ɛ]).
Also note, that the letters sch in Häschen belong to two different syllables (Häs-chen), and therefore they are pronounces as s and ch ([s] and [ç])
(look at International Phonetic Alphabet on Wikipedia to learn more about pronunciation symbols)

About hase:
There is no German word »hase«. Only the noun »Hase« exists.

About haschen:
This word exists, and it has two meanings, both of them are verbs.
The first meaning is: to catch

Der Polizist wird den Dieb sicher bald haschen.
  The policeman surely will catch the thief soon.

But this meaning is outdated and almost forgotten.
The second, more common usage is a verb, derived from the noun Hasch which is a shortened form of Haschisch, which is hashish, hemp, cannabis or pot in Englisch. The verb haschen means: to smoke cannabis.
But in haschen the three letters sch belong to the same syllable (hasch-en), and therefor this is a triglyph, that is pronounced the same like English sh, i.e. as [ʃ].
The pronunciation of the full word haschen is [ˈhaʃən] or [ˈhaʃn̩] (listen to the pronunciation of haschen).

The Meaning Of Haschen?


earthquake effects on total station surveys

Question: What I have been wondering is whether an earthquake can affect a closed system survey.  We are using Leica TCR 307s and TCR 407s and I was wondering if an earthquake can throw off your fixed points if staying within a 500m grid?  The fault line does not run through the site.
Answer: I think it can, if the earthquake in question induces substantial tectonic movements. There has been a study by IIT Bombay, India where the researchers have found out that their fixed positions have moved as much as an inch over a long period of time (7-8 years).
If your survey is short-lived i.e. you are not fixing the total stations for a some future readings, I don't think it should be a cause of concern, as you said the fault line does not pass through the area.
Cheers!
Comment: (+1) for the IIT paper.  Note that the Indian stations span a much greater area than a 500 m grid cell.
Answer: You are effectively asking if the relative positions within a 0.5 km x 0.5 km region would have distorted? In my opinion that is more of a geotechnical question. It also depends if the maximum distortion change from the earthquake is greater than the instrument measurement error from the total station.
Generally, if the site is on hard bedrock, there shouldn't be much or any relative changes, as the whole site would move (each point should be relative to each other). But you could expect some distortion on a soil with "plastic" characteristics (e.g., plastic clay; see Compressability), or if you have unconsolidated sediments and a shallow water table (see Liquefaction/Soil liquefaction).
The best way to find out is if you have any "known" locations, resurvey these and check to see if the relative distances have changed between them before and after the earthquake.
Comment: (+) The study referenced by @ujjwalesri reports compression at 0.1 ppm/yr: only 1 mm in 40 years over a 500m grid. However, major events can cause [substantial shifting of whole regions](http://www.nytimes.com/2011/03/14/world/asia/14seismic.html), implying greater strain even beyond the fault itself. You don't have to be over a fault for there to be [substantial ground movement](http://earthquake.usgs.gov/research/groundmotion/modeling/santa_clara/index.php). In addition to liquefaction, [lateral spreading](http://earthquake.usgs.gov/learn/faq/?categoryID=8&faqID=100) can affect locations.
Comment: Thanks for the answer.  That is generally what I had thought but thought I would consult some people that would know more than me.


run screen after 'su'ing to a specific user

Question: so, I have ssh setup on a Linux machine to start screen when user (root) logs in on ssh (on a basically single-user machine) I have dataplicity installed too, so I can access it from anywhere. when I remote to it, it runs as user dataplicity, so I su as root user to do anything, which doesn't reconnect to any available screen sessions. is there a way to add things that happens after 'su' only for a specific user?
Comment: It's not even so much that we don't understand the question, it's that we're wondering what the hell you're trying to accomplish, because chances are that the method you're asking for is the wrong way to go about it.
Answer: When you su - to any user ID it means that you login to that ID . There is file on  user home directory which read after user logged in . In recent Linux it's ~/.profile or in older version ~/.bash_profile . You can add anything which start when user logged in in this file . If you couldn't find these files on user home directory try to edit ~/.bashrc .
Comment: But this will be executed for all root logins. As I understand the question, the `screen` session should only be reattached if user dataplicity `su`s into root account.
Comment: He can put `screen -r` in any user `.profile` so whenever user login screen will attached again .
Comment: Either you don't understand what I'm trying to say or the other way around, so I better keep out of it.
Answer: su stands for "switch user" and logs you in as the user you indicate.  If you don't indicate a user, then you log in as root.
The - invokes a new login shell, which cleans your slate of environment variables.
If it is safe to do so, you can use sudo to run a command as a privileged user, while remaining logged in as dataplicity.  For example:
sudo lastb
The machine will ask you for the dataplicity login and then run lastb (checks for failed logins) as a privileged user.
In order to use sudo from your dataplicity account, you would need to add dataplicity to your /etc/sudoers account (in SUSE).  Do this by using:
su -
visudo
Then add: dataplicity ALL=(ALL) ALL to the list.  Usually you add it right after the root ALL=(ALL) ALL entry.
Comment: While all of this is true and well explained, it doesn't seem to address the question: How to attach to a running `screen` session automatically only when `su`ing from a specific user?
Comment: I am suggesting to use `sudo` on commands instead of logging into root with `su -`.  That way, commands such as `screen` should be run from and apply to the dataplicity account instead of to the root account.  It should also not wipe out the environmental variables opened by dataplicity.

But that's assuming the specific user that pcs3rd wants `sudo` actions applied to is the dataplicity account.
Comment: I don't believe he wants that, but he seems to have lost interest in the answer, so I vote to close the question.
Comment: ... im using Kali
Comment: Kali and SUSE are both Debian based, so the above command should work.  If that's what you're looking for.


Lib curl with openssl compilation fails

Question: I want to build the lib curl 7.54.0 with openssl statically for a VS2015 project on win 7. I have built the openssl but unable to build the curl. It fails with error code U1077.
I am running following command in "Developer command prompt for VS2015",
G:\Libs\curl-7.54.0\winbuild>nmake /f Makefile.vc mode=static WITH_SSL=static WITH_DEVEL="G:\Libs\openssl-1.0.1g\output" VC=14 ENABLE_WINSSL=no DEBUG=no MACHINE=x86 GEN_PDB=no
It compiles some files then fails as follows,
Copying libs...
        rc /i../include /dDEBUGBUILD=0 /Fo ..\builds\libcurl-vc14-x86-release-static-ssl-static-ipv6-sspi-obj-curl\curl.res ..\src\curl.rc 'rc' is not recognized as an internal or external command,
operable program or batch file.
NMAKE : fatal error U1077: 'rc' : return code '0x1' Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 14.0
\VC\BIN\nmake.exe"' : return code '0x2'
Stop.
Not sure how to fix this. Please suggest.
Thanks,
R.
Answer: I have been solving similar problem with another library. rc.exe is part of Windows SDK and I had to add path of Windows SDK to PATH environment variable.
In my case I have added this to PATH environment variable:

c:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x86\

Hoping, it helps.
PM

Lib curl with openssl compilation fails


What's the goal behind signing a CRL with an old certificate key?

Question: I was reading a CPS/CP for a CA, and it mentioned that there's a possibility after rekey that you can still use the old key to sign CRLs of the old end user certificates verified by the old CA certificate, the only case where I see that would be applicable is if a browser for example doesn't add the new CA certificate in its trust store for a period of time and so it can't verify the new CRLs, is that the case?
Answer: Correct.  There is no reason to invalidate all issued certificates when a CA decides it needs to re-key - that would simply cause chaos.  As such, all those extant certificates need to be managed throughout their life-cycle.  In order for clients to continue to carry out revocation checking on any of these certificates the CA must continue to sign a CRL with the original key-pair; as well as a sign a new CRL with the new key-pair.
The CA will now be signing multiple CRLs and clients will need to access the correct version.  Therefore the crlDistributionPoint extension on certificates signed by the new key-pair will have a different URL to the certificates signed by the original pair.  For example, Microsoft's ADCS appends a (n) to the filename for each re-key, where n increases by one each time.
Comment: This hassle is also the reason why OCSP is preferable in this instance. You don't need to manage multiple revocation lists with multiple keys. The OCSP response can just be signed with whatever key the client understands.
Comment: @MechMK1 - the OCSP response certificate has to be signed by the CA which issued the certificate being queried - [RFC6960 Section 188.8.131.52](https://tools.ietf.org/html/rfc6960#section-220.127.116.11) - and not any key the client understands. If the CA re-keys, it will need to issue a new OCSP signing certificate to the responders.


Should a support incident be opened for every stack dump, or just ones that cause an outage?

Question: Assuming that the stack dump in question can't be mapped to a know issue, if a stack dump doesn't seem to cause a problem and everything is working afterwards, should a support incident be opened for it?  Or should incidents be opened only when it causes an outage or loss of functionality?
Comment: This seems very opinion-based.
Comment: @AaronBertrand I can appreciate your opinion that this might seem opinion-based.  But it's not--which approach will result in me not wasting my time and Microsoft's support staff time, while still providing them the information they need to make the product better?  It would seem to me there is a definite answer, but perhaps only Microsoft folks know, or someone who's asked them this question.
Comment: If a stack dump is generated by SQL server, to me its a clear bug that needs to be investigated. Now if the stack dump caused a service interruption for your app and your business that part you have to handle it by proper monitoring and providing better visibility when your service degrades.
Comment: 3rd party modules, detouring, heap corruption, etc., can all have stack dumps generated by SQL server but SQL Server isn't the cause... so it's not quite 100% on that.
Comment: To be fair, if you read your question, it certainly could be interpreted that you mean "should I open a support incident?" as in "will I get any benefit from doing so?" If you are talking about more altruistic things, like making the product itself better, those should be stated in the question, but it still is something that only Microsoft would know for sure would help them. It probably depends a lot on things that your peers can't answer, like how serious is the issue, how prevalent is it, how easy is it to happen, is there an easy fix, does the team have time right now to investigate...
Comment: @TonyHinkle My2 cents, if I get a stack dump I would first check whether SQL Server is on latest SP/CU or not ?. Not all stack dumps are caused by bug in SQL Server some(very few) may also come when your SQL Server is under tremendous load. So before you open support ticket make sure who is the culprit
Answer: It's fairly cut and dry: If you want to actually work on the issue, collect data, uninstall/reinstall, isolate, test, potentially provide more dumps, potentially use things like appverifier and debugdiag or have a valid repro, then by all means open a ticket so it can be looked into and worked on.
If you just want to ship off a stack dump, with no other data, and have someone look at it in a vacuum, then I would not open a ticket as it'll have no traction and go nowhere. Neither party will be happy.
That's the short and sweet version.


Redirect URL after Content DB split

Question: We have moved some sub-sites from a Content DB of 140GB to a new SC in sharepoint 2010.
Now, both the sites are up and running and we want to redirect the old URL to new URL so that we delete the old site.
We want if someone enters http://servername/sites/SC/sitename so it should redirect to http://servername/sites/SC1/sitename
Answer: The way I have done this before was to create a database table with the mappings of the urls.  The first column holds the old url and the second column holds the new url.  Then I wrote a httpmodule that checks each request on beginrequest to see if the url matches a value in column 1, if so redirect to the url in column 2.  I installed it to the old farm.  It works pretty well but I would recommend plenty of testing and some caching to not reduce performance.  An improperly coded httpmodule can really screw up your environment's performance and functionality.
Another way I've done this was just to create a redirect webpart.  Then I put the webpart on the homepage of the old site.  This doesn't handle as many cases as httpmodule but it is a safer solution.
Comment: Thanks for your response.
I have also tried this with web part but the issue is it only works for the home page what if someone has a direct URl for a Library/list.
Moreover i would not be able to write anything as I am a Zero coder. :)
Comment: I have used a HTTP Module before to redirect subsites on the fly, but you are right with the need to test, as it runs on every single HTTP request to the site.
Answer: Try using your web server or load balancer to perform the redirections. If you are running IIS7 or higher, take a look at the URL Rewrite module.

Redirect URL after Content DB split


SQL query help: Calculating days between observations

Question: I'm extremely new to SQL, in fact, I just really started playing around with it.  So I'm not exactly sure how to search for appropriate terms related to the question I have.  I'll do my best.
CONTEXT:
I have a table that I'd like to query using SQL Server.  That table has behavioral data for hundreds of thousands of animals over multiple days (I know! Lots of animals! Rats, actually, and it is data that has been compiled over many many years by many many people).  Here are the columns:

AnimalID (an identifying ID unique to that animal)
DateID (Date of observation-- for example, 20151111)
Behavior1 (# of times observed eating on that DateID-- could be 0, max is 337!)
Behavior2 (# of times observed grooming on that DateID-- could be 0, max is 36)
Behavior3 (# of times observed mating/attempted mating on that DateID-- could be 0, max is 77!)

There are other columns like "gender," "AgeInDays," and several more behavior types.  I don't think it is worth listing them all out.
I'd like to be able to use WHERE and GROUP BY in a query to summarize this dataset.
So far I have been able to write queries that give me the total number of days that each animal does a behavior or the total number of times that an animal has done a behavior across all records for each animal.  For example, I've done this by making WHERE [Behavior1] > 1 and GROUP BY [AnimalID].
This is actually pretty cool!  And I'm stunned at how quickly these queries run!  But I'm stuck on a different type of query.
QUESTION:
I want to write a query that will tell me the number of days (DateID) between the first date an animal (each unique AnimalID) tried to mate (Behavior3) and the second date the same animal tried to mate.  In the same output, I'd like to have the number of days between the SECOND date they tried and the THIRD date they tried.  All while having WHERE [Behavior1] > 1 and GROUP BY [AnimalID].
Ideally the output would have columns like this:

AnimalID
NumDays1 (number of days between first and second attempts for that AnimalID to mate)
NumDays2 (number of days between the second and third attempts for that AnimalID to mate)

Is this even possible to do in a single query?  I know I need to use DATEDIFF...   Any help would be greatly appreciated!
Apologies if I've messed up the way I was supposed to ask this question on this forum.
Thanks!
Comment: Can you add sample data and expected output? Table definitions are always a plus too
Comment: SQL Server? Please update tags with your RDBMS. SQL is a language used by many RDBMS.
Comment: SQL Server 2012.
Answer: I think in this case, you best best since you are on SQL 2012 is to use Window Functions and specifically the LEAD function.
Here is an example to try and match your data.
Say I created a table with the columns you have here in the following way and then insert rows into that:
CREATE TABLE #AnimalBehavior
(
    ID int identity(1,1) primary key clustered
    ,AnimalID int
    ,DateID int
    ,Behavior1 int
    ,Behavior2 int
    ,Behavior3 int
);
GO

insert into #AnimalBehavior (AnimalID, DateID, Behavior1, Behavior2, Behavior3)
Values (1, 20150101, 0, 1, 1)
    ,(1, 20150201, 0, 1, 1)
    ,(1, 20150301, 0, 1, 1)
    ,(1, 20150401, 0, 1, 1)
    ,(2, 20150101, 0, 1, 1)
    ,(2, 20150301, 0, 1, 1)
    ,(2, 20150501, 0, 1, 1);
GO

From here I will want to only look at the times where your behavior3 is greater than 0 (so that we know it occurred during that period) and take the difference between the LEAD of the 2nd compared to the initial row, and the LEAD of the 3rd compared to the LEAD of the 2nd.  You can do that in this way:
With ab
as
(
Select AnimalID
, DateID
, LEAD(DateID, 1, 0) over (Partition By AnimalID order by DateID) DateID_1
, Lead(DateID, 2, 0) over (Partition By AnimalID order by DateID) DateID_2
, row_number() over (Partition By AnimalID order by DateID) as rown
from #AnimalBehavior
where Behavior3 > 0
)
Select AnimalID, Convert(date, Convert(varchar(8), DateID))
, DateDiff(dd,  Convert(date, Convert(varchar(8), DateID)),  Convert(date, Convert(varchar(8), DateID_1)))
, DateDiff(dd,  Convert(date, Convert(varchar(8), DateID_1)),  Convert(date, Convert(varchar(8), DateID_2)))
from AB
where rown = 1;

I believe this covers what you are looking for.  But feel free to ask questions if not.


Subset netCDF based on last valid variable by level

Question: I have a netCDF file (in this LINK) which contains monthly average values for 4 parameters at 11 different depth levels (0-200m). I would like to extract the monthly value for temperature "votemper" at the maximum valid depth (i.e. when the water is 20 m deep there are only NA vlaues for greater depths) however, the last valid depth varies spatially based on the water bathymetry. I have got as far as turning the netCDF into an array in R but am having trouble with how to extract just the values from the maximum valid depth value.
Comment: Code please - there are at least four R packages on CRAN with independent read tools for NetCDF. Also the usual info such as OS and R and package versions is important.
Answer: You can use the raster package and its functionalities regarding netCDF files to address your problem. Make sure the ncdf package is available.
# Required packages
library(raster)
library(ncdf)
library(RColorBrewer)

You can manually retrieve some information about the netCDF file you are dealing with using open.ncdf(). This step is important for subsequent loops along available depth levels and time steps included in the file.
# Information about ncdf file, e.g. variables, dimensions, no. of time steps
nc <- open.ncdf("oceandata.nc")
nc
[1] "file oceandata.nc has 4 dimensions:"
[1] "time   Size: 3"
[1] "depth   Size: 12"
[1] "lat   Size: 23"
[1] "lon   Size: 15"
[1] "------------------------"
[1] "file oceandata.nc has 4 variables:"
[1] "short vosaline[lon,lat,depth,time]  Longname:Sea Water Salinity Missval:-32768"
[1] "short vomecrty[lon,lat,depth,time]  Longname:Northward Current Velocity in the Water Column Missval:-32768"
[1] "short votemper[lon,lat,depth,time]  Longname:Sea Water Potential Temperature Missval:-32768"
[1] "short vozocrtx[lon,lat,depth,time]  Longname:Eastward Current Velocity in the Water Column Missval:-32768"

Now that you know how much time steps (3) and depth levels (12) are included, you can start importing the data into R. However, I am still wondering whether you can directly import daily RasterBricks consisting of 12 layers, i.e. one for each depth level (resulting in 3 RasterBricks in this particular case), rather than RasterBricks consisting of all available RasterLayers per depth level (status quo, resulting in 12 RasterBricks comprising three layers (3 time steps) each).
# Import ncdf file as 'Raster*' object by looping through all available
# depth levels (Size: 12), returning a list containing one RasterBrick with
# all available time steps per depth level
lst_by_depth <- lapply(1:12, function(i) {
  brick("oceandata.nc", varname = "votemper", lvar = "depth", level = i)
})

rst_by_depth <- brick(lst_by_depth)

Now that you have the RasterBricks for each depth level, you can start reordering your data by manually concatenating all available depth levels that correspond to the same day, resulting in a list of daily RasterBrick objects.
# Loop through no. of time steps (Size: 3), returning a list containing one
# RasterBrick with all available depth levels per day
lst_by_time <- lapply(1:3, function(i) {
  indices <- seq(i, nlayers(rst_by_depth), 3)
  rst_by_depth[[indices]]
})

Next, you need to define a function that you can later on pass to calc for identifying the last valid (i.e. non-NA) temperature value on a pixel basis. If no NA values exist, it will return the deepest possible value. If no non-NA values exist (I suppose this should correspond to land, then), it returns NA.
# Define a function that, for each cell,
# - returns NA in case all depth level values are NA
# - returns the value of the last available depth level in case no NA occur
# - else returns the value of the last non-NA depth level
deepestValid <- function(x) {
  na <- is.na(x)
  if (all(na)) {
    return(NA)
  } else if (all(!na)) {
    return(x[length(x)])
  } else {
    first_na <- which(na)[1]
    last_valid <- first_na - 1
    return(x[last_valid])
  }
}

Finally, apply this function to each element, i.e. to each daily RasterBrick, in the previously generated list. This results in a list of three daily RasterLayers holding the temperature value of the deepest possible point per pixel.
# Apply custom function to each daily RasterBrick, returning daily RasterLayers
# with deepest available value
deepest_valid <- lapply(lst_by_time, function(i) {
  calc(i, fun = deepestValid)
})

col <- colorRampPalette(rev(brewer.pal(9, "RdBu")))
spplot(deepest_valid[[1]], col.regions = col(100), cuts = 50)

However, I have to confess that the approach seems rather long-winded to me, and I am still wondering whether there is a more convenient solution to your problem.
Comment: Hi flowla, i think that is a very well documented answer - thanks! I tried a different approach by converting to a data frame, removing NA values and then selecting the maximum depth level but the process of converting from netCDF to large matrix didn't feel very efficient.


Combining C and Python functions in a module

Question: I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?
For example:
import my_module

my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()

I'm primarily interested in Python 2.x.
Answer: The usual way of doing this is: mymod.py contains the utility functions written in Python, and imports the goodies in the _mymod module which is written in C and is imported from _mymod.so or _mymod.pyd. For example, look at .../Lib/csv.py in your Python distribution.
Comment: csv.py is a really helpful example
Answer: Prefix your native extension with an underscore.
Then, in Python, create a wrapper module that imports that native extension and adds some other non-native routines on top of that.
Answer: The existing answers describe the method most often used: it has the potential advantage of allowing pure-Python (or other-language) implementations on platforms in which the compiled C extension is not available (including Jython and IronPython).
In a few cases, however, it may not be worth splitting the module into a C layer and a Python layer just to provide a few extras that are more sensibly written in Python than in C. For example, gmpy (lines 7113 ff at this time), in order to enable pickling of instances of gmpy's type, uses:
copy_reg_module = PyImport_ImportModule("copy_reg");
if (copy_reg_module) {
    char* enable_pickle =
        "def mpz_reducer(an_mpz): return (gmpy.mpz, (an_mpz.binary(), 256))\n"
        "def mpq_reducer(an_mpq): return (gmpy.mpq, (an_mpq.binary(), 256))\n"
        "def mpf_reducer(an_mpf): return (gmpy.mpf, (an_mpf.binary(), 0, 256))\n"
        "copy_reg.pickle(type(gmpy.mpz(0)), mpz_reducer)\n"
        "copy_reg.pickle(type(gmpy.mpq(0)), mpq_reducer)\n"
        "copy_reg.pickle(type(gmpy.mpf(0)), mpf_reducer)\n"
    ;
    PyObject* namespace = PyDict_New();
    PyObject* result = NULL;
    if (options.debug)
        fprintf(stderr, "gmpy_module imported copy_reg OK\n");
    PyDict_SetItemString(namespace, "copy_reg", copy_reg_module);
    PyDict_SetItemString(namespace, "gmpy", gmpy_module);
    PyDict_SetItemString(namespace, "type", (PyObject*)&PyType_Type);
    result = PyRun_String(enable_pickle, Py_file_input,
                          namespace, namespace);

If you want those few extra functions to "stick around" in your module (not necessary in this example case), you would of course use your module object as built by Py_InitModule3 (or whatever other method) and its PyModule_GetDict rather than a transient dictionary as the namespace in which to PyRun_String. And of course there are more sophisticated approaches than to PyRun_String the def and class statements you need, but, for simple enough cases, this simple approach may in fact be sufficient.
Comment: Thanks: I was interested to see how this could be done, as well as the more common way.