Why is node.js not suitable for heavy CPU apps?

Question: Node.js servers are very efficient concerning I/O and large number of client connection. But why is node.js not suitable for heavy CPU apps in comparison to a traditional multithreading server?
I read it here Felix Baumgarten
Comment: Regardless of its truth; where did you pick this claim up? Why do you think this is the case?
Comment: If you *know* that it's not, then you should *know* why it's not. Otherwise you're just parroting somebody else's opinion.
Comment: Node is a web server/app server. It was designed with the high concurrent users and heavy I/O in mind. CPU intensive jobs were not the key idea. Gradually it added cluster to make use of multi-core CPU.
Comment: I read it here [Felix Baumgarten](http://nodeguide.com/convincing_the_boss.html)
Comment: @vuvu Personally i don't think that article is a good article, most of the stuff is more like random jabber
Answer: Node is, despite its asynchronous event model, by nature single threaded. When you launch a Node process, you are running a single process with a single thread on a single core. So your code will not be executed in parallel, only I/O operations are parallel because they are executed asynchronous. As such, long running CPU tasks will block the whole server and are usually a bad idea.
Given that you just start a Node process like that, it is possible to have multiple Node processes running in parallel though. That way you could still benefit from your multithreading architecture, although a single Node process does not. You would just need to have some load balancer in front that distributes requests along all your Node processes.
Another option would be to have the CPU work in separate processes and make Node interact with those instead of doing the work itself.
Related things to read:

Node.js and CPU intensive requests
Understanding the node.js event loop
Comment: Your code won't run on those worker threads. They are only used when you start something asynchronously (I/O stuff), but as soon as they call the callback, you are back on the event loop. So all the code you write will be on a single thread.
Comment: what about the worker threads doing the call backs, these belong to a threadpool according to this article: http://www.aaronstannard.com/post/2011/12/14/Intro-to-NodeJS-for-NET-Developers.aspx
Comment: This youtube video https://youtu.be/8aGhZQkoFbQ explains the event loop and the above answer in detail.
Comment: This doesn't sounds accurate to me. event loop is single thread, but it works as a task queue managers to different threads and process your work in parallel if you write them as a async task in Node. While one thread could be CPU busy, but others can do different works once their current task are finished, and the current task doesn't necessarily the CPU busy work.
Comment: @user2734550 No, unless you explicitly use the newer worker threads, CPU-bound tasks, which is usually the JavaScript code you write, will run in a single thread. As I stated in the answer, I/O operations run separately but your code is restricted to that single main thread because JavaScript is by design single-threaded. That is still the case today.
Answer: A simple Node.js server is single-threaded, meaning that any operation that takes a long time to execute will block the rest of your program from running. Node.js apps manage to maintain a high level of concurrency by working as a series of events. When an event handler is waiting for something to happen (such as reading from the database), it tells Node to go ahead and process another event in the meantime. But since a single thread can only execute one instruction at a time, this approach can't save you from a function that needs to keep actively executing for a long time. In a multithreaded architecture, even if one function takes a long time to compute the result, other threads can still process other requests — and as long as you have a core that is not fully used at the time, there's a good chance they can do it about as quickly as if no other requests were running at all.
In order to deal with this, production Node.js apps that expect to hog a lot of CPU will usually be run in clusters. This means that instead of having several threads in one program's memory space, you run several instances of the same program under the control of one "master" instance. Each process is single-threaded, but since you have several of them, you end up gaining the benefits of multiple threads.
Comment: I read this article, where is says only the event loop is single threaded but not the computation fot the events, look there is a threadpool in the dawing http://www.aaronstannard.com/post/2011/12/14/Intro-to-NodeJS-for-NET-Developers.aspx
Comment: @vuvu: That article is a little confusing. He explains it incorrectly first (suggesting each event handler gets its own thread), but later explains it correctly (many utility functions that you'd use in your event handlers run on a background thread so you don't block when you are, say, reading a file). [This article](http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/) explains it more clearly.
Comment: @Chuck I know Promises didn't exist at the time of this answer, but with its introduction, you can just wrap any long running function that's "blocking" in a Promise callback and make it behave like an asynchronous function since NodeJS will put your wrapped function in a Microtask queue.

And if that function is very CPU intensive and frequently used, you might as well create a dedicated server in a language built for computation to handle those functions/requests. Now you can just use your NodeJS server purely as an API layer that interfaces with your server(s) handling those functions.
Answer: Node is flawless if you are having asynchronous tasks because java script will run these things by worker pool. But if you run CPU intense tasks (where you heavily use CPU ) Ex you have a billion users and you want to sort those people on name. Its quit a Intense tasks, and this is synchronous which will block other code from running.
So its not a good idea to use node for these kind of applications. Technically you can find alternatives to address those kind of tasks. The above example is better addressed in a Db. then passing that result is great.
In the same way avoid Intense task and keep your CPU cool for better performance
Answer: You can have a look at this package, the-computer, which may help you do some cpu intensive works in a single instance of node.js app in a simple way.
Definitely it is not as effective as raw c++ libs, but it can cover most general computing cases, keeping you in node.js garden while allowing you leverage the cores of the cup.
Answer: Node.js runs JavaScript code in a single thread, which means that your code can only do one task at a time. However, Node.js itself is multithreaded and provides hidden threads through the libuv library, which handles I/O operations like reading files from a disk or network requests. Through the use of hidden threads, Node.js provides asynchronous methods that allow your code to make I/O requests without blocking the main thread.
Although Node.js has hidden threads, you cannot use them to offload CPU-intensive tasks, such as complex calculations, image resizing, or video compression. Since JavaScript is single-threaded when a CPU-intensive task runs, it blocks the main thread and no other code executes until the task completes. Without using other threads, the only way to speed up a CPU-bound task is to increase the processor speed.

 Node.js introduced the worker-threads module, which allows you to create threads and execute multiple JavaScript tasks in parallel. Once a thread finishes a task, it sends a message to the main thread that contains the result of the operation so that it can be used with other parts of the code. The advantage of using worker threads is that CPU-bound tasks don't block the main thread and you can divide and distribute a task to multiple workers to optimize it.

ref: https://www.digitalocean.com/community/tutorials/how-to-use-multithreading-in-node-js


What is the interpretation of mutual information for events?

Question: The mutual information is usually calculated for random variables. I don't know what it exactly measures. Events are more intuitive to me. Can we use it for events, for example, cloudy sky and rainy weather? If yes, could you bring examples of events with high/low mutual information?
Comment: You ask multiple different questions at once, please make it a single, focused question.
Comment: "what is the process of your thinking to find such examples" is highly subjective and doesn't define an answerable question.
Comment: @Tim I simply meant give two typical examples, however, I now doubt if it applies to events or random variables and that is the first part of question.
Comment: have you tried [Wikipedia](https://en.wikipedia.org/wiki/Mutual_information#Motivation)? High mutual information: one variable is a deterministic function of the other, so if X is a dice throw,  Y = X + 1. Low mutual information: two variables are independent, e.g. two independent coin tosses. This is what your question is about?
Comment: @Tim, I checkd but it's not intuative to me, I sent parts that I didn't understood. Also, being determinist function isn't a realistic and intuitive example. For example, consider these events: A: Cloudy sky B: Rainy weather or A: Summer B:rainy weather. Which pair has high and which has low mutual information...
Comment: @Tim Moreove, it seems mutual information is related to correlation and correlation coefficient (strong or weak dependence). But do we have such concepts for events? Can two events be correlated? Can they be weakly or strongly dependent? In each case how one can determine that?
Comment: Please make your question more concrete & precise. It's too broad & ambiguous. Check https://stats.stackexchange.com/help/how-to-ask
Comment: @Tim I modified it to some extent...
Comment: @Tim, I moved some of the questions to another question I posted now.
Answer: It sounds like you're looking for the pointwise mutual information (pmi), which relates two events. Mutual information averages the pmi over all possible events.
What this measures is whether two events tend to occur together more often you'd expect, just considering the events independently. If they occur more often than that, pmi is positive. Less often, it's negative. Conditionally independent, it's zero.
$$\operatorname{pmi}(x;y) \equiv \log\frac{p(x,y)}{p(x)p(y)} = \log\frac{p(x|y)}{p(x)} = \log\frac{p(y|x)}{p(y)}$$
I'll leave to your own intuitions the sort of events that do or don't have high pmi.

In the example you provide, $x$ might be the event of a cloudy sky, from a space of options $\mathcal{X} = \{\text{cloudy}, \text{not cloudy}\}$, and $y$ might be the event of rainy weather, from a space of options $\mathcal{Y} = \{\text{rainy}, \text{snowy}, \text{hazy}, \text{sunny}\}$. By averaging the pmi over all of these combinations, you get the mutual information.
Comment: pmi seems to be (a special case of) what statisticians call a *log likelihood ratio*.
Comment: Yes, between the joint distribution and the individual distributions if they were independent.
Comment: Thanks, it says " Note that even though PMI may be negative or positive, its expected outcome over all joint events (MI) is positive." Can you say why?
Comment: It's provable with Jensen's inequality.
Answer: Mutual information is linked to the concept of entropy of a random variable that quantifies the expected "amount of information" held in a random variable, or the amount of uncertainty about the outcome of a random variable.
The key point is that it's about a random variable, such as $Weather$ or $Sky$. A random variable consists of a finite number of events or outcomes whose occurrence is by random with a probability.  For example, outcomes of $Weather$ are:
$\mathcal{W} = \{\text{rainy}, \text{sunny}\}$
and outcomes of $Sky$ are:
$\mathcal{S} = \{\text{cloudy}, \text{half-cloudy}, \text{clear}\}$ each with a probability.
A random variable like $Weather$ has the highest entropy when all outcomes have equal probability. Then you can't predict that whether tomorrow is likely rainy or sunny, and any outcome is a surprise for you. For these two outcomes, we need $1$ bit (0 or 1) to report the weather of each day, which is the maximum entropy value in this case.
However, if $P(\text{sunny})$ is much higher than $P(\text{rainy})$, predicting tomorrow is $\text{sunny}$ has less information content compared to predicting that it's $\text{rainy}$. So, it's not a news for you if one says tomorrow is sunny.
The entropy for a variable averages the information content of all outcomes. If always is sunny, we have no entropy. We need zero bit to transfer information for every day.
The mutual information quantifies the amount of information or uncertainty that remains for a random variable like $Weather$ when we know the outcome of another variable like $Sky$. So if you know that $Sky=\text{clear}$ it affects the probabilities of $Weather$ outcomes. Then the probability of $\text{rainy}$ can decrease! It shows a type of dependence. It's a non-negative value and it's zero when two random variables are independent. It has various formulas, one is:
$$I(X;Y) = H(X) - H(X | Y)= H(Y) - H(Y|X)$$
$H(X)$ is the entropy of $X$ and $H(X | Y)$ is the conditional entropy of two variables $X$ and $Y$. When they are independent, then $H(X) = H(X|Y)$, which means knowing about $Y$ has no effect on the entropy of $X$.
Also as the accepted answer pointed out, there is a measure called pointwise mutual information, which measures the mutual information between two single events, such as rainy weather and cloudy sky. The mutual information is the expected value of PMI among pairs of outcomes of two random variables.
Comment: if you would like to answer your own question, please consider doing so while asking it, not after. You can do so by checking the "Answer your own question" box under the box where you enter your question.
Comment: @mhdadk thanks, no I reach conclusions after reading the other answers and related articles and then post my understandings for myself and others.


How can I set the zoom of the Outlook reading pane?

Question: I know we're able to use Ctrl+Mouse Wheel to zoom in and out, but is there a way of permanently setting the default zoom for the reading pane?
Answer: The Zoom level fixed appears to be fixed now in Outlook 2016.  If you click on the zoom number in the lower right corner of your Outlook window, it will pop up a dialog.

Enter the desired zoom level, and click the box to save the preference.  Walla!  This will cure it for your messages in the reading pane.
Comment: OMG! I've been searching for a solution to this problem for literally ten years. I didn't realize this had been added. Thank you so much for the information! I wish I could give this 1000 upvotes.
Answer: This looks to be linked to the DPI settings on your computer as well as the zoom level set in Outlook.
One thing could be to change the text size on the emails -

Customize the font size for Plain Text messages
For Plain Text you can modify the display font via

Outlook 2007 and previous:
  Tools → Options… → tab Mail Format → button Stationery and Fonts
  (or just Fonts… in previous versions of Outlook)
Outlook 2010:
  File → Options → section Mail → button Stationery and Fonts

Source: Enlarge font in the Reading Pane – MSOutlook.info
Comment: Cheers - that certainly works for plain text messages (in Outlook 2007).
Answer: How to set the default zoom for incoming emails in MS Outlook 2010:

Start - Microsoft Office - Tools and Microsoft Office - a digital certificate for the Project VBA, create a certificate with the name, for example, Zoom
Start Outlook
File - Options - Trust Center - Trust Center Settings - Options, select Macros, or "notice for all macros" or "notification for digitally signed macros, all unsigned macros are disabled"
Alt+F11 - run the VBA Editor
In the upper left window, click on the Draft Project - MS Outlook Object and double-click on ThisOutlookSession
To the right opens a window (View.Zoom.Percentage = 150 - scale by default)
Tools - References, check Microsoft Word 14.0 Object Library
F5 - come up with a name, for example, "Zoom - Create"
Tools - Digital Signature: select the signature that we have previously created with the name of Zoom
File - save
Alt+Q
Restart Outlook
Box appears with a request to add to the trusted zone certificate.

Option Explicit

Dim WithEvents objInspectors As Outlook.Inspectors
Dim WithEvents objOpenInspector As Outlook.Inspector
Dim WithEvents objMailItem As Outlook.MailItem

Private Sub Application_Startup()
    Set objInspectors = Application.Inspectors
End Sub

Private Sub Application_Quit()
    Set objOpenInspector = Nothing
    Set objInspectors = Nothing
    Set objMailItem = Nothing
End Sub

Private Sub objInspectors_NewInspector(ByVal Inspector As Inspector)
    If Inspector.CurrentItem.Class = olMail Then
        Set objMailItem = Inspector.CurrentItem
        Set objOpenInspector = Inspector
    End If
End Sub

Private Sub objOpenInspector_Close()
    Set objMailItem = Nothing
End Sub

Private Sub objOpenInspector_Activate()
    Dim wdDoc As Word.Document

    Set wdDoc = objOpenInspector.WordEditor
    wdDoc.Windows(1).Panes(1).View.Zoom.Percentage = 150
End Sub

Comment: In the future, please write your posts in English!
Comment: As far as I can tell, this only seems to set the zoom when you open an email which you can do by simply using the zoom option in the ribbon after you open one. Doesn't seem to affect the Preview Pane
Answer: I am shocked that there isn't a better answer for Outlook 2010 on Windows 7, so I will be checking back.  What I settled on is pretty poor: using the "Make it easier to read what's on your screen" feature in Windows 7 and setting an overall magnification to 125%.  Unfortunately, you have to log off and log back in in order to see the effect, which makes it a pain to experiment.
This feature is accessed in Windows 7 by right-clicking on the desktop, selecting "Screen resolution", and then clicking "Make text and other items larger or smaller" near the bottom.  There is also an option to "Set custom text size (DPI)", but I didn't take the time to try it out.  You can also access this dialog by typing "Make it easier to read" into the control panel search.

I tried 150%, but this caused unacceptable degradation to fonts in certain programs, such as MATLAB.  At 125%, I am unhappy with some of the effects, but it is a fair balance to be able to read my email without zooming on every message.  On the other hand it is a big downside to overcome deficiencies in one app, so I think I may just switch to this mode when I have a lot of email to read and then switch back - despite logging off and on twice!
Answer: I've been looking for a solution to help with this too in Outlook 2013 and just came across a third party commercial add on to help with this called "Zoom Email Windows Add-In" from http://www.sperrysoftware.com/outlook/zoom-email-windows.asp.
I just installed the trial in Outlook 2013 32bit and it is working well for me, i.e. it automatically sets the zoom value in the Reading Pane to what I configured.  I wanted to suggest this if you are still looking for a solution.
Answer: here is updated Outlook VBA code that resizes both opened messages and the reading pane.  Microsoft blocked access to the Zoom parameter so you will have to first install Redemption drivers (http://www.dimastr.com/redemption/home.htm) and then under VBA Tools/References activate "Microsoft Word 15.0 Object Library" and "Redemption Outlook and MAPI COM Library".  paste and run the code below, zoom is set in MsgZoom constant.
Option Explicit
 Dim WithEvents objInspectors As Outlook.Inspectors
 Dim WithEvents objOpenInspector As Outlook.Inspector
 Dim WithEvents objMailItem As Outlook.MailItem
 Dim WithEvents myOlExp As Outlook.Explorer
 Dim sExplorer As Object
 Dim Document As Object
 Dim Msg
 Const MsgZoom = 130

Private Sub Application_Startup()
 Set objInspectors = Application.Inspectors
 Set myOlExp = Application.ActiveExplorer
 Set sExplorer = CreateObject("Redemption.SafeExplorer")
 End Sub

Private Sub Application_Quit()
 Set objOpenInspector = Nothing
 Set objInspectors = Nothing
 Set objMailItem = Nothing
 End Sub

Private Sub objInspectors_NewInspector(ByVal Inspector As Inspector)
 If Inspector.CurrentItem.Class = olMail Then
 Set objMailItem = Inspector.CurrentItem
 Set objOpenInspector = Inspector

End If
 End Sub
 Private Sub objOpenInspector_Close()

Set objMailItem = Nothing
 End Sub

Private Sub objOpenInspector_Activate()
Dim wdDoc As Word.Document
 Set wdDoc = objOpenInspector.WordEditor
 wdDoc.Windows(1).Panes(1).View.Zoom.Percentage = MsgZoom

End Sub

Private Sub myOlExp_SelectionChange()
On Error GoTo ErrHandler:
 Set Msg = Application.ActiveExplorer.Selection(1)
 Application.ActiveExplorer.RemoveFromSelection (Msg)
 Application.ActiveExplorer.AddToSelection (Msg)
 sExplorer.Item = Application.ActiveExplorer
 Set Document = sExplorer.ReadingPane.WordEditor
 Document.Windows.Item(1).View.Zoom.Percentage = MsgZoom
Exit Sub

ErrHandler:
    Exit Sub

End Sub

Comment: It looks like a lot of work went into your answer.  Are you sure you want to trash it?  If so, you can delete it yourself by clicking on the "delete" link below the answer.
Comment: Looks like the code came from here: http://www.slipstick.com/outlook/adjust-outlooks-zoom-setting/   Edit: Also it looks like you can't have conversations view in the reading pane to use this macro, which limits its usefulness.
Answer: I've dug around everywhere to find a way to do this and just stumbled across it accidentally on my own.
Inside the Outlook client, on the bottom right of the Outlook pane, there's the zoom slider bar. Click on the number next to the bar. This pops up a new dialog box that lets you select a zoom level or type in a custom level. There is a checkbox at the bottom that says "Remember my preference." I've closed and re-launched Outlook several times and so far seems to be sticking at the level I set.
I have no idea why MS can't provide a straightforward answer for this, but I finally found it on my own.
Answer: The problem I'm encountering is that the Reading Pane changes with these fixes but the display text (File, Home, the ribbon button text) stays 100% sizing.
A band aid solution: I seem to have different visuals on my laptop for these controls since the laptop is a lower DPI (the laptop screen is not as high resolution). By using Outlook and other items with smaller text on my Laptop, I see these better than by scaling EVERYTHING too much. It's not an ideal solution but I now read my emails and other desktop applications on my laptop, and webpages on my monitor.


Detecting motion

Question: In the television show " Ascension " they are supposed to be 50 years into a 100 year journey to another Star System but get this, they never left Earth . They are here on Earth in a huge biosphere . My question is if this is possible that people can be here on Earth and not know that they are not traveling through Space in a Spacecraft ? How could they not have instruments or any other way of not knowing . This plot seems a little far fetched to me, what do the rest of you have to say about it ?
Comment: My question is a valid and legitimate question and I don't see why it would be down voted with not even a reason given ? The question may belong in a television forum perhaps but it is a Science question so as such it has a reason  to be posted here.
Answer: Can they see the stars? If not then motion is undetectable in a closed environment as it would constitute an inertial frame. But even if they could see the "stars" presumably these would be generated by some form of display technology and behave consistently with the supposed mission profile.
However acceleration is detectable, it would manifest as a gravity like force. The way gravity varies withing the environment could indicate that this was a planetary field rather than an artificial one (depending on how the artificial gravity is supposedly generated). I would expect the payload will have been told some story that would explain this away though.
Answer: It is part of General Relativity that if you are in a (small) closed box, you cannot tell the difference between acceleration and a gravitational field.
I suppose you could argue that you would explain Earth's gravity to the occupants of the biosphere as a 1g acceleration away from the Earth for 50 years, a slow swivel of the spacecraft, and then deceleration at 1g for 50 years.
It is hard to say whether such a deception is possible without more details, but in principle it could be done if you have some way of obscuring the initial part of the journey - launch etc, where you would think some non-uniform acceleration would be inevitable.
There is also the question of how far you are going and whether there is a feasible propulsion system. An acceleration of 1g for only a year gets you up to relativistic speeds. You could easily travel to other galaxies in 50 years at this acceleration. So, if the destination was supposed to be a nearby star then the deception fails miserably, unless you try to convince the passengers that you are executing some sort of weird trajectory to get there.
Additionally, how big is the biosphere? What about tides due to the Sun and moon? Any sizeable body of water would show up tides (and indeed possibly the coriolis force due to the Earth's rotation).

Detecting motion


Java/Swing: ownership of the system clipboard

Question: I'm writing a small Java program that's supposed to run an external program that copies an image to the system clipboard (i.e. the Windows 7 "snipping tool"), wait for it to finish, save the image from the clipboard to disk and copy a URL (from which the image can be accessed) to clipboard. In short, it is supposed to:

run external tool and wait for it
copy an image from clipboard
copy a string to clipboard

This, my program is perfectly able to do. However, I would like to use Swing/AWT to present a user interface. I'm using a system tray icon, but for simplicity's sake, it could just as well be a JButton in a frame. When the button is clicked, the process above should be carried out. The first time this is done, it works as it should. The image is copied, pasted to disk and the string is copied to clipboard. Then, the second time the button is clicked, it is as though my program does not realize that the clipboard has been updated, as it is still seeing its own string from the first time around. Only afterwards does my clipboard handling class lose ownership, and in effect, every second attempt at the procedure fails.
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
    private static BufferedImage image; //the image from clipboard to be saved

    public static void main(String[] args) throws InterruptedException, IOException {
        new GUI();
    }

    public static void run(String filename) throws IOException, InterruptedException {
        CBHandler cbh = new CBHandler();

        //run tool, tool will copy an image to system clipboard
        Process p = Runtime.getRuntime().exec("C:\\Windows\\system32\\SnippingTool.exe");
        p.waitFor();

        //copy image from clipboard
        image = cbh.getClipboard();
        if(image == null) {
            System.out.println("No image found in clipboard.");
            return;
        }

        //save image to disk...

        //copy file link to clipboard
        String link = "http://somedomain.com/" + filename;
        cbh.setClipboard(link);
    }
}

class CBHandler implements ClipboardOwner {
    public BufferedImage getClipboard() {
        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

        try {
            if(t.isDataFlavorSupported(DataFlavor.imageFlavor))
                return (BufferedImage) t.getTransferData(DataFlavor.imageFlavor);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setClipboard(String str) {
        StringSelection strsel = new StringSelection(str);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(strsel, this);
    }

    @Override
    public void lostOwnership(Clipboard arg0, Transferable arg1) {
        System.out.println("Lost ownership!");
    }
}

class GUI extends JFrame {
    public GUI() {
        JButton button = new JButton("Run");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                try {
                    Main.run("saveFile.png");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        add(button);
        pack();
        setVisible(true);
    }
}

If you try running it, notice that on the second run, the lostOwnership method is only called AFTER the attempt at copying the image. I'm guessing this is the source of my problem, and I have no idea why it is happening, except that it only happens when triggered by a Swing event. Any help solving this is appreciated.
Answer: One guess: You are doing your whole handling (calling the other process) on the AWT event dispatch thread (e.g. directly from the ActionListener or similar).
The Clipboard change messages will also be handled by the VM on the EDT ... but only after your button-click is done.
The moral: Don't do long-running stuff (and stuff which has effects which should be enqueued in the event queue) on the EDT - instead, start a new thread for this.
Comment: Could you give me an example (pseudo-code or otherwise) on how to accomplish this in my scenario?
Answer: The key to understanding the lost ownership issue is in this line
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(strsel, this);

The second parameter you are passing in is ClipboardOwner. JavaDocs for clipboard.setContents says

If there is an existing owner different from the argument owner, that owner is notified that it no longer holds ownership of the clipboard contents via an invocation of ClipboardOwner.lostOwnership() on that owner. An implementation of setContents() is free not to invoke lostOwnership() directly from this method. For example, lostOwnership() may be invoked later on a different thread. The same applies to FlavorListeners registered on this clipboard.

Okay so what's happening? When you pass in the owner, Clipboard now has a reference to that object. In this case it's CBHandler. You then create a new one and attempt to set the contents again. Clipboard then goes back to the old owner (your original instance) and tells it "Hey, your not the owner anymore".
public synchronized void setContents(Transferable contents, ClipboardOwner owner) {
    final ClipboardOwner oldOwner = this.owner;
    final Transferable oldContents = this.contents;

    this.owner = owner;
    this.contents = contents;

    if (oldOwner != null && oldOwner != owner) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                oldOwner.lostOwnership(Clipboard.this, oldContents);
            }
        });
    }
    fireFlavorsChanged();
}

You'll have to provide more details on the other issue "it is as though my program does not realize that the clipboard has been updated, as it is still seeing its own string from the first time around. "


Too many active IP Connections

Question: I have a Linksys WRT54GS v7 with a dd-wrt (micro) installed on.
When I try to view Active IP Connections, I see too many connection there.
Interestingly, there are about 120 connections that originate from my computer. At that time, I have no download programming running, (no torrent). I only have an instance of Chrome, Eclipse, Skype, Empathy running.
How come my apps consume such a large amount of connections?
I'm running Ubuntu 9.10.
Answer: I would imagine that if you checked most of those connections will be on port 80 and in a TIME_WAIT state.

TIME_WAIT is a state
  where connections could conceivably be re-used without
  making a new TCP
  between servers, so it can help reduce load.

So basically your router is saving a tcp socket for later use to the same site.
Answer: The router only saves a connection for a few minutes at most. The source might more possibly coming from skype. Skype is based on P2P technology to provide high quality calls. But that means it has to keep alot of connections up at the same time.
The problem arises when you have a lot of skype clients going through the same router, a router can only manage a fixed amount of connections. If you exceed that limit, it will block additional connections untill previous ones timeout.

Too many active IP Connections


Photoelectric effect and energy of light

Question: I have a doubt about photoelectric effect and the nature of light in general. From what I understood, in order to ionize a piece of some material, I need an electromagnetic wave with a frequence greater or equal than a certain frequence, meanwhile the intensity of the incident wave doesn't matter.
But does the intensity of the wave transfer some energy to the material (like the one calculated with the poynting vector?)? If I increase the intensity of the wave (i.e. its amplitude) will this energy be able to ionize the material at a certain point?
So the final question might be: does an electromagnetic wave possess two energy? One associated with the frequency and one associated with the intensity?
Comment: The photoelectric effect demonstrates that electromagnetic waves are not classical but quantum mechanical phenomena. Quantum electrodynamics has been tested with experiments which have up to 13 digits of precision, or so, while semi-classical explanations of the photo-effect are struggling to fit the facts. Worse, they can't reproduce the precision tests, at all. Quantum field theory in general has been remarkably successful to explain the structure of matter and the spectrum of the physical vacuum up to the TeV range, while classical field theory can't even explain the stability of matter.
Comment: It is true that it's *possible* to ionize with photons of lower energy than the photoelectric effect requires, but only at very high incident power levels. It's a multi-photon-absorption condition, and not easy to achieve.
Answer: If you want to understand the photoelectric effect and energy of light you have to be very very careful to keep the terminology correct.
The energy of a electromagnetic wave (1 photon) is completely determined by its frequency.
The intensity of the electromagnetic wave(s) is how many photons per second are hitting on some area of surface. You can't combine photons to get a "bigger" photoelectric effect.
The gist of the photoelectric effect is this. The most loosely bound electrons in the material still have some specific binding energy. Until the photon has at least this much energy then it can't knock an electron free. But if it has more than that energy, then the electron gets the excess energy.
So if the binding energy is 4 eV:

A 3 eV photon doesn't knock out an electron
A 10 eV photon knocks out an electron with 6 eV of kinetic energy

The other "kind of energy transfer" (from the intensity of the photons) creates heat. So if a huge number of photons were absorbed by the material then it gets hot. If the material gets hot enough then it will emit electrons. (But this is not the photoelectric effect.) This was the purpose of the heater in old glass vacuum tubes. It heated the metal cathode so that it would release electrons.
Comment: Ok but if my source produces N photons the energy the electron receives is Nhf (with f the frequency of the photons - suppose a monochromatic source). So why the electron can't use all this energy to escape?
Comment: Just added that answer at the bottom.
Comment: Rethinking about it: is not easier for the metal plate to emit photons in order to cool itself, before getting hot enough to ionize itself? Is there maybe a competition inside the metal plate between the number of incident photons per second (so the energy that heat the plate) and the emission of photons (maybe the thermal emission like the black body one?) that cools the plate?
Comment: As a material gets hot it emits electromagnetic waves over a broad energy range in a process known as black body radiation. That would cool the material. So you're right the incident photons on the material and the photons from black body radiation away from the material have exactly the opposite effect on the temperature. (Obviously if something gets hot in air then there are thermal currents which remove heat too.)
Answer: The energy of a electromagnetic wave is completely independent of its amplitude. The amplitude merely describes how many quanta of energy are propagated. In essence the higher the intensity the more photons with the certain energy.
A good analogy for the photoelctric effect is a big room with an infinite amount of kids in it. They need to pay 5€ to get out of the room.
If someone throws in 10 cent pieces no child will ever have enough money to escape the room because there are an infinite amount of children.
If I throw in 5€ bills however a child can take it and instantly has enough money to leave the room.
In the analogy the value of the money is the energy and the amount of bills or coins is the intensity.
When the photoelectric effect was first examined the common understanding was much like yours that if the light behaves like a wave the metal should be able to accumulate energy over time until it emitted an electron but this was not the case because there is usually only single photon absorption by an electron. This photon therefore needs the right amount of energy.
Comment: I really don't get the wave representation of light: if I have a monochromatic source the amplitude of my wave will be the number of photons per second the source produces; if I try to picture this wave as a sinusoidal wave, I don't understand when the photons reach the detector what happen to the rest of the wave. I mean, a wave is a continuum of peaks and troughs, right? But the photons travel at velocity c and reach the detector all at the same moment, so is the wave just a single peak, with the amplitude as large as the number of photons the source produced in a single moment?
Comment: The photoelectric effect is always one photon in, and one photoelectron out. The only way to "add" the energy of photons is to heat the material.
Comment: " if I try to picture this wave as a sinusoidal wave," don't think of photons like that. Imagine that each photon is a bullet. So each bullet has a certain amount of KE. // Photons are funny. Sometimes we model them as waves and sometimes as particles. To understand the photoelectric effect you need to think of the photons as particles.


Tips on preventing illness whilst in India

Question: I am going on holiday to India for 6 days and was wondering if anyone knew of any form of preventative medication which I would be able to acquire in order to try and stop some myself getting some of the local bugs.
Comment: Related: http://travel.stackexchange.com/questions/2589/how-to-prevent-delhi-belly
Comment: Illness can be prevented as you said on your title and as linked by Karlson.
Generic prophylactic medication for travel doesn't exist AFAIK. Many food or water-borne infections can be bacterial and you can't prevent that except by choosing well what you eat and drink, you can just cure them with antibiotics afterwards (under medical directions and avoiding all abuse since bacterial resistance is becoming a big challenge of our times).
Answer: I would suggest visiting your GP and ask their advice. Here in Australia, every Clinic has list of medicines or shots to be taken before travelling to particular countries.
Also prevention is better than cure. I would suggest avoid eating spicy street food and water. Get distilled or purified water bottle and carry it with you.
Stay in a clean hotel (unless you are staying at someone's home, which would be fine).
Don't be shy to say no if someone offers you to eat or drink something that you are unsure of and you will be fine.
Answer: Consider asking your doctor to prescribe you some anti-nauseates. You probably wouldn't even have to go into your phobia with your doctor-- when I traveled to Southeast Asia recently, my doctor automatically forced on me prescriptions for antibiotics and anti-diarrheal medication. (You might be encouraged to hear that I neither filled nor needed either.)
Googling reveals that there are several classes of anti-nauseate drugs. I've taken meclizine (brand name: Antivert) and promethazine (Phenergan) and both were effective-- though they pretty much knocked me out. Even if you end up not taking them, it might comfort you to have them on the trip.
Answer: I guess all you need to be mindful of, is basically the food that you will eat. Below are very effective preventive measures that you might want to read for safety:
1. Avoid eating foods or drinking beverages purchased from street vendors or other establishments where unhygienic conditions are present.
2. Avoid eating raw or under cooked meat and seafood.
3. Avoid eating raw fruits and vegetables unless you peeled them.
4. Make sure to buy only safe beverages which includes bottled carbonated beverages, beer, wine, and water boiled or appropriately treated with iodine or chlorine.
I hope this helps.
Comment: Tamara, did you copy this list from somewhere? If so, could you cite or link to it?
Comment: Oh yeah, sure thing! You'll find it below this . I didn't include some of the details though, because for me it's kinda self explanatory. Like washing your hands before eating - my three year old girl knows the importance of washing her hands before and after eating so I guess everybody does. =) http://www.fodors.com/community/asia/post-tips-for-avoiding-getting-sick-in-india.cfm


Do all my speedlites need to be trigered wirelessly to do proper HSS?

Question: What if some of them are slaves? Will they properly sync at 1/8000 along with the radio triggered ones?
Comment: Your terminology is not clear. When you say "slave" do you mean "optically triggered"?
Answer: In order to get HSS with a remote off-camera flash, you need three things:

A camera body that performs HSS. For example, the Nikon D3x00 and D5x00 bodies cannot perform FP/HSS, so no matter what flashes or triggering system you're using, there's no chance of getting high-speed sync. And your camera body has to be capable of 1/8000s to get that shutter speed with flash.  Most camera bodies max out at slower speeds.
Flashes that are compatible with the camera body that can perform HSS. That is, if you shoot Nikon, you need a flash that can perform Nikon's FP flash. If you shoot Canon, you need a flash that's compatible with Canon's HSS communication.  If you're using a manual-only flash, like the YN-560III, you're out of luck.
A system-compatible triggering system that can communicate HSS/FP.  If your radio triggers do not communicate HSS, it won't work. If you're using a manual-only triggering system such as PC sync cable, Yongnuo RF-603II, most add-on optical slaves, etc. it won't work. If you're using a hotshoe-to-hotshoe TTL cable, it will. If you're using TTL/HSS-capable radio triggers (e.g., YN-622, RadioPopper PX, Phottix Odins, etc. etc.), or the built-in wireless TTL-compatible system (Nikon's CLS, Canon's RT or optical slaving systems) with an HSS-capable master (e.g., Canon's pop-up flashes with masters cannot do HSS), then it will work.

Keep in mind, however, that HSS robs you of power (roughly two stops) and that the faster your shutter speed is, the more diminishing your returns are going to be.
Answer: If each flash/speedlite works with HSS individually they should work together. If a flash/speedlite is being triggered with something other than E-TTL then HSS on that device won't work and you'll end up with a dark band. Even if the device does support E-TTL it's not guaranteed to be HSS compatible.


How exactly does WiTricity's wireless power transfer using resonance work?

Question: The WiTricity group has made a lot of buzz but no internet article explains the exact method that they are using. Does anyone know how it works?
Answer: I don't really see anything new or unique about what they are doing.  They are just making a near-field resonator.  They avoid publishing their true efficiency numbers which is really the only characterization that matters.  There are some numbers of 42% efficiency on wikipedia.
Basically their 9.9 Mhz demos are just transformers with an air gap for coupling.  Their "resonance" claims are really just hype because no one would try to design a coupled system without making it resonant at the operating frequency.
Likewise simulating SAR is very different from the real SAR and they are using those simulations as part of their efficiency calculations which is suspect.  There are no actual studies or reports are claimed of the specific technology, power levels and use in home environments.
There's a paper on their dielectric resonators that you can read.
Answer: The method that WiTricity implements is that of magnetic resonance coupling.  Resonance is done to ensure efficient exchange of energy between the transmitter and the receiver.
The method is very simple. If you take a coil and pass alternating current through it, it will produce alternating magnetic field around itself (like a solenoid). Now, place another coil in the vicinity of the first coil. The alternating magnetic field causes alternating flux through the second coil. This generates an emf in second coil and hence provides power to load.
Witricity's method created a buzz because they portrayed it as a new invention but actually its just an improved version of inductive coupling.
Answer: This is only comment-worthy, but I don't have the reputation for a comment yet.
https://web.archive.org/web/20131207183005/http://witricity.com/pdfs/highly-resonant-power-transfer-kesler-witricity-2013.pdf
That paper from WiTricity has some more detailed descriptions and a bit of math.  It also cites references if you'd like to follow up on some details.  So hopefully it can satisfy your curiosity a bit deeper.


Advertising a job in open source software and hardware

Question: I am developing a solution to deploy open-source hardware in a way that would be similar to APT or Portage in software. As a matter of fact, the idea is to extend something like Portage to make it compatible with hardware deployment in parallel with software.
I started this project some time ago and I have an opportunity to recruit someone to help, but I am not sure where to advertise this job. This is a rather focused profile I need, and dedicated forums tend not to approve of job advertisement.
So my question is: where could I advertise a job in open source software/hardware?
Comment: Do you intend to pay "market rates" for the skill set you hire? (i.e. you won't expect your employee to take a discount because "open source is good")
Comment: The salary would be aligned on academics salary grid in the UK, as this is a research project for now. I should have mentioned it!
Answer: There are some job boards focused on open source:

fossjobs.net (the website itself is open source, too!)
opensourcejobhub.com
fossfox.com

Just for completeness, I'll also mention a couple such projects that have since gone extinct/inactive:

osjobs.net
Jobs in open source (Twitter profile)


Mac shutdown even in safe mode,but less often than in normal boot

Question: My Macbook Pro(mid 2014 15') keeps shutting down unexpectately, usually acompanied by very loud fan noise. This problem has pestered me for quite a while. I don't remember exactly when it  started, but I am sure it happened before I upgraded to the latest Catalina OS. But now it reaches a frequency that render the Mac unworkable. I tried to reboot it in safe mode, but the same thing happened in safe mode as well, though seems less frequent. I tried to reinstall the Catalina through recoverary mode but it can not be done because it shut down while downloading the files. Although the Windows bootcamp works fine. Is there any suggestion about what could be the problem and what I should do to fix it? If there is any supporting documents I can provide, please leave it at the comment and I will find it for you. Thanks in advance.
Comment: Shutting down with a loud fan noise would imply overheating. When was the last time it was completely stripped & cleaned? [not just blown at]
Comment: but that would affect boot camp as well. No?
Answer: The first thing you want to do is to backup your data. This issue may worsen and being unable to access/lose important data is the worst thing that can happen.
I recommend the following procedure:

Try to save the files with target disk mode and/or recovery mode (I would do both a copy of the raw data with target disk mode and a time machine backup). You could also try to take out the HDD and connect it to another Computer if this step fails.
If you can measure the MacBooks temperature try to check if its an overheating issue.
Reset NVRAM/PRAM and do a Hardware Test. Your Mac might be able to identify the issue by that.
If possible, try to start from another Mac startup disk and check
whether its a general macOS issue or the specific version installed
As safe mode seems to work better it might be some software. Check the activity monitor to identify unused/unnecessary software and quit as most programs as possible. You might be able to find some (background) task that is using much Energy/CPU/RAM (used Energy basically translates to heat). Also have a look at startup items. A very drastic solution is to take out the battery and run the MacBook only with the battery chord plugged in. This will throttle the components a lot.

You can find the mentioned startup modes here: Startup Options
Other than that, you should try to find a local repair store/Apple Store.
I hope this is any help. Good luck!


Empty and fresh battery in series

Question: If you have 2 (e.g. 1.5V) batteries in series and one is dead/empty, what is the reason why a device is not working? Lack of voltage (1.5 + 0 is simply not enough for the device to operate)? From my understanding, for batteries in series, the current is the same as for one of them. So, a common sense says to me that it must somehow connected with voltage, not current. Is it true?
Comment: Maybe your device needs 3V while 1.5V is not sufficient? I'm just brainstorming.
Answer: Actually, using a combination of fresh and somewhat depleted batteries was widely used strategy not so lo... well, about 40 years ago (I must remember I am already adult). I remember my grandfather (Electical Engineering PhD) doing so for his portable radio.
The practice was neither that much effective nor absolutely safe. Batteries back then already had a warning on their labels not to mix fresh and depleted batteries.
How it works:
The battery-powered devices are built with some tolerance to the power voltage. The portable radio in question used 6 x D-size, 1.5V cells. 6 fresh batteries could give like 10V (they started somewhat above 1.5V each) and the radio worked acceptably down to 5V (like 0.85V per cell). When the radio refuses to work on voltage that low, you change one of the cells and it works some more. Repeat, always changing the oldest battery.
The trick was, those cells (leclanché dry cells, ZnMno2 with ammonium chloride electrolyte) had pretty shallow discharge curve and they could give a meaningful amount of energy below the usual 0.8-0.9V end-of-discharge point.
What could go wrong:
Leclanche cells like to leak electrolyte when deeply discharged. Their container is also the negative electrode that is consumed in the discharge process.
At some point, the voltage of a particular cell can go below 0, at that point the cell actually consumes energy and (provided it is still gas-tight) builds gas pressure that can rupture the container. Or make the electrolyte leak faster.
Another limitation is that the internal resistance of the cell goes up with the state of charge going down. That's why the trick works only for small discharge currents.
Modern electrochemical cells are way better in regard to their discharge curves. When their voltage falls below their intended end-of-discharge limit, one can extract almost no energy from them. That's why it is pointless to mix fresh and depleted modern batteries. The dead cell just drops some voltage, instead of adding a little.
When we talk about rechargeable cells of any chemistry, over-discharging them usually quickly shortens their useful life (or outright destroys them). That's why it is best to use cells in series that are strictly matched by capacity.
Answer: A battery works by harnessing an electric potential to drive electrons through a conductor. When two batteries are in series, there's a sandwich of different potential regions in the pattern negative-positive-negative-positive. As electrons leave the negative end of this sandwich and through a conductor, electrons are also simultaneously filling and neutralizing the positive end too. Now the positive end is becoming more and more negative, and this causes electrostatic repulsion in the negative region next to the positive end. The repulsion pushes electrons into the next positive region to satisfy the fact that the potential is being depleted and put to use. Now let assume the pattern becomes negative-positive-neutral-neutral, you can see already that it doesn't add up. There isn't a way the electrons leaving the negative end can make it to the positive region needed to be neutralize to have electrostatic neutrality.
Comment: So, with zero voltage in one of the battery, there will be no loop, so no current flow a all? And if a battery is considered dead (see the reply below), but some voltage still remaining, does it mean that I can have luck (if voltage would be high enough) to run the circuit (but e.g. led will be dimmer)? thanks!
Comment: If it's truly zero, yes no loop. But if there's still some juice in the weak one, it'll will run the device but you won't be able to harness the full 1.5 V potential in the strong one, at least not for long.
Answer: A battery is considered dead when: 1.5 volt battery is .8 volts and below, a 9 volt battery is 5.4 volts and below.
So if you have 1 good battery and 1 dead battery, you will have 2.3 volts instead of 3 volts.
You will lack the voltage required to run a circuit.  (The amperage available stays the same).
This is where you have to understand the difference between amperage available in the battery and amperage in the circuit.

Empty and fresh battery in series


Caching one section of a CodeIgniter page

Question: I'm using codeigniter to create a web app. I'm creating the drop down menus in the header. These are included on every page using load->view(). To populate the menus some quite complex SQL is used. The contents on the menu will change infrequently (once/twice a week), whereas the rest of the data on the page is constantly changing.
Therefore I don't want the overhead of running this SQL everytime a page is loaded. I looked at using CI caching but its on a page level. I really only want to cache a small segment.
What do you think the best approach to this is? I thought about writing this to a text file, but then you'd have to manually run the code to write this every so often.
Answer: Take a look at the query caching page, or alternatively you can use a caching library to cache sections of a page (preferred method IMHO) take a look at KhCache.
Answer: Another good caching library I have found is from Phil Sturgeon. http://github.com/philsturgeon/codeigniter-cache
It allows caching models, libraries, or just partial caching like you describe.


How do I make gameobject flip and change position when player is facing left?

Question: I attached a  a gameobject labeled "Gun" to my player's back and when the player is facing left I want the Gun to continue to look like it's still attached to his back. Right now when I play the game and the player is facing left, the gun stays in the same position it was in regardless of what direction the player is facing. How do I make the gun look like it's still on the players back if facing left? (sorry if it sounds like idk what i'm doing... I'm sorta new to game dev.)
Answer: make the weapon child of player and set weapon order in layer = 1
then you can do Scale X or Rotate Y to achieving flip effect.

void Flip(){
    Vector2 scale = transform.localScale;
    scale.x *= -1;
    transform.localScale = scale;
}

/* another method
    void Flip(){
        Vector2 currentRotation = transform.eulerAngles;
        currentRotation.y += 180;
        transform.localEulerAngles = currentRotation;
    }
*/

If you want to know player is facing left or right you can do this:
 private bool facingRight;

 float h = Input.GetAxisRaw("Horizontal");
 if(h > 0 && facingRight){
 Flip();
 }else if(h < 0 && !facingRight){
 Flip();
 }

void Flip(){
    facingRight = !facingRight;
    Vector2 scale = transform.localScale;
    scale.x *= -1;
    transform.localScale = scale;
}


Possible new type of plagiarism tool

Question: I was wondering if there is a platform or a tool that can flag papers for being plagiarised?
Brief: let's say I am researching on topic X and have used Y as a reference paper. But while through the process of researching I find there are few papers published under similar topics. Or to say with the same research work as what is in Y. And I am a independent researcher just listing/downloading papers related to X.
So is there a website on which I can just upload these plagiarised articles/papers and flag it? We do have plagiarism checkers but all I want to know is if there exists one such tool where anyone from anywhere can upload a plagiarised paper.
Comment: How do you know those other papers are plagiarized? Just because they are on the same topic does not imply or guarantee plagiarism....
Comment: I don't understand. "Similar topics" doesn't imply plagiarism, nor does "same research work". Also, charging plagiarism is a pretty serious action.
Comment: I suggest that readers take this question at face value, and assume that OP actually means _plagiarism_ —for example, one paper copying large swathes of text verbatim from another, perhaps with minor cosmetic changes—and not merely parallel discovery.
Answer: I would worry that a web site that lets anyone charge plagiarism of specific work would be in for a lot of lawsuits unless there was a mechanism for actually verifying the charge.
Charging plagiarism is a very serious action. You'd better be sure before you make a public charge. It could be interpreted in some places as libel, a form of defamation. At a minimum it would cause an uproar.
I don't think many organizations would be brave/foolish enough to host such a site.
If you think something is plagiarized, then work through existing academic structures to correct it. Also, be aware that you might be entirely wrong. Parallel (independent) work, especially in popular research areas, is very common.
Comment: I agree in general, and especially for something as reasonable as being on "similar topics"... However, a minor point: It'd be more likely to be interpreted as libel in this (website) case, rather than slander.
Comment: @Anyon, technically correct. I'll edit. https://defamation.laws.com/defamation-laws/libel-vs-slander. Thanks.
Comment: Good answer. "work through existing academic structures to correct it" means contacting the editors of the journals who published the paper, and suggesting they take a look.

Possible new type of plagiarism tool


Prescribing zeros and poles of a rational function on $\bar {\mathbb C}$ at once

Question: I have to show that for any points $P_1$, $\ldots$, $P_n$ and $Q_1$, $\ldots$, $Q_n$ ($P_i \neq Q_j$ for all $i$, $j$) on $\bar{\mathbb C}$ there exists a rational function $f$ with poles at $P_j$, $j = 1$, $\ldots$, $n$ (with order of pole $P$ = number of points $P_j = P$) and with zeros at $Q_j$, $j = 1$, $\ldots$, $n$ (with order of zero $Q$ = number of points $Q_j = Q$). For me it is clear how to construct a function with given poles or with given zeros separately (using Mittag-Leffler's or Weierstrass' theorem). It's also clear how to build a rational function with given zeros and poles on $\mathbb C$ without a zero or a pole at $\infty$. We can also build a function with given poles using Mittag-Leffler, find it zeros, divide and multiply by appropriate linear functions to get a desired function. But this procedure is not explicit. But is it possible to do it explicitly?
Comment: If none of the $P_i$ or $Q_j$ is $\infty$, a product representation is straightforward. Is your problem what to do if some $P_i$ or $Q_j$ is/are $\infty$?
Comment: The explicit construction is

$$f(z) = \frac{\displaystyle\prod_{\substack{i=1\\Q_i\neq\infty}}^n (z-Q_i)}{\displaystyle\prod_{\substack{i=1\\P_i\neq\infty}}^n (z-P_i)}.$$
Comment: @DanielFischer have you read the question? I wrote that this case is clear
Comment: Ah, sorry, that sentence must have hidden.
Comment: @DanielFischer, thank you very much!
Answer: If you already know how to build your given function when none of the specified points are at $\infty$, then just rotate the Riemann sphere such that a point distinct from the $P$s and $Q$s end up at $\infty$, construct your function with the rotated points, and then compose it with the opposite rotation.


Merge polygons based on nearest area

Question: I have multiple polygons that show me metropolitan areas and rural areas across a state. I want to modify the layer so that there are no rural polygons by assigning portions of the rural polygons to the metro polygons. This would ideally be a distance based operation, i.e., the areas of a rural polygon would be dissolved into the metro polygon that they are nearest to.
Comment: Can you Buffer the Metro areas? Use the buffer to Intersect the rural polygons, splitting the rural polygons so you can alter the attributes overlapping the buffer.
Comment: What happens when the buffers from the metro polygons overlap with each other?
Comment: @tjam, if you have overlapping buffers, those areas are still converted from Rural to Metro. They are within the distance to a metro polygon.
Comment: I see, you need to assign a single Metro name, but there might be two Metros. Maybe sort the Metro names assign the first one, as opposed to randomly selecting a name.
Answer: This is an ideal raster situation and can be resolved with a simple tool function.
For ESRI software the tool is called Nibble: http://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-analyst-toolbox/nibble.htm
You'll need to assign your areas a unique numerical ID, convert only your metro areas (rural = NoData) as a layer to use as a mask, and convert your entire dataset to raster as the input. Then you can convert your raster back to polygon based on the unique ID and join any other attributes you wish from your initial dataset.
Comment: Thanks! I'll check this out and see if it works.

Merge polygons based on nearest area


Trigger on ListEmail or Children records?

Question: I'm trying to run some custom code when a list email is sent but I'm noticing the after insert trigger I have on Task does not run. I'm also unable to create a trigger on the ListEmail object. Has anyone found a way around this limitation? Thanks!
Answer: Mass email actions do not invoke triggers:

Some operations don't invoke triggers.
  Triggers are invoked for data manipulation language (DML) operations that the Java application server initiates or processes. Therefore, some system bulk operations don't invoke triggers. Some examples include:
...
  - Mass email actions

Unfortunately, you're going to be stuck with Scheduled Apex for operations built around list emails.


After Effects creating slider for objects to have the same distance when moving the slider

Question: I'm kinda new to After Effects and I'm having a hard time creating a slider that I can control to move the chat windows with the same distance. The chat windows will start at the center and only one would show up. When I move the slider, it will show up the remaining 6 chat windows. I wanted for them to have the same distance and have the flexibility to use the slider. Here's an image of what the chat windows would look like if I move the slider.
Answer: Here's a way to do it
Put a slider on your middle layer
Add the following expression to the middle layer's position control:
xval = transform.position[0];
yval = transform.position[1];
x = xval + effect("Slider Control")("Slider");
y = yval + effect("Slider Control")("Slider");
[x,y]

Then put this on your bottom layer's position control:
xval = transform.position[0];
yval = transform.position[1];
x = xval + thisComp.layer("middle").effect("Slider Control")("Slider")*2;
y = yval + thisComp.layer("middle").effect("Slider Control")("Slider")*2;
[x,y]

Then animate the slider value.
This adjusts the x and y position of the middle image by the amount on the slider. And doubles that amount for the bottom image.
Comment: Thank you tomh.. I'll be using multiple chat windows for the animation and maybe use the pick whip tool to link the chat windows.. but I'm still quite new to expressions and I'm not quite sure what the code below is for:

xval = transform.position[0];
yval = transform.position[1];
[x,y]

does this control the direction where the object moves? I've tried changing the value for transform.position but it displaces the object and no longer at the center. Thank you for the help though
Comment: The Xval and yval things are just to keep your original position values (there might be a better way to do this, not sure). There's a good tutorial for beginning expressions here: https://www.schoolofmotion.com/blog/six-essential-expressions-creative-coding-after-effects
Comment: Thanks for the help.. I'll do some experimentation and see if I can achieve what I want.. thanks again, this helped me a lot
Comment: If you have lots of layers to animate, you may want to use the index command to control the multiplier, instead of manually changing the multiplying value in each layer. See this tutorial for info: https://www.rocketstock.com/blog/using-the-index-expression-in-after-effects/


literature on geometrical viewpoint on calculus of variations for physics

Question: What is a good reference for a geometrical viewpoint on the calculus of variations for physics, using differential forms etc. to derive Yang-Mills equations and other topics of the standard model?
Thanks for ideas.
Comment: Besides the answers given you could look at Dubrovin, Fomenko and Novikov's Modern Geometry GTM series
Comment: VERY good suggestion,Steve-the new epic by Novikov and Tiamanov I referenced below by no means supercedes this classic.
Answer: You might want to have a look at my book, "The Geometrization of Physics" which is freely available online in numerous places, in particular from http://www.e-booksdirectory.com/details.php?ebook=3623
or directly from my homepage: http://vmm.math.uci.edu/
Comment: this is very useful
Answer: There aren't a lot of up-to-date treatments of the calculus of variations for mathematicians nowadays,let alone physics students. To be fair,though,that's changing recently with the publications of the texts by van Brunt and Dracogna. Both those treatments are rather analytical and probably not what you're looking for.
The best and most complete introduction to the subject I've seen is in the last 4 chapters of S.P.Novikov and I.P Tiamanov's  Modern Geometric Structures and Fields,available through the AMS.It walks the reader through not only modern formulations of classical and relativistic mechanics on both semi-Reimannian and symplectic manifolds with variational methods,the last chapter gives an in-depth derivation of the Yang-Mills equations using these methods.
I think you may find everything you're looking for in this book.
Answer: I think that the book

David Bleecker: Gauge Theory and Variational Principles, Addison-Wesley, 1981

contains exactly what you are looking for.
Answer: The section on classsical field theory in IAS QFT Volume 1 is a pretty good place to get started.


angular-generator with susy and breakpoint

Question: I am trying to setup an angular app using Susy and Breakpoint instead of bootstrap.
I am using yeoman to run angular-generator. During the install, instead of saying Yes to bootstrap, i say No. This all goes well and my app runs in the browser fine with 'grunt serve'.
Next i run: bower install susy and bower install breakpoint - both install fine and i can see them in the bower_components folder.
I then import them by manually adding @import reference to main.scss like this:
// bower:scss
@import "../bower_components/susy/sass/_susy.scss";
@import "../bower_components/breakpoint/breakpoint/_breakpoint.scss";
// endbower

And also in the Gruntfile.js i have added require: 'susy' to compass like so:
compass: {
  options: {
    sassDir: '<%= yeoman.app %>/styles',
    cssDir: '.tmp/styles',
    generatedImagesDir: '.tmp/images/generated',
    imagesDir: '<%= yeoman.app %>/images',
    javascriptsDir: '<%= yeoman.app %>/scripts',
    fontsDir: '<%= yeoman.app %>/styles/fonts',
    importPath: '<%= yeoman.app %>/bower_components',
    httpImagesPath: '/images',
    httpGeneratedImagesPath: '/images/generated',
    httpFontsPath: '/styles/fonts',
    relativeAssets: false,
    assetCacheBuster: false,
    raw: 'Sass::Script::Number.precision = 10\n',
    **require: 'susy'**
  },

As outlined on the susy website: http://susydocs.oddbird.net/en/latest/install/
Ok, that's all well and good, but here's the problem.. because i have manually adding them to my main.scss file, everytime i stop and start the app, it deletes the @import references in my SCSS file. i don't know how to add them dynamically / or properly to the gruntfile.js so that they get compiled and saved permenantly.  Each time i stop and start grunt, both imports are removed from main.scss leaving me with this:
// bower:scss
// end bower

Has anyone else had this same problem, if so what's the solution?
Any help would be appreciated.
thanks
~declan
Comment: ever figure this out?
Answer: Try moving the @import statements outside of the bower comments.  So, instead of:
// bower:scss
@import "../bower_components/susy/sass/_susy.scss";
@import "../bower_components/breakpoint/breakpoint/_breakpoint.scss";
// endbower

try:
// bower:scss
// endbower
@import "../bower_components/susy/sass/_susy.scss";
@import "../bower_components/breakpoint/breakpoint/_breakpoint.scss";

That worked for me.


Who know the meanings of state of CronTrigger object?

Question: Who know the meanings of state of CronTrigger object?
I wanna know the detail of those state and it is the best if answer from official documents.
Thank you all.
Answer: The documentation isn't clear, as far as I can tell, but I'll start an answer and see if anyone can fill in the blanks:
WAITING
The job is queued to be executed at some point in the future.
ACQUIRED
The necessary row/table locks have been acquired, and the job is about to start.
EXECUTING
The job is currently processing.
COMPLETE
The job has finished.
BLOCKED
The job can't acquire locks and so has to wait.
ERROR
The job failed (opposite of COMPLETE) and must be retried.
PAUSED
The job has been suspended by the system to process other jobs.
PAUSED_BLOCKED
The job has been suspended because of row locks, and will resume later.
DELETED
The job has been aborted through some API command at the request of a user.
Comment: I referred to the documentation here - https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_crontrigger.htm , here the explanation for the "Complete" state is : The trigger has fired and is not scheduled to fire again.
I can not understand the match between the explanation you provided for this status and the one that is given in documentation. Please explain ! @sfdcfoc
Answer:
The Status column lists the current status of the job. The possible
values are:
Holding -    Job has been submitted and is held until system resources are freed up.
Queued -     Job is awaiting execution.
Preparing -   The start method of the job has been invoked. This status might last a few minutes depending on the size of the batch of records.
Processing -  Job is being processed. Aborted Job was aborted by a user.
Completed -   Job completed with or without failures.
Failed -  Job experienced a system failure.

find more in the documentation
Comment: Hi Pavel, thank you for answer. Perhaps you confuse the object name form my question. Your answer refered to the AsyncApexJob object, I refered to the CronTrigger object. :) and thanks again.
Answer: As per salesforce documentation, below are the meanings for them:

WAITING: The job is waiting for execution.
ACQUIRED: The job has been picked up by the system and is about to execute.
EXECUTING: The job is executing.
COMPLETE: The trigger has fired and is not scheduled to fire again.
ERROR: The trigger definition has an error.
DELETED: The job has been deleted.
PAUSED: A job can have this state during patch and major releases. After the release has finished, the job state is automatically set to WAITING or another state.
BLOCKED: Execution of a second instance of the job is attempted while one instance is running. This state lasts until the first job instance is completed.
PAUSED_BLOCKED: A job has this state due to a release occurring. When
the release has finished and no other instance of the job is running,
the job's status is set to another state.


Weight difference in excercise for same muscle

Question: I wanted to workout by posterior delts, so I was doing revese chest fly on machine and I was able to do it with 80 pounds, but when Dumbbell Bent-Over Reverse Fly i am doing i can take only 10 pounds of dumbbell, why such a difference?
Answer: Perhaps this can help, i came across it the other day when i had the exact same question. https://breakingmuscle.com/fitness/why-the-numbers-on-weight-machines-are-a-lie
Comment: Can't agree, though partiality true. I think my other muscles are helping
Comment: Good answer, but instead of just posting a link, it would be helpful if you could post text out of the answer, that way if the page is taken down in the future, people will still be able to use this answer
Comment: @murmansk I used to train at a pretty hard core powerlifting gym, while there, I noticed that I could do tricep pulldowns with more weight on one cable machine than the other. I asked the gym owner about it, and he said it's because one machine uses an extra pulley, so there is a greater mechanical advantage, so it takes less work to move the same weight.


Jquery selectmenu combobox closes whenever button-up in IE and Chrome

Question: In my html, I have this data binding
<select data-bind="options: graders,
    optionsText: 'LastName',
    optionsValue: 'Id',
    selectmenuValue: selectedGroup().GraderId,
    optionsCaption: 'Choose a grader'">
</select>

In my JavaScript, I have following to refresh the UI in real time
ko.bindingHandlers.selectmenuValue = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        if (typeof ko.bindingHandlers.value.init !== 'undefined') {
            ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, viewModel);
        }
    },

    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        if (typeof ko.bindingHandlers.value.update !== 'undefined') {
            ko.bindingHandlers.value.update(element, valueAccessor, allBindingsAccessor, viewModel);
        }
        $(element).selectmenu();
    }
};

