Are there functions that have $\Re(f(z))$ periodic but $f(z)$ is not periodic?

Question: Let $f(z)$ be a function meromorphic in a simply connected convex domain $D$ (subset of the complex plane with positive area or the whole complex plane) where $z$ is a complex number.
Are there such functions $f(z)$ where $\Re(f(z))$ is periodic in the domain (no periods larger than the domain please :p ) but $f(z)$ is not periodic? (if $D\subset \mathbb C$ it is clear that $f(z)$ is not periodic but $\Re(f(z))$ might still be for some shapes of $D$).
In particular the case when $D = \mathbb C$ is interesting. (in other words $f(z)$ meromorphic over $\mathbb C$)
I guess it is a similar question to ask about $\Im$ , $\operatorname{Arg}$ or $|\cdot|$ instead of $\Re$.
I read about double periodic functions and Cauchy-Riemann equations but I still don't know. I can't find such a function in the literature ( i mean the one i search here , i don't mean i can't find a double periodic one in the literature of course ) and I don't know how to construct them or even if they exist.
Comment: I do not know what your last comment means.
Comment: The literature is literally filled with examples of doubly periodic functions. They are called *elliptic functions*. You can find them constructed in pretty much every textbook on complex analysis —Lang's, Ahlfors's, &c.
Comment: I was referring to the functions i was looking for. Maybe an edit.
Comment: Also, your parenthetical remark in the 2nd paragraph that something is clear is quite weird: there certainly are  periodic functions defined on proper subsets of the complex plane; for example, restrict any periodic function from the plane to any open subset of the plane invariant under the periods.
Comment: A function cannot repeat its period 2 times and then diverge when it is suppose to reach its 3rd repeat. At least not a function that is holomorphic in its period.
Comment: I thought reading about double periodic functions and Cauchy-Riemann equations would help , but its much simpler as you have shown. Oh well , it was fun reading anyway.
Answer: Suppose $f$ is meromorphic in $\mathbb C$ and its real part is periodic of period $p$. Then $z\mapsto f(z)-f(z+p)$ is a meromorphic function whose real part is identically zero.
Can you conclude something from this?
Comment: Of course ! So simple. Thank you.
Answer: The real part of $z\mapsto iz$ has period $p$ for any $p\in \mathbb R$.


Spring WebSocket - messages lost after being sent by controller

Question: I have a problem with WebSocket messages not getting sent with Spring WebSocket version 4.1.1.RELEASE. It does not happen to every message, just some are not sent for a reason I do not understand. The content of the messages takes some time to load but I am not sure if that is the reason for the issue since sometimes it works but most of the time it does not.
My web application successfully subscribes to a channel /user/queue/overview/reqinfo/events and then sends four messages to request information. My controller class fires a COUNT() statement on a database via spring-data-jpa and Hibernate and returns the result as a message to the user the request came from. All four messages are handled by the same controller method but only two responses get delivered to the sender. I extracted the relevant information from the Spring logs and attached them here. As you can see the last two messages are not being processed by the SimpleBrokerMessageHandler and are thus not sent to the user. Creating the content of these messages takes more than a minute.
12:50:54,953 DEBUG clientInboundChannel-12 user.UserDestinationMessageHandler:187 - Translated /user/queue/overview/reqinfo/events -> [/queue/overview/reqinfo/events-user8178efnd]
12:50:54,953 DEBUG clientInboundChannel-12 broker.SimpleBrokerMessageHandler:175 - Processing SUBSCRIBE /queue/overview/reqinfo/events-user8178efnd id=sub-7 session=8178efnd
[...]
12:50:54,957 DEBUG clientInboundChannel-2 support.SimpAnnotationMethodMessageHandler:348 - Searching methods to handle SEND /app/overview/reqinfo/events session=8178efnd
12:50:54,957 DEBUG clientInboundChannel-1 support.SimpAnnotationMethodMessageHandler:348 - Searching methods to handle SEND /app/overview/reqinfo/events session=8178efnd
12:50:54,957 DEBUG clientInboundChannel-16 support.SimpAnnotationMethodMessageHandler:348 - Searching methods to handle SEND /app/overview/reqinfo/events session=8178efnd
12:50:54,959 DEBUG clientInboundChannel-10 support.SimpAnnotationMethodMessageHandler:348 - Searching methods to handle SEND /app/overview/reqinfo/events session=8178efnd
[...]
12:50:54,959 DEBUG clientInboundChannel-16 support.SimpAnnotationMethodMessageHandler:446 - Invoking de.d.i.g.websocket.OverviewController#requestOverviewEvents[2 args]
12:50:54,959 DEBUG clientInboundChannel-10 support.SimpAnnotationMethodMessageHandler:446 - Invoking de.d.i.g.websocket.OverviewController#requestOverviewEvents[2 args]
12:50:54,959 DEBUG clientInboundChannel-2 support.SimpAnnotationMethodMessageHandler:446 - Invoking de.d.i.g.websocket.OverviewController#requestOverviewEvents[2 args]
12:50:54,959 DEBUG clientInboundChannel-1 support.SimpAnnotationMethodMessageHandler:446 - Invoking de.d.i.g.websocket.OverviewController#requestOverviewEvents[2 args]
[...]
12:50:55,006 DEBUG clientInboundChannel-1 websocket.OverviewController:196 - requestOverviewEvents, incoming message: MsgOverviewEventsRequest(timeframe=THIS_WEEK)
12:50:55,006 DEBUG clientInboundChannel-10 websocket.OverviewController:196 - requestOverviewEvents, incoming message: MsgOverviewEventsRequest(timeframe=LAST_WEEK)
12:50:55,006 DEBUG clientInboundChannel-2 websocket.OverviewController:196 - requestOverviewEvents, incoming message: MsgOverviewEventsRequest(timeframe=YESTERDAY)
12:50:55,006 DEBUG clientInboundChannel-16 websocket.OverviewController:196 - requestOverviewEvents, incoming message: MsgOverviewEventsRequest(timeframe=TODAY)
[...]
12:50:55,032 DEBUG clientInboundChannel-16 websocket.OverviewController:225 - requestOverviewEvents, outgoing message: MsgOverviewEvents(timeframe=TODAY, count=31, error=false)
12:50:55,035 DEBUG clientInboundChannel-16 broker.SimpleBrokerMessageHandler:152 - Processing MESSAGE destination=/queue/overview/reqinfo/events-user8178efnd session=null payload={"timeframe":"TODAY","count":31,"error":false}
12:50:55,035 DEBUG clientInboundChannel-16 broker.SimpleBrokerMessageHandler:196 - Broadcasting to 1 sessions.
[...]
12:51:01,018 DEBUG clientInboundChannel-2 websocket.OverviewController:225 - requestOverviewEvents, outgoing message: MsgOverviewEvents(timeframe=YESTERDAY, count=190292, error=false)
12:51:01,020 DEBUG clientInboundChannel-2 broker.SimpleBrokerMessageHandler:152 - Processing MESSAGE destination=/queue/overview/reqinfo/events-user8178efnd session=null payload={"timeframe":"YESTERDAY","count":190292,"error":false}
12:51:01,020 DEBUG clientInboundChannel-2 broker.SimpleBrokerMessageHandler:196 - Broadcasting to 1 sessions.
[...]
12:51:19,081 DEBUG clientInboundChannel-1 websocket.OverviewController:225 - requestOverviewEvents, outgoing message: MsgOverviewEvents(timeframe=THIS_WEEK, count=845956, error=false)
12:51:19,088 DEBUG clientInboundChannel-10 websocket.OverviewController:225 - requestOverviewEvents, outgoing message: MsgOverviewEvents(timeframe=LAST_WEEK, count=1421118, error=false)

This is a sample case where the problem occurs often. I have other views with other messages and controllers that suffer by the same issue and their messages do not take a minute to build, only some seconds or even less. I am using the SimpleMessageBroker with SockJS support (using SockJS 0.3.4). While trying to fix this issue I added this bean to my WebSocket configuration class to manually set timeouts on the connecton but it did not solve the problem:
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
    long tenMinutesInMillis = 10 * 60 * 1000;

    ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
    container.setAsyncSendTimeout(tenMinutesInMillis);
    container.setMaxSessionIdleTimeout(tenMinutesInMillis);

    return container;
}

How can it be that some messages are just dropped while other get sent properly? If you need any more information from the logs or source code please ask.
[UPDATE] Some additional information on the behavior:
The first message that counts the smallest number of items always returns. The second message returns most of the time and the last two fail to be sent about 90% of the time. After they failed to load other views won't load as well, the response messages are just not sent to the web interface even though the subscription is received and processed. After hitting refresh in the browser to reload the page everything works fine until a message gets stuck again.
However, the heartbeat system that runs in the background and uses the WebSocket as well for its messages to the users works all the time. It seems to be completely unaffected by the issue.
[UPDATE 2]
When the issue occurs it seems that the sockJsScheduler is not processing all requests. The INFO message that the WebSocketMessageBrokerStats logs gives the following output:
INFO MessageBrokerSockJS-2 config.WebSocketMessageBrokerStats:113 - WebSocketSession[1 current WS(1)-HttpStream(0)-HttpPoll(0), 1 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(1)-CONNECTED(1)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 16, active threads = 0, queued tasks = 0, completed tasks = 120], outboundChannelpool size = 16, active threads = 0, queued tasks = 0, completed tasks = 16], sockJsScheduler[pool size = 8, active threads = 1, queued tasks = 4, completed tasks = 18]

It says that there are four queued tasks for the sockJsScheduler that are not being processed, maybe these are the messages that are not sent properly? Unfortunately there is no further information on why they are not processed in the logs.
Answer: After intensive debugging of my application and especially the Spring code that handles I found the reason for that behavior.
The issue was neither the controller nor the Spring internal processes, it was the class that I use for Principal objects during Spring Security authentication. It stores the last heartbeat ID that the user answered successfully to check if a user that send a message to the system is alive or if the session was already considered dead. This ID was included in the equals(), hashCode() and toString() methods of that object.
Spring uses one of these methods (after some testing I guess it is toString(), which is not a good choice in my opinion) to translate destination paths for @SendToUser operations. If the string changes, which was the case for my application when a new heartbeat ID was answered, Spring cannot translate the destination path and does not send the message. The log entry that states this is hidden as a TRACE level message, which is why I did not find it in the first place. The message looks like this:
14:29:00,260 TRACE clientInboundChannel-16 user.UserDestinationMessageHandler:175 - No user destinations found for /user/RtAuthorizedUser(super=AuthorizedUser(username=SIEM-User 1, authenticated=true, lastAnsweredHeartbeat=9971f9ea-8e64-4c24-823b-f7e6e277c775, alive=true), rtSessionId=RT_SID_iMonitor.443=782acc747aac01b9e0a7ece3ab2d27bd)/queue/overview/reqinfo/events

I would suggest to the devs to make this message at least DEBUG level (or even WARN or ERROR), since this information is hard to spot when searching for issues during the sending process. In fact this is an error.
After removing the heartbeat ID from the three mentioned methods the systems runs well, no more lost messages. So it was a mistake on my side in the first place but I think the use of toString() is not optimal here. Now Spring can translate the messages correctly, producing these messages (which are DEBUG level instead of TRACE as the above):
14:37:35,661 DEBUG clientInboundChannel-3 user.UserDestinationMessageHandler:187 - Translated /user/RtAuthorizedUser(super=AuthorizedUser(username=SIEM-User 1, authenticated=true, alive=true), rtSessionId=RT_SID_iMonitor.443=bf3adbaa858932b64a03724b6137e95d)/queue/overview/reqinfo/events -> [/queue/overview/reqinfo/events-user_qtca5il]


