upgrading com.google.android.gcm.GCMBaseIntentService to com.google.android.gms.gcm.GoogleCloudMessaging

Question: I am trying to upgrade an old solution of google push notification based on GCM, in the further releases GCM is deprecated and com.google.android.gms.gcm.GoogleCloudMessaging is suggested to use.
There are few methods for which I did not find the alternatives in the new release like

GCMRegistrar.setRegisteredOnServer(context, true);
GCMRegistrar.getRegistrationId(this);
GCMRegistrar.register(this, SENDER_ID);
GCMRegistrar.isRegisteredOnServer(this)
GCMRegistrar.onDestroy(this);

Moreover I am referring to an old article and in that it has a service that extends GCMBaseIntentService available in the com.google.android.gcm.GCMBaseIntentService but not in new release
Can anyone help me to upgrade the below code.
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
import static com.androidhive.pushnotifications.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager; import android.app.PendingIntent;
import android.content.Context; import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super(SENDER_ID);
    }

    /**
    * Method called on device registered
    **/
    @Override
    protected void onRegistered(Context context, String registrationId) {
        Log.i(TAG, "Device registered: regId = " + registrationId);
        displayMessage(context, "Your device registred with GCM");
        Log.d("NAME", MainActivity.name);
        ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
    }

    /**
    * Method called on device un registred
    * */
    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
        displayMessage(context, getString(R.string.gcm_unregistered));
        ServerUtilities.unregister(context, registrationId);
    }

    /**
    * Method called on Receiving a new message
    * */
    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message = intent.getExtras().getString("price");

        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    /**
    * Method called on receiving a deleted message
    * */
    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
        String message = getString(R.string.gcm_deleted, total);
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    /**
    * Method called on Error
    * */
    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "Received error: " + errorId);
        displayMessage(context, getString(R.string.gcm_error, errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
        displayMessage(context, getString(R.string.gcm_recoverable_error,
             errorId));
        return super.onRecoverableError(context, errorId);
    }

    /**
    * Issues a notification to inform the user that server has sent a message.
    */
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
             context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);

        Intent notificationIntent = new Intent(context, MainActivity.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
             Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
             PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;

        //notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");

        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);
    }
}

Comment: I am referring article : http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
Comment: Unfortunately, I don't think anyone has the time to change your entire code for you. True, a lot of the Registrar methods are not available in the new library, but that's because you don't need most of them. I suggest you start [here](https://developer.android.com/reference/com/google/android/gms/gcm/GoogleCloudMessaging.html) to learn how to use the GoogleCloudMessaging object. It has the `register(senderId)` method, by the way.
Answer: Consider moving to Firebase Cloud Messaging (FCM)

As of April 10, 2018, Google has deprecated GCM. The GCM server and client APIs are deprecated and will be removed as soon as April 11, 2019. Migrate GCM apps to Firebase Cloud Messaging (FCM), which inherits the reliable and scalable GCM infrastructure, plus many new features.

Here's the migration guide


How to convert UIElement (Canvas) content (children) to BitmapImage on Windows Phone?

Question: I'm writing an app for Windows Phone 8.1 in VS 2013.
I'd like to use a WriteableBitmap, which is supposed to be in the System.Windows.Media.Imaging namespace.
But it's not.
I have no System.Windows.Media namespace.
I can't add a reference. I have two references added by the WP8 app wizard: ".Net for Windows store apps" and "Windows Phone 8.1".
Am I missing something?
Comment: the reference must be .NET for Windows Phone and not for the Store!
Answer: Windows.UI.Xaml.Media.Imaging.WriteableBitmap

You are trying to reference OLD SILVERLIGHT API's in NEW XAML API's, by using Windows.UI.Xaml.Media.Imaging you will be able to get the WriteableBitmap class in Windows Phone 8.1 & to know more this Link will help you.
Hope this is what you were looking for. See if this helps.


Element overlapping when absolute positioning applied on a Custom Tag - HTML, CSS

Question: I created a custom tag called <bubble></bubble> and its styles can be applied using the custom type attribute.
Code:

bubble[type=normal] {
  border-radius: 10px;
  background-color: #5e9bff;
  text-align: center;
  color: white;
  padding: 6px;
  width: 50px;
}
<bubble type="normal">Hello!</bubble>

The problem comes in positioning the element when placed with the div tags. First of all, the width: 50px; gets ignored unless I use Position: Absolute; which has another problem I'll describe below. Second, It partially overlays the text when

 tags are used even after applying the margins on Top and Bottom.
Code with Absolute Positioning:

bubble[type=absoluteposition] {
  position: absolute;
  border-radius: 10px;
  background-color: #5e9bff;
  text-align: center;
  color: white;
  padding: 6px;
  width: 50px;
  margin-top: 10px;
  margin-bottom: 10px;
}
<bubble type="absoluteposition">Hello!</bubble>