Everything is working good in Firefox but on IE and Chrome, whenever I mouse up the combobox, its popup immediately closes. The popup should stay opened like in firefox. With many tries, I found that I can make it stay opened if I move my mouse from the first item to one of the other items while pressing its button and press up at the point.
Anybody knows how to fix this problem?
Update: I just realized that location of its popup is little off in IE and Chrome and I believe that's the reason of the behavior above. Still looking for a fix.
Answer: You want style to be set to 'dropdown' I believe
$(element).selectmenu({style: 'dropdown'});


How to recover Yahoo! account

Question: I made a Yahoo! account a while ago, and I thought I was just going to use it for small stuff, but I ended up depending on it very heavily. Since I was going to use it only for small stuff, I didn't really pay attention to the sign up information, so I put a random phone number, and I also did not put a recovery email. I've forgotten my password and I can't get back in. I am depending on this email very heavily so if you have any solutions, please help me.
Answer: Use the Sign-in Helper to get back into your account using your Yahoo ID, mobile number, recovery phone number, or recovery email address. If you forgot your password, be sure to change your password to a strong one that you'll remember after you're in.
If you don't have recovery option(s), probably you will not be able to sign-in your account.
From Yahoo! Help:

If account recovery information is incorrect:
  We take your privacy and security very seriously, and only let you reclaim an account if you prove you're the rightful owner. When you register for an account, it's up to you to provide valid recovery info that proves ownership. The best way to safeguard your account access is to update your recovery info whenever your mobile phone number or email address changes.
