asynchronous and non-blocking calls? also between blocking and synchronous

Question: What is the difference between asynchronous and non-blocking calls? Also between blocking and synchronous calls (with examples please)?
Comment: Related: http://stackoverflow.com/a/9489547/194894
Comment: An interesting article: [Boost application performance using asynchronous I/O](https://www.ibm.com/developerworks/linux/library/l-async/). It categorizes I/O paradigms into 4 categories: (1) Blocking + Synchronous, (2) Non-Blocking + Synchronous, (3) Blocking + Asynchronous, and (4) Non-Blocking + Asynchronous.
Comment: I got a good understanding about the differences while reading the book  Col 1, Chapter 6.
Comment: @M.S.Dousti I was told that this is wrong in some ways, from a Google expert.
Comment: @M.S.Dousti After some study, I think there are no conbination (3) and (2) as you describes in the comments. Check the definition of Asynchronous, it's talking about the same thing of Non-Blocking.  As you can see the top answer it's confirming my opinion. Polling and callback function are merely ways/patterns to implement Asynchronous. Yes, I am saying that Blocking,Synchronous and Non-Blocking,  Asynchronous are 2 pairs of synonym.
Answer: In many circumstances they are different names for the same thing, but in some contexts they are quite different.  So it depends. Terminology is not applied in a totally consistent way across the whole software industry.
For example in the classic sockets API, a non-blocking socket is one that simply returns immediately with a special "would block" error message, whereas a blocking socket would have blocked. You have to use a separate function such as select or poll to find out when is a good time to retry.
But asynchronous sockets (as supported by Windows sockets), or the asynchronous IO pattern used in .NET, are more convenient. You call a method to start an operation, and the framework calls you back when it's done. Even here, there are basic differences. Asynchronous Win32 sockets "marshal" their results onto a specific GUI thread by passing Window messages, whereas .NET asynchronous IO is free-threaded (you don't know what thread your callback will be called on).
So they don't always mean the same thing. To distil the socket example, we could say:

Blocking and synchronous mean the same thing: you call the API, it hangs up the thread until it has some kind of answer and returns it to you.
Non-blocking means that if an answer can't be returned rapidly, the API returns immediately with an error and does nothing else. So there must be some related way to query whether the API is ready to be called (that is, to simulate a wait in an efficient way, to avoid manual polling in a tight loop).
Asynchronous means that the API always returns immediately, having started a "background" effort to fulfil your request, so there must be some related way to obtain the result.
Comment: Thanks for pointing out that the terms are context sensitive and sometimes may be used inconsistently. I find in technology especially, but other areas too, that it is often more useful to acknowledge that fact than to get into debates about which precise definition is correct, as sometimes happens.
Comment: Rather than saying the non-blocking call returns an "error", I think it would be more accurate to say that a non-blocking call does as much as can be done essentially immediately, and then indicates how much it did.  For some operations, the amount of work done will either be "everything" or "nothing", but some other operations (like stream I/O) may return a quantitative indication.  Non-blocking is semantically equivalent to blocking with a very short timeout *if* the blocking I/O implementation will allow an operation which times out to be smoothly retried later (some do; some don't).
Comment: @ChadNB - as terms, non-blocking is strongly associated with polling. Regarding the question of whether the API "remembers" your attempt to call it: the only reason for the API to remember is in order to call you back. If you're going to be calling it to re-poll, then you already have to maintain the necessary state to know to make that subsequent call, so the API would add no value by also maintaining state.
Comment: Followup Q: The answer seems to make two different distinctions between the terms. First, the notification: non-blocking implies the application must check again later (polling) whereas async implies we can forget about it and rely on the framework/OS to notify us via callback or posting an event. Second, the action: non-blocking does absolutely nothing but return an error, whereas async queues the action or does it "in the background" in some sense. Which difference is more important in distinguishing the terms? Is either distinction more strongly associated with one term? Or is it ambiguous?
Comment: ready state IO rather than completion state IO; on Linux see libaio
Comment: aside question: are 'classic sockets API' the [Berkeley sockets](https://en.wikipedia.org/wiki/Berkeley_sockets) or could you provide a link please? :)
Comment: Yes, Berkeley or POSIX (close enough to the same thing).
Comment: @ChadNB Yes,  I think the answer points out the differences between non-blocking and asynchronous as they are.
Answer: synchronous / asynchronous is to describe the relation between two modules.
blocking / non-blocking is to describe the situation of one module.
An example:
Module X: "I".
Module Y: "bookstore".
X asks Y: do you have a book named "c++ primer"?

blocking: before Y answers X, X keeps waiting there for the answer. Now X (one module) is blocking. X and Y are two threads or two processes or one thread or one process? we DON'T know.

non-blocking: before Y answers X, X just leaves there and do other things. X may come back every two minutes to check if Y has finished its job? Or X won't come back until Y calls him? We don't know. We only know that X can do other things before Y finishes its job. Here X (one module) is non-blocking. X and Y are two threads or two processes or one process? we DON'T know. BUT we are sure that X and Y couldn't be one thread.

synchronous: before Y answers X, X keeps waiting there for the answer. It means that X can't continue until Y finishes its job. Now we say: X and Y (two modules) are synchronous. X and Y are two threads or two processes or one thread or one process? we DON'T know.

asynchronous: before Y answers X, X leaves there and X can do other jobs. X won't come back until Y calls him. Now we say: X and Y (two modules) are asynchronous. X and Y are two threads or two processes or one process? we DON'T know. BUT we are sure that X and Y couldn't be one thread.

Please pay attention on the two bold-sentences above. Why does the bold-sentence in the 2) contain two cases whereas the bold-sentence in the 4) contains only one case? This is a key of the difference between non-blocking and asynchronous.
Let me try to explain the four words with another way:

blocking: OMG, I'm frozen! I can't move! I have to wait for that specific event to happen. If that happens, I would be saved!

non-blocking: I was told that I had to wait for that specific event to happen. OK, I understand and I promise that I would wait for that. But while waiting, I can still do some other things, I'm not frozen, I'm still alive, I can jump, I can walk, I can sing a song etc.

synchronous: My mom is gonna cook, she sends me to buy some meat. I just said to my mom: We are synchronous! I'm so sorry but you have to wait even if I might need 100 years to get some meat back...

asynchronous: We will make a pizza, we need tomato and cheeze. Now I say: Let's go shopping. I'll buy some tomatoes and you will buy some cheeze. We needn't wait for each other because we are asynchronous.

Here is a typical example about non-blocking & synchronous:
// thread X
while (true)
{
    msg = recv(Y, NON_BLOCKING_FLAG);
    if (msg is not empty)
    {
        break;
    }
    else
    {
        sleep(2000); // 2 sec
    }
}

// thread Y
// prepare the book for X
send(X, book);