The problem here is position: absolute; acts like float: left; which I don't want to use even after using margins on top and bottom. This problem also occurs with div tags.
Demo in JSFiddle.net
If you have a solution OR You think there is a problem in my code OR You think there is an Alternative way to fix this problem OR You need more details on my Question, please Reply.
Comment: Add rule display: inline-block
Comment: Would work with code without Absolute Position but won't work with code with Absolute Positioning.
Comment: In terms of the first problem -- *why `width: 50px` is being ignored* -- that's because *all* elements (including custom elements) have an initial setting of `display: inline` ([**details**](http://stackoverflow.com/a/36380684/3597276)). And `width` doesn't apply to `inline` elements ([**details**](http://stackoverflow.com/a/39578948/3597276)). Set `bubble` to `display: block` or `inline-block`.
Comment: Thanks but `display: inline-block;` won't work with `position: absolute;`.
Answer: if you want to specify , height , width on above when using absolute than you may try wrap bubble tag in another div with relative position like :

<bubble type="absoluteposition">Hello!</bubble>

Cheers !


Matrix for vector transformation

Question: Say we have a matrix $L$ that maps vector components from an unprimed basis to a rotated primed basis according to the rule $x'_{i} = L_{ij} x_{j}$. $x'_i$ is the $i$th component in the primed basis and $x_{j}$ the $j$ th component in the original unprimed basis. Now $x'_{i} = \overline{e}'_i. \overline{x} = \overline{e}'_i. \overline{e}_j x_{j} $. Hence $L_{ij} = \overline{e}'_i. \overline{e}_j$. Thus the matrix equation relating the primed co-ordinate system to the unprimed one in $\mathbb{R}^3$ is
$$ \begin{pmatrix}x'_{1}\\ x'_{2}\\ x'_{3} \end{pmatrix} = \begin{pmatrix} \overline{e}'_1. \overline{e}_1 & \overline{e}'_1. \overline{e}_2 & \overline{e}'_1. \overline{e}_3\\ \overline{e}'_2. \overline{e}_1 & \overline{e}'_2. \overline{e}_2 & \overline{e}'_2. \overline{e}_1 \\ \overline{e}'_3. \overline{e}_1 & \overline{e}'_3. \overline{e}_2 & \overline{e}'_3. \overline{e}_3 \end{pmatrix}\begin{pmatrix}x_{1}\\ x_{2}\\ x_{3} \end{pmatrix} $$
Where the $\overline{e}'_i$s and $\overline{e}_j$s are unit basis vectors in the primed and unprimed co ordinate systems respectively.
Now I tried to apply the above idea to the following situation (Riley, Hobson and Bence Chapter 26, Problem 2).
I took $\mathbf{A} = \overline{e}_1$ and $\mathbf{B} = \overline{e}_2$. It turns out that the matrix that transforms $\mathbf{A} \rightarrow \mathbf{A}' $ and $\mathbf{B} \rightarrow \mathbf{B}' $ is not the matrix that transforms the unprimed components to the primed components (that I used above) but the INVERSE (or transpose) of that matrix. I need to know where I am going wrong here. Thank you.
Answer: I think I've found my mistake here. The $\overline{e'_{i}}$ refer to the new basis vectors (i.e. the basis vectors in the rotated frame) and NOT the components of the old basis vectors in the rotated frame. Hence we have:
$$ \overline{e'_{1}} = \begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}$$
$$ \overline{e'_{2}} = \begin{pmatrix} 0 \\ 1 \\ 0 \end{pmatrix}$$
$$ \overline{e'_{3}} = \begin{pmatrix} 0 \\ 0 \\ 1 \end{pmatrix}$$
in the NEW frame. Furthermore, to evaluate the dot products we need components in the same frame. Now we know the components of $\mathbf{A}$ and $\mathbf{B}$ in the rotated frame. So, for example,
$$ L_{21}=\overline{e'_2}.\overline{e_1} = \begin{pmatrix} 0 \\ 1 \\0 \end{pmatrix}.\frac{1}{2} \begin{pmatrix} \sqrt{3} \\0 \\ 1\end{pmatrix}  = 0$$.
and so on and so forth.

Matrix for vector transformation


How to download attachment from OERP using oerplib

Question: I am working on a project moving data from Open ERP to Xero. I am stuck on moving attachments. I am using a Python lib oerplib 0.8.3. I can't find a way to download an attachment or is there a way to move them directly to Xero from Open ERP.
Using the usual oerplib methods I have managed to get some data on attachments:
attachment_obj = oerp.get('ir.attachment')
attachment_ids = attachment_obj.search([])

Sample Data:
{
    "create_date": "2013-10-09 08:35:07",
    "file_type": "application/vnd.oasis.opendocument.spreadsheet",
    "res_model": "project.task",
    "write_uid": 4,
    "res_name": "Map Categories",
    "db_datas": "False",
    "file_size": "27278",
    "partner_id": 44,
    "id": "111",
    "create_uid": 4,
    "user_id": 4,
    "company_id": 1,
    "parent_id": "False",
    "index_content": "",
    "type": "binary",
    "store_fname": "5a2/5a264e792eaa5305879a89e7ce2cbb6bd0099fcd",
    "description": "False",
    "write_date": "2013-10-09 08:35:07",
    "name": "Codes(1).ods",
    "url": "False",
    "res_id": "44",
    "datas": "",
    "datas_fname": "Codes(1).ods"
}

Any help is highly appreciated.
Answer: After digging through Open ERP docs, I found out that attachments are saved as base64 encoded strings in DB unless the document addon is set up. So for anyone else who may find themselves stuck just read the data from datas property of the attachment resource object
attachment_obj = oerp.browse('ir.attachment', 17)
attachment_data = attachment_obj.datas


can't start play! server on ec2 (play! framework)

Question: recently i have created a new ec2 instances (quick launch ) and i tried to deploy my Play! application the security group gives access to port 80 and port 22 (SSH)
but when i run :
play start 80

it gives me this
[error] org.jboss.netty.channel.ChannelException: Failed to bind to: /0.0.0.0:80
[error] Use 'last' for the full log.

which means that the 80 port is used
when i run
netstat -tlnp

i get
    Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      3692/sendmail
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      3653/sshd
tcp        0      0 :::22                       :::*                        LISTEN      3653/sshd

i've searched all the web but i didn't figure it out, help me please !
NOTE : i just solve this all i have to do is start it with sudo.
Comment: Are you trying to start the Play! application as root (i.e. with sudo)? You need superuser privileges to bind to ports below 1024. Also, the second line of the error says to 'use last for the full log'. What is displayed in the 'full log'?
Comment: i just figured out, i'm dumb actually i just have to run with sudo.
thank you!
Answer: Since you're binding to a port below 1024, it must be started with root privileges.
Try something like:
sudo play start 80

Comment: Is it safe to do that?
Comment: I wouldn't think so.
Comment: So what's a safe way to bind to port 80?
Comment: That's a whole other question entirely.
Comment: @MichaelHampton not helpfull, i got error sudo: `play: command not found`,
Answer: To deploy on EC2 you should create a standalone version of your application in your local machine using:
play dist

Then you copy the generated .zip to your EC2 instance using scp, unzip it using unzip.
You would then want to run your application like so:
sudo nohup yourAppName-version/bin/yourAppName -Dhttp.port=80

sudo in order to be able to bind to a port below 1024.
nohup in order to be able to exit the ssh session without sending the HUP signal to your play app.
yourAppName-version/bin/yourAppName replaced with YOUR app's name & version should be where your script is.
-Dhttp.port is the option to bind to a given port.

Additional Info: You should consider adding -J-Xms128M -J-Xmx512m to avoid RAM allocation problems (I use micro instances, adjust to your needs).


Limit the number of nodes per User

Question: How to limit user for adding new nodes?
For example:
Users can not Create/Add more than One post for specific Content Type.
Answer: To limit users from adding more than one node for a specific content type, you can use the hook hook_form_alter() to alter the node form and disable the submit button if the user has already created a node for that content type. Here's an example code snippet:
function my_module_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'node_form' && $form['#node']->type == 'my_content_type') {
    $node_count = db_query("SELECT COUNT(*) FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'my_content_type', ':uid' => $user->uid))->fetchField();
    if ($node_count > 0) {
      $form['actions']['submit']['#attributes']['disabled'] = 'disabled';
    }
  }
}

In this code, you first check if the current form being altered is a node form for our desired content type. Then, we count the number of nodes that have been created by the current user for that content type. If the count is greater than zero, then disable the submit button.
To add a specific limit number for user role type, you can modify the above code to check for the user's role and apply different limits accordingly. Here's an example:
function my_module_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'node_form' && $form['#node']->type == 'my_content_type') {
    switch ($user->roles[3]) { // assuming the role ID we want to limit is at index 3
      case 'editor':
        $limit = 5; // limit editors to 5 nodes
        break;
      case 'contributor':
        $limit = 3; // limit contributors to 3 nodes
        break;
      default:
        $limit = 1; // default limit for all other users is 1 node
        break;
    }
    $node_count = db_query("SELECT COUNT(*) FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'my_content_type', ':uid' => $user->uid))->fetchField();
    if ($node_count >= $limit) { // use >= instead of > to allow users to edit existing nodes
      $form['actions']['submit']['#attributes']['disabled'] = 'disabled';
    }
  }
}

In this code, you first check the user's role and set a specific limit for each role. Then, it count the number of nodes created by the user for the desired content type and compare it with the limit. If the count is greater than or equal to the limit, it disable the submit button.
I hope this help!
Comment: Thanks for the Help!
Answer: The Node Limit module does exactly that:

The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create.

Among its features are:

Per-role node limits
Per-user node limits
Per-time interval node limits
Any combination of the above

Limit the number of nodes per User


Why there is no main() method in android?

Question: A Java program execution starts from main() method. Right? Since Android apps run on Java, Then why we didn't create a main() method in Android studio?
Answer: There's one, but you don't need to see it. Android takes care of threading and keeping threads organized for you, see here.
Moreover, the entry point for an activity is the onCreate() method, so all initialization is normally done in there. The first activity run by your app is normally specified in the manifest file under the launcher keyword.
See here to know more about how android runs the launcher activity.
Comment: Can you explain little more?
Comment: The article I referenced has a nice image showing the steps from calling the main() function in the ActivityThread class to calling the onCreate() function from an activity. It's pretty neat :)


Tfs not working on hosting application to IIS

Question: ***strong text***On localhost i am able to login to TFS with the help of that i am generating list.
But when i am deploying this code to IIS it is not asking for the credentials as no dialog box for credential it is asking  and i am unable to generate list.
Is it possible to host TFS application TO IIS?
I
Comment: Please add a little more detail on what you're doing. It looks like you may be trying to generate some kind of report or for on top of data in TFS and you're expecting IIS to handle the impersonation for you to connect to TFS. It's unclear how you've configured IIS to authenticate... It's unclear how you are passing the credential to TFS. It's unclear what services on TFS you're calling. Are they REST calls? SOAP calls? Are you using the TFS Client Object Model?
Comment: From a license perspective, be sure to read the Visual Studio and TFS license whitepaper. If you're impersonating your users to TFS, each of these users needs a TFS CAL. http://www.microsoft.com/en-us/download/details.aspx?id=13350
Comment: @jessehouwing Please check the screenshot.
Comment: Iis is probably configured to allow anonymous access and isn't configured for Windows auth.
Comment: @jessehouwing But while giving my credentials in application pools i am able to generate list..But it's not good to give my credentials..so for that i used popup thing to give his/her credentials
Comment: Yeah so enable Windows auth on the virtual directory/site and configure asp.net to apply impersonation from the web.config.
Answer: To configure ASP.NET to impersonate the Windows identity supplied by IIS as the WindowsIdentity for the ASP.NET application, edit the Web.config file for the application and set the impersonate attribute of the identity configuration element to true, as shown in the following example.
<code><configuration>
  <system.web>
    <identity impersonate="true" />
  </system.web>
</configuration>
</code>


More about the deterministic part of Wold decomposition

Question: This is a follow-up on this question of mine. Wold's representation theorem states that every covariance-stationary time series $\{Y_t\}$ can be written as the sum of two time series, one deterministic and one stochastic:
$$
Y_t = \mu_t + \sum_{j=0}^\infty b_j\varepsilon_{t-j}
$$
where $\{\mu_t\}$ is the deterministic one. According to Hansen "Econometrics" (2022) p. 472, $\mu_t$ is the projection of $Y_t$ on the history of infinite past: $\mu_t=\lim_{m\rightarrow\infty} \mathcal{P}_{t-m}(Y_t)$. For example, it could be
$$
\mu_t = \left\{ \matrix{ (-1)^t \ \ \ \ \text{with probability 1/2} \\ (-1)^{t+1} \ \text{with probability 1/2} } \right\}.
$$
Now if we observe only a single path of the stochastic process, we only face one of the two cases, either $\mu_t=(-1)^{t}$ or $\mu_t=(-1)^{(t+1)}$. Without additional information, we would probably just model that component as deterministic, thinking that $\{Y_t\}$ is not stationary but $\{Y_t-\mu_t\}$ is. I do not think this would cause any trouble for modeling and predicting the future elements in that path, even though it would mess up inference about the stochastic process itself and predictions of its other paths.
Thinking back about my original question (linked at the very beginning), I can say, if only all instances of Wold's decomposition were this nice! Are they, perhaps? Or does there exist a case in which $\{\mu_t\}$ is not completely deterministic within a single path?
Comment: glad to hear it. way back when, I asked him some questions about that document and he answered them one by one in a latex document with detailed notation-explanations etc. I was shocked.
Comment: Hi Richard: I'm not certain about your example above but the last part of the christiano document explains why the deterministic part cannot be a time trend and why his specific example works. Also, there's a 23 page proof of the wold decomposition theorem by Herman Bierens. I read it once like 7 years ago. All I can say and remember is that it's more understandable than the informal proof that christiano ( really sargent ) provides. If you can't find it and you're interested,  let me know. I know it's somewhere on the net but my eyes are closing.
Comment: @mlofton, thank you. I found a [26 page document](https://www.docsity.com/en/the-wold-decomposition/8246747/) on a site that won't let me download it without registering and earning some points on that site. I have not looked very hard elsewhere, but the document does not seem to be floating anywhere right on the surface (except for the case above). I sent prof. Bierens an e-mail, perhaps he will share the document with me...
Comment: Hi Richard: I remember it not being easy to find but that must be it. He's a very generous and kind person. I think he's Emeritus now but I bet he'll respond. If he doesn't, let me know and I'll give a search a shot. and you're welcome. It's the only proof I know that doesn't skip steps.
Comment: @mlofton, already got his answer with the document attached. Hats off to the gentleman!
Comment: One last thing I noticed  about your example above: The expectation of $\mu_t = 0$ so it doesn't violate stationarity there either.
Answer: $\mu_t$ is unfortunately called "deterministic", because its defining property is that it is "completely determined" by past values of the process, it is a "deterministic function" of the past values of the process:
$$\mu_t = h(Y_{t-1}, Y_{t-2},...)$$
But this means that $\mu_t$ is a stochastic process, and one that it must be covariance-stationary, otherwise it could not be a component of a stationary process (given that its other component in the Wold decomposition is stationary). It can be a degenerate process, a constant, which is trivially stationary. The mention that existed in the wikipedia article

$\mu_t$ is a deterministic time series, such as one represented by a
sine wave.

was totally misleading, because it conveyed the sense that $\mu_t$ can be any process (so not necessarily covariance-stationary). But this is not correct. I write "was" because I just corrected the wikipedia entry.
The example given in Sargent (1987) Macroeconomic Theory (2nd ed) p. 289 is illuminating, because it does formulate $\mu_t$ using $\cos$ and $\sin$, but in a way that the process is covariance stationary.
Sargent models
$$\mu_t = \sum_{j=1}^{m} [a_j \cos(\lambda_jt) + b_j \sin(\lambda_jt)]$$
where $\lambda_j \in [-\pi, \pi]$, while $a_j, b_j$ are random variables (that do not change with $t$), with
$$E(a_j) = E(b_j) = E(a_jb_j) = E(a_ja_k) = E(b_jb_k)= 0 ,\quad j\neq k,$$
$$E(a_j^2) = E(b_j^2) =\sigma_j^2.$$
Obviously, $E(\mu_t) = 0$. As for the covariance, we have (setting $m=1$ for simplicity, it does not affect the result),
\begin{align}
{\rm Cov}(\mu_t, \mu_{t-\ell}) &= E\Big\{\big[a_1 \cos(\lambda_1t) + b_1 \sin(\lambda_1t)\big]\cdot \big[a_1 \cos[\lambda_1(t-\ell)] + b_1 \sin[\lambda_1(t-\ell)]\big]\Big\}\\
&=\sigma^2_1 \cdot\Big[\cos(\lambda_1t)\cdot \cos[\lambda_1(t-\ell)] + \sin(\lambda_1t)\cdot \sin[\lambda_1(t-\ell)]\Big]
\end{align}
Then we invoke the trigonometric identity
$$\cos\gamma \cdot \cos \delta + \sin \gamma \cdot \sin \delta = \cos(\gamma-\delta)$$
to get
\begin{align}
{\rm Cov}(\mu_t, \mu_{t-\ell}) &=\sigma^2_1 \cdot \Big[ \cos\big[\lambda_1t - \lambda_1(t-\ell)\big]\Big]\\
\\
&= \sigma^2_1 \cdot \cos\left[\lambda_1\ell\right]
\end{align}
So the covariance of the process $\mu_t$ does not depend on the index $t$, but only on the distance $\ell$ between two instances of the process, and we have covariance stationarity of $\mu_t$.
We see that while we can use "sine and cosine" to model $\mu_t$, at the same time the whole setup must be such that it preserves covariance-stationarity of $\mu_t$: All the properties of the $a_j, b_j$ random variables are needed to arrive at the covariance-stationarity result. For example, if we had $E(a_1^2) \neq E(b_1^2)$ we would not arrive at the trigonometric identity which allowed us to eliminate $t$ from the covariance function.
Comment: Thank you for your answer! It seems to address a somewhat different point than I am asking about. I wonder what you think about the more specific question I have in this post. Even so, I found your answer stimulating and I think I might have understood the gist of the matter. (I may still find out I have not, though.) Also, I think you probably need a limit in $\mu_t=h(Y_{t-1}, Y_{t-2},\dots)$ so that the past is not recent but distant.
Comment: My current understanding of $\mu_t$ is that it is **predetermined** within a path, for every future time point in the path. In other words, it is perfectly predictable within the path, even though each path forks out in every time instance. It stays the same in each branch stemming from the same origin in the infinite past. Thus when we observe a single path, we know the pattern of $\mu_t$ will continue deterministically in every branch of this process in the future.
Comment: @RichardHardy I got rather confused as I read presentations of Wold decomposition in various sources. So I found Wold's original book, and I will post a question on the matter, providing the source material and asking for explanations on how it evolved into the modern presentations.
Comment: @RichardHardy  This is the best I can do for the topic, https://stats.stackexchange.com/q/636863/28746


Return a PHP page as an image

Question: I am trying to read a image file (.jpeg to be exact), and 'echo' it back to the page output, but have is display an image...
my index.php has an image link like this:

and my php script does basically this:
1) read 1234.jpeg
2) echo file contents...
3) I have a feeling I need to return the output back with a mime-type, but this is where I get lost
Once I figure this out, I will be removing the file name input all together and replace it with an image id.
If I am unclear, or you need more information, please reply.
Comment: Just add some security so that attacks like `` can be avoided
Answer: The PHP Manual has this example:
<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;
?>

The important points is that you must send a Content-Type header. Also, you must be careful not include any extra white space (like newlines) in your file before or after the <?php ... ?> tags.
As suggested in the comments, you can avoid the danger of extra white space at the end of your script by omitting the ?> tag:
<?php
$name = './img/ok.png';
$fp = fopen($name, 'rb');

header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

fpassthru($fp);

You still need to carefully avoid white space at the top of the script. One particularly tricky form of white space is a UTF-8 BOM. To avoid that, make sure to save your script as "ANSI" (Notepad) or "ASCII" or "UTF-8 without signature" (Emacs) or similar.
Comment: To that end, some (including Zend, PEAR, or both -- I forget) recommend omitting the closing ?>.  It's perfectly syntactically valid, and guarantees no issues with trailing whitespace.
Comment: But, but... it's weird not to close what one open's :-)
Comment: Totaly agree with Frank Farmer, a code without the ending ?> will be easier to debug.
It's just a really useful tip.
And to answer to Jared Farrish, easier here do mean better, it's right, and it should be used everywhere, since your code should not be bugged or anything, if you don't put it, it will advert you if there are some errors.
It saves a lot of debugging times.
Comment: Don't omit the ?>. "Easier" doesn't mean "better".
Comment: Agreed, omit the closing `?>`.  @Jared Farrish; why do you think it is better not to?
Comment: I just consider it to be a better practice, "close your tags". I don't have any fancy answer, but it's two letters and semantically, I just think it's more complete. That's just my opinion. :)
Comment: agreed, omit it.  Technically it's more correct, because we don't want the PHP parsing to ever end on the script in question.
Comment: instead of hardcoding your header, you could just add: $size = getimagesize($filename); header("Content-type: {$size['mime']}");
Comment: Eliminating bugs and potential bugs is the best practice by far.  This case is a clear counter-example to "close your tags".  Give your head a shake.
Comment: WARNING : `filesize($name)` will break the script if your $name is a url.
Comment: Good example from the docs, but the page says "If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call." so [`readfile`](http://php.net/manual/en/function.readfile.php) is better and more efficient in this case.
Comment: Thank you for the White Space warning.
Comment: Ommitting the closing ?> tag seems very "experienced knowledge only" type stuff.  Maybe the practice should be documented (i.e. wherever you omit the closing tag, put a line at the end of the code that explains why it isn't present).
Answer: I feel like we can make this code a little bit easier by just getting the mime type from $image_info:
$file_out = "myDirectory/myImage.gif"; // The image to return

if (file_exists($file_out)) {

   $image_info = getimagesize($file_out);

   //Set the content-type header as appropriate
   header('Content-Type: ' . $image_info['mime']);

   //Set the content-length header
   header('Content-Length: ' . filesize($file_out));

   //Write the image bytes to the client
   readfile($file_out);
}
else { // Image file not found

    header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");

}

With this solution any type of image can be processed but it is just another option. Thanks ban-geoengineering for your contribution.
Comment: The code `header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");` can be used if the file does not exist and a notification of this in the response is required.
Comment: The `fpassthru` docs page says "If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call." so [`readfile`](http://php.net/manual/en/function.readfile.php) is better than `fpassthru` as it is more efficient in this case.
Comment: The variable `$fileOut` should contain the file name:

`$fileOut = "your_file_name.png";`
Comment: @ban-geoengineering — no, I don't, and it seems that there are no viable alternatives out there on the 'net (or, if there are, Google can't find them...). It was not a 'complaint', mind you, just a note — although these days I'd guess that most PHP installations will have GD built-in, some won't, thus my note.
Comment: @Edward and metatron, thanks for your responses. I've now updated my answer and code accordingly.
Comment: Note that this requires PHP being compiled with GD (because of `getimagesize()`).
Comment: @GwynethLlewelyn Do you know of an alternative to `getimagesize()` that doesn't require GD?
Answer: I worked without Content-Length . maybe reason work for remote image files
// open the file in a binary mode
$name = 'https://www.example.com/image_file.jpg';
$fp = fopen($name, 'rb');

// send the right headers
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: January 01, 2013'); // Date in the past
header('Pragma: no-cache');
header("Content-Type: image/jpg");
/* header("Content-Length: " . filesize($name)); */

// dump the picture and stop the script
fpassthru($fp);
exit;

Answer: Very, very easy.
<?php

//could be image/jpeg or image/gif or whatever
header('Content-Type: image/png')
readfile('image.png')
?>

Answer: This should work. It may be slower.
$img = imagecreatefromjpeg($filename);
header("Content-Type: image/jpg");
imagejpeg($img);
imagedestroy($img);

Comment: This requires PHP having GD compiled in.
Comment: I don't see any need for getting GD library involved for this.
Answer: Another easy Option (not any better, just different) if you aren't reading from a database is to just use a function to output all the code for you...
Note: If you also wanted php to read the image dimensions and give that to the client for faster rendering, you could easily do that too with this method.
<?php
  Function insertImage( $fileName ) {
    echo '';
  }
?>

    This is my awesome website.

    <?php insertImage( '1234.jpg' ); ?>

    Like my nice picture above?

Comment: This "answer" would work, but **does not address this page's question stated above. Answers should always answer the original question.**
Comment: Imho if you want hide location of picture, put base64 encrypted source into img tag. **But this is not what he asked.** `src="data:image/png;base64,[...]"`

Return a PHP page as an image


What is the best way to have user specific numbering in Django?

Question: I'm making a web site for a friend for a small business, and for each user, I want them to be able to access their orders by number which starts from 1 for each user, but in the backend this should be a global numbering. So for each user, their first order will be at /orders/1/ and so on. Is there a consensus on how this should be achieved in general? Way I see it, I can do this 2 ways:
Store the number in another column in the orders table. I'd prefer not to do this because I'm not entirely sure how to handle deletions without going through and updating all the records of the user. If someone knows the edge cases I need to handle, I might go with this.
OR
For every queryset I make when getting the orders page for each user I handle the numbering, benefit of this is that it will always give the correct numbering, especially if I just do it in the template. Right now this seems easier, but I have a feeling this would give rise to problems in the future. Main problem I see is I'm not sure how to make it link to the correct url without the primary key being in that url.
Answer: I recommend you to store MyUser in a separate app, say accounts
class MyUser(BaseUser):
    # extra fields

And store Order in a separate app, say order
from accounts.models import MyUser

class Order(models.Model):
    user = models.ForeignKey(MyUser)
    order_num = models.IntegerField()
    # other fields

keep update this order_num by the count of orders the user has made.
to get the count,
count = Order.objects.filter(user==request.user).count()


Understanding Galerkin method of weighted residuals

Question: I have a puzzlement regarding the Galerkin method of weighted residuals. The following is taken from the book A Finite Element Primer for Beginners, from chapter 1.1.
If I have a one dimensional differential equation $A(u)=f$, and an approximate solution $U^N = \sum_{i=1}^N a_i \phi_i(x) $, and the residual $r^N = A(u^N)-f$. The Galerkin method is to enforce that each of the individual approximation functions $\phi_i$ will be orthogonal to the residual $r^N$. So in mathematical formulation is reads:
$$ \int_0^L r^N (x) a_i \phi_i(x) dx = a_i \int_0^L r^N (x)  \phi_i(x) dx =0    \Rightarrow \int_0^L r^N (x)  \phi_i(x) dx =0 \, .$$
Then, in the above equation we have to solve $N$ equations for $N$ unknowns, to find the $a_i$. But if $a_i$ are canceled here, how do I solve for them?
Comment: They are not cancelled, they are included in $r^N$
Comment: I highly recommend this book: Computational Galerkin Methods | C. A. J. Fletcher
Comment: Thanks, got it!
Answer: To be more specific, suppose that we have the following one-dimensional differential equation:
$$
\frac{d^2 T}{dx^2} = p^2 T(x)
$$
With boundary conditions:
$$
T(0)=1 \quad \mbox{and} \quad \left.\frac{dT}{dx}\right|_{x=1} = 0
$$
It (approximately) describes heat conduction in a cooling rib: dimensionless coordinate $x=$ real coordinate divided by length $L$ ; dimensionless temperature $T:=(T-T_0)/(T_w-T_0)$ , with $T=$ real temperature , $T_w=$ wall temperature , $T_0=$ ambient temperature ; dimensionless constant $p^2=\alpha L^2/(\lambda H)$ , with $\alpha=$ heat transfer coefficient , $L=$ length ,  $\lambda=$ conductivity , $H=$ half thickness of cooling rib.

In order for a numerical solution with FEM to be feasible, a so-called
weak formulation is set up, with an arbitrary non-zero function $\,f$ , called test function:
$$
\int_0^1 \left[\frac{d^2 T}{dx^2} - p^2 T\right]f(x)\,dx = 0
$$
First we have the usual partial integration trick for second order derivatives:
$$
\int_0^1 \frac{d^2 T}{dx^2}f(x)\,dx = \int_0^1 f(x)\,d\left(\frac{dT}{dx}\right) =\\
\left[f(x)\frac{dT}{dx}\right]_0^1 - \int_0^1 \frac{dT}{dx}\frac{df}{dx}\,dx
$$
Taking notice of the boundary condition for $\,dT/dx\,$ at $\,x=1\,$ and assuming that $\,f(0)=0\,$ we thus have:
$$
\left[f(x)\frac{dT}{dx}\right]_0^1 = 0 \quad \Longrightarrow \quad
\int_0^1 \left[\frac{d^2 T}{dx^2} - p^2 T\right]f(x)\,dx =\\
- \int_0^1 \left[\frac{dT}{dx}\frac{df}{dx} + p^2 T(x)f(x)\right]dx = 0
$$
This is our Finite Element Mesh / Finite Difference Grid:

Assume a linear
isoparametric interpolation at each of the finite elements, with local coordinate $\,-1/2 < \xi < +1/2$ :
$$
f(\xi) = \left(\frac{1}{2}-\xi\right)f_i + \left(\frac{1}{2}+\xi\right)f_{i+1} \\
T(\xi) = \left(\frac{1}{2}-\xi\right)T_i + \left(\frac{1}{2}+\xi\right)T_{i+1} \\
x(\xi) = \left(\frac{1}{2}-\xi\right)x_i + \left(\frac{1}{2}+\xi\right)x_{i+1}
$$
From the last equation it follows that isoparametric transformations are not really needed with linear 1-D elements,
because we can easily express local in global coordinates:
$$
\xi = \frac{x-(x_i+x_{i+1})/2}{x_{i+1}-x_i}
$$
Whatever. The weak formulation integral is taken over the whole 1-D grid:
$$
\int_0^1 \left[\frac{dT}{dx}\frac{df}{dx} + p^2 T(x)f(x)\right]dx = \\
\sum_{i=1}^{N-1} \int_{-1/2}^{+1/2}\left[\left(\frac{dT}{d\xi}\frac{d\xi}{dx}\right)\left(\frac{df}{d\xi}\frac{d\xi}{dx}\right)
+ p^2 T(\xi)f(\xi)\right]\frac{dx}{d\xi}\,d\xi = 0
$$
With:
$$
\frac{dx}{d\xi} = x_{i+1}-x_i \quad \Longrightarrow \quad \frac{d\xi}{dx} = \frac{1}{x_{i+1}-x_i} \quad ; \quad
\frac{dT}{d\xi} = T_{i+1}-T_i \quad ; \quad \frac{df}{d\xi} = f_{i+1}-f_i
$$
Hence:
$$
\sum_{i=1}^{N-1} \int_{-1/2}^{+1/2} \left[\left(\frac{T_{i+1}-T_i}{x_{i+1}-x_i}\right)
\left(\frac{f_{i+1}-f_i}{x_{i+1}-x_i}\right) \\ + p^2 \left\{\left(\frac{1}{2}-\xi\right)T_i+\left(\frac{1}{2}+\xi\right)T_{i+1}\right\}
\left\{\left(\frac{1}{2}-\xi\right)f_i+\left(\frac{1}{2}+\xi\right)f_{i+1}\right\}\right](x_{i+1}-x_i)\,d\xi = 0
$$
The following integrals remain to be calculated:
$$
\int_{-1/2}^{+1/2} \left(\frac{1}{2}-\xi\right)^2 d\xi = \frac{1}{3} \quad ; \quad
\int_{-1/2}^{+1/2} \left(\frac{1}{2}+\xi\right)^2 d\xi = \frac{1}{3} \quad ; \quad
\int_{-1/2}^{+1/2} \left(\frac{1}{4}-\xi^2\right) d\xi = \frac{1}{6}
$$
Consequently:
$$
\sum_{i=1}^{N-1} \left[\frac{(T_{i+1}-T_i)(f_{i+1}-f_i)}{(x_{i+1}-x_i)^2}
+ p^2\left\{\frac{1}{3}\left(T_i f_i + T_{i+1} f_{i+1}\right)
+ \frac{1}{6}\left(T_i f_{i+1} + T_{i+1} f_i\right)\right\}\right](x_{i+1}-x_i) = 0
$$
With a little bit of matrix algebra the above is "simplified" to:
$$
\sum_{i=1}^{N-1} \begin{bmatrix} f_i & f_{i+1} \end{bmatrix}
\begin{bmatrix} 1/(x_{i+1}-x_i)^2+p^2/3 & -1/(x_{i+1}-x_i)^2+p^2/6 \\
-1/(x_{i+1}-x_i)^2+p^2/6 & 1/(x_{i+1}-x_i)^2+p^2/3 \end{bmatrix}(x_{i+1}-x_i)
\begin{bmatrix} T_i \\ T_{i+1} \end{bmatrix} = 0
$$
Or:
$$
\sum_{i=1}^{N-1} \begin{bmatrix} f_i & f_{i+1} \end{bmatrix}
\begin{bmatrix} E_{0,0}^{(i)} & E_{0,1}^{(i)} \\
E_{1,0}^{(i)} & E_{1,1}^{(i)} \end{bmatrix}
\begin{bmatrix} T_i \\ T_{i+1} \end{bmatrix} = 0
$$
With upper index for the elements and lower indexes for the local nodes.
$$
E_{0,0}^{(i)} = E_{1,1}^{(i)} = 1/(x_{i+1}-x_i)+(x_{i+1}-x_i)p^2/3 \\
E_{0,1}^{(i)} = E_{1,0}^{(i)} = -1/(x_{i+1}-x_i)+(x_{i+1}-x_i)p^2/6
$$
It is observed that the usual Finite Element assembly scheme is emerging:
$$
\begin{bmatrix} f_1 & f_2 & f_3 & f_4 & f_5 & \cdots \end{bmatrix} \times \\
\begin{bmatrix} E_{0,0}^{(1)} & E_{0,1}^{(1)} & 0 & 0 & 0 & \cdots \\
E_{1,0}^{(1)} & E_{1,1}^{(1)}+E_{0,0}^{(2)} & E_{0,1}^{(2)} & 0 & 0 & \cdots \\
0 & E_{1,0}^{(2)} & E_{1,1}^{(2)}+E_{0,0}^{(3)} & E_{0,1}^{(3)} & 0 & \cdots \\
0 & 0 & E_{1,0}^{(3)} & E_{1,1}^{(3)}+E_{0,0}^{(4)} & E_{0,1}^{(4)} & \cdots \\
\cdots & \cdots & \cdots & \cdots & \cdots & \cdots \end{bmatrix}
\begin{bmatrix} T_1 \\ T_2 \\ T_3 \\ T_4 \\ T_5 \\ \cdots \end{bmatrix} = 0
$$
The above must hold for arbitrary values $\,f(x)\,$ of the test function at the nodal points. Which effectively means that each
of the (linear) equations must hold: thus we can simply strike out the $\,\begin{bmatrix} f_1 & f_2 & f_3 & f_4 & f_5 & \cdots \end{bmatrix}\,$ vector.
So now it's understood why the   Galerkin method is to enforce that each of the individual approximation functions will be orthogonal to
the residual .There is one sole exception, however, at the leftmost boundary condition, where $\,f(0) = f_1 = 0$ .
Which means that $T_1=1$ must be imposed separately.
SOFTWARE. For comparison purposes, the analytical solution of our differential equation is:
$$
T(x) = \frac{\cosh(p(1-x))}{\cosh(p)}
$$
Free (Delphi Pascal) source code belonging to the answer shall be available at this webpage:
MSE publications / references 2018 .
Running the program gives the following output.
Graphical, numerical in $\color{red}{\mbox{red}}$, analytical in $\color{green}{\mbox{green}}$ (can hardly be distinguished):

Textual, numerical on the left, analytical on the right:

Matrix size = 20 x 2
 1.00000000000000E+0000 = 1.00000000000000E+0000
 7.68056069295067E-0001 = 7.68644696945751E-0001
 5.89922699260035E-0001 = 5.90827538134464E-0001
 4.53119737860691E-0001 = 4.54163086269633E-0001
 3.48062671220386E-0001 = 3.49132299372698E-0001
 2.67391125683798E-0001 = 2.68419504231858E-0001
 2.05453194744393E-0001 = 2.06402840336432E-0001
 1.57909462409220E-0001 = 1.58762682363700E-0001
 1.21428980593141E-0001 = 1.22180766804612E-0001
 9.34559005000764E-0002 = 9.41090660988799E-0002
 7.20304080179462E-0002 = 7.25923117492373E-0002
 5.56514177323092E-0002 = 5.61318046784788E-0002
 4.31714058025089E-0002 = 4.35810268590056E-0002
 3.37160136159951E-0002 = 3.40657832876774E-0002
 2.66227895950111E-0002 = 2.69233119824588E-0002
 2.13947773625612E-0002 = 2.16561208504369E-0002
 1.76656986211829E-0002 = 1.78973360424821E-0002
 1.51742914319659E-0002 = 1.53851482154401E-0002
 1.37460060151894E-0002 = 1.39445768161580E-0002
 1.32807756672024E-0002 = 1.34752822213045E-0002


Characteristic equation on a particular curve

Question: Find the solution of $bg_x+g_y =  0$ which takes value of $g=e^{-{x^2}}$ on the line $y=-x$.
I cannot see how to incorporate the line in my solution as I am used to dealing with initial value problems like this.
Comment: b cannot equal 1
Answer: The idea is that $bg_x + g_y = 0$ implies that if we define the line $\mathbf{x}(s)=(a,-a)+(b,1)s$ with $a$ a constant, then by the chain rule $g$ is constant on these lines. As long as these lines aren't parallel to the initial data you've been given, that means that you can work out what value $g$ takes at a given point $(x,y)$ by working out which line of the above form $(x,y)$ lies on, and then seeing which point on $y=-x$ also lies on this line (call this point $(\gamma,-\gamma)$ - since $g$ is constant on these lines, $g(x,y)=g(\gamma,-\gamma)=e^{-\gamma^2}$.
The only thing left for you to do is algebraically express $\gamma$ in terms of x and y.
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
According to Characteristic Method: $\dot{x} = b$ and $\dot{y} = 1\quad\imp\totald{y}{x} = {1 \over b}\quad\imp\quad y - {x \over b} = \mbox{constant}$:
$$
{\rm g}\pars{x,y} = \fermi\pars{y - {x \over b}}\quad\imp\quad
\fermi\pars{-{b + 1 \over b}\,x} = \expo{-x^{2}}\quad\imp\quad
\fermi\pars{t} = \exp\pars{-\,{b^{2} \over \bracks{b + 1}^{2}}\,t^{2}}
$$
$$
\color{#00f}{\large{\rm g}\pars{x,y}} = \exp\pars{-\,{b^{2} \over \bracks{b + 1}^{2}}\,\bracks{y - {x \over b}}^{2}}
=\color{#00f}{\large\exp\pars{-\,{\bracks{by - x}^{2} \over \bracks{b + 1}^{2}}}}
$$
Comment: Im assuming that your f's are actually g's.
Comment: I cannot see how the third implication works, how do you arrive with -(b+1)x/b
Comment: Replace $\displaystyle{t \equiv -\,{b + 1 \over b}\,x}$ yields $\displaystyle{x \equiv -\,{b \over b + 1}\,t}$. Just replace them.
Comment: $\displaystyle{y - {x \over b} = \mbox{constant}}$ means that $\displaystyle{{\rm g}\left(x,y\right)}$ depends on the combination $\displaystyle{y - {x \over b}}$: It's an 'arbitrary function' $\displaystyle{{\rm f}\left(y - {x \over b}\right)}$. $\displaystyle{{\rm f}}$ is determined by the condition $\displaystyle{{\rm g}\left(-x,x\right) = {\rm f}\left(\left[-x\right] - {x \over b}\right)  = {\rm e}^{-x^{2}}}$.
Comment: This is the [Method of Characteristics](http://en.wikipedia.org/wiki/Method_of_characteristics).
Comment: In my comment before the last one there is a typo. It should be $\displaystyle{\bf{\rm g}\left(x,-x\right)}$ instead of $\displaystyle{{\rm g}\left(-x,x\right)}$


Como trazer dado de uma coluna dataframe para outro

Question: Tenho um dataframe onde tenho informações como id, name, company e preciso juntar ele em outro dataframe que só tenho o ownerId.
Ex:
users= pd.DataFrame([['Jay',16,'BBA'],
                   ['Jack',19,'BTech'],
                   ['Mark',18,'BSc']],
                  columns = ['name','id','company'])

historico = pd.DataFrame([['12-03-2022',16],
                   ['11-05-2022',19],
                   ['03-01-2021',18]],
                  columns = ['data','ownerId'])

Preciso colocar os dados do user.name no lugar do historico.ownerId
Pensei em algo como:
historico.ownerId = (historico.ownerId == users['id'], user['name'])

Mas não funcionou, como poderia fazer isso?
Comment: mas preciso que o user.id seja igual ao historico.ownerId e então pegar o users['name'], isso que não estou conseguindo
Comment: A pergunta continua ambígua. Você quer que seja feito o relacionamento entre dois dataframes usando como chave as colunas `users['id']` e `historico['ownerId']` porém não especificou se os valores encontrados nessas colunas serão únicos ou podem ocorrer duplicatas, não especificou se se haverão linhas vazias ou NA e não especificou se ocorrem e o que fazer com valores não relacionáveis. Numa situação perfeita onde não tenha que gerenciar adversidades teste `print(users.join(historico.set_index('ownerId'), on='id'))`
Answer: Olá para realizar isso você poderia utilizar o merge para juntar as duas tabelas e após isso deixar somente as colunas desejadas.
Segue abaixo como ficaria o código
historico = pd.merge(
    left = users[['name','id']],
    right = historico,
    left_on = 'id',
    right_on = 'ownerId',
    how = 'inner'
)

Desta forma você obterá o seguinte resultado
Imagem após o merge.
Agora basta remover as colunas com um drop historico.drop(columns=['ownerId','id'],inplace=True), que ai você tera exatamente o DataFrame da maneira que deseja DataFrame desejado.

Caso o conceito de merge sejá novo para você sugiro dar uma olhada na Documentação, ou neste artigo Pandas: combinando data frames com merge e concat


How to Combine Correlated Binary Variables

Question: I have a count data, and most of my explanatory variables are binary (they represent different types of support given to a group). Three variables seem to be correlated with each other. I don't want to drop any of them as the categories are different and essential. So, I thought maybe I could create another variable combining those variables such as creating a dummy (1), where at least one of the variables is (1) or creating a variable that represents the sum of the values. However, I am not sure about alternatives or the right way to handle this. Could anyone please help me with that?
Comment: can you explain what you are trying to do with these variables?
Comment: So the unit of observation is the group or the individual within the group?
Answer: There are several possibilities, which you choose depends on how much data you have, how many of the dichotomous IVs you have, and their pattern.
If you have a relatively large amount of data and a relatively small number of variables, you can make one variable that has all the originals. E.g. if you had three dichotomous variables, you would have a new one that was

YYY
YYN
YNY
YNN

and so on, with 8 levels.
If you have less data or more variables, you could do a count. So, if you had five kinds of support, this would get a value from 0 to 5.
More complicated is to look at the patterns and make some sensible choices from within the first idea. You could (and maybe should) do this using substantive knowledge and eyeballing the data, or you could perhaps use some kind of cluster analysis.  See this thread for some ideas.


Comparing the mean of biological replicates that are not normally distributed, low N for replicates

Question: I work in cell biology where the field standard is now to do 3 biological replicates of experiments. However, each data point is extremely laborious to get and we receive very little statistics training. I believe some kind of nested model would be the most rigorous, but I'm also worried about how "unfamiliar" tests are perceived.
Simply, I infected human cells with bacteria for a set length of time and counted how many cells are infected at the end per image/focus. I have control wild type untreated human cells, and 5 experimental conditions where I have treated the cells with various chemical reagents. For each experiment, I counted 20 images per control/condition. I repeated the entire experiment 3 times on different days for my biological replicates. The data is quite noisy (as expected) and each replicate is not normally distributed. The graph of my data with means of each replicate as bold squares and individual data points colored by replicate as circles is below.

If I wanted to compare the conditions to the control with an ANOVA followed by a multiple comparisons test, could I treat the comparison of the averages of my data points per replicate as normally distributed? ie can I run an ANOVA rather than a Kruskal Wallis test on the replicate means? Since the replicate data is not normal, would comparing medians be better?
Is there an alternate test that you would recommend, especially a more simple one? From my reading, I suspect some kind of nested data test or mixed model might be the most rigorous but I've not found very accessible explanations so I am unsure how best to proceed, especially in a sub field that often just runs repeated T-tests on everything. Thanks!
EDIT: I'm getting a lot of great suggestions to follow up on- what approach is likely to have the most power to detect differences? The difference seems to be meaningful biologically based on my further work, but it would be nice if my stats could match the biology.
Answer: I recommend "Empowering statistical methods for cellular and molecular biologists," Molecular Biology of the Cell, 30:1359, 2019 as a brief useful reference, written by biologists who appreciate statistical issues.
With count data like yours, Figure 2 of that reference shows that a generalized linear model (for example, a Poisson or negative-binomial model for counts) might be most appropriate. That said, with this type of design, this particular data set, and some care you might be able to accomplish what you want with something close to ANOVA.
Your 20 images for each combination of condition and biological replicate are simply technical replicates. For inference on the effects of treatments, what you care about is the variability among the biological replicates. Thus you could consider the sum of all infected cells across the 20 images for each combination of condition and biological replicate as the outcome variable. That would give you 18 net observations (3 biological replicates for each of 6 control/treatment classes). I think that's what you are getting at.
For ANOVA or related linear models to be valid, what's important is the distribution of residuals about the modeled means. In your particular data set, it looks like 100-200 counts for each of those 18 observations. With so many counts per observation and reasonable agreement among the biological replicates under each treatment, normality of residuals might not be a bad assumption, either on the counts themselves or on some transformation of counts (log or square-root transformations of counts sometimes help). In practice, a test of normality based on only 18 observations isn't going to be very useful, although you should evaluate the distribution of residuals around the modeled values anyway.
You do need to deal with the matching among biological replicates. That might be what you are thinking about with respect to a "mixed model," which could treat the biological replicates as "random effects." With only 3 biological replicates, however, you can simply treat the biological replicates as fixed effects in the model, adjusting for baseline (WT/control) differences in the number of infected cells among the biological replicates. That's a generalization of a paired t-test. (I think that in a simple case like this, a fixed-effect and random-effect treatment of the biological replicates will provide essentially the same results.)
In R, the general form of the model then would be something like:
outcome ~ bioReplicate + condition

where outcome is an outcome measure, bioReplicate is a 3-level factor keeping track of the biological replicate, and condition is a 6-level factor (probably with "control" as the baseline level). You then decide whether to use the sum of counts across the 20 images or some transformation as the outcome. If you use the sum of counts, you would also have to choose between a standard linear regression (lm()) or a generalized linear model suitable for counts (glm() with family=poisson), although with this large number of counts that latter choice probably won't matter much.
There are other approaches that don't depend on an assumption of normality, as the answer from Robert Long explains. The non-parametric Kruskal-Wallis test is a special case of a semi-parametric proportional-odds ordinal regression model, which trades off the normality assumption for an assumption about the association of the log-odds of a higher outcome with the predictor values. In a more complicated situation than yours, ordinal regression has the advantage that it can handle continuous predictors. I find that ordinal regression also more readily lends to comparisons among multiple treatments, although in this situation you could do repeated pairwise Kruskal-Wallis tests with correction for multiple comparisons.
Comment: @dipetkov The set-up I assumed (based on experience): for each replicate of each treatment, you have a large number of cells on the bottom of a tissue-culture dish. You take microscopic images  of 20 subregions of the dish; in each image, you count how many cells are infected. Ideally, there would also be a count of the total number of cells evaluated per image (maybe on the order of 50-100) and you would use a binomial model, but that wasn't specified in the OP. It seems that only the counts of infected cells per image (between 1 and 20) are available, hence the suggestion for a count model.
Comment: @dipetkov yes each dot is an actual count of infected cells. The bacterial kinetics for what we are more specifically measuring (total infected cells resulting from an infection of an initial single bacterium) are such that we dont see values of more than 20 infected cells. The images are taken of specific biologic criteria which is why total cells, uninfected or not, per image is not relevant as long as that value is consistent between conditions.
Comment: With the caveat that I know nothing about biology, doesn't the description of the experiment suggest that $n = 20$ is the size / support in a Binomial distribution. I'm not sure that Poisson or Negative Binomial make sense (even though the y-axis extends to 25 which suggests that the range of observations includes values > 20.)
Comment: Thank you for the explanation -- it makes sense though I still find it a bit hard to imagine why the only values observed are 1, 2, 3, ..., 19 infected cells per image (in 20 images).
Comment: @dipetkov each round dot presumably represents the actual count of infected cells in an individual image, not averaged over 20 images. The squares are the averages over the 20 images for each "biological replicate."
Answer: ANOVA assumes that the data within each group is normally distributed and that variances are equal across groups. When these assumptions are not met, the test can be unreliable. However, ANOVA is quite robust to violations of normality when sample sizes are equal across groups and reasonably large. ANOVA might still be appropriate here, but I would suggest some other models in order to compare the results. These are listed in increasing order of complexity:
Comparing Medians:
Comparing medians with a non-parametric test such as Kruskal-Wallis.
Repeated Measures ANOVA:
Repeated measures ANOVA would be a reasonable choice if you can plausibly assume sphericity (i.e., equal variances of differences between treatment levels), or use the Greenhouse-Geisser adjustment if sphericity does not hold.
Mixed Models:
Mixed models are very useful because they incorporate both fixed effects (treatments) and random effects (variability within biological replicates). Because the data is noisy and you have repeated measures, a mixed model would allow you to account for non-independence within each replicate and perhaps produce more accurate estimates of treatment effects.
If you have difficulty with any of these models you can always ask another question here!


Authlogic - Logout not working on production but working in dev?

Question: I have only just started to investigate... but thought I would throw this to the community as well.
I am building an app using Authlogic for authentication. The auth part is basically straight off the authlogic tutorials...
My logoff button works in dev, destroying the session and giving the flash on the root_url. However, on production the link spins, take me to the root_url, but no flash and the session data is still there.
Everything else works on production... like I said, I am just beginning to investigate. Hopefully someone has an idea...
Setup info:
Rails 2.3.2
Dev - standard script/server mongrel
Prod - apache/passenger/mysql
Answer: Well. Turns out there are some session issues with authlogic and versions of Passenger before 2.2.2.
I upgraded to 2.2.2 and the problem has been resolved.
So a quick upgrade and everything runs perfect.
Comment: Thanks for responding to yourself. I had the same issue. +1


Is Java eager singleton creation thread safe?

Question: I like the simplicity of the "eager singleton" in java, and most articles about it call its creation thread safe.
class Singleton {

public static final Singleton instance = new Singleton ();

    private Singleton (){};

    public static Singleton getInstance(){

        return instance;

    }
}

However I have heard some claims that its creation might not be thread safe after all. For example one source claimed that it is not safe if more than 1 class loader or App domain is used.
Is the creation of the "Eager Singleton" guaranteed by the JVM to be thread safe, so that, for example, 2 threads don't accidentally create the singleton at the same time?
Edit:
Is the keyword final required for thread safet of the object creation? Is it not thread safe if the field is not final?
Comment: *I have heard some claims...* source ???
Comment: If you have multiple class loaders in play, you could have multiple separate versions of your code, as you would expect.
Comment: If we aren't talking about `synchronized`, we're not talking about thread safetiness. They are a multitude of examples on the web , like : https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
Comment: @maspinu No idea what you mean with "If we aren't talking about synchronized, we're not talking about thread safetiness", but the link you post confirms that the eager singleton pattern that the OP uses is safe (and that is correct)
Answer: The approach that you use is thread safe. Since you haven't referenced the claims that you are talking about, I cannot directly address them.
But the Java Language Specification is clear on this topic.
In section 17.5 it describes

final fields also allow programmers to implement thread-safe immutable
  objects without synchronization. A thread-safe immutable object is
  seen as immutable by all threads, even if a data race is used to pass
  references to the immutable object between threads. This can provide
  safety guarantees against misuse of an immutable class by incorrect or
  malicious code. final fields must be used correctly to provide a
  guarantee of immutability.
An object is considered to be completely initialized when its
  constructor finishes. A thread that can only see a reference to an
  object after that object has been completely initialized is guaranteed
  to see the correctly initialized values for that object's final
  fields.
Comment: If this was an instance initializer, my response would be clearly: "no". You *need* the `final` (or `synchronized`) otherwise it's not published safely. With static initializers it's a bit trickier. I don't know of any specification that guarantees that it will work, but I've tried to create a race condition using ClassLoaders and static initializers and I failed - it's likely that you will always at some point hit a `synchronzied` block in the classloader that is also hit by the classloader that performed the static initialization, ensuring safe publication. But a future version JVM might not
Comment: @ErwinBolwidt the guarantees for static initializers [are precisely specified](https://docs.oracle.com/javase/specs/jls/se14/html/jls-12.html#jls-12.4.2). Note the occurrences of "initialization lock".
Comment: This only talks about the immutability side of the problem. They write "A thread that can only see a reference to an object after that object has been completely initialized" as a condition, not as a guarantee that this is in-fact the case.
Comment: @Gonan: This is what you asked for. Creation is perfectly threadsafe. Now if the implementation is broken that's another issue. Also problems coming from having multiple class loaders are not thread safety issues.
Comment: @GonenI I don't know how the specification could be clearer: "is **guaranteed** to see"
Comment: @GonenI Perhaps you were referring to this: https://stackoverflow.com/questions/878577/are-java-static-initializers-thread-safe (you should *really* update your question with references to these claims, to make your question more valuable!). When you're loading a class independently through more than one classloader, it's not the same class, even if it has the same name (classes in java are unique based on their name *and* classloader combined). Although they have the same name, they don't share anything, not even static variables, so they will also have their own singleton instances.
Comment: @ErwinBolwidt OK, thanks. So if the static initialization code is guarenteed to run only once, then making the instance final is not required to ensure only 1 instance is created. ( Final is a problem since I like to declare the singleton instance type as an interface and add a setter for OPC flexibility and unit testing )
Comment: I had similar question and added a unit test to verify [this](https://stackoverflow.com/questions/63698418/does-below-class-implement-correct-java-singleton-object-and-provide-thread-safe)
Answer: I don't think that the name "eager singleton" is justified.
Consider JLS §12.4.1., When Initialization Occurs

A class or interface T will be initialized immediately before the first occurrence of any one of the following:

T is a class and an instance of T is created.
A static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).

So, the initialization and in turn, the instantiation of Singleton will happen when the method getInstance() is invoked for the first time or, since you made the field public, when the field is accessed for the first time, whichever comes first. But not earlier. In other words, this initialization is already as lazy as all other attempts to perform lazy initialization try to achieve.
The safety of this initialization is given by JLS §12.4.2, Detailed Initialization Procedure

For each class or interface C, there is a unique initialization lock
LC. The mapping from C to LC is left to the discretion of the
Java Virtual Machine implementation. The procedure for initializing C is then as
follows:

Synchronize on the initialization lock, LC, for C. This involves waiting until the current thread can acquire LC.
If the Class object for C indicates that initialization is in progress for C by some other thread, then release LC and block the current thread until informed that the in-progress initialization has completed, at which time repeat this step.
If the Class object for C indicates that initialization is in progress for C by the current thread, then this must be a recursive request for initialization. Release LC and complete normally.
If the Class object for C indicates that C has already been initialized, then no further action is required. Release LC and complete normally.

…

This is the procedure, every resolution of a reference to the class has follow, acquiring the unique initialization lock of the class and releasing it when the class is already initialized or the current thread is the thread performing the initialization. This lock ensures the thread safety, regardless of whether the field has been declared final or not, as long as it is only written during the class initialization.
The reason why it still is the most efficient way to implement a singleton is given in the same chapter:

An implementation may optimize this procedure by eliding the lock acquisition in step 1 (and release in step 4/5) when it can determine that the initialization of the class has already completed, provided that, in terms of the memory model, all happens-before orderings that would exist if the lock were acquired, still exist when the optimization is performed.

Since each class is initialized only once and then used in this initialized state for a very long time compared to its initialization time, this optimization has a very high impact and therefore, is state of the art since the first Java versions. But, as this note says, the optimization must not subvert the thread safety
Comment: @VuTrongNghia it's correct that accessing an unrelated member will cause the initialization of the class. One solution is to move the singleton's field into a private nested class, so the access to the nested class will trigger the initialization and there is only one, within `getInstance()`. The simpler approach is not having unrelated things in one class. There's another solution planned for future Java versions, [Lazy Static Final Fields](https://openjdk.org/jeps/8209964) which will bring you the same robustness, simplicity, and efficiency of a class initializer for the first field access.
Comment: Agreed. You would be hard pressed to find real world cases where this singleton is less lazy than other singleton approaches.
Comment: If the class 'Singleton' has another unrelated method, like 'logSomething', then INSTANCE will be initialised when you call 'logSomething()'.

On the other hand, the IODH idiom only initialises when 'getInstance()' is called, thus lazy.
Answer: It is thread-safe even if we remove final from public static final Singleton instance = new Singleton ();.
That's because the JVM guarantees that the instance will be created before any thread access the static instance variable.


Can I use 127.0.0.2, 3, etc to map docker container ports to the same port but different loopback IP on my docker host?

Question: I am using ubuntu 22.04 as docker host. On this host I deploy an nginx reverse proxy with TLS termination.I will deploy multiple (say 3) docker compose deployments on that host, and each one there will be a web application listen on 80. The trivial solution is use
<code># in my docker compose for different services:
127.0.0.1:8081:80 # in the first deployment
...
127.0.0.1:8082:80 # in the second deployment
...
127.0.0.1:8083:80 # in the third deployment
</code>
and configure nginx server blocks accordingly.
<code>proxy_pass http://127.0.0.1:8081;
etc
</code>
My question that instead of the working solution above, can I do by this utilizing 127.0.0.x addresses on the 127.0.0.0/8 subnet like this:
(Besides I could simply try this as POC instead of asking here, my question is what could be the drawback or hidden trap using this not so conventional method instead the more mainstream method? I mean is the full 127.0.0.0/8 subnet garanted working in any linux, also is this compatible with docker container port mapping, etc)
<code># in my docker compose for different services:
127.0.0.1:8080:80 # in the first deployment
...
127.0.0.2:8080:80 # in the second deployment
...
127.0.0.3:8080:80 # in the third deployment
</code>
and configure nginx server blocks accordingly.
<code># in my nginx.conf for different server blocks
proxy_pass http://127.0.0.1:8080;
...
proxy_pass http://127.0.0.2:8080;
</code>
Comment: The short answer is "yes".
Comment: And the long answer is "yes, and why not just try?"
Comment: And a longer is answer still is that you need to provision additional loopback devices and change the netmask for 127.0.0.0 (default is 8 bits) or additional routing rules or add aliases on the current device (and add routing rules). But the elephant in the room is WHY? WHAT ARE YOU TRYING TO ACHIEVE?
Comment: @symcbean, there will be 10 docker compose and 10 web service each of them. The 10 compose are totally independent, and each of them will have 10 nodes for load balancing. I can map the ports like 80 - 180, but seems to be more organized to map them 127.0.0.1 :80-89, 127.0.0.2:80-89, etc
Comment: I don't know why it "seems" to be more organized doing it this way - it is *very* complicated to implement.
Answer: Yes you can and for the whole /8 subnet if you want to do it
Answer: Yes you can do it, but if you have routing requirements in the future it will be quite difficult because everything is running on the "front-end" site is running on one ip.
Comment: nginx is listening to the outside, and will reverse proxy by host header to different loopback addresses


NGINX reverse-proxy with SSL certificate gives SEC_ERROR_UNKNOWN_ISSUER error only in Firefox

Question: I've configured an NGINX reverse-proxy with SSL certificate and it works fine in Chrome and IE, but give me an SSL error (SEC_ERROR_UNKNOWN_ISSUER) in Firefox.
Why is that?
Answer: I've just found another answer to a similar problem that explains that this happens if the certificate chain is not fully sent by the server (or in this case the load balancer).
This other answer explains that Chrome looks for this missing chain certificates by itself while Firefox does not. Actually Firefox caches intermediate certificates from earlier connections to other sites, but in my case since I'm mostly using Chrome, Firefox didn't had any cache of these Sectigo (Comodo) root certificates, that's why I was getting the validation error.
When I purchased my PositiveSSL certificate I've received both the "crt" file for my domain but also a "ca-bundle" file which is the certification authority bundle. Both these files should be concatenated (first my certificate, followed by the certificates for the authority chain), and this combined file is what should be configured as ssl_certificate in NGINX.


Como receber o valor do  no PHP ao selecionar uma opção

Question: Como faço, para que quando o usuário selecionar uma opção, a variável do PHP $idCourse receba o value da opção selecionada.
Fiz esse código apenas para mostrar a ideia:

Código

    <select name="valor" id="idCourse">
        <option value="1">Curso 1</option>
    </select>

    <?php
       $idCourse = $_POST['valor'];
       $result = $pdo->selectAll($idCourse);
    ?>

Comment: tem que enviar usando um formulário ou usando jquery
Answer: Eu não sei se você precisa realmente fazer isso com javascript puro. Mas com jQuery e tudo bem mais fácil. Veja um exemplo abaixo:
Javascript / jQuery e HTML:

$('#idCourse').on('change', function() {

   alert(this.value);

  $.ajax({
     url: "caminho/nome_arquivo.php",
     method: "POST",
     data: { valor : this.value },
     dataType: "JSON"
  }).done(function(response) {
     console.log(response);
  }).fail(function(err) {
     console.log(err);
  });
});

<select name="valor" id="idCourse">
    <option>Selecione</option>
    <option value="1">Curso 1</option>
</select>

Código PHP:
<?php
    $idCourse = $_POST['valor'];
    echo $idCourse;
    ...
?>

Comment: Resolvido (eu acho). Obrigadão. :)


Floating elements left in an overflow wrapper set to hidden

Question: I have a scenario where I need to show only six images at a time on my page. When you click on the next button, these six images will slide out and the next six images will slide in. Here is my html

I would assume that if I floated .featuredThumbs to the left, the would display inline. Then, I would have a wrapper called thumbScroll with an overflow of hidden so that only 6 items at a time show. This wrapper I have given a height and width.
So that when I click on my next button, the first six slide out the the left and the next six slide in from the right.
My problem is though, that all 18 items in this case are below one another and not floated to the left.
How do I float these items to the left in a wrapper with the overflow set to hidden.
Answer: put a div around your ul elements inside the container.
Give this div the following css:
.theDiv {
  white-space: nowrap;
}

Then also use this css:
.featuredThumbs {
 display: inline-block;
 /* remove float */
}

The div theDiv will contain all the uls next to eachother and will display only those that fit in your wrapper.
Answer: Try
 just before closing of wrapper.
Answer: i presume it would be stupid to ask you if your have used float: left; on you li elements? Anyway, it would be really nice to see your CSS.


Pitcher with limited arsenal gets figured out too quickly, how can they become less predictable and effective?

Question: Suppose as a pitcher I have a three-pitch arsenal (e.g. fastball, curveball, slider) and I play the position of relieving pitcher. I've noticed that my pitching style becomes repetitive due to my relatively low number of choices. Eventually, because my style becomes repetitive, batters will "figure me out" too easily and will figure out where to swing and when. Assuming aforementioned batters are experienced enough, they should already know this, and I am careful with them due to this.
My pitch velocity is higher than that of some of my other teammates, and I am capable of just barely clipping the edge of the strike zone with any of my pitches, making me a decent pitcher by the standards of my league.
What strategies could a pitcher with limited arsenal use to become a more effective and unpredictable pitcher?
Comment: I think you hinted at the answer already. Location is at least as important as velocity for keeping a hitter off-balance. Also, if you can throw either breaking pitch for a strike, hitters can't, for example, expect the traditional fastball on a 3-1 count.
Answer: Most pitchers, especially in the big leagues, only have three pitches that they have in their arsenal (or three pitches that the feel comfortable throwing that day) so yours is by no means limited. A fastball, curveball, slider is a very standard combo because it can be one of the most effective with minimal learning curve.
This may sound redundant to your problem, but you don't want to pitch every batter the same. You and the catcher need to watch the hitters warming up, on deck, or during their first at bats to see what their weakness are. Do they struggle with timing? Do they straight take 0-0, 1-0 curves? Is he pulling every pitch he sees? These are the sort of questions that you need to be answering before you even step in on the mound.
Secondly, you should have some intuition when you are on the mound about how the at-bat is going. One of the most basic things you can see is hitter's timing. If they pulled the first fastball you threw foul and was super early, throw him something off-speed so he will be even earlier. If he was late on the fastball you threw and pushed it foul, do not speed him up by throwing off-speed.
Good pitchers are pitchers that have good stuff (movement, location, velocity). Great pitchers are pitchers that are able to use their stuff effectively by understanding the weaknesses of who they are throwing to.


Training set in vector quantization

Question: I am learning vector quantization in terms of image compression and reconstruction, I was wondering why do we form an initial codebook from the training set? Since we are transmitting the index of the codeword only, then why wouldn't we just treat the training set as the final codebook. This would result in more accurate reconstruction, right? What would be the difference?
Answer: The codebook is not an image to be transmitted. The codeword is a reference point to a row in a k-dimensional codebook. Note: a codebook is essentially a 2D array where the row number is the codeword.
Example:
1000 training images are of size 512x512 each.
If we want to create a codebook sized 256, to compress a 512x512 image into a 128x128 VQ (Vector Quantized) Index table, then our codebook needs 16 dimensions (i.e., each 4x4 block (16 values) in our original image is compressed into 1 value which is a codeword).
Whichever clustering algorithm (eg. LBG) you use, will find the closest 16 values which best represent a 4x4 block in the 1000 training images. These 16 values will be put into the codebook. After the best 256 groups or clusters of 16 values are found, the codebook is ready for use.
This codebook needs to be sent to the receiver once. It is a 256 row, 16-dimensional structure, compared to 1000 512x512 training images. You send a 128x128 index table to the receiver who can then lookup the location in the codebook and rebuild the 512x512 image. It will not be exact, as this type of compression is lossy.

Training set in vector quantization


Installing imagick PHP extension on Ubuntu

Question: I'm trying to install the imagick pecl extension on my Ubuntu server and am getting the below error. I've installed the ImageMagick rpm using aptitude already and the pecl extension is version 2.3.0. I've looked around online but can't find anything pointing me in the right direction. I also tried looking for anything that looked like it might be the Wand-config or MagickWand-config program that the error is mentioning but can't find any.
steven@server:/var/www$ sudo pecl install imagick
downloading imagick-2.3.0.tgz ...
Starting to download imagick-2.3.0.tgz (86,976 bytes)
.....................done: 86,976 bytes
12 source files, building
running: phpize
Configuring for:
PHP Api Version:         20041225
Zend Module Api No:      20060613
Zend Extension Api No:   220060519
Please provide the prefix of Imagemagick installation [autodetect] :
building in /var/tmp/pear-build-root/imagick-2.3.0
running: /tmp/pear/temp/imagick/configure --with-imagick
*** ... snip ... ***
checking ImageMagick MagickWand API configuration program... configure: error: not found. Please provide a path to MagickWand-config or Wand-config program.
ERROR: `/tmp/pear/temp/imagick/configure --with-imagick' failed

I snipped most of the output because it didn't really seem to helpful but I can post if requested.

PHP is 5.2.4
ImageMagick is 6.3.7
Ran sudo aptitude upgrade today to upgrade RPMs as well before install ImageMagick
Answer: You need to install the ImageMagick devel package. In Ubuntu try:
sudo apt-get install libmagickwand-dev libmagickcore-dev

Comment: I am trying to do the same on alpine linux and it appears the package name is different (imagemagick-dev).
Answer: It's in the ubuntu repos (version 2.0.1-1 for hardy), is there a reason you're trying to compile it yourself?
Comment: The version in the ubuntu repo for the version I was on (8.0.4) was 1.x and I needed at least 2.1.x. In the end I ended up upgraded to ubuntu 9 so I didn't have to.


Higher ($>1$) order Voronoi diagrams in higher ($ > 2$) dimensional spaces

Question: The $k^{th}$ order Voronoi partitioning given a set of $K$ points $X_K$ in $\mathbb{R}^d$ partitions the space into regions such that points in the same region have the same $k$ nearest neighbors in $X_K$.
Would appreciate if anyone could point me in the direction of any resources that discuss the properties of $k^{th}$-order Voronoi diagrams in higher dimensional Euclidean (not just $\mathbb{R}^2$) spaces.
Specifically for the $k^{th}$ order Voronoi diagram in $\mathbb{R}^2$, this paper (Lemma 5) addresses that if two Voronoi cells share an edge, then only the $k^{th}$ nearest neighbor changes. I am interested in knowing if a similar result holds in higher dimensional Euclidean spaces.
Answer: Maybe start here:

Agarwal, Pankaj K., Mark De Berg, Jirí Matousek, and Otfried Schwarzkopf. "Constructing levels in arrangements and higher order Voronoi diagrams." SIAM Journal on Computing 27, no. 3 (1998): 654-667. (PDF download.)

See also this book for a more recent survey with many citations:

Aurenhammer, Franz, Rolf Klein, and Der-Tsai Lee. Voronoi diagrams and Delaunay triangulations. World Scientific Publishing Company, 2013.
  (Publisher link.)
Comment: Thank you. The book by Aurenhammer seems to be very comprehensive.


React useEffect is not calling firebase read API after first load

Question: I'm making a todo app using react and firebase. I followed a tutorial from youtube to write the code.
Now I'm trying to add firebase. I'm using a useEffect hook to fetch data from firebase. It works on first render, but if I use other functionality like read, update it doesn't re-render. On refresh I get the result I wanted. If I add todos as a dependency to the useEffect, it works correctly but their are too many api calls.
App.jsx
function App() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState("");
  console.log(input);

  // Create todo
  const createTodo = async (e) => {
    e.preventDefault(e);
    if (input === "") {
      alert("Please enter input");
      return;
    }
    await addDoc(collection(db, "react-todo"), {
      text: input,
      complete: false,
    });
    setInput("");
  };

  // Read todo from firebase
  useEffect(() => {
    const getTodos = async () => {
      const data = await getDocs(collection(db, "react-todo"));
      let todoArray = [];
      data.forEach((doc) => {
        todoArray.push({ ...doc.data(), id: doc.id });
      });
      setTodos(todoArray);
    };
    getTodos();
  }, []);

  // update todo in firebase
  const toggleComplete = async (todo) => {
    await updateDoc(doc(db, "react-todo", todo.id), {
      complete: !todo.complete,
    });
  };

  // delete todo
  const deleteTodo = async (todo) => {
    await deleteDoc(doc(db, "react-todo", todo.id));
  };

  return (

Todo App

        <form onSubmit={createTodo} className={style.form}>
          <input
            type="text"
            placeholder="Add Todo"
            className={style.input}
            value={input}
            onChangeCapture={(e) => setInput(e.target.value)}
          />
          <button className={style.button}>
            <AiOutlinePlus size={30} />
          </button>
        </form>

          {todos.map((todo, index) => (
            <Todo
              key={index}
              todo={todo}
              toggleComplete={toggleComplete}
              deleteTodo={deleteTodo}
            />
          ))}

{`You have ${todos.length} no. of todos`}

  );
}

Todo.jsx
function Todo({ todo, toggleComplete, deleteTodo }) {
  return (

        <input
          onChange={() => toggleComplete(todo)}
          type="checkbox"
          checked={todo.complete ? "checked" : ""}
        />

 toggleComplete(todo)}
          className={todo.complete ? style.textComplete : style.text}
        >
          {todo.text}

      <button onClick={() => deleteTodo(todo)}>{<FaRegTrashAlt />}</button>

  );
}

Answer: Adding todos to your dependency array will create an infinite loop and is not the way to do it. As you said "there are too many api calls. This is because setTodos creates a new array each time it's called, which then causes the useEffect to run...which then calls setTodos, and so on.
Even though you call getTodos on first mount, react doesn't have any way of knowing that your database has updated when you call functions like deleteTodo. You need to manually refetch the data after each call. Something like this should work:
App.jsx
function App() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState("");

  // Get todos
  const getTodos = async () => {
    const data = await getDocs(collection(db, "react-todo"));
    let todoArray = [];
    data.forEach((doc) => {
      todoArray.push({ ...doc.data(), id: doc.id });
    });
    setTodos(todoArray);
  };

  // Create todo
  const createTodo = async (e) => {
    e.preventDefault(e);
    if (input === "") {
      alert("Please enter input");
      return;
    }
    await addDoc(collection(db, "react-todo"), {
      text: input,
      complete: false,
    });
    setInput("");
    getTodos(); // REFETCH
  };

  // Read todo from firebase
  useEffect(() => {
    getTodos(); // Initial fetch on first mount
  }, []);

  // update todo in firebase
  const toggleComplete = async (todo) => {
    await updateDoc(doc(db, "react-todo", todo.id), {
      complete: !todo.complete,
    });
    getTodos(); // REFETCH
  };

  // delete todo
  const deleteTodo = async (todo) => {
    await deleteDoc(doc(db, "react-todo", todo.id));
    getTodos(); // REFETCH
  };

  return (

Todo App

        <form onSubmit={createTodo} className={style.form}>
          <input
            type="text"
            placeholder="Add Todo"
            className={style.input}
            value={input}
            onChangeCapture={(e) => setInput(e.target.value)}
          />
          <button className={style.button}>
            <AiOutlinePlus size={30} />
          </button>
        </form>

          {todos.map((todo, index) => (
            <Todo
              key={index}
              todo={todo}
              toggleComplete={toggleComplete}
              deleteTodo={deleteTodo}
            />
          ))}

{`You have ${todos.length} no. of todos`}

  );
}

Comment: Thanks for your help. App working the way I wanted.
Answer: If you want to avoid an API call on every action so you should update your todos locally manipulating data you've changed:
const createTodo = async (newTodo) => {
  ... handle db logic

  setTodos((current) => ([
    ...current,
    newTodo
  ]))
};

const toggleComplete = async (todo) => {
  ... handle your db logic

  setTodos((currents) => currents.map(current => {
    if(current.id !== todo.id) return current

    return {
      ...todo,
      complete: !todo.complete
    }
  }))
};

const deleteTodo = async (todo) => {
  .... handle your db logic

  setTodos((currents) => currents.filter(current => current.id !== todo.id))
};

Only make sure your data was saved successfully and now you can just update what user see locally. Hope this helps
Comment: Assuming api calls are successful isn't usually best practice as it can lead to errors in what you're showing your user vs what is actually on the db.
Comment: @sallf I see no difference between fetching data again from database and updating data locally as the API call has finished without errors. In this case, if you successfully deleted a TODO you don't need to read all your database again because deletion API call was successfully. If it had an error then refetching is a good idea. Correct me if I'm wrong.
Comment: I hear what you're saying -- though I wouldn't have interpreted "API call has finished without errors" from `...handle your db logic` . One use case would be if multiple people are editing the db. Syncing after each api call would definitely be better practice , but that's above and beyond what this question is asking.


Proving the product rule for n functions

Question: I am trying to prove that the product rule works for $n$ many functions, where $n$ is an integer greater than $2$. I am able to prove it for two functions, where the rule states if $k(x)=f(x)g(x)$ , then $k'(x)=f'(x)g(x) + f(x)g'(x)$. However, I have surfed the Internet for a proof for $n$ many functions and found none; and, I believe that If I were to prove it for $n$ functions directly it would take  a very long time - given I even know how to. But, I read somewhere about an induction proof of it but it assumed that the rule works for $n$ functions then proved that if it works for $n$ functions than it also works for $n+1$ functions. So, my question is, can anyone possibly link me to a rigid proof of the product rule for $n$ functions or possibly write one since I have no idea how to write a quick proof for it.
Comment: This is how induction works though - show that it holds for $n = 2$ (the base case here) functions, assume it's true for $n$ functions, and use that to show that it holds for $n + 1$ functions.
Comment: Are you familiar with [induction](https://en.wikipedia.org/wiki/Mathematical_induction)? You need to prove the induction step (as described in your question) but also the induction basis (you already have that: namely, the rule works for two functions)
Comment: But how can I just assume it works for n without knowing?
Comment: It's an _assumption_. You are not saying that's true. You are saying "if that were true..." and you establish that then it would be true for $n+1$. Read up on mathemetical induction
Comment: Could one of you please write an answer of the induction step for n functions and then hint me on how to prove it for n+1.
Comment: @ReinhildVanRosenú If you _understand_ induction you can easily do it yourself
Comment: Ok, I'll try...
Answer: This is a case where logarithmic differentiation makes life much easier.
Consider $$F(x)=\prod_{i=1}^n f_i(x)$$ Taking logarithms of both sides $$\log\big(F(x)\big)=\sum_{i=1}^n \log\big(f_i(x)\big)$$ Differentiating $$\frac 1{F(x)}\frac{dF(x)}{dx}=\sum_{i=1}^n \frac 1{f_i(x)}\frac{df_i(x)}{dx}$$  $$\frac{dF(x)}{dx}=\Big(\sum_{i=1}^n \frac 1{f_i(x)}\frac{df_i(x)}{dx}\Big) \times\Big(\prod_{i=1}^n f_i(x)\Big)=\sum_{i=1}^n \frac{\prod_{j=1}^n f_j(x) }{f_i(x)}\frac{df_i(x)}{dx}$$ $$\frac{dF(x)}{dx}=\sum_{i=1}^n \frac{df_i(x)}{dx}\prod_{j=1,j\ne i}^n f_j(x) $$
Comment: Hello Claude.  (+1)
Answer: You can use induction on $n$, the number of functions. If $n = 2$, then you just get the product rule. Assume the claim is true for $n$ functions, and prove it for $n+1$. Write $f_1\cdot f_2 \cdots f_{n+1}$ = $f_1g$ where $g = f_2\cdots f_{n+1}$.
Now differentiate $f_1g$ using the product rule and apply the induction hypothesis to $g'$. Note that $g$ is a product of $n$ functions, so the induction hypothesis tells you what $g'$ is.
The way mathematical induction works is that if you've proved it for a base case, here it is $n=2$ and you prove that if your result is true for some integer $n$ then it must be true for some integer $n+1$ as well. Then because you've shown your result in the case $n=2$ is true, you've also shown that your result must be true in the case that $n=2 + 1= 3$ is true, and hence you've shown that $n=3+1 = 4$ is true, and hence $n=4+1 = 5$, etc...
Comment: Following these steps, I have found that a function containing n+1 terms can be represented by $f_1g'_ + f'_1g$ and is it correct to infer that the function of n terms can be represented by $$g'$$ from this?
Comment: The derivative of the function of $n$ terms is represented by $g'$, that is, $$\frac{\mathrm{d}}{\mathrm{d}x} (f_2 \cdot f_3 \cdot f_4 \cdot f_{n+1}) =g' $$, where there are $n$ terms.


Contador de tempo regressivo

Question: Estou a criar um mini-jogo com várias perguntas e quero que tenha tempo,ou seja, quero um contador que vá de x até zero. O contador só precisa de ter segundos e minutos. Alguém sabe de alguma função em C++ ou alguma "gambiarra" para obter uma contagem regressiva?
Answer: O melhor jeito para se fazer um contador em jogos é usando Threads, pois assim será possível contar o tempo sem a interferência das Frames do jogo (FPS).
void time_decrement(void *game_config){
    GameConfig *gc = (GameConfig*) game_config;

    while(gc->time > 0){
        sleep(1);
        gc->time--;
    }

    gc->game_loop = false;
}

main:
//...
pthread_create(&line,NULL,time_decrement,(void *) g_config);
//...

GameConfig representa um struct ou classe que possua as configurações do jogo, (tempo, pause, fim de jogo, etc). É um meio opcional, mas do meu ponto de vista, é melhor que deixar em variáveis separadas.
Nesse exemplo a Thread encerrará o jogo assim que o contador chegar a 0.
Comment: Obrigadão! Ajudou d+!

Contador de tempo regressivo


Can you bound $2^n$ by n!

Question: Consider the powerset of N
$(1), (2), (1,2), (3), (1,3), (2,3), (1,2,3), (4), ...$
Map this to
$(2), (3), (2,3), (5), (2,5), (3,5), (2,3,5), (7), ...$
Where n is replaced by the nth prime
If we then multiply all the primes
$(2), (3), (6), (5), (10), (15), (30), (7), ...$
We get a sequence whose range grows factorially. How can the continuum which is of the order 2^n outweigh n factorial?
Comment: https://en.m.wikipedia.org/wiki/Stirling%27s_approximation
Comment: Answering the title question- $1\times 2\times3\times4 = 2 \times 2 \times 3 \times 2 > 2^4$ and the difference gets bigger for larger $n$. For smaller $n$,
\begin{align}0! =  1 = 2^0\\ 1! = 1 < 2^1\\ 2! = 2 < 2^2 \\ 3!=6<2^3\end{align}
Comment: Yea I'm just wondering why 2^n is such a big deal if we can go to n!
Answer: What you have shown is a bijection between finite subsets of $\mathbb{N}$ and squarefree natural numbers. If you're asking whether this construction contradicts Cantor, it does not: you are missing almost all elements of $2^{\mathbb{N}}$ (the infinite subsets) so you have not proven that the power set of the natural numbers is countable.
I don't really understand what you mean about one set "outweighing" the other, though---both are (countably) infinite.

Can you bound $2^n$ by n!