Sign-in Helper can't recover your account online:
  We need valid security and recovery info to protect your account. If you weren't successful with Yahoo Sign-in Helper or the other options above, you likely won't be able to recover your account. If you remember your sign-in information later, you can come back and try again.

How to recover Yahoo! account


Are there any ancient descriptions of Aristotle's appearance?

Question: Plato wrote several references to Socrates's appearance.  And Diogenes Laertius reports that Plato was called Plato because he was broad shouldered.  Are there any ancient sources describing Aristotle's appearance?
Answer: See Diogenes Laërtius, Lives and Opinions of Eminent Philosophers: V,1: Aristotle. for description.
But Aristotle lived 384–322 BC and Diogenes ca.180 – 240: five centuries is a lot of time!
In general, portraits and marble statues are not reliable sources; but you can see: Ludovisi's Aristotle a roman copy of an original work of the Greek Lysippos: 4th century BC and personal sculptor to Alexander the Great.
See: J.H. Jongkees, On the Portraits of Aristotle and Menander, Mnemosyne (1965).
Answer: To the best of my knowledge there are no "ancient descriptions of Aristotle's appearance".  There are a few statues of Aristotle throughout Greece-(especially in Northern Greece, which was Aristotle's home territory before he arrived in Athens to study at The Academy).
Aristotle was born and raised in the Northern Greek town of Stagira.  If one visits Stagira, one will see an ancient city in scattered ruins with a statue of Aristotle overlooking it. And, in recent years, Archeologists insist that they discovered the tomb of Aristotle in the town of Stagira.
(While it does not qualify as an "ancient description" of Aristotle, one could visit The Vatican Museum and see Rafael's. "The School of Athens".  Of course Rafael lived about 1800 years AFTER Aristotle, so his painted representation of Aristotle was hardly, an archeologically accurate image).


For all practical purposes can light be bent (without the help of gravity) or just reflected?

Question: For example, if a single beam of light was directed directly at the tangent of a semi circular mirror, would it be considered bending or redirecting many times to form a near circular pattern? When I say bend I mean in a curved trajectory, not at an angle.
Comment: Certainly one can "bend" light by shining it through a medium that has an gradient in its index of refraction.
Comment: @AlecRhea, the question seems to be about ray optics.
Comment: @ThePhoton How so?  The OP seems to be asking about the nature of bending light non-gravitationally; if we are only capable of answering the question in some very approximate limit like ray optics then so be it, but I don't think a very roughly approximated answer is being requested.
Comment: @AlecRhea, He asks about  a "beam of light", and the level of the question doesn't imply prior knowledge beyond high school physics. If you want to post an answer that jumps straight to quantum mechanics, I won't downvote. But I don't think that's what will teach OP the most.
Comment: What you refer to as a 'beam of light' is actually composed of many photons in a coherent superposition; you need to be more precise for a physically meaningful answer, or wait and hope someone is nice enough to nuance your question for you then answer it.
Comment: @HotLicks This is arguably not actually bending the light, but absorbing the photons and re-releasing new ones with a different velocity vector.  What gravity does is much more subtle.
Comment: Diffraction might be thought of as bending light. For example, in a Gaussian laser beam, rays follow hyperbolic paths. But it can also be treated as a superposition of straight rays that interfere.
Comment: @ThePhoton I secretly hope that a good answer to this question might serve as a nice 'laymans intro' to the problem of merging QM and GR based views of the universe, but I would need to spend more time thinking about how to show the formalisms colliding in an easy to understand way.
Comment: @Alec Rhea When I say a "beam of light that is what I'm referring to, a "stream" of photons that to the naked eye appears to be all in one piece.
Comment: @ThePhoton You are correct in your assumption that I am not out of high school yet. This question just arises from a discussion between me and a friend, trying to decide if you can actually bend light specifically with a curved mirror.
Comment: In optical fibers it even goes into loops.
Answer: The phenomenon you're describing, of light being bent, is observed when light passes through a medium with progressively increasing, or decreasing refractive indexes.
You actually observe it when you see a mirage. When it's very hot, the temperature being progressively higher as you approach the ground, the refractive index decreases (because density decreases) and light coming from the sky is bent upwards explaining why you see "water" on the ground when it's very hot. When in fact, what you actually see is light from the sky being bent upwards into your eyes.
Hope my answer helped! :)
This image sums it up pretty well
Comment: Thanks for the well-explained answer, but I'm talking specifically about "curving" light with a semi-circular mirror.
Comment: Are you talking about light "sliding" on a curved mirror? If that's the case it's seems to me as it's theoretically possible, but not experimentally...
Answer: a beam of light can be bent through an angle by sending it through a wedge-shaped piece of glass, requiring neither gravity nor reflection. this phenomenon is called refraction and can be studied in detail on wikipedia.
Answer:
if a single beam of light was directed directly at the tangent of a semi circular mirror, would it be considered bending or redirecting many times to form a near circular pattern?

The problem with this plan is that it's not possible to make an infinitely narrow beam of light. Because of diffraction, the diameter of a beam of light is limited to roughly the wavelength of the light. And if you try to make a beam with a diameter close to this limit, it will diverge very quickly. To make a collimated beam (one that doesn't diverge very much), you have to make the diameter of the beam substantially larger.
So there's no way for all the light to travel exactly tangent to the mirror surface, and the end result will not be the light beam skimming along the surface to exit the other side of the hemisphere. Exactly what will happen depends on the exact shape of the mirror and the beam profile. You normally wouldn't try to understand this problem analytically but just use a computer simulation to approximate the result.
To answer the question in your title,