During the over can captain change the bowler?

Question: In a cricket match can the captain of the fielding team change the bowler during the over, for any reason aside from  necessity (like injury)?
Answer: No. At the time of the question, this was covered by Law 22.7(a):

Other than at the end of an innings, a bowler shall finish an over in progress unless he is incapacitated or is suspended under any of the Laws.

With the 2017 rewrite of the Laws, this is covered by Law 17.7.1; the wording is essentially identical.


Call an URL with Scheduled Powershell Script

Question: I just want to call an URL with the tasks scheduler on Windows Server 2008 and a Powershell Script.
So I developed the following script :
$url = "http://example.com"

$log_file = "${Env:USERPROFILE}\Desktop\Planification.log"
$date = get-date -UFormat "%d/%m/%Y %R"
"$date [INFO] Exécution de $url" >> $log_file

$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
$response.Close()

The script works without any issue when I execute it from the Powershell ISE, the Powershell console or with the command :
powershell PATH_TO_MY_SCRIPT.ps1

But it doesn't works when I execute it from the Scheduler tasks, it returns the code 0xFFFD0000. I found this : http://www.briantist.com/errors/scheduled-task-powershell-0xfffd0000/
So it can be a permission problem, so I tried many others profiles and option (including "Execute with all permissions") to test, without success.
I execute also another Powershell script which just mount a network drive and copy two files, and I don't have any issue with this script. So I think that the issue come from the using of the .NET object to call my URL.
I saw that I may have to include modules in my script before any other commands, but I don't know exactly what I have to do. (I don't know Powershell, I just try to use it for resolving my problems).
Thank you for you help.
Comment: I think it's more likely that the problem is with accessing the `USERPROFILE` directory - it may not be what you expect it to be. It could also be an issue with your proxy setting (or lack thereof) if it's an external URL. What user account does the scheduled task execute under?
Comment: Detailed answer for PowerShell 3+ or older versions: https://stackoverflow.com/a/12081686/155687
Comment: Can not  agree more with @alroc on the 'USERPROFILE' part. When you run it manually (or interactively) it is whoever logged into the system and open the session (Eg. if you log in as "Peter" you will get "Peter"'s profile). When run it through schedule task then it will be "SYSTEM"s profile by default which could make `${Env:USERPROFILE}\Desktop\Planification.log` no sense. But "SYSTEM" account can be changed though: In "Scheduled task" Control Panel right mouse click it and then go properties, you will be able to modify the user account under which the task runs.
Answer: i used the following in a scheduled task and it works as expected :
$url="http://server/uri"
(New-Object System.Net.WebClient).DownloadString("$url");

Comment: The difference between your and Dorian's is whether using variable in another variable's definition.
Answer: following code should do what you need.
$url = "http://www.google.com"
PowerShell Invoke-WebRequest -Uri $url -Method GET

Answer: You'll want to put that log file out somewhere in a shared directory.  Scheduled tasks may or may not have access to $env:USERPROFILE.  Also, use Start-Transcript to have PowerShell write your script's output to a log file (except for STDOUT, you'll need to pipe the output from executables to Write-Host, e.g. hostname | Write-Host).
$url = "http://example.com"

$log_file = "C:\PlanificationLogs\Planification.log"
Start-Transcript -Path $log_file

Get-Date -UFormat "%d/%m/%Y %R"
Write-Host "$date [INFO] Exécution de $url"

# PowerShell 3
Invoke-WebRequest -Uri $url

# PowerShell 2
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
$response.Close()


Spinner scrolls to top when onLongPress or scrolling slowly

Question: I have a spinner with a LOOONG list of items. What I noticed is that whenever I try to scroll the spinner items SLOWLY, it suddenly takes me back to the top of the spinner selection. I'm just using a standard Spinner with a simple ArrayAdapter. It's not really an issue, but it's kinda annoying that whenever a user would scroll slowly, the selection resets all the way to the top. You can fling the list, but if you scroll slowly, keeping your finger on the screen, it scrolls back up to the top of the list.
Has anyone else experienced this problem? Why does it occur? Is there a way to "fix" this issue?
Note: The problem I have is only on a Spinner.
Comment: Perhaps related to this issue: https://issuetracker.google.com/issues/37065626
Comment: Found any solution ?
Answer: I had exactly the same issue and removing the app:popupTheme attribute fixed it. Check this comment: https://issuetracker.google.com/issues/37065626#comment15.
Answer: I solved this issue by the following method.

API level 22 or lower: Use app:popupTheme
API level 23 or higher: Use android:popupTheme

res/layout/spinner.xml
<android.support.v7.widget.AppCompatSpinner
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:layout_marginRight="@dimen/toolbar_spinner_margin_right"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

res/layout-v23/spinner.xml
<android.support.v7.widget.AppCompatSpinner
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:layout_marginRight="@dimen/toolbar_spinner_margin_right"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

res/layout/activity_main.xml
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="?attr/actionBarTheme"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <include layout="@layout/spinner" />

</android.support.v7.widget.Toolbar>

And to solve an issue where the spinner button color is black in API level 19 or lower, you need to add the following code:
Kotlin
if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
    val spinnerDrawable = spinner.background.constantState.newDrawable()
    spinnerDrawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        spinner.background = spinnerDrawable
    } else {
        spinner.setBackgroundDrawable(spinnerDrawable)
    }
}

Java
if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
    Drawable spinnerDrawable = spinner.getBackground().getConstantState().newDrawable();
    spinnerDrawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        spinner.setBackground(spinnerDrawable);
    } else {
        spinner.setBackgroundDrawable(spinnerDrawable);
    }
}


Erro: TypeError: $http.get(...).success is not a function

Question: Estou chamando um serviço da amazon e está dando problema, segue código:
Controller:
app.controller('MainController', ['$scope', 'emails', function($scope, emails) {
emails.success(function(data) {
    $scope.email = data;
});
console.log($scope.email); }]);

Factory:
app.factory('emails', ['$http', function($http) {
return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/emails-api/emails.json')
.success(function(data) {
    return data;
})
.error(function(err) {
    return err;
}); }]);

No console aparece:

TypeError: $http.get(...).success is not a function

O que pode ser?
Answer: O método get do $http retorna uma Promise, segue abaixo a maneira correta para fazer a chamada.

Controller

app.controller('MainController', ['$scope', 'emails', function($scope, emails) {
  emails.then(function(data) {
      $scope.email = data;
      console.log($scope.email);
  });

}]);

Factory

app.factory('emails', ['$http', function($http) {
    return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/emails-api/emails.json').then(function(data) {
        return data;
    }, function (error) {
        return error;
    });
}]);

Comment: Desta maneira também deu certo, obrigada Hiago. :)
Comment: ;) disponha Rafaela
Answer: A função success do $http.get só é funcional até a versão 1.4.3 do AngularJS. Para as versões subsequentes, utilize o método then para capturar o resultado da promessa.
Substituindo no seu código:
app.controller('MainController', ['$scope', 'emails', function($scope, emails) {
  emails.then(function(data) {
      $scope.email = data;
      console.log($scope.email);
  });
}]);

E na factory:
app.factory('emails', ['$http', function($http) {
  return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/emails-api/emails.json');
}]);

Comment: Obrigada Sorack :)


What is "Sonata-Allegro form" and what other similar forms should I be aware of?

