Redirect traffic destined for one host to another

Question: On a Windows machine, I would like to direct all outgoing network traffic destined for one host to another (not another IP address). So for example, all requests to host.acme.com must go to server.ajax.net or something like that.
What is the way to do this or what must I search for? (If I understood the correct terminology, it would make it a lot easier to search for).
(A little background on what I want to achieve: I want to set up something like UnoTelly just for myself on my machine, where requests to certain hosts are sent to an AWS Cloudfront server. For this, however, it does not suffice to resolve hostnames to different IP addresses; I must actually forward the traffic to a different host by its hostname).
Answer: The simplest way to do that is to use the machine's host file:

Find out the IP address of the machine you want to redirect to
Edit the c:\windows\system32\drivers\etc\hosts file (yes, there is no extension) with any text editor. You might need to start the editor with a high security token (run as administrator" if UAC is enabled
Add a line to the host file that read:

220.127.116.11   host.acme.com
(where 126.96.36.199 is actually the IP address of your destination machine)
Save the file, and you're done. Note, however, that this will just change the IP address of the machine that you'll connect to when using the host.acme.com dns host name. It will not change anything in the content of these connections so if you're using a protocol like HTTP (or SSL) where the host name is embedded into the data, the target machine might not respond properly.
Comment: Hi, like I said in my question, I don't just need to change the IP address, I need to forward to another machine by hostname.
Comment: just perform the name resolution in advance and then use that result. Your target machine isn't going to switch IP every 5 minutes.
Comment: No, but the target machine is on a shared host. So just forwarding to that IP address doesn't help. But thanks anyway. I found another post which says that you can't do routing to a hostname: http://serverfault.com/a/301984/118544. However, I think I may have the answer. I will try it out and post the results here.
Answer: As the following answer points out, you cannot route to a host name: https://serverfault.com/a/301984/118544
However, for my purposes, because I am interested in routing only web traffic, it seems what I can do is to make requests to certain hosts go to localhost using /etc/hosts and then use a local Apache instance and mod_rewrite to forward requests on  to different hosts when the host header matches.


Explain streaming k-means

Question: I need to cluster 22 million vectors, each of which has a dimension of 1024. Can anyone explain streaming k-means to me?
Comment: By ["streaming kmeans"](https://duckduckgo.com/?q=streaming+kmeans), I assume you refer to an [tag:online] algorithm for k-means, meaning that we don't have all the data available when we cluster, but start with some initial data and cluster that - then more data arrives (one observation at a time, or in batches), and we *update* our clustering each time, instead of clustering wholly anew. If so, please be a little more specific as to what you do not understand, because otherwise your question will likely be closed as "too broad". Thank you!
Comment: @StephanKolassa, why not develop that into an answer? It would be brief, but would be appropriate for the question, as far as I can see.
Comment: By streaming, i mean using a streaming algorithm, an algorithm that prcesses streams.  (data can't fit in memory)
Answer: "Streaming kmeans" typically refers to what is also known as "online kmeans". Online algorithms refer to computations that are performed iteratively, with data arriving during the computation in single observations or in batches, in contrast to "offline" algorithms, where all the data are available when the computation starts. Typically, some intermediate result is calculated based on initial data and then modified as new data arrive. For instance, exponential smoothing is a forecasting algorithm that is very naturally performed online.
In the specific case of k-means, we would first apply a standard k-means algorithm to cluster an initial dataset. Then, the cluster centers would be updated as new data arrive. Such algorithms often keep and update clusterings with different numbers of clusters, because the optimal number of clusters may change over time as data arrives.
Alternative names for online algorithms include "sequential algorithms", and a number of other synonyms as per Wikipedia. For the specific case of online k-means, this SO question looks like a good place to start: Online k-means clustering

Explain streaming k-means


Given X, a random variable with CDF (cumulative distribution function) F, how do you find the CDF (G) of Y which is a function of X?

Question:
Given $X$, a random variable with CDF (cumulative distribution function) $F$, how do you find the CDF $G$ of $Y$ which is a function of $X$?

I've read my course materials on CDFs but I'm not finding many resources on this kind of problem. For example if $Y = e^X$ then my intuition tells me that in the cases where $u \leq 0$, $G = 0$ since $Y$'s lower limit is $0$. And for cases where $u > 0$ then $G = e^F$? I'm not sure about the latter...
Another type of problem is $Y = mX+b$ (where $m$ is non-zero). Again my intuition is that there are 2 cases: 1 for which m>0 and 1 for m<0. One of the given hints for this type of problem is that the $m<0$ case might need to be expressed in terms of both the CDF and PMF of X, not just the CDF.
Any help in understanding how to break these types of problems down would be appreciated.
Answer: If $Y=h(X)$ where $h$ is strictly increasing, then: $G(y)=P(h(X)<y)=P(X<h^{-1}(y))$ where $h^{-1}(y)=-\infty$ if $y<h(x)$ for all $x$ and $h^{-1}(y)=+\infty$ if $F(x)>y$ or all $x$.
So if $Y=e^X$, then if $y>0$ then $G(y)=P(Y<y)=P(X<\log y)=F(\log y)$.
If $h$ is strictly decreasing, then $P(Y<y)=P(X>h^{-1}(y))$. So:
$$P(Y<y)=1-P(X<h^{-1}(y)) - P(X=h^{-1}(y)) = 1-F(h^{-1}(y)) - P(X=h^{-1}(y))$$
If $X$ is a continuous random variable, then $P(X=h^{-1}(y))=0$ and you just have:
$$P(Y<y)=1-F(h^{-1}(y)) $$
It becomes more complicated when $h$ is not $1-1$, for example, if $h(x)=x^2$ or $h(x)=\sin x$.
Comment: sorry for evoking this old thread. But what happens when h is not one to one? Thanks Thomas!
Comment: And where can i find more discussions regarding these topics?
Comment: Another counter-intuitive result is when G is F i.e. G is cumulative distribution function of X.


Hatcher Theorem 1B.8 / Proposition 1B.9 concluding that a map inducing the identity is homotopic to the identity?

Question: In introducing the concept of $K(G, 1)$, Hatcher's Algebraic Topology  proves the theorem that the homotopy type of a CW complex $K(G, 1)$ is uniquely determined
by $G$, by citing a proposition and claiming the proposition may be used to deduce the theorem. I am wondering why the bolded statement is true here:

Proposition 1B.9. Let $X$ be a connected CW complex and let $Y$ be a $K(G, 1)$. Then every homomorphism $\pi_1(X, x_0) \to \pi_1(Y, y_0)$ is induced by a map $(X, x_0) \to (Y, y_0)$ that is unique up to homotopy fixing $x_0$.
To deduce the theorem from this, let $X$ and $Y$ be CW complex $K(G, 1)$'s with isomorphic fundamental groups. The proposition gives maps $f : (X, x_0) \to (Y, y_0)$ and $g : (Y, y0) \to (X, x0)$ inducing inverse isomorphisms $\pi_1(X, x_0) \cong \pi_1(Y, y_0)$. Then $fg$ and $gf$ induce the identity on $\pi_1$ and hence are homotopic to the identity maps.

I am aware that in general, a map inducing the identity on $\pi_1$ is not necessarily homotopic to the identity, so why in this context can this argument be made? I am specifically looking for a justification that one would be able to follow at this point in Hatcher's text.
Comment: This has been asked before but annoyingly has no answer relevant to your question. [Here](https://math.stackexchange.com/q/948723/815585) and [here](https://math.stackexchange.com/q/2124713/815585)
Comment: Well, observe in the very first paragraph that Hatcher claims homomorphisms on $\pi_1$ are in bijection with based homotopy classes of map $(X,x_0)\to (Y,y_0)$ (in our very specific case of $K(G,1)$ spaces!). This would give you what you want. It therefore suffices to verify Hatcher's first claim... which he probably does do in the next few sentences
Comment: eric wolfsey's answer is the correct one, but one perspective to take is via whitehead's theorem. Both the proof of 1b.9 and whiteheads theorem can be proven basically by inducting up skeleta. The proof of 1b.9 is an early example of obstruction theory (but just done sort of ad hoc iirc)
Answer: This last claim is another application of Proposition 1B.9.  By the proposition, there is a unique (up to homotopy) map $(X,x_0)\to (X,x_0)$ that induces the identity on $\pi_1$.  One such map is the identity map, and another such map is $gf$, so they must be homotopic.  Similarly $fg$ must be homotopic to the identity $(Y,y_0)\to (Y,y_0)$ since there is a unique (up to homotopy) such map that induces the identity on $\pi_1$.


How to compare the key value and remove objects from main object in javascript

Question: how to compare the key value (selected) in objects and remove the object in the main object.
My object is:-
 mainObject={
       "2022-10-29":{
          "disabled":true,
          "disableTouchEvent":true
       },
       "2022-10-26":{
          "selected":true,
          "selectedColor":"#3634A3",
          "selectedTextColor":"#FFFFFF"
       },
       "2022-10-30":{
          "disabled":true,
          "disableTouchEvent":true
       },
       "2022-11-05":{
          "disabled":true,
          "disableTouchEvent":true
       }
    }

i want to remove the object
"2022-10-26":{
   "selected":true,
   "selectedColor":"#3634A3",
   "selectedTextColor":"#FFFFFF"
}

Final output should be:-
finalObject={
       "2022-10-29":{
          "disabled":true,
          "disableTouchEvent":true
       },
       "2022-10-30":{
          "disabled":true,
          "disableTouchEvent":true
       },
       "2022-11-05":{
          "disabled":true,
          "disableTouchEvent":true
       }
    }

Comment: Does this answer your question? [How do I remove objects from a JavaScript associative array?](https://stackoverflow.com/questions/346021/how-do-i-remove-objects-from-a-javascript-associative-array)
Answer: You can remove a object's element using delete.
delete object[key];

In your code, like this.
delete mainObject['2022-10-26'];

Comment: Thank you @ChanHyeok-Im for response. But i want to delete the selected key element. The date will be changed every-time. Based on date we can't delete the object. Based on selected key we can delete the object. You can filter the selected one in above object!
Answer: If you prefer some mechanical way, that you want to see the mechanism behind, it would be something like

const removeByKey = (object, key) => {
  const keyIndex = Object.keys(object).findIndex(objectKey => objectKey === key);

  if (keyIndex === -1) return object;

  const entities = Object.entries(object);
  entities.splice(keyIndex, 1);

  return Object.fromEntries(entities);
}

const reducedObject = removeByKey(mainObject, "2022-10-26");

Or else, there is a precise way in the language itself as @ChanHyeok-Im mentioned,

delete mainObject['2022-10-26'];
Answer:

let mainObject = {
  "2022-10-29": {
    "disabled": true,
    "disableTouchEvent": true
  },
  "2022-10-26": {
    "selected": true,
    "selectedColor": "#3634A3",
    "selectedTextColor": "#FFFFFF"
  },
  "2022-10-30": {
    "disabled": true,
    "disableTouchEvent": true
  },
  "2022-11-05": {
    "disabled": true,
    "disableTouchEvent": true
  }
}

Object.values(mainObject).forEach((element, index) => {
  if (element.selected === true) delete mainObject[Object.keys(mainObject)[index]]
  //we loop through the values and select where selected is true, then we delete the object where the key index is the same index as the values.

})

console.log(mainObject)
Answer: Loop through objects and check if object has key selected and is true and delete the object
for (const key in mainObject) {
  if (mainObject[key].selected) {
    delete mainObject[key];
  }
}

console.log(mainObject);


Play a Video in Flutter Webview in full screen

Question: I am trying to play a video in full-screen mode in Flutter WebView. The video is from an anime website. I couldn't find any solutions online, so I am writing here hoping to find an answer that will not only help me but also other people facing a similar issue.
This is what i use for the webview:
<code>
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: WebView(
          initialUrl: 'https://website.example',
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (controller) {
            _controller = controller;
          },
          navigationDelegate: (navigation) {
            if (_isWhitelisted(navigation.url)) {   // a white list of websites which are allowed to get access to
              return NavigationDecision.navigate;
            } else {
              return NavigationDecision.prevent;
            }
          },
          onPageFinished: (url) {
            Uri uri = Uri.parse(url);
            if (uri.host == 'website.example' && [
              '',
              '/',
              '/index.html',
              '/#/',
            ].contains(uri.path)){
              // Inject JavaScript code to hide the first child div after class "container"
              _controller.evaluateJavascript('''
        var container = document.getElementsByClassName('container')[0];
        container.children[0].style.display = 'none';

        // Hide any element of the class "col-md-12 col-sm-12 col-xs-12"
        var elements = document.getElementsByClassName('col-md-12 col-sm-12 col-xs-12');
        for (var i = 0; i < elements.length; i++) {
          elements[i].style.display = 'none';
        }
      ''');
            }
          },
        ),
      ),
    );
  }
</code>
I tried to edit the manifest.xml file, but that didn't work. Additionally, I attempted to create a full-screen button, but it also did not work.
Answer: Instead of using WebView, use this library to load a video from a URL: https://pub.dev/packages/video_player


Android+PhoneGap FATAL EXCEPTION

Question: I'm building an Android with PhoneGap 1.4 app in Mac OSX 10.7.3 using Eclipse. This is a very simple app, the html is simple and has no JS.
I get a FATAL EXCEPTION, here is the logcat:
03-08 15:04:29.920: E/AndroidRuntime(594): FATAL EXCEPTION: main
03-08 15:04:29.920: E/AndroidRuntime(594): java.lang.RuntimeException: Unable to start          activity ComponentInfo{com.myphone.test/com.myphone.test.MyPhone}:   android.content.res.Resources$NotFoundException: Resource ID #0x0
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.os.Looper.loop(Looper.java:137)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.ActivityThread.main(ActivityThread.java:4424)
03-08 15:04:29.920: E/AndroidRuntime(594):  at java.lang.reflect.Method.invokeNative(Native Method)
03-08 15:04:29.920: E/AndroidRuntime(594):  at java.lang.reflect.Method.invoke(Method.java:511)
03-08 15:04:29.920: E/AndroidRuntime(594):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-08 15:04:29.920: E/AndroidRuntime(594):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-08 15:04:29.920: E/AndroidRuntime(594):  at dalvik.system.NativeStart.main(Native Method)
03-08 15:04:29.920: E/AndroidRuntime(594): Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.content.res.Resources.getValue(Resources.java:1019)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.content.res.Resources.loadXmlResourceParser(Resources.java:2107)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.content.res.Resources.getXml(Resources.java:907)
03-08 15:04:29.920: E/AndroidRuntime(594):  at com.phonegap.api.PluginManager.loadPlugins(PluginManager.java:82)
03-08 15:04:29.920: E/AndroidRuntime(594):  at com.phonegap.api.PluginManager.<init>(PluginManager.java:62)
03-08 15:04:29.920: E/AndroidRuntime(594):  at com.phonegap.DroidGap$1.run(DroidGap.java:518)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.Activity.runOnUiThread(Activity.java:4170)
03-08 15:04:29.920: E/AndroidRuntime(594):  at com.phonegap.DroidGap.loadUrlIntoView(DroidGap.java:494)
03-08 15:04:29.920: E/AndroidRuntime(594):  at com.phonegap.DroidGap.loadUrl(DroidGap.java:460)
03-08 15:04:29.920: E/AndroidRuntime(594):  at com.myphone.test.MyPhone.onCreate(MyPhone.java:11)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.Activity.performCreate(Activity.java:4465)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-08 15:04:29.920: E/AndroidRuntime(594):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
03-08 15:04:29.920: E/AndroidRuntime(594):  ... 11 more

And the manifest file:

<supports-screens
    android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:resizeable="true"
    android:anyDensity="true"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />

<uses-sdk android:minSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".MyPhone"
        android:label="@string/app_name"
        android:configChanges="orientation|keyboardHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.phonegap.DroidGap"
        android:label="@string/app_name"
        android:configChanges="orientation|keyboardHidden">
        <intent-filter> </intent-filter>
    </activity>
</application>

If someone could help me would be great :) Thanks in advance
Answer: You're getting a ResourceNotFoundException make sure you aren't trying to load a resource that isn't there.
Comment: Thanks for the protip :)
Yes, indeed I was trying to load a XML plugin config file that was not there.