can light be bent?

If you want to bend light, then it's more easily done with a prism or lens, or possibly gradient index optics, as described in another answer.
Comment: One thought after I wrote this: It's conceivable to get something like what OP suggested if the "semicircular mirror" is a dielectric mirror and the incoming beam approaches at the critical angle for total internal reflection (not tangent to the mirror surface).
Comment: Ok, then since it is impossible to have a beam that small, could you HYPOTHETICALLY do it? As for a prism or a lens, isn't that just refraction, which is for all intents and purposes is the reverse of reflection? If so, then it's still at an angle, so not a curve per say.
Comment: 1. Hypothetically under what circumstances? My comment above suggests one where it might be possible. 2.  Refraction isn't the opposite of reflection any more than a bicycle is the opposite of a car. 3. As shown in Gornemant's answer, refraction by a continuously varying-index medium can produce curved beams rather than sharp angles.


Why the distributed process clocks in a distributed system using Lamport clocks will eventually converge?

Question: Basically the lamport clock helps the host to order the events rather than the exact time. How does all the logical clocks end up being converged in the long term?
Comment: What do you mean by "converge"? If you mean "all have the same value" then they won't -- at the very least, the last receiver will have a value 1 greater than its sender. Perhaps you can rewrite the question to be more clear by giving an example of a system and the communications between nodes, but as written this question doesn't make a lot of sense.
Answer: You're absolutely right about this not being about the exact time. We don't even care what the real time is. We care about keeping the clocks in sync with each other. That can be made evident this psudocode from wikipedia
The algorithm for sending a message:
<code>time = time+1;
time_stamp = time;
send(message, time_stamp);
</code>
The algorithm for receiving a message:
<code>(message, time_stamp) = receive();
time = max(time_stamp, time)+1;
</code>
The essential pattern here is fastest clock wins.  That's not a good way to keep actual time since any clock is as likely to gaining time as losing time.  But it ensures no messages are scrambled by the corrections.  Since all we're trying to do is create a reliable, if partial, ordering of messages we don't care that the atomic clocks in Colorado say we're way off.
You can call this behavior "converged" if you like but I see it as all the clocks being dragged forward by one hyperactive clock because we care more about being in sync than about being correct.