You can see that this design is non-blocking (you can say that most of time this loop does something nonsense but in CPU's eyes, X is running, which means that X is non-blocking. If you want you can replace sleep(2000) with any other code) whereas X and Y (two modules) are synchronous because X can't continue to do any other things (X can't jump out of the loop) until it gets the book from Y.
Normally in this case, making X blocking is much better because non-blocking spends much resource for a stupid loop. But this example is good to help you understand the fact: non-blocking doesn't mean asynchronous.
The four words do make us confused easily, what we should remember is that the four words serve for the design of architecture. Learning about how to design a good architecture is the only way to distinguish them.
For example, we may design such a kind of architecture:
// Module X = Module X1 + Module X2
// Module X1
while (true)
{
    msg = recv(many_other_modules, NON_BLOCKING_FLAG);
    if (msg is not null)
    {
        if (msg == "done")
        {
            break;
        }
        // create a thread to process msg
    }
    else
    {
        sleep(2000); // 2 sec
    }
}
// Module X2
broadcast("I got the book from Y");

// Module Y
// prepare the book for X
send(X, book);

In the example here, we can say that

X1 is non-blocking
X1 and X2 are synchronous
X and Y are asynchronous

If you need, you can also describe those threads created in X1 with the four words.
One more time: the four words serve for the design of architecture. So what we need is to make a proper architecture, instead of distinguishing the four words like a language lawyer. If you get some cases, where you can't distinguish the four words very clearly, you should forget about the four words, use your own words to describe your architecture.
So the more important things are: when do we use synchronous instead of asynchronous? when do we use blocking instead of non-blocking? Is making X1 blocking better than non-blocking? Is making X and Y synchronous better than asynchronous? Why is Nginx non-blocking? Why is Apache blocking? These questions are what you must figure out.
To make a good choice, you must analyze your need and test the performance of different architectures. There is no such an architecture that is suitable for various of needs.
Comment: IMO the best answer since it catches the essence of the concept: the relationship between one or two participants.
Comment: @VineethChitteti  You d better not say like that. X and Y can be synchronous while X is not blocking.
Comment: So does it mean, blocking and synchronous are both the same? more like verb and noun form difference between them?
Comment: in both 1 and 3,  Y is acting as  a LIMITED resource. There are no more Y's to help X
Comment: What is this answer based on?
Answer:
Asynchronous refers to something done in parallel, say is another thread.
Non-blocking often refers to polling, i.e. checking whether given condition holds (socket is readable, device has more data, etc.)
Comment: when I/O is involved, asynchronous usually isn't "in parallel", nor "another thread", mostly it's notification-based.  that is: don't block, don't poll, just get the signal.
of course, it can be argued that the signal is coming from the 'real world' which can be thought as 'another thread'...
Comment: To anyone reading this answer: this is not arguing over exact wording. In the same way that concurrency and parallelism are not the same notions and distinguishing them is not a wording issue. Asynchronicity and parallelism are two different beasts and this answer inaccurately makes them be the same.
Comment: Async doesn't necessarily mean it's done in parallel, see this great [post](https://stackoverflow.com/questions/1897993/what-is-the-difference-between-concurrent-programming-and-parallel-programming) on stackoverflow about concurrent and parallel programming.
Comment: Well, yes, we can argue the exact wording all day :)
Comment: but how do you explain the AIO in Linux? which used both the Async and non-blocking. [AIO LINKS](http://www.ibm.com/developerworks/library/l-async/)
Answer: Synchronous is defined as happening at the same time (in predictable timing, or in predictable ordering).
Asynchronous is defined as not happening at the same time. (with unpredictable timing or with unpredictable ordering).
This is what causes the first confusion, which is that asynchronous is some sort of synchronization scheme, and yes it is used to mean that, but in actuality it describes processes that are happening unpredictably with regards to when or in what order they run. And such events often need to be synchronized in order to make them behave correctly, where multiple synchronization schemes exists to do so, one of those called blocking, another called non-blocking, and yet another one confusingly called asynchronous.
So you see, the whole problem is about finding a way to synchronize an asynchronous behavior, because you've got some operation that needs the response of another before it can begin. Thus it's a coordination problem, how will you know that you can now start that operation?
The simplest solution is known as blocking.
Blocking is when you simply choose to wait for the other thing to be done and return you a response before moving on to the operation that needed it.
So if you need to put butter on toast, and thus you first need to toast the bred. The way you'd coordinate them is that you'd first toast the bred, then stare endlessly at the toaster until it pops the toast, and then you'd proceed to put butter on them.
It's the simplest solution, and works very well. There's no real reason not to use it, unless you happen to also have other things you need to be doing which  don't require coordination with the operations. For example, doing some dishes. Why wait idle staring at the toaster constantly for the toast to pop, when you know it'll take a bit of time, and you could wash a whole dish while it finishes?
That's where two other solutions known respectively as non-blocking and asynchronous come into play.
Non-blocking is when you choose to do other unrelated things while you wait for the operation to be done. Checking back on the availability of the response as you see fit.
So instead of looking at the toaster for it to pop. You go and wash a whole dish. And then you peek at the toaster to see if the toasts have popped. If they haven't, you go wash another dish, checking back at the toaster between each dish. When you see the toasts have popped, you stop washing the dishes, and instead you take the toast and move on to putting butter on them.
Having to constantly check on the toasts can be annoying though, imagine the toaster is in another room. In between dishes you waste your time going to that other room to check on the toast.
Here comes asynchronous.
Asynchronous is when you choose to do other unrelated things while you wait for the operation to be done. Instead of checking on it though, you delegate the work of checking to something else, could be the operation itself or a watcher, and you have that thing notify and possibly interupt you when the response is availaible so you can proceed to the other operation that needed it.
Its a weird terminology. Doesn't make a whole lot of sense, since all these solutions are ways to create synchronous coordination of dependent tasks. That's why I prefer to call it evented.
So for this one, you decide to upgrade your toaster so it beeps when the toasts  are done. You happen to be constantly listening, even while you are doing dishes. On hearing the beep, you queue up in your memory that as soon as you are done washing your current dish, you'll stop and go put the butter on the toast. Or you could choose to interrupt the washing of the current dish, and deal with the toast right away.
If you have trouble hearing the beep, you can have your partner watch the toaster for you, and come tell you when the toast is ready. Your partner can itself choose any of the above three strategies to coordinate its task of watching the toaster and telling you when they are ready.
On a final note, it's good to understand that while non-blocking and async (or what I prefer to call evented) do allow you to do other things while you wait, you don't have too. You can choose to constantly loop on checking the status of a non-blocking call, doing nothing else. That's often worse than blocking though (like looking at the toaster, then away, then back at it until it's done), so a lot of non-blocking APIs allow you to transition into a blocking mode from it. For evented, you can just wait idle until you are notified. The downside in that case is that adding the notification was complex and potentially costly to begin with. You had to buy a new toaster with beep functionality, or convince your partner to watch it for you.
And one more thing, you need to realize the trade offs all three provide. One is not obviously better than the others. Think of my example. If your toaster is so fast, you won't have time to wash a dish, not even begin washing it, that's how fast your toaster is. Getting started on something else in that case is just a waste of time and effort. Blocking will do. Similarly, if washing a dish will take 10 times longer then the toasting. You have to ask yourself what's more important to get done? The toast might get cold and hard by that time, not worth it, blocking will also do. Or you should pick faster things to do while you wait. There's more obviously, but my answer is already pretty long, my point is you need to think about all that, and the complexities of implementing each to decide if its worth it, and if it'll actually improve your throughput or performance.
Edit:
Even though this is already long, I also want it to be complete, so I'll add two more points.

There also commonly exists a fourth model known as multiplexed. This is when while you wait for one task, you start another, and while you wait for both, you start one more, and so on, until you've got many tasks all started and then, you wait idle, but on all of them. So as soon as any is done, you can proceed with handling its response, and then go back to waiting for the others. It's known as multiplexed, because while you wait, you need to check each task one after the other to see if they are done, ad vitam, until one is. It's a bit of an extension on top of normal non-blocking.

In our example it would be like starting the toaster, then the dishwasher, then the microwave, etc. And then waiting on any of them. Where you'd check the toaster to see if it's done, if not, you'd check the dishwasher, if not, the microwave, and around again.

Even though I believe it to be a big mistake, synchronous is often used to mean one thing at a time. And asynchronous many things at a time. Thus you'll see synchronous blocking and non-blocking used to refer to blocking and non-blocking. And asynchronous blocking and non-blocking used to refer to multiplexed and evented.

I don't really understand how we got there. But when it comes to IO and Computation, synchronous and asynchronous often refer to what is better known as non-overlapped and overlapped. That is, asynchronous means that IO and Computation are overlapped, aka, happening concurrently. While synchronous means they are not, thus happening  sequentially. For synchronous non-blocking, that would mean you don't start other IO or Computation, you just busy wait and simulate a blocking call. I wish people stopped misusing synchronous and asynchronous like that. So I'm not encouraging it.
Edit2:
I think a lot of people got a bit confused by my definition of synchronous and asynchronous. Let me try and be a bit more clear.
Synchronous is defined as happening with predictable timing and/or ordering. That means you know when something will start and end.
Asynchronous is defined as not happening with predictable timing and/or ordering. That means you don't know when something will start and end.
Both of those can be happening in parallel or concurrently, or they can be happening sequentially. But in the synchronous case, you know exactly when things will happen, while in the asynchronous case you're not sure exactly when things will happen, but you can still put some coordination in place that at least guarantees some things will happen only after others have happened (by synchronizing some parts of it).
Thus when you have asynchronous processes, asynchronous programming lets you place some order guarantees so that some things happen in the right sequence, even though you don't know when things will start and end.
Here's an example, if we need to do A then B and C can happen at any time. In a sequential but asynchronous model you can have:
A -> B -> C
or
A -> C -> B
or
C -> A -> B

Every time you run the program, you could get a different one of those, seemingly at random. Now this is still sequential, nothing is parallel or concurrent, but you don't know when things will start and end, except you have made it so B always happens after A.
If you add concurrency only (no parallelism), you can also get things like:
A<start> -> C<start> -> A<end>   -> C<end>   -> B<start> -> B<end>
or
C<start> -> A<start> -> C<end>   -> A<end>   -> B<start> -> B<end>
or
A<start> -> A<end>   -> B<start> -> C<start> -> B<end>   -> C<end>
etc...

Once again, you don't really know when things will start and end, but you have made it so B is coordinated to always start after A ends, but that's not necessarily immediately after A ends, it's at some unknown time after A ends, and B could happen in-between fully or partially.
And if you add parallelism, now you have things like:
A<start> -> A<end>   -> B<start>       -> B<end>         ->
            C<start> -> C<keeps going> -> C<keeps going> -> C<end>
or
A<start> -> A<end>         -> B<start> -> B<end>
C<start> -> C<keeps going> -> C<end>
etc...

Now if we look at the synchronous case, in a sequential setting you would have:
A -> B -> C

And this is the order always, each time you run the program, you get A then B and then C, even though C conceptually from the requirements can happen at any time, in a synchronous model you still define exactly when it will start and end. Off course, you could specify it like:
C -> A -> B

instead, but since it is synchronous, then this order will be the ordering every time the program is ran, unless you changed the code again to change the order explicitly.
Now if you add concurrency to a synchronous model you can get:
C<start> -> A<start> -> C<end> -> A<end> -> B<start> -> B<end>

And once again, this would be the order no matter how many time you ran the program. And similarly, you could explicitly change it in your code, but it would be consistent across program execution.
Finally, if you add parallelism as well to a synchronous model you get:
A<start> -> A<end> -> B<start> -> B<end>
C<start> -> C<end>

Once again, this would be the case on every program run. An important aspect here is that to make it fully synchronous this way, it means B must start after both A and C ends. If C is an operation that can complete faster or slower say depending on the CPU power of the machine, or other performance consideration, to make it synchronous you still need to make it so B waits for it to end, otherwise you get an asynchronous behavior again, where not all timings are deterministic.
You'll get this kind of synchronous thing a lot in coordinating CPU operations with the CPU clock, and you have to make sure that you can complete each operation in time for the next clock cycle, otherwise you need to delay everything by one more clock to give room for this one to finish, if you don't, you mess up your synchronous behavior, and if things depended on that order they'd break.
Finally, lots of systems have synchronous and asynchronous behavior mixed in, so if you have any kind of inherently unpredictable events, like when a user will click a button, or when a remote API will return a response, but you need things to have guaranteed ordering, you will basically need a way to synchronize the asynchronous behavior so it guarantees order and timing as needed. Some strategies to synchronize those are what I talk about previously, you have blocking, non-blocking, async, multiplexed, etc. See the emphasis on "async", this is what I mean by the word being confusing. Somebody decided to call a strategy to synchronize asynchronous processes "async". This then wrongly made people think that asynchronous meant concurrent and synchronous meant sequential, or that somehow blocking was the opposite of asynchronous, where as I just explained, synchronous and asynchronous in reality is a different concept that relates to the timing of things as being in sync (in time with each other, either on some shared clock or in a predictable order) or out of sync (not on some shared clock or in an unpredictable order). Where as asynchronous programming is a strategy to synchronize two events that are themselves asynchronous (happening at an unpredictable time and/or order), and for which we need to add some guarantees of when they might happen or at least in what order.
So we're left with two things using the word "asynchronous" in them:

Asynchronous processes: processes that we don't know at what time they will start and end, and thus in what order they would end up running.
Asynchronous programming: a style of programming that lets you synchronize two asynchronous processes using callbacks or watchers that interrupt the executor in order to let them know something is done, so that you can add predictable ordering between the processes.
Comment: @Helsing Also, concurrent is not the same as parallel. It doesn't mean two things are happening at the same time, it only means progress on more then one thing is made before any of them finishes. That could be accomplished with parallelization, or simply with interleaving, a.k.a. task switching.
Comment: Not sure why you said "Synchronous is defined as happening at the same time."? The whole idea is that it's not concurrent, aka not happening at the same time.
Comment: @Helsing That's literally what the word means. Synchronous means same time, and asynchronous means not same time :p. The reason something is asynchronous, is because it cannot happen at the same time, it must happen before or after. If it could happen at the same time, you could simply parallelize it, or do it in any order, and you wouldn't need explicit synchronization. That's why async programming is all about doing this, then that, wait on these things and then, etc. Because none of those things can happen together at the same time.
Comment: It's best to see it like this. Synchronous -> orderly. Asynchronous -> unorderly.
Comment: For those still confused, if you've got operations and they can happen in non-deterministic order, they are asynchronous, aka out of sync. For example if you send two messages to update the same thing over the network, the messages could arrive out of order. This is because sending messages over the network is asynchronous, the messages are not synchronized in any way. If this is an issue for your update behavior to be correct, you will need to synchronize them. One technique to do so got the name "async programming", where you send the first and await it to be received until you send the next
Answer: A nonblocking call returns immediately with whatever data is available: the full number of bytes requested, fewer, or none at all.
An asynchronous call requests a transfer that will be performed in its whole(entirety) but will complete at some future time.
Answer: Putting this question in the context of NIO and NIO.2 in java 7, async IO is one step more advanced than non-blocking.
With java NIO non-blocking calls, one would set all channels (SocketChannel, ServerSocketChannel, FileChannel, etc) as such by calling AbstractSelectableChannel.configureBlocking(false).
After those IO calls return, however, you will likely still need to control the checks such as if and when to read/write again, etc.
For instance,
while (!isDataEnough()) {
    socketchannel.read(inputBuffer);
    // do something else and then read again
}

With the asynchronous api in java 7, these controls can be made in more versatile ways.
One of the 2 ways is to use CompletionHandler. Notice that both read calls are non-blocking.
asyncsocket.read(inputBuffer, 60, TimeUnit.SECONDS /* 60 secs for timeout */,
    new CompletionHandler<Integer, Object>() {
        public void completed(Integer result, Object attachment) {...}
        public void failed(Throwable e, Object attachment) {...}
    }
}

Comment: `FileChannel` is not selectable and can't be configured to non-blocking.
Answer: As you can probably see from the multitude of different (and often mutually exclusive) answers, it depends on who you ask. In some arenas, the terms are synonymous. Or they might each refer to two similar concepts:

One interpretation is that the call will do something in the background essentially unsupervised in order to allow the program to not be held up by a lengthy process that it does not need to control. Playing audio might be an example - a program could call a function to play (say) an mp3, and from that point on could continue on to other things while leaving it to the OS to manage the process of rendering the audio on the sound hardware.
The alternative interpretation is that the call will do something that the program will need to monitor, but will allow most of the process to occur in the background only notifying the program at critical points in the process. For example, asynchronous file IO might be an example - the program supplies a buffer to the operating system to write to file, and the OS only notifies the program when the operation is complete or an error occurs.

In either case, the intention is to allow the program to not be blocked waiting for a slow process to complete - how the program is expected to respond is the only real difference. Which term refers to which also changes from programmer to programmer, language to language, or platform to platform. Or the terms may refer to completely different concepts (such as the use of synchronous/asynchronous in relation to thread programming).
Sorry, but I don't believe there is a single right answer that is globally true.
Comment: +1 Good answer. People need to be aware that "asynchronous" can mean _either_ non-blocking, _or_ the Microsoft asynch (event-based/ callback) approach.
Answer: Blocking call: Control returns only when the call completes.
Non blocking call: Control returns immediately. Later OS somehow notifies the process that the call is complete.

Synchronous program: A program which uses Blocking calls. In order not to freeze during the call it must have 2 or more threads (that's why it's called Synchronous - threads are running synchronously).
Asynchronous program: A program which uses Non blocking calls. It can have only 1 thread and still remain interactive.
Comment: Non-blocking call: Control returns after doing as much as can be done essentially immediately; the method indicates how much was done.  That is different from an asynchronous call, which behaves as you described for blocking call.
Answer: Non-blocking:  This function won't wait while on the stack.
Asynchronous:  Work may continue on behalf of the function call after that call has left the stack
Comment: @Marenz meaning you can't do non-blocking io directly with posix calls. That doesn't change the meaning he gives here.
Comment: @Marenz Which only means that the flag is ignored for files. It doesn't affect the meaning of this answer.
Answer: Synchronous means to start one after the other's result, in a sequence.
Asynchronous means start together, no sequence is guaranteed on the result
Blocking means something that causes an obstruction to perform the next step.
Non-blocking means something that keeps running without waiting for anything, overcoming the obstruction.
Blocking eg: I knock on the door and wait till they open it. ( I am idle here )
Non-Blocking eg: I knock on the door, if they open it instantly, I greet them, go inside, etc. If they do not open instantly, I go to the next house and knock on it. ( I am doing something or the other, not idle )
Synchrounous eg: I will go out only if it rains. ( dependency exists )
Asynchronous eg: I will go out. It can rain. ( independent events, does't matter when they occur )
Synchronous or Asynchronous, both can be blocking or non-blocking and vice versa
Answer:

synchronous
asynchonous

block
Block I/O must be a synchronus I/O, becuase it has to be executed in order. Synchronous I/O might not be block I/O
Not exist

non-block
Non-block and Synchronous I/O at the same time is polling/multi-plexing..
Non-block and Asynchronous I/O at the same time is parallel execution, such as signal trigger…

block/non-block describe behavior of the initializing entity itself, it means what the entity does during wating for I/O completion
synchronous/asynchronous describe behavior between I/O initilaizing entity and I/O executor(the operating system, for example), it means whether these two entity can be executed parallelly
Answer: TL;DR: Synchronous/Asynchronous refers to how a task is executed, while blocking/Non-blocking refers to the amount of effort an operation puts into performing a task.

Synchronous/Asynchronous refers to how a task is executed. An operation is considered synchronous when it is executed in the foreground without spawning any background job; otherwise, it is considered asynchronous and executed in the background concurrently*.
Blocking/Non-blocking refers to the amount of effort an operation puts into performing a task especially when the task may need multiple retries or waiting. A blocking operation puts in its best effort to complete the task in the foreground, meaning that it keeps retrying to get the final result, while a non-blocking operation is allowed to return an intermediate result after attempting but failing to complete.
Based on the definition, we can draw the following conclusions:

A blocking operation is synchronous. This is because a blocking operation puts in its best effort to complete the task in the foreground, meaning that it does not spawn a background job. Examples of blocking operations include blocking send.
An asynchronous operation is non-blocking. This is because an asynchronous operation spawns a background job and does not perform everything in the foreground. Examples of asynchronous operations include CLFLUSHOPT.
A non-blocking operation can be either synchronous or asynchronous. Since a non-blocking operation does not put in its best effort in the foreground, it can either return the current result or spawn a background job to complete the task. Examples of non-blocking operations include non-blocking send (synchronous) and CLFLUSHOPT (asynchronous).
A synchronous operation can also be either blocking or non-blocking. This is because a synchronous operation does not spawn a background job. It can either put in its best effort to complete the task in the foreground (blocking) or try once and return the result (non-blocking). Examples of synchronous operations include non-blocking send (synchronous and non-blocking) and blocking send (synchronous and blocking).

Below is a table to facilitate the points.

synchronous
asynchonous

block
normal functions, like sum(), send(), printf()
Not exist

non-block
functions that tries to do something.  Eg. non-blocking send/recv(), try_lock()
all asynchronous functions, may or may not have a call back function.  Eg. await in asyncio.

Note:

its better to say async is utilizing concurrency but not necessarily parallelism, as concurrency refers to the ability of a system to perform multiple tasks or processes at the same time, and it may or may not be parallel (eg. multiplexing).
Answer: The blocking models require the initiating application to block when the I/O has started. This means that it isn't possible to overlap processing and I/O at the same time. The synchronous non-blocking model allows overlap of processing and I/O, but it requires that the application check the status of the I/O on a recurring basis. This leaves asynchronous non-blocking I/O, which permits overlap of processing and I/O, including notification of I/O completion.
Answer: To Simply Put,
function sum(a,b){
return a+b;
}

is a Non Blocking. while Asynchronous is used to execute Blocking task and then return its response
Answer: They differ in spelling only.  There is no difference in what they refer to.  To be technical you could say they differ in emphasis. Non blocking refers to control flow(it doesn't block.) Asynchronous refers to when the event\data is handled(not synchronously.)
Answer: Blocking: control returns to invoking precess after processing of primitive(sync or async) completes
Non blocking: control returns to process immediately after invocation
Comment: This does not even answer what is being asked.


Can I get back desktop Gadgets?

Question: There is no option to add desktop Gadgets in Windows 8 desktop view, Can i still get them back, without having to use untrusted third party software?
Comment: Gadgets were removed from Windows 8/8.1 as they were a security flaw.
Answer: I Found One, the CPU usage widget.

Open the task manager.
Go to performance tab.
Right click on left bar. as shown below. Or Double click on there.

Then, Enjoy a better widget than Windows 7 with complete info of CPU, RAM, Disk Usage and Network Usage. Just Loved it.
Comment: Yeah I'd love to see some small summary of what applications/processes are using the resources. But I do love your tip, will be useful until then =)
Answer: Nope, not without resorting to third party software. Windows Desktop Gadgets has been removed from Windows 8.
http://www.theverge.com/2012/7/5/3138572/windows-8-desktop-gadgets-support
Apparently, Live Tiles (on the Start screen) is a replacement for Windows Desktop Gadgets.
Answer: See this if you do not want 3rd party software, it installs the sidebar and gadgets that originally came with W8 Release Preview.
or consider this software for easier installation.
8GadgetPack (free)
Adding on to Rakib's answer, there is always 8GadgetPack, which brings back the functionality of the desktop gadgets of Windows 7 to Windows 8 in a nifty little sidebar.  It comes pre-installed with a few common gadgets (along with Microsoft's default) and will give you the option to install more .gadget files.
Visit their homepage here.

.
Also see this if you do not want 3rd party software
.
Comment: are you able to install GPU Observer or other gadgets that measures GPU temperature/memory/etc? because windows 8 blocked or removed the API that were being used on the ones i tested
Answer: The gadgets aren't removed from windows 8.
Here is my screen showing the gadgets:

Perhaps the trick was to enable Media Center, which I have just done today, and don't know if gadgets were available earlier.
EDIT:
yes, they are removed from the later builds. Just read this.
Comment: You are running release preview.
Answer: GADGETARIAN adds gadget support on Windows 8 and 10 in a few seconds, and it is safe, because it just enables the native (now hidden) Windows OS gadget functions.
Comment: This isn't safe. Gadgets were removed because they had a major security flaw.
Comment: Https://windows.microsoft.com/en-IN/windows/gadgets and HTTPS://technet.microsoft.com/library/security/2719662

Can I get back desktop Gadgets?


FCC certified module in europe

Question: If I have an FCC certified BLE module, can I use it in a product destined for Europe and CE mark the product with no additional (intentional radiator) testing?
Comment: Nice to see someone tries to do something properly. Global webshops have made possible to sell and purchase stuff where certification stamps are not worth more than the ink they contain. Authorities here in far west have no way to prevent a criminal which hides in a place like Wuanhungtsouhai  to produce and sell his low-cost "genuine" Sony or Hitachi counterfeits which radiate like a radio station and have direct connection from mains AC input to touchable parts.
Comment: @user287001 That EU and USA uses different radio standards has nothing to do with that though, it's just made that way politically, to prevent export and free trade. Specifically, greedy authorities in USA (and Canada) charge you a one time free beyond the EMC testing costs. Now _that_ should be criminal - no such thing exists in EU for license-free bands. I'm not up to date with the technical specifics in this case, but EN/ETSI 300 328 vs FCC Part 15C will likely boil down to similar technical requirements at least on the 2.4GHz band.
Answer: Not likey. The regulations differ a bit. However:

If you still have the test results, you might be able to compare them to the EU standards and pass the tests
I heard that a lot of manufacturers just slap on the CE marking and only test for compliance when their compliance is challenged. (At court or somewhere else). When you are confident it will pass, you could do this.

Disclaimer: I only did some research on this matter and have no real life experience whatsoever, so take this with a pinch of salt or mostly some general guidance on which to conduct your own research.
Answer: If your module is soldered or connected to a system that you designed, you have to go to an EMC lab and do some tests.
Not all, but just some.
For example, you will have to do the output power test.
This is true in Europe but I guess that holds in the US as well.
When coming to Europe from FCC you need to have a CB Report. It's basically paper.
That paper contains for example the extra tests you need to do to comply to European CE regulations.
UL, TUV and many others do that all the time.
https://gma.ul.com/about/cbscheme/

FCC certified module in europe


Difference in Premove Limits: Lichess vs. Chess.com

Question: I've noticed a distinct difference in the premove system between Lichess and Chess.com. Lichess allows only one premove at a time, whereas Chess.com permits multiple premoves. What is the rationale behind this difference in design? Does it significantly affect the strategy or pace of online chess games?
Answer: The difference is somewhat significant (chaining premoves can be useful in certain situations, such as promoting an unopposed passed pawn in the endgame), but even more significant is that chess.com takes a tenth of a second off for each move regardless of premoving. This increases the danger of being low on time as a player often cannot effect a checkmate with a handful of seconds remaining even if the position is otherwise completely trivial to win.  On lichess, such positions are often winnable regardless of clock situation due to premoving.


Does any beach in Sentosa Island in Singapore allow swimming after 7pm?

Question: I went to a beach in Sentosa Island in Singapore, namely Siloso beach, and I read that swimming was not allowed after 7pm on the sign pictured below. Does any beach on Sentosa Island in Singapore allow swimming after 7pm?
Comment: there are _hours_ for being in the water? (are those beaches on a private property?)
Comment: @njzk2 swimming hours are regulated indeed, and I have no idea whether it's private property. I also wonder whether it's lawful and the penalty if any of someone gets caught for "using the sea". If you ask me, they should focus on regulating individuals who pollute the sea rather than people who want to enjoy it, and definitely not penalize people who prefer to avoid UVs. I am much more concerned about skin cancer than drowning. If someone can't swim against the current, just float away and wait to be fished or run across some area with less current.
Comment: @FranckDernoncourt Zoinks, if you suddenly disappear should we notify the Singaporean Coast Guard to go look for you? Singapore has been making HNQ quite a bit thanks to your trip! Since you like doing a bunch of stuff at night, let me recommend Night Safari. Best evening attraction that I experienced during my short time there.
Comment: @AldusBumblebore Thanks, it's ok, you can let me float away, I would like to visit Batam anyway. Thanks for the recommendation!
Answer: No, they do not.  There are only three beaches on Sentosa (Tanjong, Palawan, Siloso) and they're all managed by the Sentosa Development Corporation with the same rules.
The reason you're not allowed to swim at night is because the beaches are artificial and there are strong currents right outside the line of buoys.  People who go beyond them regularly get in trouble, and at night when it's dark and there are no life guards this would be a likely death sentence.
Comment: in Singapore, you should assume all rules are implemented at all times
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/150219/discussion-on-answer-by-lambshaanxy-does-any-beach-in-sentosa-island-in-singapor); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.


Parking brake left on

Question: So I went to move  my car this morning around two blocks from my house. My parking brake was on and I didn't know. When I parked I realized it was on the whole time. It was driven for 2 block going 5 miles per hour 10 at the most but I just want to know if there was any damage for that small amount of driving and slow speed. It's a 2019 Dodge Charger
Comment: Been asked before, search on here.
Answer: The short of this is yes, you MAY have damaged your rear brakes.  The only way to tell for sure is to have them inspected by a mechanic (or if you know what you are doing, inspect them yourself) and determine if there has been damage, what is the extent of it, and what (if anything) needs to be fixed.
In some cases the damage is just premature wear of the pads and rotors or drum.  In other cases the pads can become "glazed" due to the heat and will no longer brake properly.  The rotors or drums can also be damaged by heat and warp or even crack.
It's also possible that the brake calipers or cylinders have "baked" and now have solidified brake fluid in them. In this case they will need to be rebuilt or replaced.
I know that's a lot of "ifs" but any or all of this is possible.  It just depends.
Comment: Thank you. Yeah it is a lot of ifs but it makes sense but I don't think or know if driving around the block at 10 miles an hour or slower will damage it like that.
Comment: if the brakes still seem to work the same as before they're probably fine.

Parking brake left on


How does electricity produce magnetisim?

Question: I am in class 10 and I have just read the electromagnetism chapter. They always keep on saying that electricity produces magnetism! but how!? We know electrons move, but how do they produce something that can exert a force on something metallic far away from those electrons? I have tried to read about it on wikipedia but I am not able to understand the complicated terms! Please answer in such a way  that it will remove all my confusions!
Comment: How? Because that is a fundamental property of charges! If they move, they generate a magnetic field. In many ways, there is no more deep explanation. If you understand special relativity, you can transform the electric field from the rest frame of the particles to the laboratory frame, and see that a magnetic field arises, but I guess, you will not find that very illuminating.
Comment: http://physics.stackexchange.com/questions/184646/are-magnetism-and-electricity-the-same-thing/184737#184737
Comment: I donnot find it even illuminating!
Comment: Op, there exist several descriptions of this system at various levels of complexity...to help give an appropriate answer, it would help to know a few things: are you familiar with calculus, or have an intuition for the concept of a field?  How has electricity been described in class 10 thus far?
Answer: There is neither electricity alone nor magnetism alone produced by it. There exists an inseparable electromagnetic field produced by (moving) electric charges, in mutual interaction with them, and the splitting to its "electric" and "magnetic" parts depends upon the motion of the observer.The concept of electricity alone and magnetism that produces is due to educational reasons, since there is no way to understand this during your school years (except the case to be a genious). In your next years such questions will be the motivation to meet : (1) Maxwell with his famous equations of electrodynamics, a unification of "electricity" and "magnetism" and (2) Einstein with his theory of Special Relativity and his ideas, unification of the 3-dimensional space and 1-dimensional time to the 4-dimensional space-time.
But don't be disappointed by all these. These ideas must not prevent you from studying the trees :electrostatics (Coulomb's Law etc), magneto-statics (Biot and Savart Law, Faraday's Law etc) and others, in order to see later the forest of Classical Electrodynamics (Maxwell's Equations etc) inextricably coupled with the theory of Special Relativity.
Don't forget, Ladies and Sirs : we try to answer to a 15 years old boy !!!
Comment: A moving electric charge does not emit light.
Comment: There is a difference between a magnetic field and an e-m field.  A horseshoe magnet is not emitting and e-m field.
Comment: This is the best answer so far: no one else has made the IMO crucial point that the two phenomena belong to one, indivisible whole.
Answer: It is an observed result that a moving electric charge can produce a magnetic force.  As to the 'how', that's a bit troublesome.  At this level, one has to accept some things as axiomatic.
As to the force at a distance, this is also true of ordinary electric potential.  So magnetic force at a difference should be no more troublesome than electric force at a distance.
Answer: I'll attempt to "explain" it as simply as possible but without cheating ("not simpler"). This is indeed not an answer to the "how" does something happen, but rather how physicists describe it.

in physics, one calls a scalar field a function $\psi:\mathbb{R}^4 \rightarrow \mathbb{R}$ from $\mathbb{R}^4$ to $\mathbb{R}$, (where $\mathbb{R}^4$ is the mathematical object corresponding to "space-time", i.e. a set of points whose position is given by 4 numbers, the first coordinate being the time t, and the 3 others the (x,y,z) coordinates). One could also consider a function from space $\mathbb{R}^3$ only, to $\mathbb{R}^3$

This notion allows to describe for example the evolution the temperature in a room: a temperature scalar field $\psi$ would associate to each point $P\in\mathbb{R}^4$ with "temporal position" $t_P$ and spatial position $(x_P,y_P,z_P)$ the value denoted $\psi(t_P,x_P,y_P,z_P)$ of the temperature at that precise time and spatial position.

In eletromagnetism one needs the notion of vector field: to each point in space-time is associated a vector:
1- the eletric field $\vec{\mathbf{E}}: \mathbb{R}^4 \rightarrow \mathbb{R}^3$ describes the force that is exerted on a charged particule with charge $q$ at space-time position $(x_P,y_P,z_P)$ via the following formula
$$\vec{\mathbf{F}} =q \vec{\mathbf{E}}(t_P,x_P,y_P,z_P)$$
$\vec{\mathbf{F}}$ is a vector, it is the mathematical description of the force exerted on a charged particule at position $(x_P,y_P,z_P)$ in presence of the field $\vec{\mathbf{E}}$. The vector $\vec{\mathbf{F}}\in\mathbb{R}^3$ (belongs to $\mathbb{R}^3$), one indeed needs 3 numbers to describe the direction and intensity of a force.
2- The magnetic field $\vec{\mathbf{B}}: \mathbb{R}^4 \rightarrow \mathbb{R}^3$ describes another force that is exerted on charged particles (or also on particles with a magnetic momentum). In the case of charged particles, the formula is given by
$$\vec{\mathbf{F}} =q \vec{\mathbf{v}}\wedge \vec{\mathbf{B}}(t_P,x_P,y_P,z_P)$$
where $\vec{\mathbf{v}}$ is the speed of the particle and $\vec{\mathbf{v}}\wedge \vec{\mathbf{B}}$ (also denoted $\vec{\mathbf{v}}\times \vec{\mathbf{B}}$) is some vector defined by some formula which depends on $\vec{\mathbf{v}}$ and $\vec{\mathbf{B}}$, but one can just remember that it is perpendicular to both $\vec{\mathbf{v}}$ and $\vec{\mathbf{B}}$. In particular this formula says that if the particle does not move, the magnetic field has no effect on it.

To summarize, if you are a charged particle with charge $q$ at position $(x_P,y_P,z_P)$ and at that point in space and time $t_P$ there is an electric field with value $\vec{\mathbf{E}}(t_P,x_P,y_P,z_P)$ and a magnetic field with value $\vec{\mathbf{B}}(t_P,x_P,y_P,z_P)$ then you are submitted to the so-called Lorentz force
  $$\vec{\mathbf{F}} =q \left( \vec{\mathbf{E}}(t_P,x_P,y_P,z_P)+ \vec{\mathbf{v}}\wedge \vec{\mathbf{B}}(t_P,x_P,y_P,z_P)\right)$$

There is a distinct phenomenon: an electron or any charged particle also produces an electric field which is given by the Coulomb law (previously the electric field was a given data, we did not care about how it was produced)
  $$\vec{\mathbf{E}}_{produced} = \pm \frac{q}{\left\lVert\vec{\mathbf{r}}\right\rVert} \vec{\mathbf{r}} $$
(I'm not sure which sign) where $q$ is the charge, and $\vec{\mathbf{r}}$ is a vector giving the relative position at which we want to know the value of $\vec{\mathbf{E}}$ with respect to the position of the charged particle. $\left\lVert\vec{\mathbf{r}}\right\rVert$ is the norm of a vector, i.e. its length. A more complicated formula gives the magnetic field created by an moving charge.

So an eletric field is different from a magnetic field as to how it affects a charged particle, however there is a relation between the two. All the quantities mentionned depend on the referential, exactly like the notion of speed: if you observe an object, you will not measure the same speed depending on whether you are in a train or fixed at some place. The thing I'll skip now are the arguments, the reasoning that led to the following relation, (wikipedia) between the eletric and magnetic field $\vec{\mathbf{E}}_1,\vec{\mathbf{B}}_1$ in a first referential, and those $\vec{\mathbf{E}}_2,\vec{\mathbf{B}}_2$ in a second: (argument in a few words: "symmetry"of the Maxwell equations)
$$ \vec{\mathbf{E}}_2 = \gamma \left( \vec{\mathbf{E}}_1 + \vec{\mathbf{v}} \wedge \vec{\mathbf{B}}_1\right ) - \left ({\gamma-1} \right ) \left( \frac{\vec{\mathbf{E}}_1 \cdot \vec{\mathbf{v}}}{\lVert\vec{\mathbf{v}}\rVert} \right) \vec{\mathbf{v}} $$
$$ \vec{\mathbf{B}}_2 = \gamma \left( \vec{\mathbf{B}}_1 - \frac {\vec{\mathbf{v}} \wedge \vec{\mathbf{E}}_1}{c^2} \right ) - \left ({\gamma-1} \right ) \left( \frac{\vec{\mathbf{B}}_1 \cdot \vec{\mathbf{v}}}{\lVert\vec{\mathbf{v}}\rVert} \right) \vec{\mathbf{v}}$$
(where $\vec{\mathbf{v}}$ now denotes the speed of the second referential relative to the first one (i.e not the same $\vec{\mathbf{v}}$ as before) and $\gamma$ is some function of $\vec{\mathbf{v}}$.) It is based on this formula that people say that eletric and magnetic fields are the same thing. E.g. even if $\vec{\mathbf{B}}_1=0$, but $\vec{\mathbf{E}}_1, \vec{\mathbf{v}} \neq 0$ then $\vec{\mathbf{B}}_2\neq 0$, in words even if in a first referential there were no magnetic field but there is an eletric field, then in a second referential that is moving you will observe a magnetic field.
Comment: I am 15 years old :-P
Comment: you can always read it again in a few years...
Comment: This is not the most appropriate level to answer this question - as is clear by the wording.
Answer: It not produced from, it is the exact same force that do difference thing. Magnetic force is like a torque coiling around direction of electricity. And so if electric charge run in circle then the magnetic that coiled around will be merged in one direction, produce a strong magnet
Still the force is actually came from attractive and repulsive force of electric charge
There are youtube video explain about how electric charge force being magnet related to relativity theory of Einstien
here https://m.youtube.com/watch?v=1TKSfAkWWN0
Answer: I'd just like to add to diracpaul's excellent answer, which to summarize, makes the point that both electricity and magnetism belong to an inseparable whole: you can't treat one as a more fundamental phenomenon producing the other.
Probably the most compelling reason for looking at things in this "indivisible" way is special relativity, wherein we accept the postulate that there is no way of telling whether one is in uniform motion relative to something else without looking outside our laboratory. This is essentially as described in Galileo's famous allegory of Salviati's Ship, and it was taken up again very earnestly by Einstein after having been abandoned in the 19th century because 19th century scientists before the Michelson Morley experiment believed in the luminiferous aether (and thus one could in principle always measure one's motion relative to the aether).
So, if Galileo's postulate truly does hold, then we cannot treat electricity and magnetism as one "causing" the other because different observers in different, relatively moving (at a constant relative velocity) will measure different relative amounts of "electricity" and "magnetism" in an electromagnetic field. It is the way Einstein made sense of certain generator and motor thought experiments that seemed to prefer a particular reference frame if one insists on thinking of electricity producing magnetism or the other way around.
Electricity and magnetism are united in a geometrical object called a 2-tensor which you likely won't have met yet and these objects transform very differently when one shifts one's reference frame from the three component vectors that are commonly used in electrostatic and magnetostatic formulas you have probably seen. The formulas you have most likely seen may give the impression of electricity producing magnetism, but they are not accurate when changing reference frames (without some really messy accounting).


How do I wire this ceiling light?

Question: I know I can connect the loose cable from light switch to light fixture, but what do I do with that extra cable coming down to the outlet? Previously this was a fan/light combo with remote that had two loose three conductor (with red wires) cable  coming from the light switch to fan installed by previous HO.
Comment: Which cable is the power supply?
Comment: You didn't, perchance, take pics of the wiring before you started disassembling things, did you? The wire in question _could_ be supplying power to the light/switch. It could be switched power from the switch to the outlet. What's with all the other cables you've identified at the switch?
Comment: I don't get it, what are we looking at here?  My ants tell me you've drawn every single cable with a red wire.  That's not likely.  Also why remove the /3 (with red) cable? Just because you don't want a fan doesn't mean the next owner doesn't. Rule of thumb: if it's a fan-rated box, run /3 to the box.
Comment: Where does power come into this setup at, and can you post *photos* of the insides of the boxes involved?
Answer: In electrical we don't just throw wires around.
Rules for cable routing
We start at the service panel and we run a cable from there to the first point-of-use (aka "outlet": that's a switch, receptacle etc., sometimes a lamp but there are special rules required if we do that).
From there (often, not always) we run another cable to another outlet (again: switch, receptacle, etc.)
It's a daisy-chain: from panel to outlet 1 to outlet 2 etc.
It's perfectly OK to have branches/tees: so outlet 3 could have its cable go to outlet 1 (it doesn't need to go to outlet 2).
The cable layout cannot have loops, though.  Two separate chains coming from the breaker (or branched off a string) cannot rejoin. If they do, they must be carefully separated in the box. No wires from either side can touch, except the bare safety ground wires.
Your answer depends on the routing of the 2 branches you'd be joining
So now, you must either follow the wires from the switch, and the wires from the outlet... or else make some educated guesses about what they're all about.
In particular, if turning the power on causes both sides to be energized even though they're not connected yet, that means they shouldn't be connected because that would be a loop.
On the other hand, it's possible one side is entirely dead and has no route back to the panel. In that case one side needs to get power from the other.  Maybe the old /3 cable carried always-hot for the onward circuit + neutral + switched-hot for the lamp.
If it's a fan-rated box, please run /3 cable to it.
I get you don't want a fan, but many people do. The next buyer of your home might be one of them.  Having /3 cable from the fan to the fan-rated box will mean that person doesn't have to bust out drywall later to reinstall what you removed.
If the box is not rated for fans, don't bother; no fan should be there.

How do I wire this ceiling light?


Gravitational Potential Energy between atoms within the same object

Question: How can you calculate the gravitational potential energy (GPE) of just one object? I learned that there must be at least two masses in order for gravitational potential energy to exist, but any object is composed of multiple atoms, so isn't there GPE between those atoms within the object? If two spheres have GPE between them, but then I glue the two spheres together, or the two spheres touch at a point, don't they still have GPE?
Answer: For atoms and molecules, the electromagnetic force is much stronger than gravity.
So you could calculate the GPE of the molecules making up a baseball, but it would be vanishingly small.  Much smaller than the energy required to break the molecular bonds holding the material together (or to break the glue holding the spheres together).
Unless you're looking at something of the size of an asteroid or larger, generally we ignore the internal gravitational energy because other things are more important.
Answer: You can calculate the gravitational potential energy of an extended object by using integral calculus to treat it as a collection of infinitesimally small masses $dm$, with GPE $-G(dm_1)(dm_2)/r$ between each pair. You can think of this as adding up the GPE between each pair of atoms.
When you do this for a uniform-density sphere of mass $M$ and radius $R$, you find that its gravitational potential energy is
$$U=-\frac{3GM^2}{5R}.$$
A baseball has a mass of about 145 grams and a radius of about 37 millimeters. Its gravitational potential energy is therefore about negative 23 trillionths of a Joule. This is very small; 23 pJ is approximately the energy it takes to lift a flea 0.005 millimeters under Earth gravity.
By contrast, gravitational potential energy is very large for astronomical objects. For the Earth, it is about $-2\times10^{32}$ Joules! It would take all of the energy radiated by the Sun for a week to gravitationally disperse the Earth's atoms, according to Wikipedia.
When a uniform-density sphere of mass $M_1$ and radius $R_1$ touches another uniform-density sphere of mass $M_2$ and radius $R_2$, the gravitational potential energy of the whole system is
$$U=-\frac{3GM_1^2}{5R_1}-\frac{3GM_2^2}{5R_2}-\frac{GM_1M_2}{R_1+R_2}.$$
The first two terms are the GPEs of each sphere. The third term is the GPE between the two spheres. This GPE between spheres turns out to be as if the whole mass of each one were concentrated in a point at its center, even though what is really going on is that every atom in the first sphere interacts with every atom in the second sphere.


In Florida, if you are caught with stolen property. But didn't steal the property, can you be charged?

Question: Lets say you are walking around your neighborhood and you find a golf cart in the middle of the road with the keys in it. You get curious to see if you can find something with the owners info on it and sit down to look through the cart. As you are looking around while sitting in the cart, the Police roll up and find you in the cart and it turns out it is stolen. Can you be charged for theft of the item, even thou you didn't steal it?
Answer: They can charge you with anything they think you did.
And yes, the circumstances play a large part in the decision to arrest, charge and prosecute.
However, circumstances include you: Reputation is everything.
If you are a 17 year old male troublemaker with a long juvie rap sheet, including 3 past instances of stealing golf carts, then expect to be charged with the theft.  Honestly you would probably be charged with the theft if you had simply stayed away and called the cops to report it abandoned.
If you came upon it in your vehicle and it's obviously blocking the road and your apparent motive is to figure out how to move it so you can get by, then you're probably in the clear.
If you're a 44 year old owner of a golf cart business, PAL supporter, city councilwoman and know half the cops including one in the car that stopped you, then, they're going to pretty much listen to you as far as what's the deal with the cart.  Probably ask you for help moving it safely, might even ask you to get your cart-hauler to take it to impound. You won't hear from the D.A. obviously; nobody will say "Sue Councilwoman stole a golf cart" because it would sound absurd and make the speaker appear to be a politically motivated liar.
That's the power of reputation; no one would speak it even if you did steal it.  (Of course if you got caught doing it on a Ring camera, well, the hero takes a fall!)
Anything in between, they'll deal with it in proportion to both the facts about you and the fact about the situation. You do not have a right to get the same credibility as the councilwoman; that is earned.  That's the power of reputation.
Comment: I love real world common sense answers like this. Not just citations of case law.
Answer: Probably, that person could be charged with theft.
In Florida, theft is defined as

812.014 Theft.—
  (1) A person commits theft if he or she knowingly obtains or uses, or endeavors to obtain or to use, the property of another with intent to, either temporarily or permanently:
  (a) Deprive the other person of a right to the property or a benefit from the property.
  (b) Appropriate the property to his or her own use or to the use of any person not entitled to the use of the property.

The question is whether that person will be charged or whether that person will be convicted. That is more up to prosecutorial discretion.
That person would be more likely to be charged if they matched the description of the person that did steal it. Otherwise they would be less likely to be charged.
The police can only arrest if they have probable cause. It is likely that they would be able to arrest that person and such an arrest would be maintianed.
The prosecution has a lot of discretion as to whether to file charges and there is not a standard that is applied to the prosecutor as far as I'm aware. So if the police chose to arrest, the prosecutor could file charges. In this circumstance, without any more information, I would find it doubtful that the prosecutor would file. It seems like it would be a fairly weak case.
The last question, whether that person would be convicted would be almost entirely dependent on how sympathetic they would be in the court room.


Best practice for testing chef recipes?

Question: My team has created a large number of chef cookbooks. I was wondering what methods and frameworks I should look into so we can start creating tests to assure that our nodes are configured properly?
Comment: Sounds like it belongs on cooking.se ;)
Comment: For a moment I thought you was talking about Chef: http://en.wikipedia.org/wiki/Chef_%28programming_language%29
Answer: You might (also) look into Vagrant for this.

A video is showing how to use the combo of Vagrant and Chef cookbooks.
And there's a dedicated page to Vagrant and Chef on the Opscode site (update 2015-01-23: page has gone...).
Answer: There's the cucumber-chef ruby gem and a recently released book Nelson-Smith et al - "Test-driven Infrastructure with Chef" that makes use of that gem - http://www.cucumber-chef.org/
Just remembered this from my github watchlist: https://github.com/gregretkowski/vmth/

The VMTH (Virtual Machine Test Harness) provides a mechanism to unit-test your infrastructure automation - puppet policies, chef recipes, release deployment scripts, etc. It uses features of modern VM monitors (like qemu) to snapshot system state, and then reset that state after each test, so that a series of tests can be performed on a VM instance in rapid succession
Answer: There's a number of options.

cucumber-chef rubygem by Stephen Nelson-Smith, with a related / accompanying book.
minitest cookbook by AJ Christensen.
vagrant to provide test virtual machines thanks to Mitchell Hashimoto

Opscode has on the Chef development roadmap "no-op" support which will help with testing. We do argue that "no-op" doesn't necessarily do what you want, but understand the desire for the feature.
Answer: Some of the answers here seem a bit old. For CI and local testing I would look into leveraging a test harness tool like Test Kitchen which also supports Vagrant if you've been using that already.
It will allow you to run your coobkooks against many cloud and virtualizations solutions out there today: EC2, Digital Ocean, Vagrant, Docker, etc..
It also has plugins to allow you to run one of the many infrastructure test tools that exist out there today:

serverspec - Most popular testing framework.
goss - YAML, simple, self-contained binary, extremely fast.
inspec - think of it as serverspec improved (written by the chef guys).
testinfra - Python based server testing framework.
Answer: In my experience, the only way to really do this is with a staging environment and careful development practices.  Mocking out the actual work to be done is incredibly messy and fragile, and CI test suites running on commit or push are a lot of effort to write and maintain (although Chef is probably a lot better at this than Puppet, which is my main experience), and take a ridiculous amount of time to run.
EDIT
Just after I wrote this, I suddenly realised there might be a way to do reasonably efficient "unit" testing of Chef/Puppet recipes with a union filesystem and a significant amount of scaffolding.  However, I can't find anything out there that anyone's done already in this area.  I might have just found myself a project.
Comment: Testing the infrastructure itself is incredibly important.  Naturally, there are a number of methodologies, i.e, functional and nonfunctional,  necessary to implement this slightly differently than software methodologies.

Best practice for testing chef recipes?


Is there a Linux equivalent for VHD from which it can boot?

Question: I have searched for this quite a lot, yet all I could find was VLite. By the way, I'm talking about an equivalent for Windows native VHD boot and not virtualization.
Answer: Grub can map pretty much any disk image files and boot from that

grub4dos and grub1 support the map command for booting from read-only images. I'm not sure about their capabilities to boot read-write images. There are 2 types of mapping

Memory map: The image is loaded onto memory before mapping as disk, usually used with floppy disk images. When memory mapping is used the disk image file can be non-contiguous. For example:
map (hd0,0)/win98.ima (fd0)

Direct map: map the file using int13, requires the file to be contiguous
map (device)/path/file.iso (hd32)

After all mappings were done you'll need to commit them with map --hook
These types of mapping allow you to easily boot any live Linux distros. If necessary you can use a casper rw persistent disk image for non-volatile data. For more information read LiveCD/Persistence

In grub2 you'll have to use the loopback command which can be used to boot both read-only and read-write images

5.2 Loopback booting
GRUB is able to read from an image (be it one of CD or HDD) stored on any of its accessible storages (refer to see loopback command). However the OS itself should be able to find its root.
This usually involves running a userspace program running before the real root is discovered. This is achieved by GRUB loading a specially made small image and passing it as ramdisk to the kernel. This is achieved by commands kfreebsd_module, knetbsd_module_elf, kopenbsd_ramdisk, initrd (see initrd), initrd16 (see initrd), multiboot_module, multiboot2_module or xnu_ramdisk depending on the loader.

In the past wubi used the same technique to boot Ubuntu from an image without an ext4 root partition

If you're using syslinux then there's an equivalent feature called MEMDISK

MEMDISK is meant to allow booting legacy operating systems. MEMDISK can boot floppy images, hard disk images and some ISO images.
MEMDISK simulates a disk by claiming a chunk of high memory for the disk and a (very small - typically, 2K) chunk of low (DOS) memory for the driver itself, then hooking the INT 13h (disk driver) and INT 15h (memory query) BIOS interrupts.

See

Booting an EXT4 image file from GRUB2
grub: boot from ISO
How to boot Fedora Live CD iso from a Hard Drive?
How to boot Linux from image on disk or "Poor Man's Install"?
Can I boot Linux from a VHD?
Install Ubuntu from ISO image directly from hard disk of a system running Linux?
Deploy Linux into, and boot from, VHD
How to Boot Linux ISO Images Directly From Your Hard Drive
Is it possible to native boot Linux from raw disk image?
booting linux from a loop file system
Comment: I thought so - might help to add some information on the specifics on how to do that - for posterity's sake.


Google Analytics: how to see event sequence for a given user

Question: Is it possible to see all the events generated by a single user? In other words, is it possible to trace his/her actions on a page? The goal is to understand what a given user tried to do, as opposed to seeing a summary of all events.
Answer: Yes you can indeed, you can actually track everything user did how much time he spent what event he triggered, but every user on your site get a generic id number set by GA cookie, so if you have registration modal and specific privacy policy accepted by user you can even know which user did what and when. FOR the report just go to your view and than under audience click user explorer you shall see a list with some long generic numbers separeted with dot. This numbers are your user. Drill donw and enjoy


how can I stop fizz from dancing around so much?

Question: Fizz drives me insane he jumps around the hits me then jumps around some more then siks his stupid shark on me and boom I'm dead.....Is there a way to avoid this champion, stop him from doing his lil dance or a sure way to counter him?
Answer: Silence plays a key role in stopping fizz. or any hard cc. As long as you can stop him from trickster then you should be able to melt him as he is generally squishy. An item that can help with this if you are a caster is Zhonyas Hourglass. That way you can use it to avoid the shark damage and then turn on him. Other than that it is hard to counter the trickster from Fizz seeing as the point of it is to make him untargetable.
Answer: Targeted stuns (Such as Taric's Dazzle) when his Playful/Trickster is on cd, but as an Assassin type character, his mobility is a strong aspect of him.
Comment: When the other team has a fizz I try and stay ver very far away because what Ive noticed is when he does that play/trick thing he does splash damage and he ends up getting 2 or 3 kills from just one team fight
Answer: The obvious answer is if you are in ranked or draft mode and team captain, simply ban fizz or pick fizz yourself.  Otherwise, you can't stop fizz from using his untargetable skill, just like you can stop vlad from using his pool or a player from activating their zhonya's.  Simply try to force them to put it on cooldown through a gank, or simply outplay them.


What does `: Hold[$IterationLimit]` mean?

Question: In this answer, what does the  : Hold[$IterationLimit] part of the following construct do?
cfRemainders[x_, iter_: Hold[$IterationLimit]]

Answer: The original complete definition is
cfRemainders[x_, iter_: Hold[$IterationLimit]] :=
 NestWhileList[FractionalPart[1/#] &, FractionalPart[x], # != 0 &, 1, ReleaseHold[iter]]

The iter_ : Hold[$IterationLimit] makes iter an Optional argument with the default value Hold[$IterationLimit] if the argument is omitted.
Secondly, by using Hold, $IterationLimit is not evaluated until cfRemainders is actually called and ReleaseHold[iter] is executed.  So if a user resets $IterationLimit, subsequent calls to cfRemainders will respect it.

One question might be why did I do it this way.
(My feeling is that I'm overlooking something and someone will suggest a better way to limit the number of times an iteration occurs.)
Without some limit on NestWhileList, calling cfRemainders on an irrational number would run forever (or until Mma ran out of memory).  $IterationLimit seemed like a convenient system variable to use ($RecursionLimit is another and one can argue which seems more appropriate).  But without Hold in the definition
cfRemainders[x_, iter_: $IterationLimit] := ...

the current value of $IterationLimit is substituted and the definition is equivalent to (assuming $IterationLimit == 4096)
cfRemainders[x_, iter_: 4096] := ...

(You can check with ? cfRemainders.)  In this case, if a user changes $IterationLimit, cfRemainders is unaffected.
Alternative definition could be to set my own arbitrary limit or make the argument iter mandatory:
cfRemainders[x_, iter_: 1000] := ...
cfRemainders[x_, iter_] := ...

Another good question is why worry about this, when I neglected to put a restriction on x to be numeric, which would be helpful, too:
cfRemainders[x_?NumericQ, iter_: Hold[$IterationLimit]] := ...

In fact, I think I'll go edit my other answer.
Comment: I think your method is quite reasonable, but if you seek another you could also do something like: `f[x_, iter_: -1] := [. . ., iter /. -1 :> $IterationLimit]` Or, you could you Options.
Answer: What this does is set a default value for iter, meant for use if cfRemainders is called with only one argument. The default value for iter in this case is $IterationLimit, and the Hold[] enclosing it means cfRemainders will use $IterationLimit symbol for the new rule. If there was no enclosing Hold[], $IterationLimit would have been replaced with the Integer value assciated with it, in the new rule defined for cfRemainders. This makes cfRemainders more robust\general because, upon calling it, it'll always iterate the appropriate number of times, even if $IterationLimit has been changed. Check the differences with  DownValues[cfRemainders], with/without Hold[].
Answer: Actually this is more like a comment to Michael E.'s answer than an own answer, but it became too long for a comment. I think it is worth mentioning that $IterationLimit (and also $RecursionLimit and probably some others as well) is somewhat special and thus needs  special treatment: For a "normal" variable it would be quite simple to achieve what Michael wants with something like:
 $iterationlimit = 4096;
     Block[{$iterationlimit},cfRemainder[x_, iter_: $iterationlimit] := Print[iter];]

Now if you look at DownValues[cfRemainder] or just use the followings lines of code you find that it will behave as wanted even without the extra Hold and ReleaseHold:
DownValues[cfRemainders]

(*
==> {HoldPattern[cfRemainders[x_, iter_ : $iterationlimit]] :>
  Print[iter]}
*)

cfRemainders[10]
Block[{$IterationLimit = 20}, cfRemainders[10]]

For some deeper reason out of my knowledge that doesn't work for $IterationLimit as it seems to not behave as a normal variable within Block: it will always have that OwnValue even if it is Blocked, presumably this is to build an extra barrier against infinite iterations (which would lead to a crash):
Block[{$IterationLimit},
      cfRemainders[x_, iter_: $IterationLimit] := Print[ReleaseHold[iter]];
  ];
DownValues[cfRemainders]

(*
==> {HoldPattern[cfRemainders[x_, iter_ : 4096]] :>
  Print[ReleaseHold[iter]]}
*)

There are possibilities to overcome that situation, the trick Micheal used with using an extra Hold and ReleaseHold is one, here are two ways which avoid the extra ReleaseHold but need some more complicated definitions:
Variant 1:
ClearAll[cfRemainders];
Module[{marker},
  cfRemainders[x_, iter_: marker] := Print[iter];
  DownValues[cfRemainders] =
    ReplaceAll[DownValues[cfRemainders], marker :> $IterationLimit];

];
Variant 2:
ClearAll[cfRemainders];
Block[{$IterationLimit},
       OwnValues[$IterationLimit] = {};
   cfRemainders[x_, iter_: $IterationLimit] := Print[iter];
]

By looking at the DownValues[cfRemainders] you can check that both these variants will put an unevaluated $IterationLimit into the definition and will work as expected. While I think that the second variant is somewhat more elegant I have the feeling that it might undermine the extra barriers against inifinite recursions and might be dangerous in certain circumstances. So I'd probably go with version 1 which I think should be safe. I'm also  quite sure that there are even better ways to put that unevaluated $IterationLimit into the optional part of such a function definition that I couldn't make up...


Catalog Search index process error during indexation process: Could not ping search engine: No alive nodes found in your cluster

Question: I installed Magento 2.4.6-p3 by 1-click installation under Hostmonster webhosting c-panel. I didn't touch any thing. It went through well and gave me Admin Access of Magento 2.4.6-p3.
I searched whole last week to fix 'product not showing issue', and read about reindex via SSH. So, I ran it found the following error while reindex. I ran it under my webhosting Hostmonster SSH.

catalog search index process error during indexation process:
could not ping search engine: No alive nodes found in your cluster
Could you help me how to fix this issue under my webhosting at Hostmonster environment? Should I put some kinds of SSH command to fix? Or, change some value under Magento Back End Admin?
'No alive nodes found in your cluster' kept showing while I click 'Test Connection' under Admin - Configuration - Catalog. Could you help me how to fix this issue and use Magento 2.4.6-p3 properly under Hostmonster webhosting environment?

How can I check if the opensearch is working? As I see Store - Configuration - Catalog, the opensearch was set as default. As I test connection, No alive nodes found in your cluster just as I posted the error image. After 1-click installation under c-panel on Hostmonster, I haven't touch any thing. Every thing should be set as default mode.
Is there any way to start the opensearch if it was turn off as a default mode? How can I turn it on?
Many many thanks.
Best,
CMYK337
Comment: Please restart your Elasticsearch service and ensure that you are using the correct host.
Answer: 1st Start -------> elasticsearch
2nd Start--------> Xampp or wamp
Then Go to Magento root Directory ---> Run CMD Command
Paste and Enter Following Command
php bin/magento indexer:reindex
--------After Finish------
Then Paste and Enter Following Command
php bin/magento cache:flush
its woking..
Please try this. let me know this is working or not. if my solution is working then accept my answer and give an upvote.
thanks


Why the need to limit what tags you can create documentation for?

Question: Many of the niche technologies seem to suffer from the "Tag is to new or does not have enough activity".  I would like to understand why SO is limiting documentation for tags which have been ratified?
Answer: I'm not on the Docs team, but I'll offer a possible explanation: We don't want to have a huge number of ghost-town tags with documentation.
By requiring some level of activity in a tag before creating documentation for it, we have some assurance that there will be:

Enough people who know something about it to create content, and
Enough people who know enough to vet that content.

We also don't need a bunch of 3-question tag documentation pages filled with documentation on where to get quality handbags or other fine products. Documentation is, by nature, much more hidden than normal QA, so we need to make sure there are enough people around to notice spam and abuse happening in a Docs page.
Comment: I mean surely all of this is true of questions and answers too?!  I mean you don't need to know the technology to recognize spam.
Comment: @bated Questions and answers are inherently more visible - they bump the front page, and there are convenient ways for community projects to monitor all QA. That doesn't exist for documentation *yet*.
Comment: But surely you could limit the ability to add/edit documentation based on reputation.  This would filter out most the spam.


How to offline install tor+obfs package

Question: I have TBB 3.62 that contains everything I need to run on openSUSE 13.1, but they can not be used in the command-line mode (no gui), how to install tor+obfs offline in terminal and openSUSE 13.1?
Comment: How will you run TBB of you have no GUI?
Comment: @civos Your answer below is not an answer but a comment. If you just want to install Tor, take a look at https://www.torproject.org/download/download-unix.html.en for the official GNU/Linux repositories of Tor.
Comment: Reply to Tichodroma: No, TBB can not run without GUI, but I think Tor client can and I need obfsproxy to connect to Tor network.
Answer: If you want to run Tor in command-line mode, Tor Browser Bundle is not necessary. Instead you can use the RPMs to install Tor. Go to the bridges page. This page shows you some available bridges and you can also choose obfs3 here. Now open your torrc and add the lines you see at the bridges page. The lines look like
obfs3 127.0.0.1:60746 67890fea1264b5e535def1eb41e06

It doesn't matter where these lines are. After you copied them, save the torrc and restart Tor. It will connect to the obfs3 bridges now.
Comment: I don't have 50 reputation. To Jens Kubieziel: Which RPMs https://www.torproject.org/docs/rpms.html.en I should download? The web site only provide Fedora/Redhat support, I tried to download them from its repo and install manually, but says could not found, what happen?

How to offline install tor+obfs package


How to go back to list view of songs in playlists on iTunes 12.6

Question: How do I get the old Songs list view within playlists on iTunes 12.6? Some of my playlists (whether old or new) are now showing up in the stupid huge list that shows the album cover and all kinds of extra crap, and I only have about 8 songs per screen that I can see at once without scrolling. How do I go back to just the text-only list view within individual playlists (not just the main library) in iTunes 12.6?
Answer: View menu > View as.
Pick your favourite.
Playlist has 'mini covers' Songs is most minimal, text only.
Unfortunately, it's not a global setting, it's per playlist.
Answer: I don't know how to change the default view mode for new playlists, but you can run a script like the one below in Script Editor to change the view mode of all existing playlists.
tell application "iTunes"
    repeat with p in user playlists
        set view of browser window 1 to p
        try
            tell application "System Events" to tell process "iTunes" to click menu item "Songs" of menu 1 of menu item "View As" of menu 1 of menu bar item "View" of menu bar 1
        end try
    end repeat
end tell

Without the try block the script above would exit with an error when it reaches a "special" playlist like the "Songs" view where the "View > View As > Songs" menu item does not exist. You can remove the try block if you replace user playlists with user playlists whose special kind is not none and smart is false. In my version of iTunes, tell application "iTunes" to name of user playlists whose special kind is not none returned {"Music", "Movies", "TV Shows", "Podcasts", "iTunes U", "Audiobooks", "Purchased"}.
I use a script like the one below to create most new playlists. It requires GNU xargs and readlink which you can install by running brew install findutils coreutils.
osascript -e'on run {a}
    set l to {}
    repeat with f in (get paragraphs of a)
        set end of l to POSIX file f
    end repeat
    tell application "iTunes"
        if number of l is 1 then
            tell application "Finder" to set n to name of (item 1 of l as alias)
            set p to make new user playlist with properties {name:n}
        else
            set p to make new user playlist
        end if
        with timeout of 0 seconds -- don't exit with an error if the add command takes over 20 seconds
            add l to p
        end
        set view of browser window 1 to p
        tell application "System Events" to tell process "iTunes"
            click menu item "Songs" of menu 1 of menu item "View As" of menu 1 of menu bar item "View" of menu bar 1
        end tell
    end tell
end run' "$(printf %s\\n "${@-$(cat)}"|gxargs -rd\\n greadlink -f)"

If the System Events application is not on the list of applications in "System Preferences > Security & Privacy > Privacy > Accessibility", the script above results in an error like this: 636:751: execution error: System Events got an error: osascript is not allowed assistive access. (-1719).
Answer: In iTunes using Mac, to make songs within a playlist in list view, simply click on the playlist you want, then click on View on the top menu, then click on As Songs, that gives you the list view.
Comment: How is this different than the first answer provided in 2017?  It looks like you're just restating that answer.
Answer: This has been frustrating me for years; how have they mimicked so many other (now standard) behaviors like navigation history, but not made views global?
Essentially the closest thing I've read (and implemented) to solving this is loading a fresh install of iTunes, and creating the first list, then setting it all the preference on it, then in the future all lists will actually inherit the settings of the original list.


Remote Control Raspberry Pi

Question: Is there any other way to remotely control the raspberry pi? I built a 4 wheeled robot that is automated by ultrasonic sensors, yet today I have to decided it to make it remote controlled, what are my options?
Answer: In terms of remote control, you've got a few options.
You could SSH into the Pi and control it via the command line. You could install VNC on the Pi and then use a client on another computer to connect to it that way.
Alternatively, you could use a bluetooth dongle and pair up a Wii remote, PS3 controller or anything else that uses the bluetooth protocol. There are a variety of tutorials available online for all of them, so let us know if any of those take your fancy :-)
Comment: I guess the PS3 controller would sound perfect since I already have it in my arsenal, problem is what's the range limit for bluetooth devices?
Comment: Oh there _is_ a limit, I'm sure. But I think you'll find that you'll want to keep it within visual range anyway so you should find it's okay. Take a look at the Pi Borg website for some info on using the PS3 controller. https://www.piborg.org/doodleborg/ps3-source

Remote Control Raspberry Pi


client should buy minimum 2 kilo products then and then he should be able to proceed to check out

Question: i have developed a online web store for my client and he has a query that the client (product buyer) should not be able to proceed to check out until he buys minimum 2 kilo product
Comment: Can you give a little more info? Do you need 2Kg total weight in the card? Do you need to set a minimum sales amount for one specific item? It's not quite clear from your question.
Answer: You can add your weight validation using the event catalog_product_type_prepare_full_options as described in this answer:
How to allow only one product in a cart?


bash: preallocate memory for array

Question: Can memory be preallocated in bash for arrays of a defined size? I am iteratively adding strings to an array (declared by declare -a arr) in a loop (arr+=("$str")), and am wondering whether performance would be improved by preallocating memory of the appropriate size (e.g., 10,000 elements containing strings not larger than 512 characters).
Comment: If you want performance, use another shell than `bash`. Or even better, don't even use a shell. If you need arrays, chances are it's more a proper programming language than a shell that you need/
Comment: Possible duplicate (okay, not really a duplicate) of [Is there something wrong with my script or is Bash much slower than Python?](https://unix.stackexchange.com/a/303387/135943)  ;)
Comment: Bash simply lacks a lot of important data- and control structures, if you want to do big things with it, you will fail (or you will waste a very big effort for a half-result). To play with 10000 strings in an array, in a linux scripting environment, in your place I would use probably go (particularly if you have the intent to continously train also your programming skills). Others would say perl, python, a different shell, node.js or c.
Answer: No, that's not possible in bash.
To speed up your script, try rethinking your program flow and logic. It is very seldom necessary to read in huge amounts of data in a variable or array.
Most Unix tools are filters that allows you to send data from one stage of a pipeline to the next without storing very much of the initial or intermediate data in memory (often just a line from a file at a time). It's uncommon to read a dataset into a variable and then manipulate it in the shell. It's more common to run transformations on data, while possibly aggregating parts of it.
If you find yourself handling shell variables with more than a few words in them, then chances are there's a more efficient way of doing it.
Comment: @user001 Sounds like you're reinventing `xargs`.
Comment: Thanks for your advice on `xargs`. I was able to achieve the desired behavior simply by using `xargs -L  ./script.sh`, where script.sh merely contains a short preamble and then `printf "%s\n" "$@"`.
Comment: Thanks for your helpful reply. In this case, I am chunking commands (each string is a command) and then writing the strings to a script once a limit on some counter has been reached. The program flow is:  |
Comment: Hmm, I hadn't thought of using `xargs` for a shell script (I've only ever used it for standard system binaries). (The content of my while loop is essentially a short shell script.) I'll give it a try, thanks.
Comment: Actually, there is one problem, namely that I normally use another counter to give the chunks separate names (e.g., commands01.sh, commands02.sh) so that they don't overwrite one another. Is there some way that a counter can be accessed with `xargs`? The flow is:  | xargs -L  ./script.sh , in which `script.sh` takes the commands, writes a script file, and notifiers a launcher that the script is ready to be run. Is there a simple way by which a counter (from xargs) could be passed to script.sh to give the files separate names? (I could also use `date +%s`..)
Comment: Perhaps the only way to accomplish this would be to have the script called by `xargs` determine the count by reading it from a file and updating the value in the file at each execution.
Comment: @user001 Your script will be called with `N` arguments (if using `xargs -L N`. This number should be available in `$#`. You may iterate over `"$@"` in the script to loop over the command line arguments.
Comment: Thanks. I meant whether the number of times `xargs` has processed `N` arguments (e.g., if there are 10*`N` arguments, can the the first `N` be distinguished from the second `N` and so forth by some environment variable?). I don't believe this is the case, and that use of the file system (to the store the counter) may be necessary.

bash: preallocate memory for array


Why does typing a variable (or expression) print the value to stdout?

Question: Take this example:
>>> 5+10
15
>>> a = 5 + 10
>>> a
15

How and why does Python do this without an explicit print statement?
If I do the same thing in an IPython cell, only the last such value is actually printed on stdout in this way:
In[1]: 5+10
       1

Out[1]: 1

Why does this happen?
Answer: When Python is in "interactive" mode, it enables certain behaviors it doesn't have in non-interactive mode. For example, sys.displayhook, originally specified in PEP 217.

If value is not None, this function prints it to sys.stdout, and saves it in __builtin__._.
sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session.

You can modify this behavior:
>>> import sys
>>> def shook(expr):
...   print(f'can haz {expr}?')
...
>>> sys.displayhook = shook
>>> 123
can haz 123?
>>> False
can haz False?
>>> None
can haz None?

And also set it back to normal:
>>> sys.displayhook = sys.__displayhook__
>>> 3
3

In the default Python repl, sys.displayhook is
>>> import sys;
>>> sys.displayhook
<built-in function displayhook>

but in IPython it's
In [1]: import sys

In [2]: sys.displayhook
Out[2]: <IPython.terminal.prompts.RichPromptDisplayHook at 0x7f630717fa58>

So that's why you see different behavior between Python and IPython.
Answer: That's how all interpreters work. They don't need any print, but one thing, and without print they do the repr of everything, and print doesn't, example:
>>> 'blah'
'blah'
>>> print('blah')
blah
>>>

Look at the quotes.
Also see this:
>>> print(repr('blah'))
'blah'
>>>

repr does the same.
Comment: Let's say CPython in interactive mode works like that.
Comment: any comment on the IPython behavior?


While rendering HTML on iPad, How can we create Page Numbers and TOC dynamically? As done by iBooks

Question: We are developing an app and we have issue that we want to show page numbers and Table of content for our book shown in our app but we are stuck at the point that how can we get the number of pages while rendering HTML on iPad and iPhone? How can we create Page Numbers and TOC dynamically? As done by iBooks.
Answer: Here's one of the closest answers I've seen:
How do I retrieve a page number or page reference for an Outline destination in a PDF on iOS?
Here's some more info I've given others for general pdf info in the past:
Reading text and images from a pdf document in iOS