/res/xml/plugins.xml

Many thanks code bro :)

Android+PhoneGap FATAL EXCEPTION


Find locii of $z$ without putting $z=x+iy$

Question: We have interpret the locii of $z$ for all complex number.
$$\operatorname*{Re}\left(\frac{z+2i}{iz+2}\right) \leq 4 \qquad (z\neq 2i)$$
I know one method by putting $z =x+iy$.
I want to know if there is any other method to do this.
Answer: We have $\Re(\frac {z+2i}{iz +2}) = \Re (\frac {(z+2i)(iz-2)}{(iz+2)(iz-2)}) = \Re (\frac {4z -iz^2 +4i}{z^2 +4}) \leq 4 $. Now, for the condition to be satisfied, we must have $4\Re (z) \leq 4 (z^2 +4) $ $\Rightarrow \Re (z) \leq z\bar z + 4 = |z|^2+4 $ where $\bar z $ is the conjugate of $z $. Hope it helps.
Comment: How do you know $-iz^2$ is always imaginary?
Comment: How you have written $4\Re (z) \leq 4 (z^2 +4)$
Comment: @user123733 $-iz^2$ is always imaginary so is $4i $. So the only factor contributing to the real part is the real part of $z $. Also the denominator is real. So, the real part of the entire expression is $\frac {4\Re (z)}{z^2+4} $.
Answer: Disclaimer: This doesn't avoid the use of $z = x + iy$, but just makes its application easier.
$$
\Re\left(\frac{z + 2i}{iz + 2}\right) = \Re\left(\frac1i\frac{z + 2i}{z - 2i}\right) = \Im\left(\frac{z + 2i}{z - 2i}\right)
$$
Notice that vectors $\vec{u} + \vec{v}$ and $\vec{u} - \vec{v}$ are mutually perpendicular. Hence,
$$
\frac{z+2i}{z-2i} = \frac{|z+2i|}{|z-2i|}(\pm i)
$$
which basically means $\frac{z-2i}{z+2i}$ is purely imaginary. So you're down to just finding the locus when
$(1)$ $\frac{z+2i}{z-2i} = \frac{|z+2i|}{|z-2i|}i$, i.e. $z$ lies to the right of the $y$-axis.
$
\frac{|z+2i|}{|z-2i|} \le 4 \\
\implies x² + (y+2)² \le 16x^2 + 16(y-2)² \\
\implies 15x² + 15y² - 68y + 60 \ge 0
$
which is all points on and in the exterior of the right semicircle $15x² + 15y² - 68y + 60 = 0$.
$(2)$ $\frac{z+2i}{z-2i} = -\frac{|z+2i|}{|z-2i|}i$, i.e. $z$ lies to the left of the $y$-axis.
In a similar fashion, you get
$$
15x² + 15y² - 68y + 60 \le 0
$$
which is all points on and in the interior of the left semicircle $15x² + 15y² - 68y + 60 = 0$.
Comment: What are u and v
Comment: That's just for an example. I guess you know that complex numbers can be treated as vectors in two dimensions.


Centralizar na vertical formulario com Zurb Foundation

Question: Estou usando o framework CSS Zurb Foundation, e já realizei varias tentativas de centralizar este formulário no centro da tela. Já tentei atacar com um CSS normal de colocar 50% no topo e na esquerda e definir margens negativas com posição absoluta. Mas, mesmo assim não obtive êxito. Contudo, estou a pouco tempo utilizando este framework. Alguém sabe como centralizar esse formulário verticalmente, estou usando Foundation puro.
O resultado que consegui até agora foi este:

Segue HTML:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SPARV 2.0 | Login</title>

<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/foundation.css">

        <form id="centro" action="">
            <fieldset>
                <legend>Login</legend>
                Usuário
                    <input type="text" placeholder='Digite seu usuário aqui'>

                Senha
                    <input type="password" placeholder="******">

                <input type="submit" style="margin-bottom: -0.3125rem;" value="Log in" class="button tiny right">

            </fieldset>
        </form>

Answer: Se não me engano ele não tem por padrão como diz aqui, mas você pode fazer desta forma:
div {
display: table-cell;
vertical-align: middle;
height: 50px;
border: 1px solid red;
}

Comment: coloca no fiddle para podermos ajudar mais
Comment: Implementei sua sugestão. Mas, não deu certo!


What is the right way to deal with terminated socket "client"

Question: I have socket serve/client application. The "server" is waiting for data from "client", but if the client had been terminated the server throws EOFException.
Somewhere in the code in the server socket I have:
private ObjectInputStream in;

and somewhere I read the data:
in.readObject();

So should I just surround in.readObject(); in try-catch block or there is another solution?
Comment: Yes. Use `try-catch`
Answer: If you look in the Javadoc API for ObjectInputStream.readObject, you'll see the list of exceptions

ClassNotFoundException - Class of a serialized object cannot be
found.
InvalidClassException Something is wrong with a class used by
serialization.
StreamCorruptedException Control information in the stream is inconsistent.
OptionalDataException Primitive data was found in the stream instead of objects.
IOException - Any of the usual Input/Output related exceptions.