Conection of two routers

Question: I have wireless router Cisco Linksys E900 connected to modem, but I can't get the WiFi signal on the other side of my house. So I put there a second wireless router Asus RT-N10E and connected it with an internet cabel to may first wireless router Cisco. How I have to configure second Asus router?
Answer: Connect Asus router to a LAN port from your Cisco router. Make sure you had disabled DHCP server on Asus router. Set IP address to range of Cisco's DHCP server (usually something between 192.168.1.1 - 192.168.1.254)
For a WiFi setting, if you are using 2.4Ghz make sure you use only channels 1 6 or 11. These channels don't overlap. If you want seamless experience with WiFi (say, you move within the house and your device automaticaly choose better signal) make sure you use same SSID of WiFi (name of your WiFi) and same encryption (use WPA2-AES) and same passphrase on both routers.

Conection of two routers


Loading page with time consuming script

Question: Is there a way to tell a page to start showing the page data while a php function is executing?   have a page where I show a year calendar with descriptions for each day of the year.  The page takes a long time to run. I am looking into ways to optimize the speed.  However, I had a general question about page loading.  I have seen web pages that start filling out a scrolling area as the page data becomes available.  My page only loads when the PHP script is done.
Here is the code structure.

Build page header.
Call PHP script to fill out page content.
Print echo statement to write out calendar table.
Loop through months of the year.
Call date functions to show each day of the month.
Call php function on external domain to echo description for each day of the month as table row.
Build page footer.
Scroll-top to current day.