Question: There are lots of classical pieces called "Sonata", and they usually have 3 movements. But there are guitar Sonatas by Paganini that only have 2 movements! And I heard there's a crazy Tchaikovsky -- maybe it was a symphony, but that's still sonata-form, right? -- piece that has 4 movements. I heard orchestras get spooked-out when playing this piece in Japan because they alone, having done their homework, know not to clap after the boisterous III. Allegro.
Would someone explain what the 'Sonata-Allegro' form is, and perhaps shed some light on these side-questions by-the-by?
[PS. Willing to separate this part as new question if appropriate.]
There's also the Rondo (== 'Rondeau'?) form that shows up in the same Piano collections. Are there others that belong to the same class?
Comment: As far as "other similar forms" see the answer to [What are the parts of a classical composition?](http://music.stackexchange.com/questions/25124/what-are-the-parts-of-a-classical-composition).
Answer: There are three different things here: the sonata(-allegro) form, the (multi-movement) sonata form, and the title sonata.
The sonata(-allegro) form is a form of one movement. It's usually fast (hence the allegro) and the big structure is ABA, where the first A is called exposition, B is development, and the second A is recapitulation. Sometimes there's a slow introduction and, especially with Beethoven and later composers, a coda at the end. In the most classic form, the exposition introduces a main theme, a secondary theme (in a different key), and a closing theme. In the development section the themes are varied and taken through different keys. The recapitulation is then a (varied) repetition of the exposition, often with the secondary theme transposed to the main key.
The (multi-movement) sonata form is a different thing, and refers to the structure of a whole composition. This (together with the sonata-allegro form) only really developed in the classical era. The classical multi-movement sonata usually consists of three or four movements:

A fast movement in sonata-allegro form.
A slow movement.
A menuetto or scherzo.
A fast finale, often in sonata-allegro or rondo form.

In three-movement sonatas the missing movement is usually one of the middle ones. Now, this structure is not only used for pieces called a sonata, but also for symphonies, concerti, trios, quartets, and other multi-movement "big" pieces.
Then there is the "Sonata" title. Originally, any instrumental piece could be called a sonata, for example the sonatas of Scarlatti. In the classical era, most pieces called a sonata were pieces of multi-movement sonata form written for one or two instruments. Since then we've been going back to the original meaning. I think if you want to describe a "sonata" in a way that encompasses most sonatas written after the classical era, you would have to say that it's a not-small piece for at most a few instruments. Usually it's also in more than one movement, and the form of the first movement quite often resembles the sonata-allegro form.

As you can see above, the rondo form can appear as a part of a multi-movement sonata. Rondo is usually of ABACADA or similar form, that is, there is a repeating main theme and then contrasting themes in-between. It may also be symmetric, for example ABACABA. The rondo form is not tied to the sonata form, though, and it often appears in independent pieces (the rondo form is actually much older than the sonata). Also, the finale of a classical multi-movement sonata can be something else than mentioned, for example a set of variations.


How to make sure multiple threads run methods from different classes in order?

Question: I am making a program where a server offers a quiz to any number of clients. I have to make this using sockets, so I am trying to solve this by making multiple threads with socket objects in my server class, each socket maintaining the connection to one client.
This was working fine until I did some refactoring, after which I discovered through debugging that information between client and server was being sent in the right order by sheer luck.
Here is the code for my client threads. It's an inner class of my Server class and the questionList is an attribute thereof.
private class ClientThread implements AutoCloseable, Runnable
{
    private Socket clientConnection;
    private DataOutputStream output;
    private DataInputStream input;

    public ClientThread(Socket clientConnection) throws IOException
    {
        this.clientConnection = clientConnection;
        output = new DataOutputStream(clientConnection.getOutputStream());
        output.flush();
        input = new DataInputStream(clientConnection.getInputStream());
    }

    public void sendQuestion() throws IOException
    {
        if (input.available() > 0) if (input.readBoolean())
        {
            Question question = questionList.get((int) (Math.random() * questionList.size()));
            sendQuestionInfo(question);
        }
    }

    private void sendQuestionInfo(Question question) throws IOException
    {
        sendInfo(question.getAuthor());
        sendInfo(question.getTitle());
    }

    private void sendInfo(String info) throws IOException
    {
        output.writeUTF(info);
        output.flush();
    }

    @Override
    public void run()
    {
        try
        {
            sendQuestion();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {...}
}

And here is the relevant code from my Client class:
public class QuizClient implements AutoCloseable
{
    private Socket serverConnection;
    private DataOutputStream output;
    private DataInputStream input;

    public QuizClient(String serverAdress, int portNumber) throws IOException
    {
        serverConnection = new Socket(serverAdress, portNumber);
        output = new DataOutputStream(serverConnection.getOutputStream());
        output.flush();
        input = new DataInputStream(serverConnection.getInputStream());
    }

    public void getQuiz()
    {...}

    private void playQuiz(boolean firstRun, Scanner scanner) throws IOException
    {...}

    private boolean playQuizTurn(Scanner scanner) throws IOException
    {...}

    private boolean isFirstRun()
    {...}

    private void askQuestion(Scanner scanner) throws IOException
    {
        output.writeBoolean(true);
        output.flush();
        Question question = getQuestion();
        question.quizMe(scanner);
    }

    private Question getQuestion() throws IOException
    {
        String author = input.readUTF();
        String title = input.readUTF();
        return new Question(author, title);
    }

    @Override
    public void close() throws IOException
    {...}
}

The intended order of execution is askQuestion() -> sendQuestion() ->  getQuestion(), but with the current code it insteads runs like sendQuestion() -> askQuestion() -> getQuestion(), and the program ends up being unresponsive.
How can I get this under control?
Comment: This answer requires an enormous answer, explaining various parallel computing paradigms, traps and pitfalls. I recommend reading some [literature](http://beginnersbook.com/2013/03/multithreading-in-java/), especially the [tag:Java] doc on [synchronization](http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html).
Comment: maybe ditch threads and go back to lock-in-step?
Comment: It seems my question has been a bit more convoluted than I thought, I apologize about that. Either way, I have solved the issue with methods running in the wrong order by introducing a lock and a condition, changing the first line of  `sendQuestion()` to `while (!(input.available() > 0)) condition.await();` and making a thread dedicated solely to signal the condition.
Comment: running things *in order* means *serialized* which is the **opposite** of concurrent. use a single thread. as this is worded now this is **off topic: too broad**
Comment: @JarrodRoberson You can't avoid two concurrent processes if a client and a server are running on different machines.  The issue is synchronizing those concurrent processes, which is a legitimate issue.  As my answer illustrates, the problem the poster could be answered in three lines, so it was far from two broad.  Upvoted and voted to keep open.
Comment: @WarrenDew - you are conflating `concurrent` with `asynchronous`; they are **not the same thing**, the question is about concurrent processes on the same server, `threads` on the server in this case. the question clearly states *by making multiple threads with socket objects in my server class,* Unfortunately it does **not show** where the threads are created or how they are managed.
Comment: @WarrenDew - read what I wrote for comprehension, your attempt at an answer also demonstrates you did not read the question for comprehension either.
Answer: Your server's ClientThread.sendQuestion() method exits silently if input.available() is 0 - that is,  if the "true" has not yet been received from the client - which will often be the case with a newly established client.  Try having it wait patiently until there is data available, and see if you get any further.


How is $A_5$ is the union of cosets $H, gH, g^2H$?

Question: Working on a proof to show that $A_5$ has no subgroup H of order 15 or 20.
I am obstructed at this point: if $g$ is an element of the group $A_5$ of order 5, why is that if g is not in a subgroup H, then $A_5$ is the union of cosets H, gH, $g^2$H?
Comment: https://math.stackexchange.com/questions/2995244/how-do-i-prove-that-any-subgroup-of-a-5-has-order-at-most-12?noredirect=1 this may help you
Comment: It did not @Koushik_halder :(
Can you elaborate please?
Comment: any subgroup of $A_5$ has order at most 12.Then,is it possible that $A_5$ has a subgroup of order 15 or 20?
Comment: It's not. I am able to map out elements and see the structure: 24 of order 5, 20 order 3, and 15 order 2, and identity. But I am compelled to show that $A_5$ is the union of the cosets I mentioned above which I cannot figure how to do.
Comment: If it's a normal subgroup, then it must be a union of some conjugate classes of $A_5$, one of which should be the class containing the identity, i.e. of size $1$. The other conjugate classes have sizes $20$, $15$, $12$, $12$. No sum of those numbers including $1$ is a divisor of $60$ other than $1=1$ and $60=20+15+12+12+1$.
Comment: @WilfredoGuillermo The 24 elements of order 5 split into 2 conjugate classes in $A_5$, those of $(12345)$ and $(12354)$.
Answer: The most important observation is that the cosets $H, gH, g^2H, g^3H, g^4H$ should be disjoint if $g$ is an element of order $5$ and $g$ is not in the subgroup $H$. To show this, let $n$ be the least positive power of $g$ that is in $H$. Since $g$ is not in $H$, $n > 1$. But also $n$ is a factor of $5$, since $g^5 = e$ is in $H$. So $n = 5$.
When $12 < |H| < 24$, this leads to a contradiction because $H$ cannot contain all elements of order $5$, so it is possible to find an element $g$ of order $5$ not in $H$. Yet, $H, gH, g^2H, g^3H, g^4H$ are disjoint sets in $A_5$ containing more than $60$ elements altogether, when $A_5$ only has $60$ elements to begin with.
You may phrase this in terms of $A_5$ being the union of cosets $H, gH, g^2H$ by reversing the logic and only considering three cosets (because four cosets would give us more than $60$ elements), but I think the way I have written is simpler.
Comment: Can you explain why this is? "The most important observation is that the cosets ,,2,3,4 should be disjoint if  is an element of order 5 and  is not in the subgroup "
Comment: The idea is in the next sentence: if $g^{i}H = g^{j}H$, then $g^{i-j}$ is in $H$, which can only happen if $i-j$ is a multiple of $5$.


Python deleting half the elements in a list after iterating through it

Question: I've been completely stumped on this one:
I have the following python code:
<code>def remove(self, widgets):
    for widget in widgets:
        widget_found = False
        for widget_sig in self.widgets:
            if widget_sig.id == widget:
                #remove all objects from selected widget
                widget_found = True
                to_remove = widget_sig.objs
                for obj in to_remove:
                    #objs are all intances of oo_canvas classes
                    obj.destroy()
                    self._build(widget, obj)
        if not widget_found:
            #if we iterated through the entire list and still couldn't find anything
            raise mockingbird_errs.InternalMockingbirdError("The requested widget was not registered with this builder: "+str(widget))
</code>
This should be pretty straight forward. The thing is, it never iterates through to_remove correctly. For some reason, it skips every other element. Even more baffling, is if I have it print the length of to_remove before and after the for loop, it prints 254 and 127. Huh? As far as I know, iterating through a list does not involve deleting every other element.
Am I missing something straightforward? What on earth is going on?
Comment: what is obj.destroy() doing???
Comment: obj.destroy() changes one attribute in the class from False to True. Later, a different method will be called on obj that actually collects the data and uses it.
Comment: There is actually no code inside your snippet actually performing a remove operation. You are hiding details from us!
Comment: If you actually want to delete half the `list` (as opposed to just one element), you're usually better off building a new `list` of just the elements you want to keep. This doesn't work in all cases (e.g., if someone else is holding a reference to the same `list`, and needs to see the changes), but when it does, it's easier to reason about, and usually simpler code, and more efficient.
Comment: I'll just clarify quickly. I wasn't trying to delete half the list. I was trying to iterate through the whole list without deleting any of it. Anyway, I fixed the problem by copying the list first.
Answer:
... it skips every other element.

That's because you keep deleting them, shortening the list by 1. And then you move on to the next index. Either work backwards, or iterate over a copy of the list.
Comment: I did try iterating over the copy, and that fixed the problem. Thanks.
Comment: How to do that ?


require 'rubygems'

Question: I have seen many samples of Ruby code with this line (for example, http://www.sinatrarb.com/). What is purpose of this require?
# require 'rubygems'
require 'sinatra'
get '/hi' do
  "Hello world!"
end

In all cases the code works without this line.
Answer: require 'rubygems' will adjust the Ruby loadpath allowing you to successfully require the gems you installed through rubygems, without getting a LoadError: no such file to load -- sinatra.
From the rubygems-1.3.6 documentation:

When RubyGems is required, Kernel#require is replaced with our own
  which is capable of loading gems on demand.
When you call require 'x', this is what happens:

If the file can be loaded from the existing Ruby loadpath, it
  is.
Otherwise, installed gems are searched for a file that
  matches. If it's found in gem 'y', that gem is activated
  (added to the loadpath).

The normal require functionality of returning false if that file
  has already been loaded is preserved.

See the documentation for Kernel#require to understand why this is necessary.
Comment: Btw, I don't recommend it. See this post by Ryan Tomayko: http://gist.github.com/54177
Comment: In Ruby 1.9 'require "rubygems"' happens automatically. In previous Rubies rubygems is not automatically required and you will get the error. Your best bet is to automatically type it in unless you are sure you are running always in 1.9+. Ruby won't care if you require it twice in 1.9+ and your code will be happy in 1.8.whatever.
Comment: @Carmine Paolino, regarding your comment: Sinatra is a gem. What is the best way to make sure that requiring it does not produce an error without using `require 'rubygems'`?
Comment: @Greg: quoting Ryan Tomayko: "The system I use to manage my $LOAD_PATH is not your library/app/tests concern. Whether rubygems is used or not is an environment issue. Your library or app should have no say in the matter. Explicitly requiring rubygems is either not necessary or misguided."
Comment: @yar: The post I linked presents 3 solutions.
Comment: @Carmine Paolino, seems like all of the three solutions require rubygems, just indirectly.
Comment: @yar: in fact they are solutions to the problem (in your own words) "the best way to make sure that requiring it does not produce an error without using `require 'rubygems'`". If you don't use rubygems you just use `Kernel#require` which is quite straightforward...
Comment: I took the -rubygems option, was easy to do for my command line utility: #!/usr/bin/env ruby -rubygems
Answer: It is often superfluous. It will allow you to require specific versions of particular gems though, with the gem command.
https://guides.rubygems.org/patterns/#requiring-rubygems
Comment: Actually, "require 'rubygems'" does not load a needed gem, it only modifies the behaviour of the "require" method.
Comment: RubyGems will select the latest installed version of the gems that follow. If no such software is found, a exception is generated.
Comment: Why is it superfluous? It's the best way to load a needed gem.
Answer: As an addition to prior (and correct answers): Ruby 1.9 and newer ship with RubyGems built-in, so there is no real need to require 'rubygems'. Source here
Comment: You are right, as long as ruby is not build with `--disable-rubygems`.

require 'rubygems'


Complex integrals

Question: Let $f$ be an analytic function, $C^1$ on an open and connected set $U$.
for all $z\in U$ : $|f(z)-1|<1$.
Prove that $\int_\gamma \frac{f'(z)}{f(z)}dz =0$ for every closed curve (closed curve- $\gamma(a)=\gamma(b)$) in $U$.
Any hints?
Answer: The other answer, which I can't understand why is downvoted, is correct. You can also argue as follows:
The condition $\;|f(z)-1|<1\;,\;\;\forall\,z\in U\;$, makes sure the function $\;f\;$ can not vanish in $\;U\;$ (why?), and thus $\;\cfrac{f'}f\;$ is analytic in $\;U\;$ , so the claim follws directly from CIT.
Comment: The function $f$ wont vanish because if it does then $1<1$?(I'm not the one who downvoted the other answer).
Comment: @ChakaChaka You are right...and didn't think you were the downvoter. Some rogue member of the site must be bored on christmas...
Answer: Hint: The complex logarithm admits an analytic branch on $U_1(1)$.
Edit: Alternatively, by the definition of the line integral we have
$$\int_\gamma \frac{1}{f(x)} f'(x) \, dx = \int_a^b \frac{1}{f(\gamma(x))} f'(\gamma(x)) \gamma'(x) \, dx = \int_{\beta} \frac{1}{x} \, dx,$$
where $\beta = f \circ \gamma$. Now use the Cauchy integral theorem.
Comment: What do you mean by $U_1(1)$?
Comment: $U_r(x_0)$ denotes the open ball of radius $r$ around $x_0$.
Comment: I'm sorry, I just can't see how it helps..
Comment: $\log(f)$ is an antiderivative of $\frac{f'}{f}$.
Comment: Can i say this -  $\int_\gamma \frac{f'(z)}{f(z)}dz =\int_\gamma log(f(z))'dz=log(\gamma(b))-\log(\gamma(a))=0$?
Comment: Yes, if you know that the logarithm is analytical on $U_1(1)$.
Comment: But where do we use the fact that $|f(z)-1|<1$?
Comment: To guarantee that the logarithm has an antiderivative. It seems that you haven't covered the complex logarithm as of yet, I will update my answer with an alternative proof.
Answer: Hint:
To be able to use the fact that Log(f) is the antiderivative of f′/f, i.e. to be able to say that (Log(f))' = f'/f, you need to make sure that Log(f) is differentiable.
Yet, the complex logarithm Log is not continuous everywhere (and hence not differentiable everywhere).
The condition |f(z)−1|<1 can be used to guarantee that Log is continuous and differentiable.
Does this make sense ?
Comment: $|f(z)-1|<1$ make sure that $f$ wont vanish, and that's why $Log$ is continuous and differentiable correct?

Complex integrals


Is the value of the limit $\lim_{h\to 0}\frac{\sin(h)}{h}$ equal to 1, when $h$ is in degrees?

Question: $$\lim_{h\to 0}\frac{\sin(h)}{h}$$
I wanna ask whether the value of this limit equal to 1 or not if the "h" is used in degrees and not in radians ? My teacher told me that it's not equal to 1 if "h" is used in degree but I wanna confirm because he was also not so sure.
Comment: do you mean $\displaystyle \lim_{h \to 0}\frac{\sin h}{h} $?
Comment: Your teacher's right. See the answers here: https://math.stackexchange.com/questions/1339540/why-does-the-derivative-of-sine-only-work-for-radians
Comment: Note that $\displaystyle \lim_{h \to 0}\frac{\sin h^\circ}{h}$ i not of the same form as $\displaystyle \lim_{h \to 0}\frac{\sin h^\circ}{h^\circ}$, the later of which is equivalent to  $\displaystyle \lim_{h \to 0}\frac{\sin h}{h}$.
Comment: What is $h°$ supposed to do in the denominator then?
Comment: Then you can consider $\frac{\sin(2\pi (d/360))}{2\pi (d/360)}$ with $d$ in degrees.
Comment: @user2628206 so $$lim_{h\rightarrow 0}\frac{sin(h°)}{h°}=1$$ ??
Comment: @Ankit Yes, if using degrees as formulated in Sangchul Lee 's response. Also I have a typo in previous comment: i should be is!
Answer: In mathematics, each trigonometric function only takes pure numbers as arguments, and the argument is geometrically interpreted as radian.1) Even the unit $\text{rad}$ is defined in SI units purely as the number $1$.
So, what is the degree then? You can simply consider the degree symbol ${}^{\circ}$ as the constant having the value
$${}^{\circ}=\frac{\pi}{180},$$
i.e., it is simply a conversion factor. Then

If you regard $\sin$ to take degree as the input, then it is the same as considering $\sin(x^{\circ})$, where ${}^{\circ}$ is the above constant. In this case,
$$ \lim_{h\to 0} \frac{\sin(h^{\circ})}{h} = {}^{\circ} = \frac{\pi}{180}. $$

If you simply replace $h$ by $h$ degree, i.e. $h^{\circ}$, then nothing changes because
$$ \lim_{h\to 0} \frac{\sin(h^{\circ})}{h^{\circ}} = 1. $$

1) This interpretation is valid only when the argument is real. The trigonometric functions can take complex arguments as well, and then the geometric interpretation no longer applies.
Comment: But now you have $h$ playing two roles.  In the numerator, you've replaced $h$ by $ah$, so now _that_ $h$ is $180/\pi$ times bigger than the $h$ in the denominator.
Comment: He says $h$ is measured in degrees.  So isn't the bottom $h$ also counting how many degrees?  I think this is more of a problem of being sloppy with what $\sin x$ means.
Comment: @B.Goddard, I think I might have misinterpreted OP's claim. So I now presented two versions of answers depending on the interpretation. Thank you for pointing this out.
Comment: @Sangchul Lee thanks for your second edit I was asking for the second part you added where h is in degree in both num. and deno..
Answer: I'll write $\operatorname{Sin}h^\circ$ with a capital $\text{S}$ and let $\sin,$ with a lower-case $\text{s}$ mean sine in radians. Then
$$
\operatorname{Sin}h^\circ = \sin\frac{\pi h}{180}.
$$
So:
$$
\frac{\operatorname{Sin}h^\circ} h = \frac{\sin(\pi h/180)} h = \frac\pi{180}\cdot\frac{\sin(\pi h/180)}{\pi h/180} = \frac\pi{180}\cdot\frac{\sin u} u.
$$


Delete Function of a Class

Question: I'm having trouble with the delete function. I have everything working except the delete function.
Any help would be appreciated. I've tried to change it a bit but it still doesn't  delete. I have no idea what the problem is with my remove function.
public class Person
{
    private string name;
    private string phoneNumber;

    public string Name
    {
        set { name = value; }
        get { return name; }
    }
    public string PhoneNumber
    {
        set { phoneNumber = value; }
        get { return phoneNumber; }
    }
    public void PrintInfo()
    {
        Console.WriteLine();
        Console.WriteLine(" Name: {0}", name);
        Console.WriteLine(" Phone Number: {0}", phoneNumber);
        Console.WriteLine();
    }
    public void SaveASCII(ref StreamWriter output)
    {

        output.WriteLine(name);
        output.WriteLine(phoneNumber);

    }
    public void LoadASCII(ref StreamReader input)
    {

        name = input.ReadLine();
        phoneNumber = input.ReadLine();

    }

}

public class membershipList
{

    public Person[] ML = null;

    public void AddMember(Person p)
    {
        if (ML == null)
        {
            ML = new Person[1];
            ML[0] = p;
        }
        else
        {
            Person[] temp = ML;
            ML = new Person[temp.Length + 1];
            for (int i = 0; i < temp.Length; ++i)
            {
                ML[i] = new Person();
                ML[i] = temp[i];
            }
            ML[temp.Length] = new Person();
            ML[temp.Length] = p;
            temp = null;

        }
    }
    public void DeleteMember(string p)
    {

        if (ML != null)
        {
            foreach (Person pers in ML)
            {
                if (pers.Name.ToLower().CompareTo(p.ToLower()) == 0)
                {
                  pers.Remove();
                  break;

                }
            }
        }

        else Console.WriteLine("Then list is empty.");
    }

                //   {
                //      int memberIndex = Array.FindIndex(ML, p => p.Name == name);
                //      if (memberIndex == -1)
                //    {
                //        Console.WriteLine(name + " had not been added before.");
                //      return;
                //   }
               // else
               // {
                //    List<Person> tmp = new List<Person>(ML);
               //     tmp.RemoveAt(memberIndex);
               //     ML = tmp.ToArray();
               // }
       // }
  //  }

    public void PrintAll()
    {
        if (ML != null)
            foreach (Person pers in ML)
                pers.PrintInfo();
        else Console.WriteLine("Then list is empty");
    }
    public void Search(string p)
    {
        if (ML != null)
        {
            foreach (Person pers in ML)
            {
                if (pers.Name.ToLower().CompareTo(p.ToLower()) == 0)
                {
                    Console.WriteLine("1 Record Found:");
                    pers.PrintInfo();
                    break;
                }
            }
        }

        else Console.WriteLine("Then list is empty.");
    }

    public void ReadASCIIFile()
    {
        StreamReader input = new StreamReader("memberlist.dat"); ;

        try
        {

            int num = Convert.ToInt32(input.ReadLine());
            ML = new Person[num];

            for (int i = 0; i < num; ++i)
            {
                ML[i] = new Person();
                ML[i].LoadASCII(ref input);

            }
            input.Close();
        }
        catch (FormatException e)
        {
            Console.WriteLine(e.Message);
            input.Close();
        }

    }

    public void SaveASCIIFile()
    {

        StreamWriter output = new StreamWriter("memberlist.dat");

        output.WriteLine(ML.Length);
        foreach (Person pers in ML)
        {
            pers.SaveASCII(ref output);

        }
        output.Close();

    }
}

class Program
{
    static void Main(string[] args)
    {

        membershipList ML = new membershipList();
        ML.ReadASCIIFile();

        string option;
        do
        {

            // Console.Clear();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("MemberShip List MENU");
            Console.WriteLine();
            Console.WriteLine("     a. Add");
            Console.WriteLine("     b. Seach");
            Console.WriteLine("     c. Delete");
            Console.WriteLine("     d. Print All");
            Console.WriteLine("     e. Exit");
            Console.WriteLine();
            Console.Write("option: ");
            option = Console.ReadLine().ToLower();

            switch (option)
            {
                case "a":
                    Person np = new Person();
                    Console.Write("Enter Name: ");
                    np.Name = Console.ReadLine();
                    Console.Write("Enter PhoneNumber: ");
                    np.PhoneNumber = Console.ReadLine();
                    ML.AddMember(np);
                    break;
                case "b":
                    Console.Write("Enter Name: ");
                    string name = Console.ReadLine();
                    ML.Search(name);
                    break;
                case "c":
                    Console.Write("Enter Name to be Deleted:");
                    string pers = Console.ReadLine();
                    ML.DeleteMember(pers);
                    break;
                case "d":
                    ML.PrintAll();

                    break;
                case "e":
                    ML.SaveASCIIFile();
                    Console.WriteLine("BYE...... ");
                    break;

                default:
                    Console.WriteLine("Invalid Option");
                    break;
            }

        } while (option.ToLower() != "d");
    }
}

Comment: You seem to have `pers.Remove();` but that probably shouldn't even compile (given that your `Person` class doesn't seem to have a `Remove()` method). Think about this for a moment - what are you trying to remove the person *from*?
Comment: Your question is really vague. Can you clarify a bit?
Comment: Please avoid asking questions because you're too lazy to do your own debugging.
Answer: I see two things:

If you are going to add and remove items from the list, use a List<Person> instead of an array.  As it stands now you need to copy the array to a temporary list, remove the item, then copy back to an array.
Your Delete function can then be just:
if (ML != null)
{
    Person pers = ML.FirstOrDefault(x => x.Name.ToLower() == p.ToLower());
    if(pers != null)
    {
          ML.Remove(pers);
          break;
    }
}

Answer: Your problem is this:
foreach (Person pers in ML)
{
    if (pers.Name.ToLower().CompareTo(p.ToLower()) == 0)
    {
        pers.Remove();
        break;
    }
}

You are removing from the collection you are iterating through and that throws off the iterator of the loop.
Either loop through the collection backwards, so removing does not throw off the iterator of the loop.
OR
Create a second list that holds the values you want to keep. So you would, in essence, be doing the opposite; instead of deleting you would be not adding to the keep list.
Comment: Turns out even if we use VS2012 we still have to understand something about programming ( no offense to present company intended,of course )
Answer: You are looping over an array and then calling remove on the person.  One thing about the for each loop is that it uses iterators which cannot be modified during the for each.  But even if you could it's not that simple because you cannot simply remove from an array.  You could do it from a generic List or a ListArray but not from an array. To follow the same pattern that you are already following (assuming you are required to use arrays and resize them), you need to create a temp array and copy all the elements from the ML array into the new array minus the deleted member.
Check my syntax because I didn't test this code but you should get the idea.
public void DeleteMember(string p)
    {

        if (ML != null)
        {
            Person[] tempList = new Person[ML.Length - 1];
            bool deletedAPerson = false;
            int i = 0;
            foreach (Person pers in ML)
            {

                if (pers.Name.ToLower().CompareTo(p.ToLower()) == 0)
                {
                   deletedAPerson = true;
                   continue; //skip over this person and do not copy over to the new Array
                }

                if(i < pers.Length) //if no person was found, prevent index out of bounds exception
                    tempList[i++] = pers;
            }
            if(deletedAPerson)
               ML = tempList;
        }

        else Console.WriteLine("Then list is empty.");
    }

Delete Function of a Class


For which $x \in \mathbb{R}$ is $f(x) = \sum_{n=0}^{\infty} \frac{x^2}{(1+x^2)^n}$ continuous/differentiable

Question: For which $x \in \mathbb{R}$ the following function is continuous / differentiable:
\begin{align}
f(x) := \sum_{n=0}^{\infty} \frac{x^2}{(1+x^2)^n}
\end{align}
A collection of ideas:
As a hint it is given to use the geometric series. Trying that I found:

\begin{align}
f(x) := \sum_{n=0}^{\infty} \frac{x^2}{(1+x^2)^n} = x^2 \sum_{n=0}^{\infty} \frac{1}{(1-(-x^2))^n} = x^2+1
\end{align}
I really don't see how that should help me out! Of course $f(x) = x^2+1$ is continuous and differentiable for all $x \in \mathbb{R}$.
The series obviously (follows from 1.) converges for all $x \in \mathbb{R}$ with $x^2 > 0$.
Based on that I would say the function is continuous and differentiable for all $x \in \mathbb{R}$, but to be honest that appears to be "to simple", so I'm afraid I'm doing something wrong.

It would be nice if someone could help me to get a clearer picture.
Answer: Note that the geometric series formula $\sum_{n=0}^\infty q^n = \frac1{1-q}$ is applicable only when $|q| < 1$.
For $x \ne 0$ we have that $\left|\frac1{1 +x^2}\right| < 1$ so using the geometric series gives
$$f(x) = x^2 \sum_{n=0}^\infty \left(\frac{1}{1+x^2}\right)^n = \frac{x^2}{1 - \frac{1}{1+x^2}} = x^2 + 1$$
On the other hand, for $x = 0$ we have $f(0) = 0$.
Therefore
$$f(x) = \begin{cases}
x^2 + 1,  & \text{if $x \ne 0$} \\
0, & \text{if $x = 0$}
\end{cases}$$
so $f$ is continuous and differentiable if and only if $x \ne 0$.
Comment: I was almost there ...
Thank you!
Answer: It is not a power series, hence for me the notion of radius of convergence has no sense here. However you can use the continuous/derivative theorem for series.
To show it is continuous, you need normal convergence but you need first to find for which $x$ this sum exists. You say $x \in \mathbb{R}$, you have the good feeling but prove it. The series has positive terms and you need to split cases because the behavior of $x^n$ depends on $x>1$, $x<1$, $x=1$

For $|x|>1$
$$
\frac{x^2}{\left(1+x^2\right)^n}\underset{(+\infty)}{\sim}\frac{x^2}{x^{2n}}
$$
Suppose $x \ne 0$, then
$$
\frac{x^2}{\left(1+x^2\right)^n}\underset{(+\infty)}{\sim}\frac{1}{x^{2n-2}}
$$
which converges only for $\left|x\right|>1$.If $x=0$, then it converges.
If $|x|<1$
$$
\frac{x^2}{\left(1+x^2\right)^n}\leq \frac{1}{\left(1+x^2\right)^n}
$$
which converges. Hence no problem.
If $x= \pm 1$ no problem it converges hence it is defined on $\mathbb{R}$. For $x \in \left[a,b\right]$ on $\mathbb{R}^{*+}$ you have
$$
\frac{x^2}{\left(1+x^2\right)^n}\leq \frac{b^2}{1+a^2}
$$
Hence, taking the sup, you have normal convergence on every compact set of $\mathbb{R}^{*+}$ and by partity same for $\mathbb{R}^{*-}$ so you have continuity on $\mathbb{R}^{*}$. What about $0$ ?
To show that it is differentiable you need to show that the series of $f'_n$ uniformly converges to its sum.
Comment: Thank you! I'm going to take a closer look on it tomorrow.
Comment: I don't think "$x=0$ vs $x\neq0$" is a concern within the case $|x|>1$.
Comment: It is because i I divided by 0 and i would've been equivalent to 0 which is impossible.
Comment: It's impossible anyway within the first case where $|x|>1$, since $x=0$ does not belong to that case: $|0|=0\not\gt1$. Of course, it is important to take it into consideration within your second case where $|x|<1$.
Comment: Aaah sorry I misunderstood you, i'm tired, you are right
Answer: The case $x=0$ is an important subtlety: is a discontinuity since $f(0)$ is the sum of infinitely many zeroes.


Flutter: Link inside the webview opens to built in browser instead of the webview

Question: I have created a webview using flutter, i want to display a local webapp for now to my created webview.
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:webview_flutter/webview_flutter.dart';

class EnableJavacriptWebView extends StatefulWidget {
  @override
  EnableJavacriptWebViewState createState() {
    return new EnableJavacriptWebViewState();
  }
}

class EnableJavacriptWebViewState extends State<EnableJavacriptWebView> {
  bool _isJSEnabled = true;

  _onChanged() {
    setState(() {
      _isJSEnabled = !_isJSEnabled;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("TEST")),
      body: Stack(
        children: [
          WebView(
            initialUrl: 'https://flutter.io/',
            javascriptMode: _isJSEnabled
                ? JavascriptMode.unrestricted
                : JavascriptMode.disabled,
          ),
        ],
      ),
    );
  }
}

but what happen is when i load the application(webview) it opens the Builtin browser instead of the inside webview application.
Answer: Old Version of flutter_webview_plugin and webview_flutter was used in the pubspec.yaml
Should use latest version.


TypeScript convert json structure

Question: I cant figure out how to make this conversion iterating a json.
I have this pojo in my backend:
<code>class Part{
  Long id;
  String name;
  Set<Part> parts = new HashSet<>();
}
</code>
Every part can have parts and this part more parts and so on.
I get this parts from httpclient in angular and get this json:
<code>[{
        "id": 1,
        "name": "Parts A and B",
        "parts": [{
                "id": 2,
                "name": "A",
                "parts": [{
                    "id": 4,
                    "name": "A1",
                    "parts": []
                }]
            },
            {
                "id": 3,
                "name": "B",
                "parts": []
            }
        ]
    },
    {
        "id": 2,
        "name": "A",
        "parts": []
    },
    {
        "id": 3,
        "name": "B",
        "parts": []
    },
    {
        "id": 4,
        "name": "A1",
        "parts": []
    }
]
</code>
And need to convert to this to populate a PrimeNG TreeTable:
<code>{
    "data": [{
            "data": {
                "name": "Parts A and B",
                "id": "1"
            },
            "children": [{
                    "data": {
                        "name": "Part A",
                        "id": "2"
                    },
                    "children": [{
                        "data": {
                            "name": "A1",
                            "id": "4"
                        }
                    }]
                },
                {
                    "data": {
                        "name": "Part B",
                        "id": "3"
                    },
                    "children": []
                }
            ]
        },
        {
            "data": {
                "name": "Part A",
                "id": "2"
            },
            "children": []
        },
        {
            "data": {
                "name": "Part B",
                "id": "3"
            },
            "children": []
        },
        {
            "data": {
                "name": "A1",
                "id": "4"
            },
            "children": []
        }
    ]
}
</code>
How can I do that?
In angular I get this in an array parts: Part[] and need partsTree: TreeNode[]
Thanks!!!
Comment: are you sure your structure is correct  that children outside data.
Answer: Its just a simple conversion by a map;
<code>    interface PartAPI{
  id: number;
    name: string;
   parts : PartAPI[];
}

interface Data {
   id: number;
    name: string;
}

interface Part {
     data : Data;
     children : Part[];
}

console.log('a')

let convert = (inputArr: PartAPI[] = []) : Part[] => {

 return inputArr.map(partApi =>  ({ data : { id : partApi.id , name : partApi.name }, children: convert(partApi.parts)   }) as Part)

}

let data : PartAPI[] = [{
    "id": 1,
    "name": "Parts A and B",
    "parts": [{
        "id": 2,
        "name": "A",
        "parts": [{
          "id": 4,
          "name": "A1",
          "parts": []
        }]
      },
      {
        "id": 3,
        "name": "B",
        "parts": []
      }
    ]
  },
  {
    "id": 2,
    "name": "A",
    "parts": []
  },
  {
    "id": 3,
    "name": "B",
    "parts": []
  },
  {
    "id": 4,
    "name": "A1",
    "parts": []
  }
]

console.log(convert(data));
</code>

TypeScript convert json structure


Converting a makefile to an Xcode project

Question: So here's my dilemma.  I am familiar with compiling programs from makefiles on the command line.  I am more than familiar with compiling programs in Xcode.  My question is - Is there a straightforward process for converting a makefile to an Xcode project?
Just to be clear, I know how to build an Xcode project with an external target.  This is not what I am looking to do.
I want to add this to be a little more clear.  I am porting a game written in C++ utilizing libSDL to iOS 3.2.  I, therefore, have no choice but to convert the makefile to an Xcode project.
Answer: Have you looked at cmake ? I haven't used it myself but apparently it can generate Xcode project files.
Comment: I have.  This may end up being the direction that I take.  However, the cmake -G Xcode command which generates an Xcode project requires a CmakeLists.txt file.  For the project that I am undertaking, writing this file might be just as difficult or not more so than converting the project manually for Xcode.
Comment: Personally I use the legacy makefile method for projects with existing makefiles. If you drag the source directory into the project then you still get the benefits of the IDE and source level debugging etc. It's not perfect but for me at least it has a good cost/benefit ratio.
Answer: Except for using the "External Build System" project template (which sounds like not what you want), there is no Makefile import tool in Xcode. What features are you missing by using an external target, however? You can still use Xcode, of course. You won't be able to use the build settings UI, but you claim to be comfortable enough with Make to not need it.


LDAP Configuration with Synology DSM

Question: We have Synology DSM (Disk Station Manager) Installed in our office, and my Drupal 7 site is hosted on it. I want to use Directory Users to use Drupal with same credentials using LDAP.
I installed the LDAP required modules, but I am still having trouble configuring and connecting.
Did anyone work with LDAP with Drupal?
Answer: We have successfully integrated Drupal with DSM using LDAP project: https://www.drupal.org/project/ldap
Basicall DSM is running OpenLDAP which is supported by the project. Be sure to enable php-ldap extension.
The ldap module distribution comes with a set of submodules that you enable to configure LDAP authentication and authorisation:

ldap_servers - define LDAP server
ldap_user - Sync users (User entity fields to LDAP attributes) with LDAP
ldap_authentication - Allows user to authenticate with their LDAP username/password
ldap_authorization - Give Drupal users roles based on LDAP group.

It also provides a comprehensive GUI to visually configure everything. Also integrates with 'devel' to debug.
HTH

LDAP Configuration with Synology DSM


IBM x3650 M3: can an installed vanilla vSphere 5.1u1 be replaced with "vSphere enhanced for IBM"?

Question: Some 4 years ago we got the free vSphere Hypervison 5.0 (ESXi) directly from the VMWare for installation on a donated IBM x3650 M3 server. Basically, we are novices in both IBM server management as well as vSphere, but somehow we managed to install this thing and throw in some 5 VMs. We also installed the free license and all went fine. With upgrading over the last years, server is now on vSphere 5.1 update 1.
After having to examine a possible disk fault on the disk mirror, we updated the various firmware of the box. In the process though, we discovered that IBM provides versions of vSphere/ESXi that include customizations for its server systems (see http://www-03.ibm.com/systems/x/os/vmware/ ).
The questions here are:

Can one upgrade from the "vanilla" vSphere 5.1 update 1, to the
equivalent IBM version without reinstalling from scratch?
If it can be done, are there any documentation on how to go about
it? Is it a safe procedure?
Finally, will this change void the license key of the free
version we are using?

Thank you in advance for any info provided.
Comment: I'm not sure if you can to an "upgrade" from the same version to the same version for [OEM], but if you were to upgrade to a higher version at the same time as going over to the ESXi for IBM version, it would be exactly the same as a normal upgrade.
Comment: I would assume that if such documentation exists, that IBM support would know where to find it. If not, they would be the go-to source for, well, support :-)
Answer: Yes... Just as with HP or Dell, you can safely upgrade to a newer version (with hardware-specific extensions) on a standalone host by using the vendor-provided .ISO.
HP and Dell also allow you to download and install the handful of additional .VIB software packages to bring a generic ESXi installation to a version with vendor hardware support. IBM only seems to allow this through the vSphere Update Manager, which you wouldn't have on a single host setup.
There are no licensing implications here.


Creating a function that maps a base 36 number into an RGB Color (tuple of 3)

Question: I am working on a code that needs to do the following:
imagine I have a string of characters, for example:
$\text{dk48vns203lvm923dpvgj39dkv}$
The characters can be $0,\dots,9$ or not capital letters $a,\dots ,z$, so $36$ options per character.
I would like to create a function that maps a part of this string into an RGB color. What it means is that I need $3$ $0-255$ numbers
for example $\text{fj3k0} = (233,9,48)$.
So thinking about it, the total options for an RGB color is $256^3 = 16\ 777\ 216$.
Each character has $36$ options so if we look at $4$ chars it's $36^4 =  1\ 679\ 616$ and $5$ chars is $36^5 = 60\ 466\ 176$.
I want a function to be as  unique as possible and uniformly distributed.
I have a working solution right now but I believe it can be improved.
My solution:
Take $6$ chars, every $2$ chars will map to a different $256$ number ($2$ chars for R, $2$ chars for G, $2$ chars for B).
These $2$ chars are mapped just like a base $36$ number which means $00$ is $0$ and $\text{zz}$ is $1296$ $(36 \times 36^1 + 36 \times 36^0)$.
I then take the calculation and normalize it for $255$.
Main problems:

Not really unique.
Because of the normalization, a lot of numbers become real numbers, for example $700$ can be something like $146.4345$. RGB is integers so this is rounding down which ruins the uniqueness even more.
I am using $6$ chars. $6$ chars can potentially map to $36^6 = 2\ 176\ 782\ 336$ unique RGB tuples, but this mapping struggles to find $16\ 777\ 216$ inside them so this is kind of a waste in information.

Thanks
Answer: You could take the remainder of the number represented by the two characters divided by $256$, i.e. if the number represented is $n$, then calculate $n \bmod 256$
... a small problem is that two characters have $36^2=1296$ combinations which is $5\cdot256+16$, and so it 'favors' the numbers $1$ through $16$ ... although only $16$ out of $1296$ times, which is a little more than $1$ out of $100$ times ... I don't think that's bad, and if that is acceptable to you as well, then go for it.
Otherwise, you can take $6$ characters, take the number $m$ represented by that, calculate $m'=m \bmod 256^3$, and then compute the RGB values as follows:
$$R = m' \bmod 256$$
$$G = \frac{m'-R}{256} \bmod 256$$
$$B = \frac{m'-R-256\cdot G}{256^2}$$
You will still have numbers that are still more likely to be the outcome than other numbers, but this time that happens only about $1$ in $200$ times.
Answer: It's very inconvenient to represent colors using base 36 as norm.
The most common standard datatype and representation of a pixel (that can choose 1 out of 16 million colors) are represented using 32-bit datatypes, not 36. Red, green, blue and alpha channels use 8-bits each for this.
We are left with 4 bits which we can use to represent the next pixel in the line. This is sometimes refered to as pixel-packing, some video-modes in the past used this for different color-modes and if I recall the SIMD-instruction set use some similar technique. But I have a feeling that base-36 is more complicated than aligned representations.
Now, since your question regards the use of 36 symbols instead of 16 (as in hexadecimal) (0-9 and a-f),
we get $\frac{36}{16} = 2,25$ bytes for a type of 36-symbols. $16$ symbols can be represented using $log_2(16) = 4$ bits. 36 symbols can be represented using $log_2(36) = 5,1699$... bits. Since bits act like flags (that are either on or off), it has to be discrete and hence not real.
Imagine a processor-register having 36 bits.
We then have $2^{36} = 68719476735$ combinations, this is alot more than 16 million colors.
Colors would be repsented like this:
<code>[ggggbbbbbbbbrrrrrrrrggggggggbbbbbbbb] register 1.
</code>
Here we see that the second pixel is the bits on the left and has some missing bits.
It is not convenient to have a real part, so instead of representing 4,5 channels we represent $9$ channels using two symbols each time instead of one. This means the total number of symbols that we store has be an even number.
Two symbols would use two $36$-bit registers and look like this:
<code>[rrrrrrrrggggggggbbbbbbbbrrrrrrrrgggg] register 2 (continue of 1).
[ggggbbbbbbbbrrrrrrrrggggggggbbbbbbbb] register 1.
</code>
Now we see that the two registers represent 3 colors. i.e. "packed pixels".
We used base-2 above, where r,g,b are bit-flags. So it doesnt matter what base-representation you use for visualizing whats going on. Example: $8g_{36}$ is the same as $100110000_2$. They are just different representations.
In your example you use a 26 char string:
<code>dk48vns203lvm923dpvgj39dkv
</code>
It fits the description above about representing colors by an even amount of symbols. And 26 is an even number. You are not using the alpha channel, so 3 channels (24-bits) represent one pixel. You can then pack 3 pixels using two symbols as we showed above. This means that your string of 26 characters/symbols represent $\frac{26}{2}*3 = 39$ pixels.
Normalizing numbers is not needed if you restrict your string to an even number of symbols and also normalizing can complicate the programming and encode/decode. If you want to do packing. Using real numbers for color representation can overcomplicate things further. Stick to simple solutions first, and then if you are considering jpeg and such compression have a knowledge about how colors are represented in base-2.
You need some logic operations and doing bit-manipulation to convert these pixel-formats.
Comment: Because historically (and there is a reason for it which you can read about computer architectures) registers work with 8, 16, 32 and 64 bits each. The arithmetical operations that most computers work with are done for these common datatypes that only support 8,16,32 etc.databits. If you want other number of bits you need to make your own bit-manipulation routines which doesnt make any sense, since they will will be slow and difficult to program.
Comment: To represent an 8 bit number you can use hexadecimal representation. The same with 32-bits. It makes it easier to read and write values in your code. For example a 32-bit pixel value are represented as **33ffcc** or something like this. The **33** represent the red value, the **ff** the green and so on.
Comment: You've said that it easier to do it with a 32 bit and that there are standard way to do it. How would one do so?


Lower bound for the number of $4$-element sets generated from an arbitrary family of $3$-element sets in the worst case

Question: Suppose we have $x_3$ distinct $3$-element sets chosen arbitrarily among the $\binom{7}{3}=35 \ge x_3$ subsets of $U=\{1,2,3,4,5,6,7\}$. Consider the $x_4$ distinct $4$-element sets that can be obtained as a union of any two of the above $3$-element sets. I know the probability that a couple of $3$-element sets chosen at random in $U$ have $2$ elements in common and thus their union is a $4$-element set (as computed here).
I would like to find a lower bound for $x_4$ as a function of $x_3$, in the worst case:
$$x_4 \ge f(x_3)$$
Ideally, I would like to later extend the result to any $j \lt k \le n$, i.e. find a lower bound:
$$x_k \ge g(x_j, j, k, n)$$
instead of the above case $j=3, k=4, n=7$.
Any hint?
Answer: You can solve the problem via integer linear programming as follows.  For each $3$-subset $S \subset U$, let binary decision variable $y_S$ indicate whether $S$ is chosen.  For a given $x_3$, the problem is to minimize
$$\sum_{T \subset U: |T|=4} \max_{(R,S): R \cup S = T} y_R y_S \tag1$$
subject to
$$\sum_S y_S = x_3. \tag2$$
The objective function $(1)$, which can be linearized, represents the number of $4$-subsets that are covered exactly by some pair of chosen $3$-subsets.  The constraint $(2)$ enforces selection of exactly $x_3$ of the $3$-subsets.
The resulting optimal objective values are
$$f(0)=\dots=f(7)=0, f(8)=2, f(9)=4, f(10)=f(11)=5, f(12)=6, f(13)=8, f(14)=11, f(15)=12, f(16)=f(17)=14, f(18)=f(19)=f(20)=15, f(21)=19, f(22)=22, f(23)=24, f(24)=f(25)=25, f(26)=28, f(27)=30, f(28)=f(29)=31, f(30)=33, f(31)=f(32)=34, f(33)=f(34)=f(35)=35.$$
To linearize $(1)$, introduce a binary (or nonnegative) variable $z_T$ for each $4$-subset $T \subset U$ and minimize
$$\sum_{T \subset U: |T|=4} z_T \tag3$$
subject to $(2)$ and
$$z_T \ge y_R + y_S - 1 \quad \text{for all $T$ and $(R,S): R \cup S = T$}. \tag4$$
Comment: That would be $\binom{13}{6}=1716$ ILP problems (one per value of $x_6$), and most of them are not easy to solve.  But the LP relaxation provides a lower bound, and for odd $n$, $j=\lfloor n/2\rfloor$, and $k=\lceil n/2\rceil$ the LP lower bound appears to be $\max(2x_j-\binom{n}{j}, 0)$.
Comment: Thank you. Although I am looking for a lower bound, so I suppose I have to replace $max$ with $min$ in the objective function. For example $f(2)=0$ because in the worst case I can choose $\{1,2,3\}$ and $\{4,5,6\}$. I believe that $f(x_3)=0$ for $x_3<6$. Also, any suggestion of a reading for how to linearize the objective function, or in general, an introduction to linear programming?
Comment: And I want to minimize the objective function rather than maximise it, I think.
Comment: OK, I guess I misinterpreted what you meant by *arbitrary* and *worst case*. I thought that an adversary was picking the $3$-subsets to make the number of $4$-subsets large, but from your comments now it sounds like *you* get to pick the $3$-subsets to make the number of $4$-subsets small.
Comment: Yes, I want to make sure that in any case $x_4 \ge f(x_3)$ so that I can work out an inequality that I have for the background problem, like this $x3 + A \gt x_4 + B \ge f(x_3) +B$, for which I need that $f(x_3)$ be the lowest possible for any choice of the $3$-subsets.
Comment: I updated the answer just now to minimize instead of maximize.
Comment: Thank you very much. Do you think that it is computationally feasible finding a similar lower bound for $x_7$ and $x_6$ ($x_7 \ge f(x_6)$) with a $13$-element universe?


Nonlinear regression SSE Loss

Question: Notation
$y_i$ is observation $i$ of some response variable $Y$.
$\hat{y}_i$ is the value of $y_i$ predicted by the regression.
$\bar{y}$ is the average of all observations of the response variable.
$$ y_i-\bar{y} = (y_i - \hat{y_i} + \hat{y_i} - \bar{y}) = (y_i - \hat{y_i}) + (\hat{y_i} - \bar{y}) $$
$$( y_i-\bar{y})^2 = \Big[ (y_i - \hat{y_i}) + (\hat{y_i} - \bar{y}) \Big]^2  =
(y_i - \hat{y_i})^2 + (\hat{y_i} - \bar{y})^2 + 2(y_i - \hat{y_i})(\hat{y_i} - \bar{y})
$$
$$ \sum_i ( y_i-\bar{y})^2 = \sum_i(y_i - \hat{y_i})^2 + \sum_i(\hat{y_i} - \bar{y})^2 + 2\sum_i\Big[ (y_i - \hat{y_i})(\hat{y_i} - \bar{y}) \Big]$$
$$ = SSRes + SSReg + Other $$
When $Other = 0$, as we have in linear regression, then $SSRes$ is a perfectly reasonable measure of what strikes me as the real value of interest: $SSReg$. As one decreases, the other increases, so we can get a strong model fit (high $SSReg$) by minimizing $SSRes$.
However, $Other \ne 0$ in general, such as in nonlinear regressions. A popular nonlinear regression these days is a neural network. While neural nets may be most used for classification problems, they are perfectly reasonable to use in regression problems. In neural network regressions, I have seen $MSE$ as the loss function. For instance, sklearn's MLPRegressor uses SSRes as the loss function  (same $argmin$ as $MSE$).
Minimizing $SSRes$ misses the $Other$ term! The $SSRes$ could be very small, yet there could be a major contribution from the $Other$ term that shows the regression model not to be good.
I've tried it out in Python, using some code I found on Stack Overflow for MLPRegressor. That $Other$ term definitely doesn't drop to zero.
from sklearn.neural_network import MLPRegressor
import numpy as np
import random
random.seed(2019)

x = np.arange(0.0, 1, 0.001).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel()
nn = MLPRegressor(hidden_layer_sizes=(100,), activation='relu')
n = nn.fit(x, y)
train_y_pred = n.predict(x)
Other = (train_y_pred - np.mean(y) ) * (y - train_y_pred)
sum(Other)

Questions

What is the reason for using $SSRes$ or $MSE$ loss when there is that $Other$ term?

This might be more philosophy or perhaps not so different from the first question, but am I off-base to claim that $SSReg$ is the real value of interest and that we use $SSRes$ as a proxy because we're used to minimizing loss rather than maximizing gain?

Code for linear regression:
import numpy as np
from sklearn.linear_model import LinearRegression
import random
random.seed(2019)
X = np.random.normal(10,1,100).reshape(-1, 1)
X = np.sin(X).reshape(-1, 1)
e = np.random.normal(0,0.25,100).reshape(-1, 1)
y = X + e
y.reshape(-1, 1)
reg = LinearRegression().fit(X, y)
y_pred = reg.predict(X)
resid = y - y_pred
Other = (y_pred - np.mean(y) )* (y - y_pred)
sum(Other)

Comment: Hummm. Maybe look at this for further thoughts https://stats.stackexchange.com/a/508394/99274.
Comment: @Carl I liked the question title when you first posted, but I do not see how my question is particularly related to yours. Could it have gotten lost in a pretty long post you wrote? Could you please point me to which part of your post pertains to my question?
Comment: R-squared ANOVA is $R^2 = 1 - \text{SSE} / \text{SST}$. Something is missing in this, and I think you put your finger on it, the "other". Search for the title of your question above.
Comment: @Carl The "other" in ANOVA is zero.
Comment: I do not understand how one can have a correlation without an interaction term. Can you explain, please?
Comment: @Carl Correlation between what and what? Interaction between what and what? I give a code example at the end showing the "other" is zero (or super close to zero because of doing math on a computer) for a linear regression.
Comment: The errors in measuring x and y are often correlated. Suppose I throw darts at a board, won't my errors in x and y away from the bull-eye be correlated as a result of my aim being more in an elliptical pattern than a rhomboid one? If the errors are uncorrelated the error "cloud" will be a rhomboid, not an ellipsoid.
Comment: In ANOVA, how do you make an error measuring the categorical $X$? I just don't follow what you're thinking.
Comment: @Carl I don't even mention an $x$ in my equations. Where is $x$ coming into play?
Comment: In code, you specify X = np.random.normal... and e = np.random.normal... Two random variates. Specified as independent without correlation. In that case, there is no interaction term to quantify, but is that case a good simulation model? Ah, that is the question, does it happen like that?
Comment: @Carl Correlation of the predictor variables has no influence on the "other" term being zero in OLS regression. Try out a simulation with np.random.multivariate_normal.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/120524/discussion-between-dave-and-carl).
Comment: @Carl You took an interest in this. Perhaps you would be interested in reading an answer (which I believe is reasonable) a few months later.
Answer: Two years later, I can answer #1.
If we assume a Gaussian response variable (common), minimizing $SSRes$ is equivalent to maximum likelihood estimation of the regression parameters. Consequently, we get maximum likelihood estimates, which feel like a natural way of estimating the parameters.
I think that this leads to answering #2 in the negative. We minimize $SSRes$ instead of maximizing $SSReg$ because we aim to find the "most likely" regression parameters via maximum likelihood estimation, not maximize the variance we can explain. (That these two notions do not coincide, however, blows my mind.)
Answer: Humm, well being as you asked. The connection between MLE and ordinary least squares (OLS) has established for linear regression for normally distributed residuals. These are not equivalent in most (if not all) other circumstances. In general, OLS has omitted variable bias in the linear case, which is also problematic for nonlinear fitting. The magnitude of omitted variable bias is zero in special cases, e.g., when the $X_i$ are sequentially equidistant. This can be understood by noting that OLS minimizes error in the $y$ direction, and does not minimize error in both $x$ and $y$. To do the latter, one needs to perform some other type of regression, e.g., in the linear case Deming regression. This requires knowledge of both variance in $y$ and in $x$. In the linear fit equation case Deming regression has no omitted variable bias. For OLS, the minimum error is for prediction of least error in $y$, with omitted variable error, this makes the slope more shallow but optimizes the $r$-value. Deming regression will have a steeper slope, as it no longer "splits" the $y$-value error to be too much on one side and too little on the other just to minimize that error globally. In Deming regression, the correlation will be of lesser magnitude, but the regression line follows the "cloud" of data points more accurately and extrapolation beyond the range of the data is more accurate. There are nonparametric procedures that reduce omitted variable bias in the linear case, e.g., Passing-Bablok, and Theil-Sen, which unlike Deming regression do not require explicit knowledge of relative variances of $x$ and $y$.
The formula you wrote, after changing the order of subtraction of $ \hat{y_i}-\bar{y}$, is written as $$ \sum_i ( y_i-\bar{y})^2 = \sum_i(y_i - \hat{y_i})^2 + \sum_i(\hat{y_i} - \bar{y})^2 - 2\sum_i\Big[ (y_i - \hat{y_i})(\bar{y} - \hat{y_i}) \Big]\;\;,$$
and has the same structure as the law of cosines $$c^2=a^2+b^2-2\, a\, b\cos(\theta)\;\;,$$
for the exact same reasons. Moreover, this is (changing the sign back again) the variance of the sum of two correlated variables. In the answers to that question, note the equivalence of the law of cosines, i.e., the vector form, to the variance treatment, where $\cos(\theta)$ and the correlation coefficient $r$ are equivalent. Finally, error propagation, or at least the first approximation from Taylor series to it, takes the form $$\left(\frac{\sigma_f}{f}\right)^2 \approx \left(\frac{\sigma_a}{a} \right)^2 + \left(\frac{\sigma_b}{b}\right)^2 + 2\left(\frac{\sigma_a}{a}\right)\left(\frac{\sigma_b}{b}\right)\rho_{ab}\;,$$
where $\rho_{ab}$ is the correlation between $a$ and $b$. To make a long story short, it would seem that for OLS in $y$, we are assuming that the $x$ and $y$ errors are uncorrelated, "Homoscedasticity and independence of the error terms are key hypotheses in linear regression where it is assumed that the variances of the error terms are independent and identically distributed and normally distributed. When these assumptions are not possible to keep, ... the variance of the parameters corresponding to the beta coefficients of the linear model can be wrong and their confidence intervals as well."
Comment: There's a lot in here that's interesting, but I don't see how it answers the question I asked two years ago.
Comment: Dave, I just explained what your "other" is, and filled in the blanks in your questions.

Nonlinear regression SSE Loss


Como colocar um título na legenda do angular-chart

Question: No meu gráfico de linhas queria que quando passar o mouse na linha do gráfico ao aparecer a legenda, e que ela tivesse um título. Isso so é possível preenchendo o array de labels, porem aparece em baixo do gráfico, no eixo "X" os nomes, e eu não quero, quero apenas os títulos nas legendas.
Segue o código:
angular.module("app", ["chart.js"]).controller("LineCtrl", function($scope) {
    $scope.labels = ["Titulo 1", "Titulo 2", "Titulo 3", "Titulo 4", "Titulo      5", "Titulo 6", "Titulo 7"];
    $scope.series = ['Legenda 1', 'Legenda 2'];
    $scope.data = [
        [65, 59, 80, 81, 56, 55, 40],
        [28, 48, 40, 19, 86, 27, 90]
    ];
    $scope.onClick = function(points, evt) {
        console.log(points, evt);
    };
});

Dessa forma, ele gera um titulo sobre as legendas ao passar o mouse, porem aparece os nomes abaixo do gráfico, eu queria que não aparecesse os nomes abaixo do gráfico, somente no título mesmo ao passar o mouse, como ficaria?

Referência: http://jtblin.github.io/angular-chart.js/
jsfiddle:http://jsfiddle.net/Lfmhcab3/4/
Comment: Alguem??? ......
Comment: Isso não é possível e o criador do Chart.js [recomenda que você crie uma outra extensão para o gráfico de linhas](https://github.com/nnnick/Chart.js/issues/12#issuecomment-47473304) e realize o tratamento. Nessa mesma issue existem soluções alternativas que podem ser úteis para você.
Comment: Talvez esse link possa te ajudar: http://stackoverflow.com/questions/32841302/hide-labels-on-x-axis-chartjs
Comment: Veja que a legenda não aparece quando você passa o mouse sobre a linha e sim sobre o ponto.
Answer: A parte de mudar o conteúdo da tootlip podes fazer assim, modificando o multiTooltipTemplate:
// Chart.js Options
$scope.options = {
  multiTooltipTemplate: '<%= datasetLabel + ": " + value %>',

Para remover a legenda do eixo X é mais complicado. Tem havido discussões longas sobre isso (1, 2, 3) mas parece que ainda não há nada implementado nesse sentido. Dá para esconder o eixo Y com scaleShowLabels: false, mas não o eixo X...
Uma opção seria esconder ambos os labels com showScale: false, (exemplo).
Porém é possivel modificar os métodos da biblioteca e baseado na sugestão que o @potatopeelings te deu no SOen podes fazer assim:
var originalLineInitialize = Chart.types.Line.prototype.initialize;
Chart.types.Line.prototype.initialize = function(data) {
    var originalLabels = data.labels.slice();
    data.labels = new Array(data.labels.length);
    originalLineInitialize.apply(this, arguments);

    this.scale.xLabels = originalLabels;
    this.datasets.forEach(function(dataset) {
        dataset.points.forEach(function(point, i) {
            point.label = originalLabels[i];
        });
    });

    var originalScaleDraw = this.scale.draw;
    this.scale.draw = function() {
        for (var i = 0; i < this.xLabels.length; i++) {
            this.xLabels[i] = '';
        }
        originalScaleDraw.apply(this, arguments);
    }
}

jsFiddle: http://jsfiddle.net/8z5gp995/1/
Answer: Use scaleFontSize: false e scaleLabel: "<%= ' ' + value%>" no $scope.options.
JsFiddle: http://jsfiddle.net/rapa09/fph4jecj/5/
Comment: fui notar agora, ele tira o texto dos lados também, vou arrumar.
Comment: Arrumado e editado!
Comment: Fui ver em outro computador meu e ficou cortando, caso isso ocorra com você use: scaleLabel: "<%= '   ' + value%>" <-Isso serve para dar um espaço antes das labels laterais aonde tem '' coloque espaços(no máximo 2 espaços são aceitos!)

Fonte: http://stackoverflow.com/questions/26498171/how-do-i-prevent-the-scale-labels-from-being-cut-off-in-chartjs
Answer: Adicione legend="false" no canvas que está sendo gerado o chart, dentro do arquivo html.
Comment: isso desabilita a legenda, eu nao quero desabilitar a legenda, quero desabilitar os labels em baixo, mas deixar o titulo ao passar o mouse, coloquei uma imagem, na imagem mostra que quero aquele titulo da legenda, e não quero q o mesmo apareça em baixo.
Comment: coloquei o jsfidle, veja que ao passar o mouse na linha aparece os dias da semana no titulo, aquilo eu quero, so nao quero que apareça em baixo.


Are all parametrization via homogeneous polynomials rational curves?

Question: Definition: A rational curve is a one dimensional projective variety that is birational isomorphic to a projective line.
If we have a curve $c:P^1 \to P^n, [x_0,x_1]\mapsto [f_0(x_0,x_1),...,f_n(x_0,x_1)]$ , where $f_i$ are homogeneous polynomials with same degree.
I've known that the imgae of $c$ is a projective variety and it's easy to see that there is a homomorphism from the function field of the image of $c$ to the function field of the projective line. But I don't know how to get the other direction to prove they are birational equivalent.
Answer: Yes. Let $C = c(\mathbb P^1)$ be the image curve. Then $C$ is rational if and only if its normalization $\tilde C$ is a $\mathbb P^1$. By the universal property of normalization, the map $c: \mathbb P^1 \to C$ lifts to a non-constant map of smooth curves $\tilde c: \mathbb P^1 \to \tilde C$. Such a thing only exists of $\tilde C$ is isomorphic to $\mathbb P^1$, because whenever you have a non-constant map $C_1 \to C_2$ of smooth curves, then $g(C_1) \geq g(C_2)$ by Riemann-Hurwitz. Note however that $\tilde c$ need not be an isomorphism. (Find a counterexample!)


Path-connected and topology

Question:
Hi everyone. I am a little bit confused about question 12.2 and 12.3.
I think, is it enough to say in question 12.3 that if we remove one point from $X \times Y$ then $X \times Y$ will still be path-connected, but if we remove a point from R then R is not path-connected.
Is it enough for answering question 12.3 or should there be more?
Then about question 12.2 I dont know really how to do?
Comment: For 12.2 argue exactly as if you were in a square minus the center: To connect $(a,b)$ to $(c,d)$, first follow $(\gamma(t),b)$ from $(a,b)$ to $(c,b)$ using a path $\gamma$ that connects $a$ to $c$ in $X$. Then follow $(c,\delta(t))$ from $(c,b)$ to $(c,d)$.  The only thing that can prevent this is if $b=y$ and $\gamma$ passes through $x$. Then use $\delta$ and $\gamma$ in the reverse order. For 12.3 that is the argument, yes.
Comment: For 12.2, a path from $(a,b)$ to $(c,d)$ could be along $(a,b)\to (a,d)\to (c,d)$ or along $(a,b)\to (c,b)\to (c,d)$. At least one allows you to avoid $(x,y)$.
Comment: Hi user517969 - I am a little bit confused about how I should choose γ(t) and δ(t)?
Comment: [Please do not use pictures for critical portions of your post.](https://math.meta.stackexchange.com/a/20529/290189) Pictures may not be legible, cannot be searched and are not view-able to some, such as those who use screen readers.
Comment: If $f:A\to B$ is a homeomorphism and $a\in A$ then $P^B_{f(a)}=f(P^A_a). $ So with $A=\Bbb R$ and $B=X\times Y,$  your approach to 12.3 is correct, by applying 12.2, as in the A by Andres Mejia.
Answer: Since $2$ is answered in the comments, I'll just assume that it is proven.
Suppose that $\mathbb R \cong A \times B=X$. Clearly $A  \times B$ is path connected, and in particular, so are $A,B$ since projections onto each factor $\pi_1(X)=A$ and $\pi_2(X)=B$ are both continuous, we deduce that $A,B$ are path connected.
Remove some point $(p,q)$ from $X$, and by $12.2$, this is still path connected, but then the image of projections are $\mathbb R\setminus \{p\}$ and $\mathbb R\setminus \{q\}$  are disconnected, a contradiction.
Note that in the last part, the first assumption of $12.3$ is essential.

Path-connected and topology


Como gerar um jar através do ANT?

Question: estou utilizando o Jdeveloper em conjunto com o Ant, entretanto me deparei com uma situação bem chata... eu nao consigo gerar um .jar funcional através do ant.
Eu ja constrúi um build.xml que contem o caminho pra main class, entretanto... sempre quando tento executar o jar que foi gerado, eu recebo a menssagem:
"cannot load or find main class"
Quando criamos um profile de deploy no Jdeveloper, construimos uma espécie de manifest, apontando pra classe principal e carregando as demais classes para dentro. Eu gostaria de saber se é preciso gerar esse manifest antes, e por fim quais itens eu devo inserir dentro do manifest... somente as classes do meu projeto?
E se eu tiver um outro projeto como dependencia do meu projeto principal? Isso deve ser apontado no build/xml ou no manifest?
Answer: <code><property name="build.dir" value="/home/wender/" />
<property name="jar.name" value="meuQuerido.jar" />

<!-- Diretório onde sua IDE gera os .class -->
<property name="dir.compilacao.java" value="c:/No/Eclipse/fica/em/no/diretorioDoMeuWorkspace/MeuProjeto/bin" />

<jar destfile="${build.dir}${jar.name}">
    <manifest>
        <!-- Substitua org.minha.Main.class pela sua (caminho completo)-->
        <attribute name="Main-Class" value="org.minha.Main.class" />
    </manifest>
    <fileset dir="${dir.compilacao.java}"/>
        <include name="**/*.class" />
    </fileset>
</jar>
</code>

Como gerar um jar através do ANT?


spelling check for english in sublime

Question: I would like to know how to utilize the spelling check feature in sublime-text.
I have tried the following, however it is not working for me.
What I have
perferences.sulime-settings

    {
        "spell_check": false,
        "dictionary": "Packages/Language - English/en_US.dic"

    }

if anyone know please help me to found it,
Thank you.
Answer: You need to make sure the the spell_check is true.
Sublime Text currently only supports UTF-8 encoded dictionaries. Most dictionaries are not encoded in UTF-8, instead using a more compact encoding for the language in question. To use a dictionary with Sublime Text, it'll first need to be converted into UTF-8.
Once you have a UTF-8 encoded dictionary, it can be installed by placing it in a package, for example, Packages/User, which you can access from the Preferences/Browse Packages menu item. Once the file is in place, you can select the dictionary from the View/Dictionary menu.s
"spell_check": true,
"dictionary": "Packages/Language - English/en_US.dic"

See documenation.
https://www.sublimetext.com/docs/2/spell_checking.html
Comment: i tried this same from this same link but its not working
Comment: i found solution for this by my self :    (1) cnt+p (2) install package (3) type spell (4) you will see list of packages for spelling you can install whatever you want.

spelling check for english in sublime


Notes value practise without metronome

Question: When I practise scales or chords, amongst other things, I usually do it using whole notes then half notes then quarters ..etc...
I use a metronome all the time but wanted to know if there are other ways?
Do mantras, songs or anything else exists to actually give you the right rhythm without a metronome?
Comment: What instrument(s)?  If piano, you can start with quarters and go faster from there.  I don't know of any mantras etc.
Answer: I use a variant of this. Rhythmic solfege. It is very effective. I never really got a sense of reading rhythms with numbers and as a result I had to rely heavily on memorization. One day I met a piano teacher who used this method (with different syllables) and I was very quickly able to overcome my hurdles. You are right ot one to learn how to practice these things without a metronome since you really can't always rely on one to follow you through ritardandos and tempo changes.
Don't try to learn the syllables all at once since you would be compounding learning the rhythms and the syllables. Just learn one set of syllables and get used to it it and then keep adding as saying the syllables become automatic.
EDIT: The variant of rhytmic solfege originally posted is called takadimi. I suspect that there are several other names based on the syllables used. Takadimi is just the first google result.
Comment: Glad i could help. Also I'll add the name. I'm trying to remember what my piano teacher called it because it def wasn't takadimi. Today is the first time I came across that. Another teacher called it called it rhythmic solfege which is what I called it in the answer.
Comment: Just what I was looking for. I have struggled as you have and oddly, my metronome practise is always"approximate" I do better when I listen to the rhythm in my head but I needed a support. I'll try this for sure or a variant I might make up
Comment: @xerotolerant  - You might want to put the name of the method, Takadimi, in your answer in case your link goes down, make it easier for people to look it up.
Comment: I've always heard it as Takadimi, so probably a common usage.
Comment: Something similar to 1e&a 2e&a 3e&a 4e&a, which works too. And helps to say which actual beat one is on.

Notes value practise without metronome