IOException (which 99% of the time is a SocketException (subclass of IOException) is special case where your Socket has shutdown, so you should process this as if you have lost connection.
All of the other exceptions however indicate that your client is sending you something you aren't expecting. You should catch each of these Exceptions by name and send back a message saying that they need to update the client software version to the version that your server is ready to communicate with. Flush that message out, and then probably best to close the socket.
Answer: You can use like following. EOFException is a direct subclass of IOException. You should also catch IOException.
try{
    ....
    in.readObject();
    ....
} catch(EOFException ex1){
    // eof exception is thrown
} catch(IOException ex2){
    // other types of IO exception is thrown
}


$\lim_{x\to0} \frac{(1+x)^a-1}{x} $

Question: $\lim_{x\to0} \frac{(1+x)^a-1}{x}  $ I really stuck, because $a$ is not an integer. If it is, I can solve it, but here I totally stuck
Comment: Can you use L'Hôpital?
Comment: Or this: https://math.stackexchange.com/questions/1789815/how-to-solve-lim-x-rightarrow-0-frac1xa-1x
Answer: Using L'hopital you could easily find that: $lim_{x->\infty} \frac{(1+x)^a -1}{x} = lim_{x->\infty} a(1+x)^{a-1}$. Do you think you can answer it from here?
Answer: This is the limit of the rate of variation of the function $(1+x)^a$  when $x$ tends to $0$. The limit is the derivative of the function at $x=0$.

$\lim_{x\to0} \frac{(1+x)^a-1}{x} $


Derivative of matrix equation

Question: In here, we can see:
$$ \phi: \beta \mapsto \Vert y - X \beta \Vert^2 = \Vert y \Vert^2 - 2 y^T X \beta + \beta^T X^T X \beta $$
$$ \dfrac {\partial \phi} {\partial \beta} = \beta^TX^TX + X^TX\beta$$
$$ \dfrac {\partial^2 \phi} {\partial \beta^2} = 2X^TX$$
I am confused howto get the first derivative. I understand that $\Vert y \Vert^2$ is gone because it is a scalar, but I don't understand the rest.
Can someone explain it to me or redirect me to a good resource if this is a property or something?
Thank you.
Comment: Expand the squared norm as an inner product and use the definition of a  derivative
Comment: That first derivative at your link isn't even correct. The dimensions of $\beta^TX^TX$ and $X^TX\beta$ don't match for one.
Comment: I have edited the relevant answer at the included link and corrected first derivative. It should be $- 2y^TX + 2\beta^TX^TX$.
Answer: Rather than expand and then differentiate, do the differentiation first.
Define the vector $z=(X\beta-y)$ and write the function as an inner product, which I'll denote with a colon for ease of typing. Then it's simple to find the differential, the gradient, and the Hessian
$$\eqalign{
 \phi &= z:z \cr
d\phi &= 2z:dz &= 2z:X\,d\beta = 2X^Tz:d\beta \cr
g=\frac{\partial\phi}{\partial\beta} &= 2X^Tz &= 2X^T(X\beta-y) \cr
dg &= 2X^T dz &= 2X^TX\,d\beta \cr
H=\frac{\partial g}{\partial\beta} &= 2X^TX \cr
}$$
Comment: Could you explain why $dz = Xd\beta$?
Comment: @BagusTrihatmaja In general, the differential of $z$ is $$dz=dX\,\beta + X\,d\beta - dy$$ but you are interested in the change in the value of the function due to changing $\beta$, so $X$ and $y$ are treated as constants.
Answer: Note that
\begin{align}
\phi(\beta) &= (y-X\beta)'(y-X\beta)\\
         &=y'y + \beta'X'X\beta - 2\beta' X'y,
\end{align}
where $X'X=A$ is a square matrix of order (rank) $p+1$, thus $\beta' X'X\beta = \beta' A \beta$ is quadratic form, as such you can rewrite it in the following manner
$$
\beta' A \beta = \sum_j\sum_i \beta_j \beta_ia_{ij} = \sum\beta_j^2a_{jj} + 2\sum_{i < j}\beta_i \beta_j a_{ij},
$$
taking derivative w.r.t. $\beta$ you'll get
$$
\frac{\partial}{\partial \beta} (\beta' A \beta) = 2\sum_j \beta_j a_{jj} + 2 \sum_{i < j} \beta_ja_{ij} = 2A\beta,
$$
i.e.,
$$
\frac{\partial}{\partial \beta} (\beta' X'X \beta) = 2X'X\beta.
$$
Note that $X'X\beta$ can be expressed as
$$
X'X\beta = \sum_{j=1}^{p+1} C_j(X'X)\beta_j,
$$
where $C_j(X'X)$ is the $j$-th column of $X'X$. Taking derivative w.r.t. $\beta_j$ will leave you only with the $j$-th column any time, hence,
$$
\frac{\partial}{\partial \beta} (X'X\beta) = [C_1(X'X),..., C_2(X'X)] = X'X
$$
Comment: $y'X\beta = \beta' X' y$
Comment: How do you get $-2\beta X'y$? Wouldn't it be $-2yX\beta$?
Comment: And why the order does not matter here?
Comment: Because it is scalar, so you can transpose it and it won't change
Comment: that means $-2\beta X'y = -2yX\beta$?

Derivative of matrix equation


Replicating a linear regression example from Hastie, Tibshirani and Friedman

Question: One of the standing examples in the book The Elements of Statistical Learning by Hastie, Tibshirani and Friedman (hereafter referred to as HTF) uses prostate cancer data (available here and described here) from a study by Stamey et al. (1989).
I'm trying to reproduce the results quoted in the (second edition of) HTF for ordinary linear regression, for which they report the following coefficients (table 3.2, page 50):
Intercept:  2.45
lcavol   :  0.72
weight   :  0.29
age      : -0.14
lbph     :  0.21
svi      :  0.31
lip      : -0.29
gleason  : -0.02
egg45    :  0.28

However, my own analysis gives woefully different numbers (using scikit-learn's LinearRegression, statsmodels's OLS and computing the coefficients manually using formula 3.6 in HTF). I get
Intercept:  0.429
lcavol   :  0.577
lweight  :  0.614
age      : -0.019
lbph     :  0.145
svi      :  0.737
lcp      : -0.206
gleason  : -0.030
pgg45    :  0.009

using the following (Python 3) code:
# Import data
# -----------
import pandas as pd

df = pd.read_csv('prostate.data', sep='\t', usecols=range(1, 11))

# Extract training set used by HTF
# --------------------------------
train_mask = (df['train'] == 'T')
cols_X = [col for col in df.columns if col not in ['lpsa', 'train']]
cols_y = ['lpsa']

X_train = df.loc[train_mask, cols_X]
y_train = df.loc[train_mask, cols_y]

# Use scikit-learn's LinearRegression
# -----------------------------------
from sklearn import linear_model

ols = linear_model.LinearRegression(normalize=True)
ols.fit(X_train, y_train)

print('Intercept: {:6.3f}'.format(ols.intercept_[0]))
for i, col in enumerate(X_train.columns):
    print('{:9s}: {:6.3f}'.format(col, ols.coef_[0, i]))

# Use statsmodels OLS
# -------------------
import statsmodels.api as sm

result = sm.OLS(y_train, sm.add_constant(X_train)).fit()
print(result.summary())

# Use formula 3.6 of HTF
# ----------------------
X_ext = np.hstack([np.ones((X_train.shape[0], 1)), X_train.values])
np.matmul(np.matmul(np.linalg.inv(np.matmul(X_ext.T, X_ext)), X_ext.T), y_train)

Am I doing something wrong, or are the numbers reported in the book that are wrong?
EDIT: Redefining
X_train = (X_train - X_train.mean(axis=0)) / (X_train.std(axis=0))

before any of the fits leads to coefficients that are consistent with those  reported in HTF:
Intercept:  2.4523
lcavol:     0.7164
weight:     0.2926
age:       -0.1425
lbph:       0.2120
svi:        0.3096
lip:       -0.2890
gleason:   -0.0209
pgg45:      0.2773

The book would probably benefit from making this clearer (I've seen other people confused by this same issue). Thanks to all that responded!
Comment: @Analyst1: I doubt that's the case: the book reports a *single* coefficient for both `svi` and `gleason`. While the first one takes values in the set `{0, 1}`, `gleason` can be any of `{6, 7, 8, 9}`.
Comment: While I haven't looked at this closely, my first guess would be that the parameterization that R uses in linear regression is different than scikit-learn's regression.  How does scikit-learn handle the parameterization of categorical variables?
Comment: @Analyst1: the two categorical features (`svi` and `gleason`) are reported as integers, and are fed into `scikit-learn` (and `statsmodels`, and the manual computation) as such.
Comment: I'm *guessing* that is the problem.  Take a careful look to see how these are treated in Hastie's book.  I suspect they are treated as factors in R, in which case they would be converted to 0/1 variables with one category set to zero.  This could certainly explain the differences.  I'd review that carefully.
Comment: Fair enough.  Like I said, it was just a guess and I didn't have the book in front of me to look carefully.  This is common problem when people try to match examples, so it was my best guess without all the info.
Answer: As they say in the text:

We fit a linear model to the log of prostate-specific antigen, lpsa,
  after first standardizing the predictors to have unit variance. We
  randomly split the dataset into a training set of size 67 and a test
  set of size 30. We applied least squares estimation to the training
  set, producing the estimates, standard errors and Z-scores shown in
  Table 3.2

You have not standardized the predictors.
Comment: @Alberto if your results with `normalize=True` are identical to the ones with `normalize=False`, it suggests that something is wrong. Regression coefficients should clearly be different in these two cases.
Comment: @AlbertoGarcía-Raboso you have to normalize the *predictors* and not the outcome. Don't ask me why. HTF just decided that's the way to do it.
Comment: What EXACTLY does normalize=True do?  I couldn't find any documentation which says (haven't looked at source code).
Comment: @Alberto García-Raboso And scikit-learn could benefit from making explicit what Normalize=True does.
Comment: Yes, I have: notice the `normalize=True` in `scikit-learn`'s `LinearRegression`. In any case, setting `normalize=False` gives the same results.
Comment: It seems the book reports the coefficients in terms of the normalized predictors (and unnormalized outcomes), while `scikit-learn` fits the normalized predictors but gives the coefficients in terms of the unnormalized predictors. As I say in the edit to the question: the book may benefit from making this more explicit.
Answer: When I standardize the predictors (i.e. subtract mean and divide by standard deviation), and then do standard OLS on observations marked as belonging to the training set, I get:
   2.464932922123745
   0.679528141237975
   0.263053065732544
  -0.141464833536172
   0.210146557221827
   0.305200597125098
  -0.288492772453546
  -0.021305038802948
   0.266955762119924

Which is basically the same as described in the text (minor differences remain but probably nothing important and I shouldn't have spent this much time already!)


Proving $\int_{1}^{\infty}\frac{\sin x}{\left(\log x\right)^{\frac{1}{2}}}dx$ converges

Question:
Prove that the following improper integral converges $$\int_{1}^{\infty}\frac{\sin x}{\left(\log x\right)^{\frac{1}{2}}}dx.$$

I see that you can show this using Dirichlet's Convergence Test, but how would you show it not using this test?
Comment: It's somewhat nasty, but you can integrate by parts twice. Let $du$ be the numerator each time and $v$ be the denominator.
Answer: You have two issues to address. First, is $\int_1^{1.1}\frac{\sin x}{\sqrt{\log x}}\,dx$ convergent? Second, is $\int_{1.1}^{\infty}\frac{\sin x}{\sqrt{\log x}}\,dx$ convergent?
The first integral blows up at its left end point. But we can show that for the some constant $C$, $\frac{\sin x}{\sqrt{\log x}}<\frac{C}{\sqrt{x-1}}$ for $x$ in $(1,1.1)$. Then by direct comparison, this piece is convergent. The numerator $\sin(x)$ is clearly positive and less than $1$. So we'd need to show that $\log x>k(x-1)$ for some constant $k$, for all $x\in(1,1.1)$. You can do this in the standard way by noting both are equal at $x=0$ and comparing derivatives.
The second integral breaks up into a sequence of alternating integrals $$\int_{1.1}^{\pi}\frac{\sin x}{\sqrt{\log x}}\,dx+\sum_{n=1}^{\infty}\int_{n\pi}^{n\pi+\pi}\frac{\sin x}{\sqrt{\log x}}\,dx$$ By the alternating test for integrals, we need to check that $\lim_{n\to\infty}\left|\int_{n\pi}^{n\pi+\pi}\frac{\sin x}{\sqrt{\log x}}\,dx\right|=0$. This is true, since
$$\begin{align}
\left|\int_{n\pi}^{n\pi+\pi}\frac{\sin x}{\sqrt{\log x}}\,dx\right|&<\frac{1}{\sqrt{\log(n\pi)}}\left|\int_{n\pi}^{n\pi+\pi}\sin(x)\,dx\right|\\
&=\frac{2}{\sqrt{\log(n\pi)}}\end{align}$$
Joriki reminded me that the alternating series test also requires that the absolute values of the integrals be decreasing. (Otherwise you could have say, the positive integrals going down like $1/n$ with the negative ones going down like $1/2^n$, and the whole thing diverges.) So we should check that
$$\begin{align}
\left|\int_{n\pi}^{n\pi+\pi}\frac{\sin x}{\sqrt{\log x}}\,dx\right|&>\left|\int_{n\pi+\pi}^{n\pi+2\pi}\frac{\sin x}{\sqrt{\log x}}\,dx\right|\end{align}$$ which is true since the numerator function just repeats another period with the same values, while the denominator function becomes larger.
Comment: I think to be precise we also need to check that the absolute values of the alternating integrals strictly decrease?
Comment: @joriki, Yep! I'll add that.


Finding the Partial Derivatives, given three Directional Derivatives

Question: I was working on the following question about directional derivatives.

The directional derivative of a function $\phi(x, y, z)$ at the point $(2, 0, 3)$ in the direction towards $(3, -2, 3)$ is $1.789$, in the direction towards
  $(2, 4, 4)$ it is $0.243$, whilst in the direction towards $(4, -1, 2)$ it is zero. By showing that the three first order partial derivatives of $\phi$ with
  respect to $x,$ $y$ and $z$ are $2.0$, $-1.0$ and $5.0$ respectively, verify that the value of the directional derivative of $\phi$ at $(2, 0, 3)$ in the direction towards $(0, 2, 14)$ is $4.314$.

Now I used the following approach. We know that the directional derivative of a scalar field $\phi$ in the direction of a unit vector $\hat{\boldsymbol{\mathrm{s}}}$ is given by
$$\frac{\partial \phi}{\partial s}=\hat{\boldsymbol{\mathrm{s}}}\cdot\nabla\phi$$
Let the first direction given be $\boldsymbol{\mathrm{s}}_1=(3,-2,3)$. Then $\hat{\boldsymbol{\mathrm{s}}}=\frac{1}{\sqrt {22}}(3,-2,3)$. Substituting into the result above gives
$$\frac{\partial \phi}{\partial s_1}=\frac{1}{\sqrt{22}}\begin{pmatrix}3\\-2\\3\end{pmatrix}\cdot\nabla\phi=\frac{3}{\sqrt{22}}\frac{\partial \phi}{\partial x}-\frac{2}{\sqrt{22}}\frac{\partial \phi}{\partial y}+\frac{3}{\sqrt{22}}\frac{\partial \phi}{\partial z}=1.789$$
However if we substitute the given results $\partial\phi/\partial x=2$, $\partial\phi/\partial y=-1$ and $\partial\phi/\partial z=5$, equality does not hold; nor does it hold if we repeat the procedure for the other two directional derivatives.
Is there a flaw in my approach? Perhaps the results in the question are mistaken? I'd appreciate any feedback.
Comment: I think that $\mathbf{s}_1$ is not $(3,-2,3)$, but the displacement vector *from* $(2,0,3)$ *to* $(3,-2,3)$, namely $\left(1,-2,0\right)$.
Comment: Ohhhh... so direction *towards* meaning, towards the point, not the direction given by the vector. That was a bit confusing.
Answer: The procedure is correct, but the vectors that need to be taken are the displacement vectors, i.e. the vector from $(2,0,3)$ to $(3,-2,3)$. In other words, $\hat{\boldsymbol{\mathbb s}}_1=(3,-2,3)-(2,0,3)=(1,-2,0)$.
This gives
$$\frac{\partial \phi}{\partial s_1}=\frac{1}{\sqrt{5}}\begin{pmatrix}1\\-2\\0\end{pmatrix}\cdot\nabla\phi=\frac{1}{\sqrt{5}}\frac{\partial \phi}{\partial x}-\frac{2}{\sqrt{5}}\frac{\partial \phi}{\partial y}$$
which $=1.798$ when substituting the given partial derivatives.


Are colored noises correlated / uncorrelated?

Question: Let, $x$ be a random variable (r.v) that is white Gaussian, has a flat power spectrum. $y$ can be any colored noise. I think another term for uncorrelated is i.i.d (identically and independently distributed).
Colored noises such as pink, brown, and red can be generated by filtering from a white Gaussian noise signal such as $x$. Colored noises do not have a flat power spectrum.
Question1: If the power spectrum is not flat, then does that mean the colored noises are correlated?
Reading through some texts I could understand that Brown noise has its random variable positively correlated to its previous random variable. Can this be generalized to other noises such as pink, blue, violet etc? and the other has a non flat spectrum so is colored, consider say brown color ($y$ r.v). Since $x$ is white it is uncorrelated to itself and $y$ is correlated to itself (each random number for the red noise is positively correlated to the one preceding it).
Question2: The plot below is the time series which is the output of the sum of white Gaussian noise and pink noise. I don't know if pink noise is correlated or not. In general, does the addition of an uncorrelated r.v with a correlated r.v give an output that is correlated or uncorrelated? i.e., $z=x+y$ is $z$ correlated/uncorrelated?
Please correct me if any information is wrong.
Comment: You can use $\LaTeX$-style math formatting in your posts with Mathjax. More information:  https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer:
Question1: If the power spectrum is not flat, then does that mean the
colored noises are correlated?

One way to construct the power spectral density is to take the Fourier transform of the autocovariance function. This result is called the Wiener–Khinchin theorem. According to the theorem the autocovariance function is
$$
R_{xx}(t) = \int_{-\infty}^{\infty} =  S(f)e^{2\pi itf} df,
$$
where $S(f)$ is the power spectral density. The expression $e^{2\pi itf}$ describes rotations around a circle at frequency $f$. Integrating the area this rotation traces out turns out to be 0, which implies that the autocovariance function is flat at 0 only if $S(f)$ is flat. In order to compute the autocorrelation function you have to normalise by the variance of the noise, i.e. $R_{xx}(t)/R_{xx}(0)$.
To examine autocorrelation functions for different colours of noise I simulate 1000 timeseries of length 1000 each:

As can be seen, all colours of noise apart from white are autocorrelated for $t=1$. However, the correlation for blue and violet noise is negative and for larger $t$'s violet noise is not correlated. This is because violet noise is constructed by differentiating white noise, which means that every sample is the difference between two Gaussian random numbers. If we call these Gaussian numbers $w_1,w_2,\dots$ and the samples of violet noise $v_1,v_2,\dots$ we can write
$$v_1 = w_1 - w_2, v_2 = w_2 - w_3, v_3 = w_3 - w_4,\dots$$.
Note that the Gaussian random number $w_2$ is part of $v_1$ and $v_2$ with opposite signs (which explains the negative correlation) but not of $v_3$ (which explains that it is not correlated for $t>1$).
To illustrate this further I have also plotted the partial autocorrelation, which is the autocorrelation when controlling for all smaller $t$'s. Here violet noise is partially autocorrelated throughout. The reason is that the estimate of $v_3$ from $v_2$ can be improved by also knowing $v_1$. This is because $v_1$ contains in formation about $w_2$, which can be used to more accurately estimate the $w_3$ part of $v_2$, which in turn is needed to estimate $v_3$. (Note that the partial autocorrelation for violet noise would be flat if $t=1$ were not included.)
Another interesting observation is that the partial autocorrelation for brown noise beyond $t=1$ is flat at 0. This is because brown noise is obtained by integrating white noise, which makes every sample the cumulative sum of all previous Gaussian random numbers. The sample at $t=1$ is not crucial for estimating the current sample (thus the high autocorrelation for $t>1$) but if the sample at $t=1$ is known, then any sample $t>1$ does not add any new information (thus the low partial autocorrelation for $t>1$).
Pink and blue noise can be considered cases between these two extremes.
As a final aside, the autocorrelation for an infinite timeseries of brown noise is flat at 1 because the autocovariance $R_{xx}(t)$ and the variance $R_{xx}(0)$ are approaching infinity at the same rate.

Question2: The plot below is the time series which is the output of
the sum of white Gaussian noise and pink noise. I don't know if pink
noise is correlated or not. In general, does the addition of an
uncorrelated r.v with a correlated r.v give an output that is
correlated or uncorrelated? i.e., z=x+y is z correlated/uncorrelated?

As you can see from the above plot pink noise is autocorrelated. You can obtain this result yourself from your simulated data by shifting its values by different lags $t$ and computing the correlation for each lag. Generally, if you add a correlated timeseries to an uncorrelated one the resulting timeseries will be correlated but less so.
Comment: Hey! It's not the peak at lag=1 that makes them correlated. The peak at lag=1 implies that they are all most strongly correlated for this lag. But even if the autocorrelation would peak later they would still be correlated. I would argue that they can be considered correlated if the autocorrelation function is positive/negative for any lag larger than 0, regardless of what that lag is.
Comment: Thank you for your answer. Just to clarify if I have understood you correctly, for your answer to Q1 - - you say that except for white noise, all colored noises are correlated. The reason is that the autocorrelation graphs for colored noises (Except white noise) have a peak value at lag = 1. Is my understanding correct? Having a peak at lag = 1, what does it imply?


Non-Abelian subgroup element composition

Question: Let $H$ be a subgroup of the non-Abelian group $G$ with elements $h \in H$ and $g \in G$ but $g \notin H$.
It is proved here for the Abelian case that the product $gh \notin H$. To prove the non-Abelian case we need to establish that both $gh \notin H$ and also $hg \notin H$.
Working through the proof for the non-Abelian case we obtain $x=hgh^{-1}$ and it is not clear that $x \notin H$.
How do complete the proof for the non-Abelian case? An alternative proof strategy will be accepted.
Comment: Several comments in the question you link explicitly discuss the fact that your proof there worked in the non-abelian case.
Comment: In this case, it would be better to edit your first question and note that the same arguments work when $G$ is non-abelian. This is preferable to creating two different questions that are very nearly identical.
Comment: Not following.  If $gh_1=h_2$ then $g=h_2h_1^{-1}\in H$.  If $h_1g=h_2$ then $g=h_1^{-1}h_2\in H$.
Comment: This is not the case because $g \notin H$.
Comment: That's the point.  We have a contradiction, which means that our premise , $gh_1\in H$, must have been false.
Comment: This question is about a *proof* of the non-Abelian case. It must be shown that $gh \notin H$ and $hg \notin H$. Both are required.
Comment: Ok, but both are trivial.  I did them both in my first comment.  As others have remarked, there is no meaningful difference between the abelian and non-abelian cases.
Comment: @conchild Your same proof from the other question still works. In the $hg$ case, just do the exact same proof but multiply on the left by $h^{-1}$ instead, not the right.
Comment: I have answered the question myself.
Answer: There is no difference between the Abelian and non Abelian case. Suppose $g\in G$ and $h\in H$. If
$$
gh=x\in H
$$
then $g=xh^{-1}\in H$.
Similarly, if $hg=y\in H$, then $g=h^{-1}y\in H$.
Comment: @conchild You want to prove: "for all $g\in G$, $h\in H$, if $g\notin H$, then $gh\notin H$ and $hg\notin H$". I proved the contrapositive: "for all $g\in G$, $h\in H$, if $gh\in H$ or $hg\in H$, then $g\in H$".
Comment: The question is about $g \notin H \implies x \notin H$.
Comment: @conchild I proved that if $gh\in H$ or $hg\in H$, then $g\in H$. Isn't it sufficient?
Comment: I am not convinced.


Microsoft Exchange Active Directory Topology service on server localhost can't be contacted via RPC. Error 0x6D9

Question: I have Exchange installed and the certificate verified.
On a computer in Network I can send out emails but can not receive them.
On a computer outside the network I am not send or receive.
When I attempt to go https://mail.advsystems.com/owa/
I am given the following error.
The Microsoft Exchange Active Directory Topology service on server localhost can't be contacted via RPC. Error 0x6D9.
Comment: This reads like a firewall issue.
Comment: We have no outisde firewall. Just Exchange, 2 Domain Controllers and a Gateway Server.
Comment: The Exchange Server's firewall is the one I meant. And honestly, you should have at minimum a firewall between the public internet and the LAN.
Comment: How do I configure the Exchange Firewall. Once I am getting mail my exchange account then I will look at external firewalls
Comment: @Davidw for testing I turned the firewall off.
Answer: What's your current Exchange version? How many users meet this issue?
Since you mentioned that can't send/receive messages on external network, make sure that you have enabled Outlook Anywhere.
https://social.technet.microsoft.com/Forums/exchange/en-US/7806a15e-7b8c-4ef5-86da-cf6a3503f74f/off-site-users-unable-to-connect-all-the-sudden-to-exchange-2010-enviroment?forum=exchangesvrclients
Comment: 2019 all 4 of them.


non-blocking datagram socket, read and write

Question: for non-blocking datagram socket, like UDP,
when I call write()/send() on the socket, if the bytes to write is 1000 bytes,
but in case that I write too often, maybe the write(send) buffer is not enough,
for example, only 200 bytes buffer available.
then I will write 200 bytes or 0 bytes? is the returned error is EAGAIN nor any other error?
for read()/recv() on a socket, each call of them will just return extacly 1 datagram, is it or not?
thanks!
Answer:
if the bytes to write is 1000 bytes, but in case that I write too often, maybe the write(send) buffer is not enough, for example, only 200 bytes buffer available. then I will write 200 bytes or 0 bytes?

Zero.

is the returned error is EAGAIN nor any other error?

EAGAIN or EWOULDBLOCK depending on your platform.

How about read()?

It will return either a complete UDP datagram or zero.
This is a primary property of UDP.
Comment: If you are referring to recvfrom(), it returns the number of bytes received if there was no error. Why don't you check your documentation?
Comment: for non-blocking datagram socket, recvfrom() returns the number of bytes? I think it returns the whole packet,isn't it?  there is no specific information in this regard in the documentation.
Comment: Here is copy/paste from the MSDN: If no error occurs, recvfrom returns the number of bytes received. If the connection has been gracefully closed, the return value is zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
Comment: @user1764961 this is obviously for tcp connection, not datagram socket.
Comment: read the first sentence here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740120(v=vs.85).aspx
Comment: @user1764961 it seems to me that what EJP said is different from the documentation.
Comment: I guess this could be different on different platforms. You didn't tell what is your platform.


Views date range filter adds weird condition

Question: I have a view for a content type. This content type has a date field (only date) and I have added and exposed a filter for this field ("date is between" option).
I have added and exposed a filter for other text field.
If I put a condition on the text field in the filter of the view, then it generate a weird SQL for the date field.
SELECT node_field_data.nid AS nid, node_field_data_node__field_liq_club.nid AS node_field_data_node__field_liq_club_nid
FROM
node_field_data node_field_data
LEFT JOIN node__field_liq_club node__field_liq_club ON node_field_data.nid = node__field_liq_club.entity_id AND node__field_liq_club.deleted = '0'
INNER JOIN node_field_data node_field_data_node__field_liq_club ON node__field_liq_club.field_liq_club_target_id = node_field_data_node__field_liq_club.nid
LEFT JOIN node__field_liq_ejercicio node__field_liq_ejercicio ON node_field_data.nid = node__field_liq_ejercicio.entity_id AND node__field_liq_ejercicio.deleted = '0'
LEFT JOIN node__field_liq_fechaliq node__field_liq_fechaliq ON node_field_data.nid = node__field_liq_fechaliq.entity_id AND node__field_liq_fechaliq.deleted = '0'
LEFT JOIN node__field_liq_fechapago node__field_liq_fechapago ON node_field_data.nid = node__field_liq_fechapago.entity_id AND node__field_liq_fechapago.deleted = '0'
WHERE
(node_field_data.status = '1') AND (node_field_data.type IN ('liquidacion')) AND (node__field_liq_ejercicio.field_liq_ejercicio_value = '2010') AND
((DATE_FORMAT(node__field_liq_fechaliq.field_liq_fechaliq_value, '%Y-%m-%d') BETWEEN DATE_FORMAT('2019-01-01T00:00:00', '%Y-%m-%d') AND DATE_FORMAT('2019-12-31T00:00:00', '%Y-%m-%d')))
AND ((DATE_FORMAT((node__field_liq_fechapago.field_liq_fechapago_value + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') BETWEEN DATE_FORMAT(('2018-12-31T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') AND DATE_FORMAT(('2019-12-30T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s')))
LIMIT 25 OFFSET 0

My text field add the condition:
node__field_liq_ejercicio.field_liq_ejercicio_value = '2010'
But, although I don't fill any condition for date-range, it adds:
    and ((DATE_FORMAT(node__field_liq_fechaliq.field_liq_fechaliq_value, '%Y-%m-%d') BETWEEN DATE_FORMAT('2019-01-01T00:00:00', '%Y-%m-%d') AND DATE_FORMAT('2019-12-31T00:00:00', '%Y-%m-%d')))
AND ((DATE_FORMAT((node__field_liq_fechapago.field_liq_fechapago_value + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') BETWEEN DATE_FORMAT(('2018-12-31T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') AND DATE_FORMAT(('2019-12-30T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s')))

I don't know why it is added, and how to solve this issue. Why this INTERVAL 7200 SECOND?. Any suggestion?
Answer: After some test I have found that a module was changing filter form states, and then the filter fields were wrong when the query were constructed. I fix that and now it works good.


Evaluating a nasty integral that Mathematica can't deal with

Question: The nasty integral is
$\displaystyle \frac{\lambda}{4\pi \varepsilon }\left [ z\mathbf{\hat{z}}\int_{-L}^{L}\frac{1}{\left ( x^{2}+z^{2} \right )^{3/2}}dx \right ]$
What Mathematica returned was

{0,0,ConditionalExpression[([Lambda] L)/(2 [Pi] z [Epsilon] Sqrt[L^2+z^2]),Im(z)^2<=Re(z)^2[And](Im(z/L)>1[Or]Im(z/L)<-1[Or]Re(z/L)!=0)[And](Sqrt[-((Im(z) Re(z))/(Im(L) Re(L)))][NotElement][DoubleStruckCapitalR][Or]Im(z) ((Re(L) Re(z))/Im(L)+Im(z))<=Re(z) ((Im(L) Im(z))/Re(L)+Re(z))[Or]Re(Sqrt[-((Im(z) Re(z))/(Im(L) Re(L)))])>=1)]}

Any help is appreciated.
Comment: This integral is not difficult. Try the substitution $x = z \tan \theta$.
Comment: Try to add `Assumptions->L>0&∈[z,Reals]&&z!=0` as an option to `Integrate` (in case those assumptions are true, of course).
Comment: Another successful substitution is $x=z\sinh(\theta)$.
Comment: I'm not sure what you typed in but, for what it's worth, I found the result quite easily with Mathematica using: `Integrate[1/(x^2 + z^2)^(3/2), {x, 0, L}, Assumptions -> {L > 0, z > 0}]`.
Comment: The cube is making integrals otherwise it was just standard results
Comment: WAT? ... As to the original post, your integral depends on how $z$ is related to $L$ (is $z>L$? $z<L$? $z=L$?), so Mathematica is doing the best it can.
Comment: @okrzysik Good start. Been ages since i did these manually but I can remember this trig identity you posted. Will get my hands dirty.
Comment: The antiderivative does not mak any problem. The conditions are introduced when using the bounds since, beside you, nobody knows if $L$ and $z$ are real or complex.
Comment: It was the "Assumption" function that I left out.
Comment: One notable fact about the $x=z \tan \theta$ is that, in the context of the electric field of a finite wire, it has a geometric interpretation: $\theta$ is the angle between the $z$-axis and $\mathbb{r}$, so one essentially is choosing to integrate w/r/t this angle rather than the position along the wire.
Answer: You want to find the electric field due to finite wire, right?
\begin{align*}
  \mathbf{E}_{z} &= \frac{\lambda}{4\pi \varepsilon} \mathbf{z} \times
           2\int_{0}^{L} \frac{dx}{(x^{2}+z^{2})^{3/2}} \\
        &= \frac{\lambda}{4\pi \varepsilon} \mathbf{z} \times
           2\left[ \frac{x}{z^{2} \sqrt{x^{2}+z^{2}}} \right]_{x=0}^{L} \\
        &= \frac{\lambda}{2\pi \varepsilon} \mathbf{z} \times
           \frac{L}{z^{2} \sqrt{z^{2}+L^{2}}}
\end{align*}
Comment: You know your stuff.


Read a file a number of bytes per time in c

Question: I am trying to write a program on how to read a file 10 bytes per time using read, however, I do not know how to go about it. How should I modify this code to read 10bytes per time. Thanks!!!!
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>

int main (int argc, char *argv[])
{
    printf("I am here1\n");
    int fd, readd = 0;
    char* buf[1024];

    printf("I am here2\n");

    fd =open("text.txt", O_RDWR);
    if (fd == -1)
    {
            perror("open failed");
            exit(1);
    }
    else
    {
            printf("I am here3\n");

            if(("text.txt",buf, 1024)<0)
                    printf("read error\n");
        else
        {
            printf("I am here3\n");

            /*******************************
            *  I suspect this should be the place I make the modification
            *******************************/
            if(read("text.txt",buf, 1024)<0)
                    printf("read error\n");
            else
            {
                    printf("I am here4\n");
                    printf("\nN: %c",buf);
                    if(write(fd,buf,readd) != readd)
                            printf("write error\n");

            }
        }

    return 0;
}

Comment: `if(("text.txt",buf, 1024)<0)`  what will this line do ??
Answer: The final parameter of read() is the maximum size of the data you wish to read so, to try and read ten bytes at a time, you would need:
read (fd, buf, 10)

You'll notice I've also changed the first parameter to the file descriptor rather than the file name string.
Now, you'll probably want that in a loop since you'll want to do something with the data, and you also need to check the return value since it can give you less than what you asked for.
A good example for doing this would be:
int copyTenAtATime (char *infile, char *outfile) {
    // Buffer details (size and data).

    int sz;
    char buff[10];

    // Try open input and output.

    int ifd = open (infile, O_RDWR);
    int ofd = open (outfile, O_WRONLY|O_CREAT);

    // Do nothing unless both opened okay.

    if ((ifd >= 0) && (ofd >= 0)) {
        // Read chunk, stopping on error or end of file.

        while ((sz = read (ifd, buff, sizeof (buff))) > 0) {
            // Write chunk, flagging error if not all written.

            if (write (ofd, buff, sz) != sz) {
                sz = -1;
                break;
            }
        }
    }

    // Finished or errored here, close files that were opened.

    if (ifd >= 0) close (ifd);
    if (ofd >= 0) close (ofd);

    // Return zero if all okay, otherwise error indicator.

    return (sz == 0) ? 0 : -1;
}

Answer: change the value in read,
read(fd,buf,10);

From man of read
ssize_t read(int fd, void *buf, size_t count);

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

 if(read("text.txt",buf, 1024)<0)// this will give you the error.

First argument must be an file descriptor.


Which hook to allow specific users to add/edit/view comments?

Question: Is there a hook that I can use that would give specific users permissions to add a comment, or edit their own comment?  I was hoping there would be something like hook_node_access().
In my form, I have a select list with all the users that the submitter can choose.  If the person is selected, then that selected person can comment on that specific node.
I looked at the comment access module, but that does not work since it is still being controlled by role permissions.
Answer: There is no hook to do this. One possibility that doesn't require editing of the comment module is to change the comment status of the node depending on the current user using hook_node_load:
function MyModule_node_load($nodes, $types) {
    global $user;
    foreach($nodes as $node) {
        if(!user_has_access_to_node($user, $node)) {
            $node->comment = COMMENT_NODE_HIDDEN;
        }
    }
}

The hook will be called after the one in comment module, and will prevent users from posting comments unless user_has_access_to_node returns true.
The implementation of user_has_access_to_node would simply check if the current user is in the list of users allowed to edit the viewed node.
Comment: This is a good suggestion, however, it still requires me to give the specific user the allow comment permissions to leave a comment, which is something I want to avoid since I would then have to control comment permissions throughout my entire site.  But since you told me there is no hook to control comment access, then I will just write my own module that is very similar to the comments module, but with my own set of rules based on field values from the select dropdown list.


knockout foreach css multiple classes $data

Question: In this example I have two additional css classes I want to add to a DIV.

The first being 'tile-selected' based on a boolean. This works well.
The second is actually a name of a class 'Triple', (and in this example, always add it, ie 'True')
I get the error:

Uncaught Error: Unable to parse bindings.
  Message: SyntaxError: Unexpected token .;
  Bindings value: css: {'tile-selected': true, $data.size : true}

I'm assuming that I can't use the $data.size part to pull in the 'Triple' literal from the 'size' property. Is there a way that I can do this? ($data['size'] also didn't seem to work)
Comment: What is the type of $data.size ? Is it an observable?
Comment: isn't $data the current iteration of the foreach?
Comment: Yes it is, I was asking about size.
Comment: size is a property of the hard coded array in the first div
Answer: You cannot use the ko observables or properties as class names. Instead you would have to create a separate property for this and use the same for dynamic css binding something like below.

   Profit Information

var viewModel = {
/// some view model properties here.
        };

viewModel.sizeCSS = ko.computed(function() {
    return this.size();
}, viewModel);

EDIT: Check the dynamic CSS binding example here: http://knockoutjs.com/documentation/css-binding.html
Comment: Something i discovered is that it is not strictly true that you can't have properties as css class names. You can when using them in templates...
Comment: @RonWeston Is that with the css binding or the class binding? If it is with the css binding, can you share a sample?


Running a simple Scala.React expression

Question: I am looking into Scala.React, and the updated paper on the issue, trying to get a simple Signal based example to work.
I understand that the Signal method in the paper doesn't exist as such, but instead there are Strict and Lazy. So my naive first attempt:
Setting up the whole thing:
object dom extends scala.react.Domain {
  val engine    = new Engine
  val scheduler = new ManualScheduler
}
import dom._

Trying out composition:
val v1, v2 = Var(0)

val f = Strict { v1() + v2() }

The second line crashes with
java.lang.AssertionError: assertion failed: This method must be run on its domain
  scala.react.NilDebug@4eaf6cb1
    at scala.Predef$.assert(Predef.scala:179)
    at scala.react.Debug.assertInTurn(Debug.scala:37)
    at scala.react.EngineModule$Propagator.defer(EngineModule.scala:120)
        ...

So I must be doing something wrong. But what?

Second attempt:
scala> dom.start()

scala> var v1, v2, f = (null: Signal[Int])
v1: dom.Signal[Int] = null
v2: dom.Signal[Int] = null
f: dom.Signal[Int] = null

scala> schedule { v1 = Var(0); v2 = Var(0) }

scala> schedule { f = Strict { v1() + v2() }}

scala> engine.runTurn()

scala> schedule { println(f.now) }

scala> engine.runTurn()
Uncaught exception in turn!
scala.react.EngineModule$LevelMismatch$

Comment: @Madoc Yes, I wouldn't bet on it for production, I was just trying it out. Also the CPS compiler plugin will be abandoned as far as I know. Probably best is to wait for Haller/Miller publishing the source code of [RAY](http://infoscience.epfl.ch/record/188383/)
Comment: I would love to get into reactive programming, but I have the impression that Scala.React is not maintained any more. Therefore, I am very reluctant to use it.
Comment: I have the same problem in getting a simple examle runnning, see [Simple Example for Scala React](http://stackoverflow.com/questions/19386516/simple-example-for-scala-react)
Answer: Ok, so first of all we should use Lazy instead of Strict if we want to keep a reference to those signals, because Strict requires to be run within a scheduled turn.
The following is my new attempt. Not sure if this is how it's intended, but it works:
object Test extends scala.react.Domain with App {
  val engine    = new Engine
  val scheduler = new ManualScheduler

  val v2   = Var(0)
  val v1   = Lazy { v2() + 10 }
  val f    = Lazy { v1() + v2() }

  start()

  schedule {
    new Observing {
      observe(f) { p =>
        println(s"Observed: $p")
      }
    }
    v2() = 5
  }

  runTurn()
}

Running a simple Scala.React expression


Server disk full after upgrade from Ubuntu 14.10 to 15.10

Question: I upgraded an older server from 13.10 -> 14.04 -> 14.10 -> 15.10 yesterday. Today I'm seeing that 100% of the disk space is being used but I can't track down where the usage is.
When I run du -h --max-depth=1 / I get the following log which seems to indicate the root path is full, but I can't tell what the source is.
du: cannot read directory '/proc/4390/task/4390/ns': Permission denied
du: cannot read directory '/proc/4390/fd': Permission denied
du: cannot read directory '/proc/4390/map_files': Permission denied
du: cannot read directory '/proc/4390/fdinfo': Permission denied
du: cannot read directory '/proc/4390/ns': Permission denied
du: cannot read directory '/proc/4392/task/4392/fd': Permission denied
du: cannot read directory '/proc/4392/task/4392/fdinfo': Permission denied
du: cannot read directory '/proc/4392/task/4392/ns': Permission denied
du: cannot read directory '/proc/4392/fd': Permission denied
du: cannot read directory '/proc/4392/map_files': Permission denied
du: cannot read directory '/proc/4392/fdinfo': Permission denied
du: cannot read directory '/proc/4392/ns': Permission denied
du: cannot access '/proc/4393/task/4393/fd/3': No such file or directory
du: cannot access '/proc/4393/task/4393/fdinfo/3': No such file or directory
du: cannot access '/proc/4393/fd/4': No such file or directory
du: cannot access '/proc/4393/fdinfo/4': No such file or directory
0       /proc
du: cannot read directory '/sys/kernel/debug': Permission denied
0       /sys
4.0K    /mnt
1.5G    /usr
du: cannot read directory '/root': Permission denied
4.0K    /root
4.0K    /srv
104M    /home
7.6M    /sbin
12M     /bin
47M     /boot
du: cannot read directory '/var/lib/snmp/mib_indexes': Permission denied
du: cannot read directory '/var/lib/php5': Permission denied
du: cannot read directory '/var/lib/mysql': Permission denied
du: cannot read directory '/var/lib/sudo': Permission denied
du: cannot read directory '/var/lib/nginx/proxy': Permission denied
du: cannot read directory '/var/lib/nginx/uwsgi': Permission denied
du: cannot read directory '/var/lib/nginx/scgi': Permission denied
du: cannot read directory '/var/lib/nginx/body': Permission denied
du: cannot read directory '/var/lib/nginx/fastcgi': Permission denied
du: cannot read directory '/var/log/unattended-upgrades': Permission denied
du: cannot read directory '/var/log/mysql': Permission denied
du: cannot read directory '/var/log/nginx': Permission denied
du: cannot read directory '/var/spool/rsyslog': Permission denied
du: cannot read directory '/var/spool/cron/atspool': Permission denied
du: cannot read directory '/var/spool/cron/crontabs': Permission denied
du: cannot read directory '/var/spool/cron/atjobs': Permission denied
du: cannot read directory '/var/cache/ldconfig': Permission denied
du: cannot read directory '/var/cache/nginx': Permission denied
18G     /var
8.0K    /media
4.0K    /lib64
du: cannot read directory '/run/log/journal/41cc217bd9afc046de32243850804999': Permission denied
du: cannot read directory '/run/systemd/inaccessible': Permission denied
1.5M    /run
359M    /lib
0       /dev
4.0K    /opt
20G     /

When I ls -la in / I see this:
total 100
drwxr-xr-x  22 root root  4096 Jul 16 00:21 .
drwxr-xr-x  22 root root  4096 Jul 16 00:21 ..
drwxr-xr-x   2 root root  4096 Jul 16 00:16 bin
drwxr-xr-x   3 root root  4096 Jul 16 00:21 boot
drwxr-xr-x  13 root root 13680 Jul 16 18:46 dev
drwxr-xr-x 108 root root 12288 Jul 16 00:23 etc
drwxr-xr-x   3 root root  4096 Jul 15 23:23 home
lrwxrwxrwx   1 root root    32 Jul 16 00:18 initrd.img -> boot/initrd.img-4.2.0-42-generic
drwxr-xr-x  21 root root  4096 Jul 16 00:16 lib
drwxr-xr-x   2 root root  4096 Jul 16 00:14 lib64
drwx------   2 root root 16384 Oct 18  2012 lost+found
drwxr-xr-x   3 root root  4096 Jul 15 23:21 media
drwxr-xr-x   2 root root  4096 Oct  9  2012 mnt
drwxr-xr-x   2 root root  4096 Oct 17  2012 opt
dr-xr-xr-x 169 root root     0 Jul 16 18:46 proc
drwx------   5 root root  4096 Jul 15 23:21 root
drwxr-xr-x  19 root root   740 Jul 16 18:49 run
drwxr-xr-x   2 root root 12288 Jul 16 00:16 sbin
drwxr-xr-x   2 root root  4096 Oct 17  2012 srv
dr-xr-xr-x  13 root root     0 Jul 16 18:57 sys
drwxrwxrwt   7 root root  4096 Jul 16 19:04 tmp
drwxr-xr-x  10 root root  4096 Jul 15 23:23 usr
drwxr-xr-x  14 root root  4096 Jul 16 00:17 var
lrwxrwxrwx   1 root root    29 Jul 16 00:18 vmlinuz -> boot/vmlinuz-4.2.0-42-generic

Again, not seeing what's using the disk space.
What are some steps I should be doing here?
Comment: Try `sudo apt-get autoremove`!
Answer: Run the following command to find free disk space information:
df -h
Then run the following command to find disk utilization information:
sudo du -shc /
(note the sudo, this should resolve the permission issues you were seeing)
When you find a directory taking up a considerable amount of disk space, cd to the directory and repeat step #2. Keep repeating this step until you identify the source of the disk space issue.
Comment: Yep, using sudo helped to clear out the noise. Found the cause. Had an old logging process that would write to a mongodb db maybe a dozen times a week. The process freaked out about something during/after the upgrade and wrote over 17gb of logs overnight. I'm not really using the old logger anyway so just removed the entire mongodb db. All smooth now!
Comment: Also, your ```/var``` directory is a 18 gigabytes. That might be worth looking at as well.
Comment: Glad to hear it worked out!
Answer: I would have commented on @Paul Calabro's answer if I had enough reputation on serverfault.
I also realise that the OP's happy that their problem is resolved but I thought it useful for those that are more nervous or at a novice level.
Would
sudo du -shc /*

not have been a better option as it would list each folder in the root directory?
However as @Paul then later refers to using cd then maybe
cd /

# position 1
sudo du -shc *

cd <into whatever folder you want drill down into>
# repeat from position 1

I was originally thinking about du -x but when this did not work i realised it was because du -x * is not stripping out the home folder because whilst it is indeed in a different filesystem the folder * expands to include home explicitly.
Further to make the output slightly easier to discern the large from the not so large replace du -h with du -BM, or for a coarser view du -BG, as then you would get a report something like
0M      /sys
0M      /mnt
1500M   /usr
0M      /root
0M      /srv
104M    /home
8M      /sbin
12M     /bin
47M     /boot
18000M  /var
0M      /media
0M      /lib64
2M      /run
359M    /lib

Now the /var folder noticeably sticks out as you don't have to pay attention to whether the units are K, M or G.  I realise the original without -h or -BM would have also highlighted the size however it is possibly a case of too much detail or information overload.  Are you really bothered if a folder uses 4 blocks or 400 blocks on a 20G device?
Whilst writing this I thought it was a pity there is not a -B% option which reports each line as a percentage of the total.
And finally for a bit of light relief...
Bragging rights

 sudo du -scBP /

Extreme bragging rights

 sudo du -scBE /


Como executar método clicando num button type

Question: Ola,
Estou a fazer uma aplicação que pode fazer recover da password do utilizador e mandar a password para o email da team de suport.
Para isso tenho uma página .aspx que tem codigo html e tenho na classe recoverpassword um método que lhe chamei sendemail() para enviar os mails. O que eu quero é quando se clicar nesse button seja executado o método sendemail que esta dentro da classe da página. O método sendemail() tem o código igual a muitos exemplos da net.
Código HTML:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Cegos Analytics | Lockscreen</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

  <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

  <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">

    <form class="lockscreen-credentials" action="RecoverPassword.aspx" method="post">

         <input id='user' type="Text" class="form-control" placeholder="Username">

              <button id='enviar' type="submit" class="btn"></button>

    </form>

    Enter your username to retrieve your session

    Or sign in as a different user

  <%--

--%>

© <%: DateTime.Now.ToShortDateString() %> - Cegos Elearning Reports

            </form>

página EnviarEmail.aspx.cs :
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.Net;
using System.IO;

namespace Email
{
    public partial class Enviaremail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        private void SendEmail()
        {

            SmtpClient cliente = new SmtpClient();
            cliente.Host = "smtp.sapo.pt";
            cliente.EnableSsl = true;
            cliente.Credentials = new NetworkCredential("firstname.lastname@example.com", "cegoc123456");

            MailMessage mensagem = new MailMessage();
            mensagem.Sender = new MailAddress("firstname.lastname@example.com");
            mensagem.From = new MailAddress("firstname.lastname@example.com");
            mensagem.To.Add(new MailAddress("email@example.com"));
            mensagem.Subject = "Pedido de suporte Plataforma Cegos Analytics";
            mensagem.Body = "Recebeu um pedido de suporte da  Plataforma Cegos Analytics para recuperação de passwor referente ao utilizador:";
            mensagem.IsBodyHtml = false;
            mensagem.Priority = MailPriority.High;

            cliente.Send(mensagem);

        }
    }
}

E no EnviarEmail com a ajuda do @Duque e @Leonardo Coelho tenho isso:
<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

        <%--<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />--%>
        <input type="text" name="email" class="campo" /> <button type="button" class="botao">Recuperar senha</button>

    </form>

Que esta faltando para ainda não ter sucesso? Eu clico no botão e não faz nada nem submite nem nada. Me ajudem por favor
Podem-me ajudar a ver o que estou a fazer mal?
Obrigado.
Comment: Não está duplicada. editei a pergunta para me ajudarem. Coloquei mais informação. Não é duplicação
Comment: Nelson, apesar de ter código diferente, as perguntas parecem tratar exatamente do mesmo problema: enviar email ao clicar no botão. Eu li e reli e não vi distinção prática. Por isso também votei pra fechar como duplicada. Se vc não concorda, edite esta novamente pra tentar deixar ainda mais claro. Assim talvez ela seja reaberta.
Answer: O melhor caminho é fazer uma chamada Ajax, para isso:
var sendEmail  =   function () {

    $.ajax({

        type: 'POST',

        url: 'http://www.seusite.com.br/metodo',  //Aqui é a URL até o método onde está a instrução de enviar o e-mail

        dataType: 'html',

        success: function (data) {
           //Trate o retorno sem erros
        },error: function(request, status, error){
            //Trate os erros
        }

    });

}

$("#enviar").click(function () {
    //Faz a chamada da função ajax
    sendEmail();
});

Mais detalhes sobre chamadas AJAX com JQuery: Função Ajax JQuery
Comment: Obrigado Duque. Mas onde coloco este código? o url é por exemplo localhost.//Report/Recoverpassword.aspx? Obrigado
Comment: Esse codigo ficará no mesmo lugar onde está o seu código JS da página.
Se a URL que você acessa para enviar o email é: localhost.//Report/Recoverpassword.aspx, então esse é o valor a ser setado no parametro URL.
Answer: Utilizando o framework jQuery você pode usar a propriedade $.ajax desta forma.

$('.botao').on('click', function() {
 var campo = $('.campo');
 $.ajax({
  url: 'url_do_seu_metodo_php',
  method: 'post',
  data: campo.serialize(),
  success: function(resultado) { // Resultado da Consulta
   console.log(resultado); // Verifique o console
  }
 });
});
<input type="text" name="email" class="campo" /> <button type="button" class="botao">Recuperar senha</button>

Você está usando asp, este exemplo está em PHP, a diferença é só a forma como você irá capturar o post que foi enviado ao documento.
<?php
var_dump($_POST);
?>

Comment: Solução duplicada não ?


Licenses renewals prediction

Question: I have come recently to the following real world problem concerning licence renewals of a software product. I have just rudimentary knowledge of the basics in this field and I mostly interested in solving this problem, but I would love to learn something along the way.
The input is  vector of renewed licenses $(r_i)_{i=1}^n$ indexed by days and  a vector of expiring licenses for each day $(e_i)_{i=1}^{n+k}$. That is $r_i$ is number of licenses renewed on day $i$ and $e_i$ is the number of expiring licenses on day $i$. The renewals depend very much at the weekday. E.g. there are lot of renewals on Mondays and Sundays and not very much on Thursdays.
The problem is to predict or extrapolate the vector of renewals $(r_i)$ for $i=n+1, \ldots, k$.
What I find interesting about this problem is the fact that $r_i$ does not depend only on $e_i$ but also on neighbouring values since people often decide to renew the license before it expires or after it expires. In fact, you know that on average 95% of people renews the license in 60 days centred around the day their license expires and even more - you have a histogram of these renewals $(h_j)_{j=-30}^{30}$. If I understood the data correctly, the value $h_j$ represents the part of renewals that happen on average $j$ days before (or after depending on sign of $j$) the license expires for $j=-30,\ldots, 30$ and the values for $j=-30,30$ cover the renewals that happened more than one month after or before the expiry. In particular $\sum_{j=-31}^{31} h_j = 1$.
Q1: What is the best approach for this type of problem?
After some thought I came up with the following. Let $c_{ij}$ be the proportion of licenses that expire on day $j$ and are renewed on day $i$ to the total number of licenses that expire on day $j$. Then
$$
r_i = \sum_{j=1}^n c_{ij}e_j
$$
or in matrix form $r = Ce$. Moreover we have
$$
h_j \approx \frac{1}{n} \sum_{i=1}^n \frac{c_{i+j,i}}{t_i},
$$
where $t_i = \sum_{j=1}^n c_{ji}$ is the quotient of renewed licenses to all expiring licenses at day $j$. This gives me $n+60$ equations for $n^2$ variables.
Q2: Is hidden Markov model the right approach here? I know nothing about them so if this approach is the right one I would appreciate some links to materials from which I can learn the theory as well as links to implementations.
We can cut down the number of variables by setting $c_{ij} = 0$ for $|i-j| > 30$ but that still leaves us with very underdetermined system. Right now I am about to try out replacing $c_{ij}$ by $h_{i-j}t_j$. This will give me $n$ equations for $n$ unknowns. Which I can hopefully solve and then I will just extrapolate the values $p_i$ for $i=n+1, \ldots, k$ and estimate the renewals by $r_i = \sum_{j=-30}^{30} h_{i-j}t_je_j$.
Update: The solutions oscillate towards $i\to n$.
Disclaimer: Crossposted at math.stackexchange
Comment: You mention sales at one point. Did you mean 'renewals' there, or is sales another variable in the problem?
Comment: Sorry. It's a leftover from previous badly worded version of my question. I'll edit it accordingly.
Answer: The way I would approach this would be to start with that histogram, and with an "average" renewal rate.  This should be enough to give you the expected number of renewals that would occur on a particular day (by looking at how many would be expected from the 60 days in the histogram window) at an average renewal rate and average seasonality.
Next, I would accommodate daily seasonality, because you seem to indicate renewals are more likely to occur on some days of the week than others.
At the end of this would will have a baseline and can then look for patterns in the actual due to gradual declines/increases in the renewal rate, whether promotions increase the renewal rate overall or just accelerate the timing, and so forth.  That will give you an idea of how you need to model promotion effects (and introduction of competitive products).
Answer: The number of renewals could be predicted from the number of licenses expiring, the history of expired licenses , the future number of expired licenses, the day-of-the-week , the day-of-the month , holiday effects and of course level shifts and trends waiting to be discoverd . Additionally there maybe non-constant error variance which can be remedied by incororating an ARIMA structure reflecting the impact of prior renewals, changes in parameters or determinstic changes in the error process. You could also incorporate promotion effects into the model. In general this is called a Transfer Function and falls under the class of Generalized Least Squares. If you wish you can post your data or actually send it to me at email@example.com and I will post it and perform an analysis which could include some of the structure mentioned herein. Data like this is common in the cable industry.

Licenses renewals prediction


Internal Rewrite in Nginx not work, and redirected

Question: Hi I want a rewrite rule, but i don't want to redirect it, and requesting one URL but load different content from another URL.  So, I think last and break flag in rewrite directive is a good solution. But, it's always redirected, I search the problem and they state that if the new URL not from nginx instance it will redirect instead. Here several lines of my config:
...
rewrite ^(/\w+/$)(.+\.php) /$2 last;
proxy_pass upstream_name:80;
...

What i ask is how i can use rewrite but not redirected?
Update:
For example, i want to make a new like /link/asd, but there is no /link/asd in my web application. I want my /link/asd link load resource from /asd link. then, i think the rewrite last flag is a good solution. If my understanding is false, please correct me and explain it. Thank you
Comment: That `rewrite` statement is not generating the redirect.
Comment: @RichardSmith yeah it shoud not redirect. But, its actually redirected
Answer: If you want to rewrite exactly /link/example to /example, where example is anything, you can use this rewrite:
rewrite ^/link/(.+)$ /$1 last;

This will also match /link/example/something/else, as the .+ matches any characters before the end of the string ($). If you want to restrict which characters are allowed in the capture group, for example, exclude / from the capture group, one can use [^/]+ notation for the regex.
Comment: Please add the configuration file in your question about your attempt. Please include the complete `server` block.
Comment: I already use that similar rewrite configuration for instance level and it works. Although, when i use the configuration in reverse proxy level it didn't  work. Are you know why?


Difference between value and avg(value)

Question: I wonder if it is possible to make query like following one.
I have a table that contains id  and value.
Exapmle:
 table EXAMPLE
|id        |  value     |
|        1 |          65|
|        2 |          13|
|        3 |          22|

What I want is to make query that returns the set like this:
|id        |  value     | average | difference|
|        2 |          13|     33.3|       20.3|
|        3 |          22|     33.3|       11.3|

The question is how to deal with different column ?
And one more question:
 How to include in the set  only values, that are less or great then average ,
SELECT id,
       value,
       (SELECT AVG(value) FROM EXAMPLE ) as average
having
       value <  average.

The reason i am using having instead of where is that where is executing before select and therefore i cant use average in it (average is computed in the select phase of query execution).
I also suspect that I am calculating AVG(value) not only once, but for every row in the table.
Am i right ?  If i am, that is pretty bad and  it is surely not what i wanted.
Please get some light for me on the MySQL execution sequence of subqueries or share some links for this theme.
Thank you in advance.
Comment: I am terrible sorry. That was from the first version of question. Edited. Nevertheless I don't think it is important in context of question. I hope I am able to be understood.
Answer: You'll have to calculate the overall average separately and force a cross join:
SQL Fiddle
select
    id,
    value,
    avgValue,
    avgValue - value as Diff
from
    table1
  cross join
    (
      select
          avg(value) as AvgValue
      from
          table1
    ) t2
where
    value < avgValue

Comment: Thank you very much! I spend hours looking for how to accomplish this.
Answer: I think this would do it.  You need to group in order to do you aggregate functions.
SELECT id, value, (SELECT AVG(value) FROM example GROUP BY id) AS average,
       average - value AS diff
FROM example
GROUP BY id
HAVING value < average;

Comment: If yoy group by id, you get the average per id. That is not what is wanted. Also, your group by is normally illegal (since all non-aggregate columns should be in a group by). That said, the OP also has an invalid query, missing even the basic `FROM` clause...
Answer: select id, value, (select avg(value) from EXAMPLE ) as average,
   (select avg(value) from EXAMPLE ) - value as difference
   from EXAMPLE ;

Answer: This also does the trick
select id, value,
       (select avg(Value) from table1) as avg,
       (select avg(Value) from table1) - value as Diff
from table1 having Diff > 0

Comment: In this case `avg` is calculated only once or every time the new row selected ?
Comment: Good question, I think that depends on the optimizer. It should be able to recognize that the average selection is constant for all rows, and thus calculate it once, but I wouldn't dare to predict whether that is true for a specific dbms or not :)

Difference between value and avg(value)


Change log4j settings in Camel TestSupport

Question: I am debugging some jUnit tests that use the Camel TestSupport interface. This gives me access to a log4j log but I can't seem to figure out how to get a reconfigured version of that. I want to be able to change the log level since a lot of my logs are written in a trace level instead of just info or debug.
What is the best way to reconfigure this log's console output?
Thanks
Answer: You need to include a log4j.xml or log4j.properties on your classpath that you're using the test.
If you're using maven, this is easy, just put it in src/test/resources.


Largest Infinitesimal Game

Question: In combinatorial game theory, you can have infinitesimal games like up={0|*}={0|{0|0}}, and if you are allowed to use expressions that involve themselves as an option, like Off={|Off}, then you can find the smallest positive game: Tiny={0|{0|Off}} in the sense that there is no game that is less than Tiny but greater than 0.
What I want to know is: Is there a game which is in that sense the largest infinitesimal? In other words, does there exist a (infinitesimal) game G such that there is no other game H greater than G but less than all games with a real number value?
Note: There has been some confusion in the answers on what type of combinatorial games I am asking about. I want to know about the largest infinitesimal game out of all combinatorial games, including loopy and transfinite games.
Answer: The original question brings up tiny, so the context is that of loopy games. If we restrict ourselves to finite loopy games, rather than the transfinite games Ted mentions in their answer, then the answer is "yes".
In that context, over={0|over} is the largest positive infinitesimal, being the infimum of the numbers of the form $1/2^n$ for integers $n$. Note: over + over = over, saving us from the "$G+G>G$" worry that Ted brought up.
over is also the supremum of numbers of the form $n\cdot\uparrow$, which answered the revised question "Is there a game $G$ such that for any infinitesimal $H$ there is an $n$ such that $H<nG$?" if you restricted things to the finite loopfree games.
Siegel's "Combinatorial Game Theory" is a great source for all of the above.
Answer: There is no largest infinitesimal game, because if $G$ is a positive infinitesimal game, then
$G+G$ is larger, but still infinitesimal.
However, in Chapter 16 of ONAG, in the section "The Gamut Revealed", we learn that the "largest infinitesimal games" are {$\alpha\, |\, \mathbb{R}^+ || \, \mathbb{R}^+\}$ where $\alpha$ is an ordinal.  I believe this means that any infinitesimal game is smaller than some game of this form, for some choice of ordinal $\alpha$.
Comment: Based on Ted's answer, no. Any infinitesimal game will be less than some $C(\alpha) = \lbrace \alpha \, |\, \mathbb{R}^+ \, || \, \mathbb{R}^+ \rbrace$. I'm not sure whether $n \cdot C(\alpha) = C(n \alpha)$, but we know that $n \cdot C(\alpha) \le C(\alpha_n)$ for some $\alpha_n$, so if we let $\beta = \bigcup \alpha_n$, we have $n \cdot C(\alpha) \le C(\beta)$ for all $n$. For the same reason, any set of infinitesimal games will be beaten by some infinitesimal game; you need a proper class to be cofinal in infinitesimal games.
Comment: Wait, if you used {On|R+||R+}, where On={On|}, would that work? It is bigger than any game {a|R+||R+}.
Comment: @Thomas Loopy transfinite games are not often studied, but that's an interesting idea... As an aside, I edited my answer to have the answer for finite loopy games.
Comment: Ah, right. Ok, revising the question a little: Is there a game G such that every infinitesimal game H is O(G)? In other words, is there a game G such that for any H there is an n such that H<nG?

Largest Infinitesimal Game


Multiple Urns With a Pre-Defined Probability Mass Function

Question: Say we have 20 identical urns containing red and green balls; in our experiment, we will select 8 balls from each urn.
Suppose that for each individual urn, the probability of drawing k green balls out of 8 is given as follows:

k
probability

0
60.0%

1
24.5%

2
4.0%

3
3.4%

4
2.8%

5
2.2%

6
1.6%

7
1.0%

8
0.5%

In our experiment, what is the probability that we will draw a combined total of exactly 10 green balls from the 20 urns?
What method (or methods) can we use to solve this problem for the general case?
Answer: Let $\mathbb{P}(X_i=k) = a_k$ where $X_i$ is the number of green balls from the $i$-th urn. The $X_i$ are two by two independent, and we search for the law of $\sum_{i=1}^{20}X_i$.
It is easy to see that $\mathbb{P}(X_1+X_2 = n) = \sum_{k=0}^n a_ka_n-k$.
If we define the discrete convolution $f*g = \sum_{k=-\infty}^{+\infty}f(k)g(n-k)$, then we have $\mathbb{P}_{X_1+X_2} = \mathbb{P}_{X_1}*\mathbb{P}_{X_2}$.
More generally, if $X$ and $Y$ are two independent variables, we have $\mathbb{P}_{X+Y} = \mathbb{P}_{X}*\mathbb{P}_{Y}$. So we need to compute $\mathbb{P}_{X_1}*\mathbb{P}_{X_2}*...*\mathbb{P}_{X_{20}}$. The discrete convolution is associative (and commutative), so you can use exponentiation by squaring. For the convolution itself, if the number of balls grows, you can also rely on Fast Fourier Transform. For calculating the power, there are also tricks relying on the Fourier Transform.
We can link it to polynomials this way :
Let $P(x) = \sum_{i=1}^8 a_ix^i$. Then the desired value is the coefficient of $x^{10}$ in $P^{20}(x)$
Comment: Thank you for the rapid answer! The 20-term convolution seems a bit daunting to an amateur like me... is there any way to construct it using something like the Bell Polynomials?
Comment: I don't think there is something more simple and canonical than expressing it as the $20$-th power of a convolution. A convolution is not that complex, (unless we start toying with Fourier Transform, but that is not mandatory), and can be implemented easily. (lots of packages have built-in for convolution also). To compute the $20$-fold convolution, I don't see many libraries that have it (but maybe I searched too quickly). Implementing exponentiation by squaring is not very difficult.
Comment: Thank you once again; I was able to get my answer in the end using a very ...interesting method for computing the 20-fold convolution: for exactly 10 total green out of 20 urns at 8 draws each, I computed a probability of approximately 4.23%.


NodeJS Paseto Key: Unable to read the generated secret key

Question: I'm using the paseto npm package for generating a secret key and further using that key to create a token.
I might be going wrong with understanding something here, how do I store the key generated?
The following is the code:
V2.generateKey("local").then(mySecret => {
        let payload = {
            user: req.body.user
        }

        V2.encrypt(payload, mySecret, {
            expiresIn: '2 hours'
        }).then(result => {
            console.log(result);
            res.json({
                result
            })
        }).catch(err => {
            console.log(err);
            res.json({
                error: err
            })
        })
    })

How do I know what "mySecret" is and how to store it?
Answer: Thanks to my friend, I found out that this is the way to go:
mySecret.export()

This prints a buffer that can be stored.
I wanted to find out the stored token so that I could share the secret with another application, even though that's not a best practice in general.


Continuous linear operators over continuous functions

Question: a) Let $C_{[a,b]}$ be the vector space of functions continuous on $a\leq x \leq b$, with the norm
$$\|f\| = \max_{a\leq x \leq b}|f(x)|$$.
Let $K(x,y) $ be a fixed function of two variables, continuous on $a\leq x \leq b , a\leq y \leq b $ and let $A$ be the operator
$$g(x)= Af(x)= \int_{a}^{b} K(x,y)f(y)dy $$
Prove that A is a continuous linear operator mapping $C_{[a,b]}$ into itself.
b) Let $C_{[a,b]}^2$ be the space of functions continuous on $[a,b]$ with norm
$$\|f\| = \sqrt{\int_{a}^{b}f^2(x)dx}$$,
and let $A$ be the same as in part a. Prove that $A$ is a continuous linear operator mapping $C_{[a,b]}^2$ into itself.
Thoughts:
My first strategy is to try and show that the operator is in fact linear by showing that $A(\alpha x+\beta y)= \alpha Ax+ \beta Ay $. So far I have not been able to do this, but I think it would be possible for me to figure out. I can also easily show that the operator maps continuous functions to continuous functions. However, proving continuity of the operator, I am very lost.
Answer: The linearity is trivially since the integral is linear: $$\int^b_a K(x,y) [\alpha f(y) + g(y)] dy = \alpha \int^b_a K(x,y) f(y) dy + \int^b_a K(x,y) g(y) dy $$ for any $f,g \in C([a,b])$ and $\alpha \in \mathbb R$. This shows that $A(\alpha f + g) = \alpha Af + Ag.$
For continuity, note that $K$ is bounded (since it is continuous on the compact set $[a,b] \times [a,b]$). Say $\lvert K(x,y) \rvert \le M$ for all $a \le x,y \le b$. Then for any $f \in C([a,b])$ and $x \in [a,b]$, \begin{align*}
\lvert Af(x) \rvert &= \left \lvert \int^b_a K(x,y) f(y) dy \right\rvert \\
&\le \int^b_a \lvert K(x,y) \rvert \lvert f(y) \rvert dy\\
&\le \int^b_a M \| f \|_\infty dy = M(b-a) \| f\|_\infty.
\end{align*} Since this holds for all $x$, we can pass to the supremum showing that $$\| Af\|_\infty \le M(b-a) \| f\|_\infty.$$ This shows that $A$ is continuous. This concludes part (a).
For part (b), use the Cauchy-Schwarz inequality: for any $f \in C([a,b])$ and $x \in [a,b]$, \begin{align*}
\lvert Af(x) \rvert &= \left \lvert \int^b_a K(x,y) f(y) dy \right\rvert \\
&\le \int^b_a \lvert K(x,y) \rvert \lvert f(y) \rvert dy\\
&\le M \int^b_a \lvert f(y) \rvert dy \\
&\le M \left(\int^b_a 1^2 dy \right)^{1/2}\left(\int^b_a f(y)^2 dy \right)^{1/2}\\
&= M (b-a)^{1/2} \| f\|_2.
\end{align*} Thus squaring both sides, integrating and taking the square root gives $$\|A f\|_2 \le M(b-a) \| f\|_2$$ which completes part (b).
Comment: That's the supremum norm: $$\|f\|_\infty := \sup_{a\le x \le b } \lvert f(x) \rvert.$$ It's the typical norm used on $C([a,b])$ since it is the norm which makes that space complete. EDIT: I see that in the question, you use the notation $\|f \|$ for this norm.
Comment: What exactly do you mean in part a when you use the infinity symbol under the norm?