I'd like to be able to show the rows for each day of the month as they are generated. Is this something that can be done when calling a PHP function?  Can this only be done with Javascript?  The script that writes the description for each day, as mentioned earlier, is a PHP script from an external domain.
For each row in the year calendar I call three PHP scripts as show here.
<code>$showfeast = file_get_contents('http://feed.evangelizo.org/reader.php?date=20110622&type=feast&lang=AM');
$showliturt = file_get_contents('http://feed.evangelizo.org/reader.php?date=20110622&type=liturgic_t&lang=AM');
$showsaints = file_get_contents('http://feed.evangelizo.org/reader.php?date=20110622&type=saint&lang=AM');
</code>
The date string sent to that script is calculated by calling the PHP date functions mktime and date, usually like this for each day.
<code>   $curTime = mktime( 0, 0, 0, $thisM, $i-$sOffset +1, $thisY );
   $curDate = date("Y-m-d", $curTime);
</code>
It wouldn't be helpful to show the entire code here. I am mostly looking for advice for the best way to design the code to achieve the goals:

Show each row for the given day of the calendar as it is generated.
Find the best way to call the external domain PHP script to meet goal 1.

It is possible for me to completely redesign the code.  The only constraint is to call the three PHP scripts shown earlier for each day of the year.
Thanks for your advice.
Answer: Have JavaScript load it via AJAX call when page is done loading.

Loading page with time consuming script


Relink dropbox account on remote server

Question: I had a dropbox account on a remote linux server. Since I was having problems with dropbox (was getting python stacktraces) I unlinked my account (from the dropbox website) to relink it again, to see if that worked.
Unfortunately, now I cannot relink to my remote server. The first time I ran dropbox I got a link to use to connect my server to dropbox. This does not happen anymore. Even after uninstalling/reinstalling dropbox I still do not get a new link to reconnect my account, the dropbox status is just "Connecting" and nothing happens (which isn't strange, since it isn't allowed to connect to dropbox anymore).
[also sent to DB support, will post answer here if I get one]
Answer: I was allowed to reconnect by just starting the dropbox daemon eventually, it just took (way too much) time.

Relink dropbox account on remote server


Understanding morphisms of affine algebraic varieties

Question: In class, we defined an affine algebraic variety to be a $k$-ringed space $(V, \mathcal{O}_V)$ where $V$ is an algebraic set in $\bar{k}^n$ defined by a system of polynomial equations over $k$, and the sheaf of regular functions $\mathcal{O}_V$ that assigns an open subset of $V$ to the set of regular functions on that open set.
We then defined a morphism of affine algebraic varieties $(V, \mathcal{O}_V)$, $(W, \mathcal{O}_W)$ to be given by a morphism of the underlying ringed spaces, i.e. a continuous map (which I'm assuming means continuous with respect to the Zariski topology) $\phi: V \to W$, together with a family of $k$-algebra homomorphisms $\phi_U : \mathcal{O}_W(U) \to \mathcal{O}_V(\phi^{-1} (U))$.
This definition is very abstract and I'm having a bit of a hard time wrapping my head around it. However, we were given some equivalent definitions of this, as well as the following correspondence:
For affine algebraic varieties $(V, \mathcal{O}_V)$, $(W, \mathcal{O}_W)$, there is a $1-1$ correspondence between the morphisms of ringed spaces between $(V, \mathcal{O}_V)$, $(W, \mathcal{O}_W)$, and the $k-$algebra homomorphisms $k[W] \to k[V]$, where $k[W], k[V]$ are the coordinate rings of $W, V$ respectively (so $k[W] = k[x_1 , \dots , x_n]/I(W)$).
So, just to make sure I am understanding this correctly. Let's say I am defining a morphism of the affine algebraic varieties of the circle $x^2 + y^2 = 1$ over $\mathbb{C}$ to the hyperbola $xy = 1$. Does the correspondence stated above mean that it is enough to just write a ring homomorphism $\phi : \mathbb{C}[x,y]/(x^2 + y^2 - 1) \to \mathbb{C}[x,y]/(xy-1)$?
Answer: More or less correct, the thing to note is however, that the functor from affine varieties to rings is contravariant. Meaning that the correspondence is arrow reversing. Intuitively this corresponds to the pullback of functions.
Comment: Ahh I see. So a morphism of affine algebraic varieties $(V, \mathcal{O}_V) \to (W, \mathcal{O}_W)$ corresponds to a $k$-algebra homomorphism in the opposite direction $k[W] \to k[V]$?
Comment: Yes! That is correct


In D7 what is the correct way to create a page template that has HEAD elements specific to that page?

Question: In Drupal 6 HEAD tags were part of the page.tpl.php.  Now that that has moved to the html.tpl.php in D7, what is the correct way to create templates that need different data in head tags?
Answer: Use hook_preprocess_html ( e.g in template.php ) to modify the html.tpl.php variables.
For different JS or CSS, check the path ( e.g current_path() == 'foo' ) and add with

drupal_add_js or
drupal_add_css

Set the 'every_page' option, and perhaps preprocess flag to FALSE.
Comment: On a related note, could there be a performance issue here? Granted it would not be noticeable only one or two pages. But, if I needed several hundred templates, would it make a differece if these were statically embedded or called from template.php?
Comment: If you need hundreds of templates or variations, you should probably rethink your design.
Comment: I have a classifieds website that has 100s of pages, each based on a taxonomy term. XML Sitemaps is configured to add each of these pages to my sitemap based on the included Sitemap taxonomy module.  What I am wanting is to have each category listing have its own template so I can fine tune the head elements (meta, etc) for each of these term pages.  Meta tags does not give me the control I need as it forces tokens to be applied unimformly across all taxonomy term listing pages. That's what I am trying to get around. Thoughts?


jQuery: How to identify which XHR handler ajaxComplete() was fired off for

Question: I have multiple $.get() handlers in my JavaScript. I'd like to be able to run specific code when a handler has successfully finished its request. From jQuery's documentation, it looks like the following is what I'm looking for:
$( document ).ajaxComplete(function() {
  $( ".log" ).text( "Triggered ajaxComplete handler." );
});

The problem I have here is, this is going to get triggered for every $.get() handler. How can I identify which one it is going off for so I can take the correct steps that are required to update my user interface?
Answer: Personally I just wrap all jQuery AJAX methods in my own function. That way I can do all sorts of tracking and caching behaviors without relying on hooks. For example:
function AJAXLoad(method, data, callback) {
    var request = method + (new Date()).toString();
    console.log("Sending request " + request);
    $.ajax(method, { data: data, success: function(msg) {
        console.log("Request " + request + " completed.");
        callback(msg);
    }});
}

Answer: You will get the xhr object and the settings object as an argument to the callback, you can use them to identify the ajax method
$(document).ajaxComplete(function (event, jqxhr, settings) {
    console.log(jqxhr)
    $(".log").text("Triggered ajaxComplete handler.");
});

But if you want to register a callback for a particular ajax request and you have access to that ajax request's promise object then you can use the .always() callback like
var promise = $.post('/echo/json/', {});//or $.ajax() etc
promise.always(function(){
    //do something
})