Intuition behid $P(A\mid B)$.

Question: What is the intuition behind the formula $$P(A\mid B)=\frac{P(A\cap B)}{P(B)}$$
I have seen this formula around, but every site/book I look at does not really have a clear & cut explanation behind this formula.
Comment: Doesn't hurt to read the wiki page: [Interpretations.](https://en.wikipedia.org/wiki/Bayes'_theorem#Interpretations)
Comment: Also, take note that initially you had written $\dfrac{P(A\color{red}{\cup} B)}{P(B)}$ but it is meant to be $\dfrac{P(A\color{blue}{\cap}B)}{P(B)}$.  I took the liberty of correcting it in your post.  The earlier has the possibility of being greater than one (*in fact it will always be if $A\setminus B$ is an event of non-zero probability*) which fails to satisfy the (*standard*) definition that probability is always between zero and one.
Comment: Rearrange it to $P(A\cap B)=P(B)P(A\mid B)$.
Answer: Imagine a venn diagram, with two circles, labelled $A$ and $B$. The quantity within each shaded region represents a Probability of an Event. Say, if you were to shade the $A$ entirely then this would give you $P(A)$. Now,let the common region be denoted by $P(A \cap B)$. Considering your question, you want the probability $P(A|B)$, which is the probability of $A$ occurring given that $B$ has already happened. Now think about it in terms of the Venn Diagram. The only region where $B$ and $A$ events can occur is in the overlapping region, therefore you get a numerator $P(A \cap B)$ as your favorable outcome. But this time, the total number of outcome is all of $A$ therefore $P(A)$ is in the denominator.
Answer: It's equivalent to $$\frac{n(A\cap{B})}{n(B)}$$ in other words the proportion of the members of set $B$ which are also members of set $A$.
Answer: All probabilities are the number of desired outcomes divided by the total possible outcomes.
So P(A|B) is the number ways A and B occur divided by the number B can occur.
In other words: #A&B / #B.
This is equal to (#A&B / #everything)(#everything / #B)
Which is the RHS.
Although I prefer to think of it simply that the LHS refers to probability of A given the limited range that B occurs as well, which reasonably should be the probability that A and B both occurring in the "big" world but then reduced to the requirement that B occured.  Which is pretty intuitive to me.
Comment: Strictly speaking this is only true when the underlying $P$ is the uniform distribution on a finite set. Still, this is essentially the intuition even in more general situations.

Intuition behid $P(A\mid B)$.


For the positively oriented circle, $\oint_{|z|=1}\frac{2\Re(z)}{z+1}dz=......$

Question:
For the positively oriented circle,
  $\oint_{|z|=1}\frac{2\Re(z)}{z+1}dz=......$
(a) $0$
(b) $\pi i$
(c) $2\pi i$
(d) $4\pi i$

$$\oint_{|z|=1}\frac{2\Re(z)}{z+1}dz$$
$$=\oint_{|z|=1}\frac{z^2+1}{z(z+1)}dz$$  ($\because$ $z$ is in the unit circle, $\overline{z}=\frac{1}{z})$
$$=2\pi if(0)=\pi i$$
But in the book, answer is $0$. Where did I go wrong? Please help me.
Comment: In the first place this integral is **divergent** and can only be saved using some exception handling measures; see Jack D'Aurizio's answer.
Comment: @ChristianBlatter where it is divergent?
Comment: can you explain, How does the cauchy's inegral formula fail?
Comment: Cauchy theorem holds for meromorphic functions, yours isn't one of them.
Comment: meromorphic function on an open subset D of the complex plane is a function that is holomorphic on all of D except for a set of isolated points, which are poles of the function. Right? $\frac{z^2+1}{z+1}$ has pole at $z=-1$. right? Except all points it is analytic right?
Comment: @JackD'Aurizio can you explain?
Comment: Re(z)/(z+1) is neither meromorphic or holomorphic in a puntured neighbourhood of -1. Cauchy formula does not apply, plain and simple, since the Cauchy-Riemann equation is not fulfilled.
Comment: @JackD'Aurizio Ok. How did you proved? by applying C-R equation?
Comment: @ManeeshNarayanan: is your function expandable as a power series in $z$ around, say, $z=0$? No, Cauchy theorem does not apply.
Comment: @JackD'Aurizio $\frac{z^2+1}{z+1}=(z^2+1)(1-z+z^2-z^3+...).$  for $|z|<1$. Right?. sorry for disturbing. still find problem. please help me.
Comment: Seems like analytic.
Comment: That function is analytic, but that function and $\frac{\text{Re}(z)}{z+1}$ are different functions on the complex plane.
Comment: The problem is not so much that the integrand is not meromorphic (you found a way around this) but that the curve passes through the singularity $z=-1$ of the integrand.
Comment: For instance, one fulfills $f(\overline{z})=\overline{f(z)}$, the other doesn't.
Comment: @ChristianBlatter: of course, but I guess the OP forgot to mention that in the definition of $\oint$ some way of "dodging" the singularity at $z=-1$ has to be included. If we dodge it in a symmetrical fashion (the usual way), we find the Cauchy principal value.
Comment: @JackD'Aurizio ok. thank you. It is clear now.
Comment: @ChristianBlatter Thank you very much.
Answer: By letting $z=e^{i\theta}$ we have $dz= i e^{i\theta}d\theta$ and the wanted integral equals
$$ \int_{-\pi}^{\pi}\frac{\text{Re}(e^{i\theta})}{1+e^{i\theta}}ie^{i\theta}\,d\theta =i\int_{-\pi}^{\pi}\frac{\cos\theta(e^{i\theta}+1)}{2+2\cos\theta}\,d\theta=i\color{blue}{\int_{-\pi}^{\pi}\frac{\cos\theta}{2}\,d\theta}-\color{red}{\int_{-\pi}^{\pi}\frac{\sin\theta\cos\theta}{2(1+\cos\theta)}\,d\theta}$$
where the blue integral equals $0$ by the periodicity of $\cos$ and red integral is, strictly speaking, undefined like $\int_{-1}^{1}\frac{dx}{x}$, but its principal value equals zero since the integrand function is odd.
Comment: Can you check my answer?
Comment: $$ \int_{-\pi}^{\pi}\frac{\text{Re}(e^{i\theta})}{1+e^{i\theta}}ie^{i\theta}\,d\theta =i\int_{-\pi}^{\pi}\frac{\cos\theta(e^{i\theta}+1)}{2+2\cos\theta}\,d\theta=i\color{blue}{\int_{-\pi}^{\pi}\frac{\cos\theta}{2}\,d\theta}-\color{red}{\int_{-\pi}^{\pi}\frac{\sin\theta\cos\theta}{2(1+\cos\theta)}\,d\theta}$$
Comment: How does the first equality come?
Comment: $\text{Re}(e^{i\theta})=\cos\theta$, then split $e^{i\theta}+1$  as the sum between its real part and i times its imaginary part, then simplify.
Comment: $Re(e^{i\theta})=\cos\theta$, fine. how $\frac{e^{i\theta}}{1+e^{i\theta}}$ tranformed to $\frac{1+e^{i\theta}}{2+2\cos\theta}$
Comment: @ManeeshNarayanan: multiply by $\frac{1+e^{-i\theta}}{1+e^{-i\theta}}=1$.
Comment: why not limits from $0$ to $2\pi $?
Comment: @TheStudent: it's the same, we are dealing with $2\pi$-periodic functions.


How Can I Open Port 80 On Mac OS X Snow Leopard?

Question: I recently upgraded to Snow Leopard, and I want to start using the included Apache web server.  I activated web sharing, and went to http:/127.0.0.1/ in my web browser.  Safari couldn't connect to the server.  Finally, using Network Utility, I found:
<code>Port Scanning host: 127.0.0.1
Open TCP Port:  21          ftp
Open TCP Port:  22          ssh
Open TCP Port:  631         ipp
Open TCP Port:  3306        mysql
...and so on...
</code>
I tried the same thing for 10.0.1.34, which is my LAN IP.  Unless I'm very mistaken, this means that TCP Port 80 is not open on my computer.  My 2wire router is forwarding port 80 to port 80 on 10.0.1.34, like it should be.  My OS X Firewall is off, according to its Preferences pane.
How do I open up TCP Port 80?

EDIT:
Well, it's semi fixed.  I think it's a problem with the Apache server itself.  I realized that I still had a copy of my old setup from OS X Tiger in /user/local/apache2.  I ran the server in that location, changing the User and Group names in httpd.conf to "_www" as in the Snow Leopard default, and it worked great.
A weird hint that led me to that conclusion: the log files from the standard Snow Leopard setup of Apache hadn't been created.  I assume that Apache ran into trouble before it could even start up (but for some reason didn't leave much evidence as to what went wrong).
Answer: Activating web sharing should be enough to get it running.  Unless you've screwed with the config and messed something up.
I just tried it, and on 127.0.0.1 I see the default Apache landing page.
Is there any possiblity that under Security->Firewall->Advanced that you've clicked the checkbox that says "block all incoming connections"?
Comment: I second that. Do you have some third party firewall running?


Convolution of two Uniform random variables

Question: We have $X \sim \mathrm{Unif}[0,2]$ and $Y \sim \mathrm{Unif}[3,4]$. The random variables $X,Y$ are independent. We define a random variable $Z = X + Y$ and want to find the PDF of $Z$ using convolution.  Here is my work so far:
The definition of convolution is:

$f_Z(z) = \int_{-\infty}^{\infty}f_X(x)f_Y(z-x)\mathrm{d} x$

We know the PDF's of $X$ and $Y$ because they are just uniform distributions. The hard part for me is finding the limits of integration. We have to solve for the constraints.
The integrand is nonzero when $3 \leq z-x \leq 4$ and when $0 \leq x \leq 2$. Together these constraints imply that $\max \{0, z-4\} \leq x \leq \min \{2, z-3 \}$.
These constraints imply that there are three cases:

Case 1 - $z \leq 4 \implies f_Z(z) = \int_0^{z-3}$
Case 2 - $4 \leq z \leq 5 \implies f_Z(z) = \int_{z-4}^{z-3}$
Case 3 - $z \geq 5 \implies f_Z(z) = \int_{z-4}^{2}$

My question is how to find the bounds of $Z$ i.e. what are the possible values of $Z$? Does $Z$ run from $0 \to 6$ since it is the sum of $X+Y$ and this sum will have some value for every value $\in [0,6]$?
Comment: "The hard part for me is finding the limits of integration" Then write down the densities correctly, that is, **including the indicator functions**. Here, $$f_X(x)=\tfrac12\mathbf 1_{0<x<2}\qquad f_Y(y)=\mathbf 1_{3<y<4}$$ hence $$f_Z(z)=\int f_X(x)f_Y(z-x)dx=\int\tfrac12\mathbf 1_{0<x<2}\mathbf 1_{3<z-x<4}dx=\tfrac12\int\mathbf 1_{0<x<2}\mathbf 1_{z-4<x<z-3}dx,$$ that is, **for every $z$**, $$f_Z(z)=\tfrac12\int_\mathbb R\mathbf 1_{\max(0,z-4)<x<\min(2,z-3)}dx=\tfrac12(\min(2,z-3)-\max(0,z-4))^+,$$ and, **only now**, turn to cases to identify the RHS. This way, you cannot fail.
Comment: @AlexanderCska "how do you evaluate min(2,z−3) and max(0,z−4)" ?? Well, by considering three cases, depending on the signs of z-5 and z-4 (what else?).
Comment: @Did yes but $z$ is limited by bound, that depend on $x$. $3+x\le z \le 4+x$. Are these cases obtained by setting the limits for $x$, $0 \le x \le 1$. Say $ 3 \le z \le 4$ and $4 \le z \le 5$
Comment: @AlexanderCska Sorry but I do not get your point. (Additionally, I am not quite sure you really read my previous comment.) Maybe ask a new question, centered around the specific problem you are facing?
Comment: @Did I am just confused how exactly do you get the limits of $z$, when looking for $min(2,z-3)$. You need to know the possible values of $z$ to get the minimum.
Comment: @AlexanderCska Yeah, which is why I explained that one has to distinguish three intervals. Did you try to compute the relevant minimum and maximum in each of these intervals?
Comment: @DId so you are basically finding the intersection of the two indicator functions. The min/max part of the integral tells you where on the real line this intersection interval is located
Answer: Instead of trying to find appropriate $z$ values at the very beginning, note that $f_X(x)$ is zero unless $0\le x\le2$.  Therefore
$$\int_{-\infty}^{\infty}f_X(x)f_Y(z-x)\mathrm{d} x
  =\int_0^2f_X(x)f_Y(z-x)\mathrm{d} x
  =\frac12\int_0^2 f_Y(z-x)\mathrm{d} x\ .$$
You can now substitute $t=z-x$ to get
$$\int_{z-2}^z f_Y(t)\mathrm{d} t$$
- see if you can take it from here.
Comment: Yes, $f_X(x)$ is nonzero only when $0 \leq x \leq 2$. To find the bounds of $z$, we see that $ 3 \leq z-x \leq 4$. But, the minimum $x$ can be is $0$ and when $x=0, z = 3$. The maximum $x$ can be is $2$ and when $x = 2$, the maximum $z$ can be is $6$. Does this all imply $3 \leq z \leq 6$?
Comment: Yes, to get a non-zero result from the last integral we must have $z-2\le4$ **and** $z\ge3$.  (Sorry for the delay, I was away from my desk for an hour.)
Comment: Thanks David. You're awesome


Where can I get the uploaded file in Meteor Files?

Question: I am using Meteor and React JS. I also added Meteor Files.
https://github.com/VeliovGroup/Meteor-Files
By using this code,
this.Images = new FilesCollection({collectionName: 'Images'});
export default class Logo extends TrackerReact(React.Component){
    constructor(){
    ...
    Meteor.subscribe('files.images.all');
    }
uploadLogo(e){
    if (e.currentTarget.files && e.currentTarget.files[0]) {
      // We upload only one file, in case
      // there was multiple files selected
      var file = e.currentTarget.files[0];
      if (file) {
        var uploadInstance = Images.insert({
          file: file,
          streams: 'dynamic',
          chunkSize: 'dynamic',
          transport: 'http'
        }, false);

        uploadInstance.on('start', function() {
          //template.currentUpload.set(this);
        });

        uploadInstance.on('end', function(error, fileObj) {
          if (error) {
            alert('Error during upload: ' + error.reason);
          } else {
              console.log("done");
            alert('File "' + fileObj.name + '" successfully uploaded');
          }
        });
        uploadInstance.start();
      }

    }else{
        console.log("error");
    }
}
render(){
...
<input type="file" id="fileinput" onChange={this.uploadLogo.bind(this)} />
}

I am able to upload the file but I don't see any files in my directory.
Here is my publish.js,
this.Images = new Meteor.Files({
  debug: true,
  collectionName: 'Images',
  allowClientCode: false, // Disallow remove files from Client
  onBeforeUpload: function (file) {
    // Allow upload files under 10MB, and only in png/jpg/jpeg formats
    if (file.size <= 1024*1024*10 && /png|jpg|jpeg/i.test(file.extension)) {
      return true;
    } else {
      return 'Please upload image, with size equal or less than 10MB';
    }
  }
});
Meteor.publish('files.images.all', function () {
    return Images.find().cursor;
  });

How can I display the image? How can I limit the user to upload files that are only images?
For me, their API Docs is not rich. I can't understand what the things they are talking in their docs.
Answer: By default uploaded files are stored in the file system. Read the FAQ:

Where are files stored by default?: by default if config.storagePath
isn't passed into Constructor it's equals to assets/app/uploads and
relative to running script:

On development stage:
yourDevAppDir/.meteor/local/build/programs/server

Note: All files
will be removed as soon as your application rebuilds or you run meteor
reset. To keep your storage persistent during development use an
absolute path outside of your project folder, e.g. /data directory.

On production: yourProdAppDir/programs/server

So you need to set a location with config.storagePath


Css redirect to other css file after logging out. Bug?

Question: I have styled the class .tab-content and it works fine whenever i logged in, but i logged out then the css file is changed to a different file as you can see on the screenshoots below. I have ran drush cc all and drush cron as well as I don't have boost module installed. Do you have any idea to fixed this?
when i login
when i logout
Comment: What makes you think these should be the same?
Answer: Drupal serves aggregated CSS. If one or more CSS files are not available (or required) for anonymous users they are not included in the aggregated file for the sake of a smaller file size. This file can obviously not be saved with the same name.
If you disable CSS aggregation (Configuration > Performance), you can see all individual files and this might explain the difference.
Comment: Thank you for your reply. I just upload again the css file from my localhost to the production site then it works. It is so weird.


Simple Java TCP socket protocols

Question: I'm trying to find a reliable way to send control messages that obey a defined protocol in order to tell the server what kind of data he will receive. For example, I want to send a pure text message to invoke a remote method:
<code>#METHOD1#CLOSE#
</code>
or I want to send a serialized object to the server:
<code>#OBJECT# .......here comes the serialized object data....#CLOSE#
</code>
So basically I just want to send string control messages that are completely independent
of the stream content that follows.
By wrapping an input stream into a Scanner object I'm able to extract strings from the input stream, but if this stream is a serialized object then the object can't be restored afterwards. Thanks for any help.
Comment: Why don't you just use one of the many existing protocols for this purpose? For instance, JSON-RPC? Do you have any specific requirements?
Comment: "if possible" is no valid reason. Which is why I asked for your requirements. There is no reason at all to hack your own protocol if an existing one already fits your need. Do not reinvent the wheel!
Comment: If possible, it should be a pure socket based solution. I just would like to know how this could be done.
Comment: It's an assignment. Protocols for strings are not a problem, because I can easily append a control message to the actual message string. However, the easierst solution seems to be to subclass ObjectOutputStream.
Answer: You can use a scheme like Base64 (e.g. use a library from Apache) to encode the Object from bytes into a string and then back.
<code>ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream(baos).writeObject(object);
String serializedObject = Base64.encode(baos.toByteArray());

byte[] bytes = Base64.decode(serializedObject);
ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
Object object = new ObjectInputStream(baos).readObject()
</code>
Comment: What about Java's BASE64Encoder/Decoder? So, basically I have to encode the object to a string and then append that object string to the control message string, right? To decode the message I read the chars that represent the control message and, if the message says it's an object, I go on adn decode the rest of the string to an object.
Comment: Yes, that's right. You can use any Base64 encoder/decoder you like.

Simple Java TCP socket protocols


HttpContext.Current.Request.IsLocal não funciona na classe Startup

Question: Estou tentando utilizar HttpContext.Current.Request.IsLocal; em uma aplicação web api 2 na classe Startup metodo Configuration(IAppBuilder app).
A ideia é só subir um servidor hangfire se estiver em produção, não quero subir local.
O problema é que no servidor sempre vem true, e isso só acontece nessa classe, fiz uma rotina de teste em um controller e ele funcionou, retornou false.
Como eu poderia saber se é local ou não nesse momento do sistema?
Segue o código de exemplo:

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {

          bool isLocal = HttpContext.Current.Request.IsLocal;
            if (isLocal == false) {
                app.UseHangfireServer(boptions);

        }

     }
Answer: A classe Startup é executada quando o servidor sobe, e isso é feito pela propria maquina que o servidor está executando.
Por isso o IsLocal sempre vai retornar true...
The IsLocal property returns true if the IP address of the request originator is 127.0.0.1 or if the IP address of the request is the same as the server's IP address.


Does a statement need to be a biconditional statement to prove by the contrapositive

Question: I am trying to write a proof and was wondering if a then b, the converse if b then a might not be true. This leads me to wonder if the statement needs to be an if and only if statement if it can be proven by the contrapositive if not b then not a.
That is do I need a statement like this a if and only if b to prove that if not b then then not a, or is if a then b sufficient to do that.
Comment: Yes you are right, just changed it
Comment: In "regular mathematics", $a\implies b$ and $\neg b\implies \neg a$ are equivalent.
Comment: I think I know what is the problem with my statement. I will fix it.
Answer: By definition, "$a \implies b$" means "not ($a$ and not $b$)". So then "(not $b$)$\implies$(not $a$)" means "not ((not $b$) and not (not $a$))". This simplifies to "not ($a$ and not $b$)", which is the same thing as "$a \implies b$". So yeah, you only need the one direction of implication.
You should probably think about this definition of $a \implies b$ if you've never seen it. Like, draw a truth table or something.
Answer: In general, $p\to q$ does not imply the converse, $q\to p$. For example, using a truth table, you can show that $p\to q$ is logically equivalent to the contrapositive:
$$p\to q \equiv \neg q \to \neg p$$
In other words, you do not need $q\to p$.
If you have that $p \leftrightarrow q$, then by definition you have that
$$q\to p.$$

If you are tasked with showing that $P$ implies $Q$, then one strategy is to show instead that $\neg Q$ implies $\neg P$, since $P\to Q \equiv \neg Q\to \neg P$. Thus, assume $\neg Q$ and arrive at $\neg P$. Then you have shown $P$ implies $Q$ since they are logically equivalent.
Comment: Thanks! You figured out what I was trying to say my bad. I have corrected my question above as well.
Comment: @Jam1 Sure, good luck.


Is the statement valid?

Question:
Now consider a point just next to point (,), say (+ℎ,′). Here, ℎ is infinitesimally small, such that ℎ→0. Now, the slope of the line between these 2 points will give us the instantaneous rate of change as after that instant we will move on the next instant/point.

Above statement is very important to understand. Point  and  are actually next to each other! (that's how we have defined). Even if you see a curve of 2 on your screen and take 2 pixels that are next to each other to be lying on the curve, they are still actually not next to each other with respect to the curve as between those 2 pixels there are infinitely many points but the points that we have taken, that is,  and  are next to each other!

The above two paragraphs are from an answer on this forum link to answer. I see flaws in the answer, but I was confused since it was getting upvotes. My question is, how can you take two points next to each other? Doesn't that violate the density property of real numbers?
For context, the answer was written to explain what derivatives are and what they mean. I just feel the statements used are mathematically invalid; if they are then the answer should be removed as it would mislead many. Let me know your thoughts.
Comment: @dumbguywithmathsmajor yes, that statement is just false. You can't talk about the notion of two points being next to each other in $\mathbb{R}$.
Comment: Still, I won't say the two points are "next to each other" but rather "close to each other"
Answer: I've spent a while trying to find the correct wording for this, as I don't want to criticize the answerer for doing their best to help someone else -- teaching mathematics is a whole other challenge! I don't really like the presentation of $P$ and $H$ as "next to each other," but for a different reason. Certainly $x+h$ and $x$ cannot be 'next to each other' when $h$ is nonzero for the reason you have stated, but in a secondary school setting I don't think the density of $\mathbb{R}$ is much helpful pedagogically speaking.
I think a good way to approach this topic is in keeping with a philosophy of "start where your learner is familiar and take steps into the unfamiliar from there." If you take a simple quadratic and pick a point on it, students familiar with the concept of a tangent line will have a pretty good idea of what it should look like. Then you ask the students to tell you about the tangent line and its properties. What is the slope of the line? What is its equation? Your students may feel dumbfounded: surely this line has to have an equation and a slope... what are they? Then after a good discussion you can start with the construction of tangent lines using secant lines between points whose distance is progressively smaller, introducing the concepts of differential calculus.
At least to me, saying that $x$ and $h$ are "next to each other" seems to me to skip the important details of the above approach: instead of making it clear where the $x$ and $x+h$ came from, you're essentially saying, "I have two points: $(x,y_1)$ and $(x+h,y_2)$, and they're, like, really close to each other." This is problematic because it (a) runs into arguments about what "close" means and (b) might give students the false belief that $h$ is a specific number rather than a quantity that approaches zero. This could be remedied by saying something like

Consider two points $P(x,f(x))$ and $Q(x+h,f(x+h))$. Say $h$ is a positive, real number. When $h$ is quite large, the secant line $PQ$ won't be very representative of the tangent line at $P$. If you want $PQ$ to look more like the tangent line at $P$, you make $h$ smaller and smaller. Of course, just going straight to $h=0$ isn't helpful because we just get the same two points -- instead, you make $h$ smaller and realize that it only seems natural that the tangent line occurs when you make a secant line $PQ$ with $h=0$.

With regard to removing the answer, I don't think that would be justified at all. Not only does the answer not violate any of the rules, but it can also help spawn discussion of the sort that we are having right now, which I think is very useful to both learners and teachers alike. If you don't think the answer does a good job, you're free to downvote it or leave a comment suggesting improvement.
Comment: I agree with what you are saying, but at least the author should mention that this is not the complete picture (in this case, the author doesn't even agree that this is not the complete picture). In any mathematics course, derivatives are taught after limits, which should be the correct order of learning about these two. Also, I asked the question author what level of education he is at, he said he is a 1st-year college undergrad.

Is the statement valid?


Probability of sample means being equal

Question: Let $X\sim N(70,16)$ and $Y\sim N(70,9)$. Given a sample of size $n=4$ from $X$ and a sample of size $m=9$ from $Y$, compute
$$
P(\bar X = \bar Y).
$$
Comment: Because the sample means have continuous distributions, the chance they are equal must be zero.  Thus, questions of this sort are fruitless: it is meaningful only to ask for the chance that the difference of means might lie within some interval of nonzero length.
Comment: @ShawnHemelstrand Yes turns out the answear is 0 because X~N and Y~N
Comment: What have you tried so far? This looks eerily like a homework question copy and pasted here.
Comment: @ShawnHemelstrand Yeah well i said that x̄ - ȳ = d and d~N. Later on another question asks to find the probability of x̄ - ȳ>2 in which case I did this:
P(d>2). Since d is a linear combination of random independent normal variables i said E(d)=E(x̄)-E(ȳ)=0 and V(d)  =  V(x̄)+(-1)^2*V(ȳ)  =  V(x̄)+V(ȳ)=. And after that i get P(Z>0.899427) = 0.81594.
What got me trippin was the equality but its probably as whuber said
Answer: By some properties of the normal distribution  (make sure you understand which)
$$\bar X \sim N(70, 16/4), \quad \bar Y \sim N(70, 9/9)$$
If $X$ and $Y$ are independent, $\bar X - \bar Y = W \sim N(0, 5)$. Therefore
$$
P(\bar X - \bar Y) = P(W = 0)=\cdots
$$
I leave the rest to you...

Probability of sample means being equal


Recover data from 1 disk after broken raid 5

Question: in a bit of an emergency. I am taking control of some servers that someone else had setup. One of them has crashed and it was critical. Here is what I found:
The server (Dell r710) was operating with one hard disk, when checking the RAID configuration, to my surprise it was setup on RAID 5, which as far as I know, it can't be. What can I do to attempt to recover the files?
I've had an idea of reconfiguring the RAID controller to RAID 0 and not initializing the disk. Would that be good?
Comment: Was the drive connected to the Raid controller or just connected to an onboard sata port?
Comment: Hey Drifter, it was connected to the Raid controller
Answer:
What can I do to attempt to recover the files?

Stop what you are doing. Power off the server. Remove the hard drives and ship them off to a professional data recovery shop. Period, full stop.
You haven't a clue how exactly it was configured before, and anything more you do to it will cause further issues.

I've had an idea of reconfiguring the RAID controller to RAID 0 and
  not initializing the disk. Would that be good?

No. Heck no. Don't even consider it.
Comment: I would recommend cloning the contents before sending the disk(s) anywhere.
Comment: Not just "the drive" but _all the drives_ in the array.
Comment: Yep, clone the disks using `dd` or equivalent.
Comment: Ok! I will consider that as an option. As a note, the odd thing here is that it was operating with a single drive on RAID 5. I've got but one drive to ship off to a data recovery company.


Asp.Net DropDownList tooltip ou title com JS

Question: Estou iniciando em Javascript, e gostaria que meu DropDownList de um controle .ascx, ao selecionar um item, exibisse o seu valor completo quando passar o mouse em cima, como se fosse um tooltip ou title.
   Este é o meu DropDown:
<asp:DropDownList CssClass="dropdown" ID="ddlDescricao
 OnSelectedIndexChanged="ddlDescricao_SelectedIndexChanged"
                        runat="server" TabIndex="0">

Tentei fazer dessa forma:

Porém não está dando certo.
Estou usando jQuery 1.7
Desde Já Obrigado a todos.
--Edit 11/02/2016 08:27
Estou invocando a função pelo onmouseover do dropdown.
Answer: Basta utilizar a seguinte instrução:
$("select[name*='ddlDescricao']")
    .prop('title', $("select[name*='ddlDescricao'] option:selected").text());

O seletor foi feito utilizando o atribute contains porque o nome dos controles normalmente é modificado na rendização.
Atualização:
Adicionando o código da segunda objeção
var $dropdown = $("select[name*='ddlDescricao']");
$dropdown.prop('title', $dropdown.attr('title') + ': ' + $dropdown.children("option:selected").text());

Comment: Boa tarde, obrigado a principio deu certo, porém, quando há mais de um dropdown na pagina, ela vai dando um "append" nos valores do tittle, por exemplo o valor do dropdown1 é carlos, o valor do dropdown2 é vinte, no dropdown2 o "title" ficara como carlosvinte, ao invés de apenas "vinte".
Comment: Alterei a resposta
Comment: Bom dia Felipe, obrigado pela resposta, mas infelizmente acontece praticamente o mesmo, veja na imagem da edição que anexei.
Answer: Não sei se entendi muito bem o problema, mas se precisa alterar o título de um elemento utilizando javascript pode fazer desta forma:

<select id="ddlTeste" onchange='alteraTitulo()'>
<option>Valor 1</option>
<option>Valor 2</option>
<option>Valor 3</option>
</select>

Dessa forma eu seleciono o elemento em questão em var ddl = document.getElementById('ddlTeste');, obtenho o texto da opção selecionado var title = ddl.options[ddl.selectedIndex].text; e altero o título ddl.title = title;.
JSFiddle
Edição
Uma solução simples (usando apenas javascript) para vários selects seria você passar o id do elemento para sua função. Seria mais ou menos isso:

<select id="ddlTeste" onchange='alteraTitulo("ddlTeste")'>
<option>Valor 1</option>
<option>Valor 2</option>
<option>Valor 3</option>
</select>

<select id="ddlTeste1" onchange='alteraTitulo("ddlTeste1")'>
<option>Teste 1</option>
<option>Teste 2</option>
<option>Teste 3</option>
</select>

JSFiddle
Utilizando o jQuery você pode realizar a troca ao executar o evento .change(), fazendo assim a substituição do título. Ficaria assim seu código:

$('select').change(function(){
var ddl = $(this);
var title = ddl.find("option:selected").text();
ddl.prop('title', title);
console.log(title);
});

<select>
<option>Valor 1</option>
<option>Valor 2</option>
<option>Valor 3</option>
</select>

<select>
<option>Teste 1</option>
<option>Teste 2</option>
<option>Teste 3</option>
</select>

JsFiddle
Comment: Bom dia, obrigado pela resposta, mas dessa forma quando houver mais de um dropdown em tela, o valor selecionado em um dropdown, sera estabelecido para todos os demais.
Comment: Eu pensei em uma forma de fazer isso, porém não sei como implementar, esse é o codigo para ter uma noção mais ou menos do que eu tentei fazer:` function alteraTitulo() {
        var $dropdown = $("select[name*='ddlDescricao']");`

        for (i = 0; i < $dropdown.children.length; i++) {
            $dropdown[i].prop('title', $dropdown[i].find("option:selected").text());
        }
    }
Comment: @CarlosHenrique Você está usando somente javascript ou jquery? Mas é exatamente isso que você quer? Claro, funcionando para mais e um `dropdown`
Comment: Estou utilizando jQuery e javascript, qualquer um que me proponha a solução. O que eu quero é que quando eu passar o mouse por cima de um valor selecionado de um dropdown, ele me exiba o que esta escrito no valor selecionado, por que há casos em que o dropdown tem espaço para 20 caracteres e o valor possui 40 por exemplo, assim o usuario não saberia o que esta selecionando, porém, as soluções que tentei funcionam se houver apenas um dropdown em tela, quando há mais de 1 dropdown, ele se perde, acaba atribuindo o valor do dropdown anterior ou proximo, vou tentar implementar a sua ultima edição.


PHP parsing Wikipedia content, UTF8 hyphen

Question: I'm currently trying to parse content from de.wikipedia.org with PHP.
After reading the pages with file_get_contents(...) and converting the received content with utf8_decode(...) from UTF8 to ISO-8859-1 the main part is displayed and saved correctly. Only some special characters like the "long hyphen" (–) are not being converted and getting display as – or ?.
This hyphen seems to have to unicode-id 150 - how may i display it on ISO-8859-1?
Example: http://de.wikipedia.org/wiki/23_%E2%80%93_Nichts_ist_so_wie_es_scheint
Comment: You can't — it's not part of the [ISO-8859-1 character set](http://en.wikipedia.org/wiki/ISO/IEC_8859-1#Codepage_layout) (although [Windows-1252](http://en.wikipedia.org/wiki/Windows-1252) does include it). You can transliterate it into a normal ASCII hyphen, however, as suggested by Niet. Or you could just change your program to output UTF-8 — it's 2014 now, why are you still using old 8-bit charsets like ISO-8859-1?
Answer: Try using iconv instead:
$iso = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $utf8);

Comment: Works like a charm! Already tried like every converting-function in PHP except this one. Thanks a lot!


OLS estimators are independent of the scale of the predictor data

Question: The title says it all: How can I see that OLS estimators (linear regression) do not depend on the scale of the predictor data? I am reading my lecture notes about lasso estimators, where it is mentioned that lasso estimators do depend on the scale of the predictor data, whereas OLS estimators don't. I can somehow see why this would be true for lasso estimators (we need to constrain the L1-norm of the coefficient estimators) and reason why it would be true for OLS estimators (the constraint disappears), but how can I understand this without considering lasso estimators and their properties first?
Thanks in advance!
Answer: Try an algebraic example. The OLS estimator is:
$$
\hat{\beta}_{OLS} = (X^TX)^{-1}X^Ty
$$
Now scale $X$ and $y$ by a scalar $\textrm{a}$:
$$
\hat{\beta}^{scaled}_{OLS} = ((aX)^T(aX))^{-1}(aX)^T(ay) \\
=(X^TX a^2)^{-1}X^Tya^2 \\
=(X^TX)^{-1}X^Ty \underbrace{\frac{a^2}{a^2}}_{=1} = \hat{\beta}_{OLS}
$$
Note that if only $X$ is scaled, then the estimator is scaled by the same factor $\hat{\beta}^{scaled}_{OLS}=a\hat{\beta}_{OLS}$ (since you would have $a^2/a=a$ in the last step).
Comment: Wow, this was surprisingly easy to verify mathematically. Thank you!
Answer: OLS simply works with whatever units you provide in the data. The contribution of predictor $i$ to the linear predictor is $\beta_i x_i$. Any changes in the scale in which $x_i$ is expressed will just result in a proportional change in the value returned for $\beta_i$.
For example, say one of your predictors is a distance, measured in miles, and the outcome is a cost expressed in dollars. The coefficient in OLS would be in units of dollars per mile.
That distance could also be measured in millimeters, with 1609344 millimeters per mile. If you instead do the OLS in those units, the coefficient would be dollars per millimeter.
As the fundamental physical reality doesn't depend on the units of the predictor, the coefficient expressed in dollars per mile would be exactly 1609344 times the coefficient expressed in dollars per millimeter. The fundamental model doesn't depend on the units of the predictor, although the numeric values of the coefficients will differ proportionately to the units.
As methods like LASSO penalize the numeric values of the regression coefficients, this poses a problem. If you use a distance measured in miles, its regression coefficient will be 1609344 times larger than if you measured it in millimeters, and the penalization would depend massively between the two measurement units. Standard practice is thus to start by standardizing continuous predictors by subtracting the mean and dividing by the standard deviation, to obtain predictor values without units. Once penalization is done, you can go back to the original units, or re-express in any other choice of units.


where to save images generated by php before moving to cloud

Question: I have a laravel php app were a user is going to upload an image.  This image is going to be converted into a number of different sizes as required around the application and then each image is going to be uploaded to aws s3.
When the user uploads the image php places it in /tmp until the request has completed if it hasnt been renamed.  I am planning on pushing the job of converting and uploading the versions to a queue.  What is the best way to ensure that the image stays in /tmp long enough to be converted and then uploaded to s3
Secondly where should I save the different versions so that I can access them to upload them to s3 and then remove them from the server(preferably automatically)?
Comment: you need to move it from the system temp to your own, or it will be deleted
Comment: The /tmp he directory is cleared by default at every boot, because TMPTIME is 0 by default.

Here you can change the time in the following file:

/etc/default/rcS
TMPTIME says how frequent the tmp dir sould be cleared in days
Answer: I would create a new directory and work on it. tmp folder is flushed every now and then depending on your system.
As for different sizes, i would create separate buckets for each size which you can access with whatever constant you use to store the image (ex: email, user id, etc..).


Erro no login do Heroku no cmd do Windows

Question: Tento acessar os serviços do Heroku pelo cmd, porém recebo essa mensagem:
C:\Users\xxx.xxx.xxx
λ heroku login
 !    EPERM: EPERM: operation not permitted, open 'C:\Program Files (x86)\GNU\SSH\_netrc'

Answer: Uma das causas para este erro é a permissão de acesso do arquivo. Verifique se o arquivo está como readonly através das propriedades do arquivo.
Se estiver, desmarque a opção e tente novamente.


$2^{5-2}$ Design : Alias Structure

Question: $2^{5-2}$ Design
Design Generators: $D=AB\quad E=AC$
Defining Relation: $I=ABD=ACE=BCDE$
$$\text{Aliases}$$
$$A=BD=CE=ABDE$$
$$B=AD=ABCE=CDE$$
$$C=ABCD=AE=BDE$$
$$D=AB=ACDE=BCE$$
$$E=ABDE=AC=BCD$$
$$BC=ACD=ABE=DE$$
$$CD=ABC=ADE=BE$$
  But the alias structure in the book Design and Analysis of Experiments by Douglas C. Montgomery [Appendix XII (c)] is as following:
$$\text{Aliases}$$
$$A=BD=CE$$
$$B=AD=CDE$$
$$C=AE=BDE$$
$$D=AB=BCE$$
$$E=AC=BCD$$
$$BC=DE=ACD=ABE$$
$$CD=BE=ABC=ADE$$
Instead of $A+BD+CE+ABDE$, this is $A+BD+CE$ in the book and so on.

Why ?
Answer: I think he's just not showing the 4- and 5-way interactions, for brevity and assuming people won't be too concerned about them
Answer: Interaction of order IV or higher are not written because they are usually not significant. This principle is called "sparsity-of-effects principle" and it is explained in Design and Analysis of Experiments by Douglas C. Montgomery.

$2^{5-2}$ Design : Alias Structure


Template template parameters and variadic templates with gcc 4.4

Question: I'm using gcc 4.4 on Debian squeeze. Consider the following code.
#include <map>
#include <string>
using std::map;
using std::string;

// Args lets the user specify additional explicit template arguments
template <typename T,
      template <typename T, typename... Args> class C,
      typename... Args>
C<T, Args...> foo()
{
  C<T, Args...> x;
  return x;
}

int main(void)
{
  map<string, int> a = foo<string, map, int>();
}

So, the idea here is that T matches string, C matches map, and the template parameter pack Args matches int. I may have some of the syntax wrong, please correct if so. In particular, if one wants the first template argument in class C to match T and the rest to match the template parameter pack Args, is template <typename T, typename... Args> class C the correct syntax?
This gives the error
In function 'int main()':
post.cc:18: error: no matching function for call to 'foo()'

This appears to be similar to the question Variadic template templates and perfect forwarding. That question suggests that this is a gcc bug, but maybe I am mistaken in thinking these questions are about the same thing.
Please be gentle. My knowledge of variadic templates is less than 12 hours old; I was just trying to rewrite some old C++ code to reduce duplication. It has also been a while since I did any C++. If there is a workaround, please let me know. Thanks.
EDIT: The workaround suggested in the comments of Variadic template templates and perfect forwarding by Ise Wisteria worked for me, which suggests that this is the same bug. Of course, I'm am now
(a) wondering how fragile this workaround is and (b) why it works, and what motivated Ise to think of it.
Though I guess only Ise can answer the last bit. :-)
Comment: The code compiles on g++ 4.7. Should be a bug.
Comment: @KennyTM: Thanks. That means I don't need to report it, right?
Comment: So, what do you want to happen to this question? Close as duplicate? Maybe answer your own question? :) This can't be left as is.
Comment: @Xeo: So, it is definitely a duplicate of the linked question in your opinion? If so, I don't have strong feelings. Would it be Ok if I answered it and then accepted my answer? Unless you or someone else would rather. :-) If it is closed, will it still be visible to people doing searches?
Comment: Not exactly, but the problem is the same, aswell as the answer. I don't really care though, might aswell go ahead and answer your own question. :)
Answer: As discussed in the edits, my question appears to tickle the same bug as the linked question, Variadic template templates and perfect forwarding. In particular, the workaround given there in a link also works in my case. The modified code that works is as follows:
#include <map>
#include <string>
using std::map;
using std::string;

template <typename T,
      template <typename T, typename... Args> class C,
      typename... Args>
struct X
{
  typedef C<T, Args...> type;
};

template <typename T,
      template <typename T, typename... Args> class C,
      typename... Args>
typename X<T, C, Args...>::type foo()
{
  C<T, Args...> x;
  return x;
}

int main(void)
{
  map<string, int> a = foo<string, map, int>();
}

Answer: I don't think variadic template parameters can match non-variadic arguments in g++4.4, so you need to overload your foo function with a non-variadic version.
Also keep in mind that map actually has more than two template parameters, and therefor wont match the new foo-function either.
This addition to your example should clarify it:
#include <map>
#include <string>
using std::map;
using std::string;

// Args lets the user specify additional explicit template arguments
template <typename T,
          template <typename T, typename... Args> class C,
          typename... Args>
C<T, Args...> foo() {
  C<T, Args...> x;
  return x;
}

template<typename T, template<typename, typename> class C, typename Arg>
C<T, Arg> foo() {
  return C<T, Arg>();
}

template<typename T, typename... Args> class A {};

template<typename T, typename Arg> class B {};

int main(void) {
  map<string, int> a = foo<string, map, int>(); // fails.
  A<string, int> x = foo<string, A, int>();
  B<string, int> y = foo<string, B, int>();
}

Comment: @Xeo: Fair enough. I'll edit the answer to reflect your point.
Comment: No, variadic templates are explicitly able to match nonvariadic templates.
Comment: Well, that's a bug. I'm talking about what the standard says. "I don't think variadic template parameters can match non-variadic arguments" seemed to suggest that you think this is the case in general.


How to create a chart about the number of nodes by content type?

Question: I am trying to make a chart with 1 column for each content type. Values are the addition of each total.
I have created a view (using the Views module) with two content-type fields. One of them is configured to Count Distinct in aggregation.
In a graph, however, only one column named Type appears, and not a column for each content type.
I am trying both with Views Dataviz and Google Charts Tools.
Any help on this would be appreciated.
Comment: More information needed. Consider writing a custom module. Always works. The Visualization API is very promising for such kind of work.
Answer: Let me try to answer this if I am getting you clearly. There are several contributed modules available for creating charts in Drupal. Refer to the comparison of charting modules for more details. You are not specifying the Drupal version, let me assume a use case for 7. Also know that there are various types of licenses (commercial, open source, ...) for each of the charting libraries, so your choices may be limited by your license needs (each module typically requires at least 1 such charting library as its charting engine).
The solution I am giving has a lot to do with the Google Charts API implemented via the Google Chart Tools module. The module provides a simple API that allows you to build your graphs on that.The module ships with an example that gives a nice pointer to writing your own custom module.
A simple module to get the content types.
function example_block_info(){
  //lets display this in a block. You can do a page if you like.
  $blocks['example_chart'] = array(
     'info' => t('Example Line Bar Showing Content Types'),
     'cache' => DRUPAL_CACHE_PER_ROLE //This is a Drupal default.You can set your own.
   );
 return $blocks;
}

function example_block_view($delta = ''){
    //Create a display for the block.
    switch ($delta) {
      case 'example_chart':
       $block['content'] = example_block_contents()
      break;
    }
  return $block;
}

function example_block_contents(){
  //This is a function specific to the block that lets you prepare the content for the chart.
    //Google Chart Tools integration begins here.
    //First empty the array that is to be passed to draw_chart().
    $settings = array();
    //We then populate the array.
    $settings['chart']['Chart for Nodes'] = array(
      //I am using just one content type. You can loop to get the other node types.
      'header' => array('My Node'),
      //This is the array to be presented to draw().
      'rows' => array(array(
                example_node_count(),
               )
           ),
      'chartType' => 'ColumnChart',
      'containerId' => 'example_chart',
      'options' => array(
            'forceIFrame' = FALSE,
            'title' => 'A column chart for nodes',
            'width' => 800,
            'height' => 600
        )
    );
    draw_chart($settings);
    //Return the DIV containing the chart.
    return '

';
}

function example_node_count(){
  //Custom function to count the nodes available.
  //Put to use Entity Field Query.
  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'my_node_type');
    //Count your node type.Introduce a loop to count your other nodes as needed.
    $my_node_type_count = $query->count()->execute();
    return $my_node_type_count;
}

This is just a shell of a working module. Get some education of the charts at Google Visualization API docs. Warning: There might be some typos in there. Just trying to give an alternative.
Answer: I seem to understand that this question is exactly what the purpose is of one of the Out-of-the-box examples that you get by simply installing (and enabling) the Charts module, and without any additional configuration.
By doing so, a new view is added to your site. Here are some more details about it, quoted from the linked page above (to which I added some formatting here):

You can see the charts created via this new view in your own site by
  navigating to charts/examples or by using a menu link with a title
  like Charts examples. After doing so, a page is shown with 2 sub-menu
  tabs:

the first tab is titled Built-in examples (this example is used to
  showcase Using the Charts API).
the second tab is titled Views
  example, and is what is created from the new view created during the
  installation of the charts module. As an alternative to using this
  tab, just navigate to charts/examples/views in your site. You should
  then see a column chart and a pie chart, which are followed by a
  tabular display also. Both charts and the table display contain data
  about the total number of nodes for each of the available content
  types.

Visit the Charts demo site for an online preview of these out-of-the-box examples.
Disclosure: I'm the maintainer of this module.


SQL Server connection breaking

Question: I am facing some issue while running a batch that pulls data from SQL Server to mysql. I am pulling data in chunks in the beginning for 5-6 lots (1 lots = 5000 rows). It works fine but after sometimes it stops suddenly without any exception/errors and I get an error

The connection is broken and recovery is not possible. The connection is marked by the client driver as unrecoverable. No attempt was made to restore the connection

Any help will be appreciated.
Comment: How good is the connection between the two PCs?
Comment: If you are pulling data from SQL Server, seems you have more of a MySQL issue - which you did not tag. But much depends on how exactly you have set this up - and perhaps which versions / editions of the various bits of software that are involved.
Answer: A simple solution would be to re-start the failed job assuming that there won't any data duplicates issue. If that doesn't help then make sure that the connection between the MySQL and SQL Server is fine or not. As far as I know, the error message is stating that it is related connection failure. Contact your admin to test whether the required connections are fine or not.
Comment: I have tried to create the connection but that doesn't help. i can't restart my whole batch process as its a long run...... it takes around 40 minutes to complete as i am loading alot of data and data needs to be run in sequence as it is dependent to the previous one.
Comment: If you are sure that the data is connection is fine, then take a back up of the data from your table and then restart the job. There will be an option called Start Job at or restart from. Then the job will resume from that step onwards. If you are newbie who is loading data using this job then contact your team members before proceeding on with this. Your job is more of an internal process and that should be handled based on how your job is designed. There is no generalized answer for your question. Reach out to your project team.

SQL Server connection breaking


Flutter auto_route, getter 'key' was called on null

Question: import 'package:myapp/core/routes/router.gr.dart' as app_router;

child: MaterialApp(
    title: 'MyApp',
    debugShowCheckedModeBanner: false,
    builder: ExtendedNavigator.builder<app_router.Router>(
      router: app_router.Router()
    ),

I have implememented autoroute however I get an error here that the getter key was called on null
Answer: As Masnun pointed out, commenting out the line 37 solves the issue. However, there is a different solution that doesn't involve touching the source of the auto_route.
I fixed this issue by removing .builder from:
builder: ExtendedNavigator.builder(
  router: Router(),
  ...
),

and changed to
builder: ExtendedNavigator(
  router: Router(),
  ...
),

Answer: The problem is here is this line (line 37).
key: GlobalObjectKey(nav.key),

Commenting out the line from library works fine for me. It may be a temporary problem.
Comment: Discussion at GitHub: https://github.com/Milad-Akarie/auto_route_library/issues/257


Let f(x) be some PDF, and F(x) be its CDF. Shouldn't F(x)=.5 give us the expected value of f(x)?

Question: I was playing around in R and have gotten myself very confused about the relation between probability distributions, their expected values, and their cumulative distribution functions.
Say we're interested in the expected value of the gamma distribution. Here's a hacky way to calculate it in R:
<code>library("pracma")
m=2
s=1
grid = seq(0,50,.01)
y = dgamma(grid, m, s)
(expected = trapz(grid,grid*y))
[1] 2
</code>
Intuitively, the expected value of the distribution is something like its 'center of mass': a point where half the weight of the distribution is on one side, and half is on the other side.
If this reasoning is right (I thought to myself), then this point should be identical to the point where the cumulative distribution function is equal to .50. Why? Well, because at the X value where the CDF is .5, a random variable has 50% change of being less than X and a 50% chance of being greater than X-- that is, X is the point where half the weight of the distribution lies on either side. (EDIT: If I had to pinpoint where my misconception occurred, I would say it was here. Center of mass isn't just about proportion of weight, as the answers below have reminded me.)
I decided to follow this hunch:
<code>(halfway  = qgamma(.5, m, s))
[1] 1.678347
</code>
Nope, my hunch was wrong. The numerical difference seems to be too systematic to be the result of using numerical integration (seems to happen on any asymmetric distribution, to varying degrees, try for yourself).
How am I thinking about this incorrectly?
Comment: In physics a center of mass differs from what you describe: it is a "balancing point" of an object. As a little contemplation of mobiles, cantilevered architecture, and other highly asymmetric but stable objects will show, much more than half the mass can lie on one side of the center of mass ("barycenter" or "centroid"). The physical analog here is excellent, because probability density and mass density are mathematically identical.
Answer: In the cases where it (the mean) exists, a nice way to look at this is that the mean is the value $M_2$ which minimizes
$$
\int_{\text{support of $x$}} |x-M_2|^2 f(x) dx.
$$
That is, the the distance from the mean is considered unevenly over the support.. all else equal the farther a point $x$ is from the mean the higher its 'cost' (if the distance is > 1).
The value for which $F(x) = 0.5$ is in fact the median, which is the value $M_1$ which minimizes
$$
\int_{\text{support of $x$}} |x-M_1|^1 f(x) dx.
$$
Distributions which are skewed* in one direction will have medians which are not in the same place as their means.. because the means will gravitate towards the longer tail to compensate for the squared distance, which penalizes further values more than the absolute difference does (when the distance is > 1).

*As rightly pointed out by @Glen_b skewness is used here as defined by Pearson's 2 skewness coeficient. That is, skew is $3\frac{\text{mean} - \text{mode}}{\text{std. deviation}}$.
Comment: @whuber i removed the section on the mode since it wasn't even part of the question anyway
Comment: "*which are skewed in one direction will have medians which are not in the same place as their means*" unless you *define* skewness to make this true (define it as second Pearson skewness, say), this is not always the case. Usually, but not always.
Comment: I've added an explanation for the last equation, which I think will make clearer what Matthew means.
Comment: *Every* real number minimizes the third integral, which equals $1$ no matter what value $M_0$ may have.
Comment: @Pat $0^0$ is *always* defined as $1$.  See, for instance, http://mathforum.org/dr.math/faq/faq.number.to.0power.html. Regardless, the argument about "losing an infinitesimal amount of probability" is wrong.
Comment: Thank you, Matthew: that takes care of the problem nicely. (+1)
Comment: Re: $0^0$, it's been historically contentious. Cauchy listed it as indeterminate. For almost all applications out there, I agree, it makes sense to define it thus. Occasionally not. I agree that the infinitesimal probability argument was weak, but was rushed for time and hoped someone else might fix it later :). I'm pretty sure a much better argument can be made by taking limits. However, Matthew's removed the section, so I guess it's moot! (+1)
Answer:
Intuitively, the expected value of the distribution is something like its 'center of mass': a point where half the weight of the distribution is on one side, and half is on the other side.

The first part of this is correct, it is a center of mass. But beware about how you interpret that; you can't just say "half the mass is each side".

If this reasoning is right (I thought to myself), then this point should be identical to the point where the cumulative distribution function is equal to .50. Why? Well, because at the X value where the CDF is .5, a random variable has 50% change of being less than X and a 50% chance of being greater than X-- that is, X is the point where half the weight of the distribution lies on either side.

No, that's the median. They'll be the same when the distribution is symmetric (assuming the mean exists at all, naturally), but when it's non-symmetric, the two rarely* coincide.
* some people mistakenly assert 'never'. It's unusual, but possible
The moment has two components - the sign (which side you're on) and the magnitude - how far away you are. It's not sufficient to say there are the same fraction on either side**, so we must be at the mean - it depends on how far away they are.
**(or the same number of values on either side for a sample)
Consider a sample, like 1,2,18 (or a distribution with 1/3 probability at each point, it doesn't matter). Let's take "2" as being our candidate for the mean - after all, by your logic, there's the same proportion either side, so they should balance, right?
But the thing is, by putting a value 16 units above the proposed mean, it exerts 16 times the moment (in the physical sense) as the value one unit below it - just as a person sitting at the far end of a see-saw doesn't balance someone of the same weight sitting partway along the other arm:

So it's not having half the distribution either side that determine the mean.
However, if you weight those proportions by their distance you will get the balance you're thinking of (quite literally - take a very light, stiff rod and hang identical weights at 1, 2 and 18 distance units along the rod and find where they balance ... which will be at 7 units. If you work out the signed distances (-6,-5,+11) you can see they balance out.
If you check various distributions on Wikipedia, you'll find that typically for asymmetric distributions the mean and the median differ.
Indeed, the difference between them is used as the basis of a measure of skewness (with appropriate rescaling) - the second Pearson skewness measure.

Another note about your question: when you say "the expected value of $f(X)$", you misspeak. You intend to say "the expected value of $X$, where $X$ has density $f$". The expected value of a continuous $X$ is $\int x\,f(x) dx$. The expected value of $f(X)$, on the other hand is the expected value of the transformed random variable $Y=f(X)$, which by the law of the unconscious statistician is $\int f(x).f(x) dx$. That's a different object altogether. Just stick with "the expected value of $X$".
Comment: Thanks for the informative answer, and the terminological correction!
Answer: $F(x)=0.5$ gives $x$ as the median of the distribution, which you could say is the centre of probability mass.
I think your understanding of the expected value being the 'centre of mass' of a distribution is a little misguided. Expected value is more of a weighted average than a centre of mass, in the discrete (and finite) case what you're doing is weighting the possible values your distribution can take on by the probability of that value occurring. In continuous distributions the analogy isn't as clear, but you're still weighting possible values your distribution can take on by their probability.
Comment: When a line is given a mass density proportional to a probability density, then indeed the mean is the center of mass: the analogy (between probability density and mass density) is *perfect*.


Use a dataset as a datasource for Repeater control?

Question: I'm just learning ASP.Net, so I hope that you bear with me and my questions.  In my program, I have a dataset that contains Url strings that point to various images.  My question is, can I use that dataset as a datasource for a Repeater control so that the Repeater uses those Urls to display the images?
Thanks so much for any help and advice.
Answer: You most certainly can. You will want to do the binding in the code-behind, probably in the Load method like this:
repeaterControl.DataSource = yourDataSet.Tables[0];
repeaterControl.DataBind();

where 0 is the index of the DataTable you're trying to get to.
Then you'll want to build the markup something like this:
<asp:Repeater ID="repeaterControl" runat="server">
    <ItemTemplate>
        <asp:Image runat="server"
            ImageUrl="<%# DataBinder.Eval(Container.DataItem, "TheFieldName") %>" />
    </ItemTemplate>
</asp:Repeater>

where TheFieldName is the name of the field/column in the DataTable that contains the URL. Now, this code may need to be debugged a little bit because I didn't build an entire project around this, but this will get you 99% of the way there, if not all of the way.
Comment: Thanks so much!  This is enough to get me going and I appreciate your help.  I will mark this as the answer as soon as the timer is up.  Again, much thanks!
Comment: @JavaRox, I'm glad I could be of assistance!


How to to render a webform (or any configurable form) in a node edit form?

Question: I have a weird use case, where I was looking to perform the following:

In a node edit form, allow a user to entity reference a collection of webforms
When a user selects an appropriate webform from the entity reference autocomplete, render that form in the current node edit form
User fills out fields in these webforms then proceeds to save the node.
On node save, the webform submit data is stored in a particular field in the node (perhaps in json format).

Is this even possible with webforms, or do any other form modules exist that support this use case?
Comment: You might want to look at Paragraphs module first.
Comment: This seems counterproductive to what Webform (basically) provides. What is the use case?
Comment: We're basically trying to compose a page using reusable components. For example, a page may contain a hero with 3 fields (image, title, subtitle), followed by a 3 col layout which may contain the fields -title, paragraph. The idea was to use a schema form to define these fields and reference the forms we needed in the node form via entity references. The user can add values to these webform fields and build a page with this. We could also use content types, but that would drastically increase the number of content types we use. Idea was derived from here - http://jeremydorn.com/json-editor/
Comment: I completely agree with @Kevin, just adding this module https://www.drupal.org/project/classy_paragraphs which might help in the front end part of the solution as well. " Classy paragraphs ships a new field type "Class list" which allows an editor to apply a selected class to paragraphs via a drop-down list."
Comment: Great, thanks all, I really appreciate it! I'll play with the paragraphs module and let you know if it covers my needs!
Comment: The paragraphs module looks like it should do the job for me. Question on performance though, would adding at least 20 paragraph bundles/types with 3-5 fields in them cause severe performance issues?
Comment: It will result in a good amount of configuration files, but the main bottleneck is how many paragraphs you have on a single node and how nested they are. We have seen sites that have paragraphs fields on paragraph types resulting in 5+ layers. Then performance on saving and load can be an issue
Answer: In this instance it sounds like the paragraphs module solves your problem. However to answer your original question...
I would use entityform, not webform to do this.
Once you added all of your field to your entity form then you can use Inline Entity Form to embed the child form.


How to do $\int e^\frac{-1}{2x^2}x^{-5}dx$?

Question: How to do $\int e^\frac{-1}{2x^2}x^{-5}dx$?
The original problem solve $xy'+\frac{y}{x^2}=\frac{1}{x^4}$
I simplified and found the integrating factor $e^\frac{-1}{2x^2}$ now the RHS of the equation is $\int e^\frac{-1}{2x^2}x^{-5}dx$
I have tried integration by parts with $u=e^\frac{-1}{2x^2}$ and $v=x^{-5}$ but this only seems to make it worse.
Comment: $1/(2x^2)$ is probably the better $u$-substitution.
Comment: Try doing a $u$ substitution with $u=1/x$.
Answer: Let t = $1/2x^{2}$
dt = $(-x^{-3}dx)$
So integration converts to
$\int {e^{-t}(-2t)dt}$
Now apply by parts
and then substitute back t.
Comment: It took a some time to see where you are going with this but it helped thank you


Hide block on specific page through custom contextual link

Question: We usually require to hide some blocks on specific pages for which we need to goto configure block page and add the URL of the page where we do not want to display a block.
Instead of going to configure block page, I want to add a contextual link " Don't display on this page"
which should add the path of the current page in the list on which the block should not appear.
Answer: You can use context module which has good number of contextual filters that can be used dynamically to display/hide a block.

Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.


MySQL structure questions

Question: I have a tblClient and tblDirectory.
I want to create a Company adress book in tblDirectory so Client have access to it. Client insert a Company adress one time so they don't have to insert it each time and can select it for shipping purpose.
My structural question:
Different client may have the same company adress contact.
Should I avoid duplicate with storing an array in tblDirectory-ClientID column? Or should I just store data like that so I won't have to vefify from time to time if there is duplicate?
Or probably a totally different way to do! :-)
Thank you!
Comment: For each client store their adress even if duplicates...
Comment: As simple as this! Thanks for your quick reply!
My goal would have been to create a big repository which Admin-Dispatch could use to insert manual pick up. I will create another table for it...
Answer: If you want to make a respository where multiple users want to synchronize contact information, then avoid duplicates. If not, store them as they are, even I feel there are duplicates.
Imagine two users have the same contact stored and one then thinks "I actually don't want to store the phone number of the headquarters of that company but the subsidiary in Belgium" and you update the data. Should it also update for the other user?
Comment: No, as they don't know each others.

We are a shipping company. We want to offer the customer to create web shipping demand, instead of calling.

So each custumer should have it's own personalized Repository of adresses and contacts.

The biggest constraint is to mix Web with Phone shipping demands

MySQL structure questions


How to view linux kernel logs live?

Question: I have a kernel module logging input of some sensor while I work with it. I want to see if there is a command that outputs /var/log/messages (for example) but waits for more logs to come. That is, some program like dmesg except that it stays on and keeps printing newly-come logs.
Comment: Of course, I can always write a user space program, and read the value from some shared memory or /proc file etc, but I am just asking this question out of curiosity.
Comment: Why "online" in the title?
Comment: @eric, some people would say "view it in realtime". But realtime has a precise meaning and this is not it. Online is the word used to mean right then and there, but without time guarantees. For example "this robot is making these decisions online" when it's doing it "on the fly", but it's not realtime.
Comment: "realtime" is better indeed, and "live" or "as they're generated" or "log stream" is even better. There are many options available.
Comment: @eric, like I said realtime is wrong (although a common mistake), but I could go with live. I see how online would be confusing outside the robotics world.
Answer: Have you tried tail -F, eg.
tail -F /var/log/messages

Comment: You can of course use the `tail -F` command which watches for changed/rotated files and continues to watch the file with the given name.
Comment: Thanks that's what I wanted. I read the man page for `tail` but the part for `-f` was not at all understandable to me.
Comment: @Shahbaz : Be careful if you are looking at a file that is `log rotated`, i.e. logs are automatically archived, like syslog.0, syslog.1.gz etc.. As soon as the file you watching is rotated, you won't see any new lines. You have to restart tail -f. (At least this is the case on my system)
Comment: @Xavier T. Thanks. I was just doing this for a small test however to see if my driver worked
Answer: Two more modern methods:
dmesg -w

On systems with systemd journalctl is also of interest:
journalctl --system -f

Comment: dmesg -w works on ubuntu 22
Answer: You can:

execute dmesg every second: while true; do dmesg -c; sleep 1; done
print everything appended to /var/log/messages: tail -f /var/log/messages
dump the logs on the serial port and read them on another PC. You will need to add to your kernel boot parameters: console=ttyS0,115200 console=tty0 ignore_loglevel and remove quiet
Answer: You could use
 cat /proc/kmsg

By this way you could get all kernel messages when they come

How to view linux kernel logs live?


Fazendo consulta em tabela especifica do WordPress?

Question: Como faço uma consulta no WordPress numa tabela especifica, sendo ela: wp_dd_spg_galleries?
Já tenho o ID da galeria, tentei fazer esta consulta, mas não retorna nada:
$query = "SELECT * FROM wp_dd_spg_galleries WHERE id = ".$idGaleria;
$idGal = $wpdb->query($wpdb->prepare($query));

Comment: Ewerton, publique sua solução como Resposta completa, obrigado!
Comment: Consegui galera, fazendo da seguinte forma: $idGal = $wpdb->get_results($query);
 Ser um analfabeto com WordPress dá nisso... rs
Answer: O $wpdb->query() vai apenas retornar o número de colunas afetadas ou false se não acontecer nada, então no caso você deveria usar $wpdb->get_results().
Recomendo também você usar {$wpdb->prefix} para pegar o prefixo do banco que nem sempre será wp_.
Além de que você usou o $wpdb->prepare() da forma errada, pois ele funcionar como printf() e é assim que ele vai escapar os dados.
Aqui a forma correta de fazer a sua consulta:
$idGal = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}dd_spg_galleries WHERE id = %d", $idGaleria ) );


Objeto que referência outro pode ser coletado?

Question: A classe possui referências ao próximo objeto e ao objeto anterior (Lista). E possui um método para ser deletado
...
function delete(){
    if($this->previousColumn){
      $this->previousColumn->nextColumn = $this->nextColumn;
    }
    if(($this->previousRow)){
      $this->previousRow->nextRow = $this->nextRow;
    }
  }
...

Se eu não configurar os campos previous e next
...
public ?CellInfo $nextColumn, $nextRow,
 $previousColumn, $previousRow;
...

para null este objeto será coletado pelo lixeiro? Ou ele continuará existindo mesmo que nenhum outro objeto tenha referência a ele, mas ele tendo referência a outros objetos
Quando chamo delete os outros objetos da lista deixam de ter referência para o objeto, dessa forma, o código deixa de ter referência a ele.
Entretanto o objeto em que chamo delete ainda continua tendo referências a outros objetos
Então ele será coletado?
class CellInfo{
  public $x, $y;
  public $possible_values = [];
  public ?CellInfo $nextColumn = null, $nextRow = null;
  public ?CellInfo $previousColumn = null, $previousRow = null;
  public $is_unique;

  function addPossibleValue($value){
    $this->possible_value[] = $value;
  }
  function setNextColumn(CellInfo $ci){
    $this->nextColumn = $ci;
    $ci->previousColumn = $this;
  }
  function delete(){
    if($this->previousColumn){
      $this->previousColumn->nextColumn = $this->nextColumn;
      //Como $this->previousColumn não foi
//cofigurado para null ele continuará tendo
//referência a outro objeto, mas não terá
// mais referência dentro da lista
    }
    if(($this->previousRow)){
      $this->previousRow->nextRow = $this->nextRow;
    }
  }
}//*/
$t1 = new CellInfo();
$t1->x = 10;
$t2 = new CellInfo();
$t2->x = 15;
$t3 = new CellInfo();
$t3->x = 20;

$t1->setNextColumn($t2);
$t2->setNextColumn($t3);
//*/
$t2->delete();//O coletor irá coletar esse $t2?

Answer: O garbage collector do PHP coleta um objeto quando ele não tem mais referências. Se você deixar apenas uma referência, não importa onde, o objeto não será coletado até o fim da execução, ou no momento que a referência deixe de existir explicitamente em alguma parte do código, ou implicitamente se a referência vem de um objeto que é destruído automaticamente por alguma razão, por exemplo quando esse this deixa de existir.
Isso é detalhe de implementação e pode mudar, mas normalmente ele tem um contador de referências. E se falhar por entrar em um ciclo ainda tem um coletor extra.
Eu não tenho como responder de forma mais precisa porque a pergunta fala em campos previous e next e em nenhum lugar do código tem campos com esses nomes. E também porque não há maior contexto.
De qualquer forma a pergunta mudou, o código nem faz o que fazia antes e n~]ao parece fazer muito sentido mais.
Mas está fazendo o que com PHP? Scripts no backend web? Se é isso então não precisa se preocupar, o script durará um tempo muito curto, alocará bem poucos objetos e mesmo que tudo falhe o fim dele coletará os objetos que ficarem.
Se está usando PHP para outra coisa que mantém o objetos vivos por muito tempo então deveria repensar a linguagem, PHP não foi feita pra isso. E quem me disse pessoalmente foi o criador da linguagem.
Comment: Eu só queria saber como ele funciona, já o campo previous e next é 'previous'Row next'Row' e column.


How to load file, when I know it's filename, but not fid?

Question: I create filenames using some ID and timestamps. I don't want to add additional table to "remember" associations, as filename keeps them pretty well:
$filename = get_symbol_by_id($id) . ' ' . get_modified_by_id($id) . '.xml';

Also, I don't care if they will be managed or not. And I don't care if they get deleted - I can recreate them on demand. They are small, so leaving older ones behind does not create any cost worth taking care of. What is the proper course of action?
"Unmanaged" files seems to be generally discouraged in 7, but using them is pretty straightforward with tools like:

file_unmanaged_save_data
file_exists($uri) in a manner shown here
file_transfer takes $uri, not $fid, so it's even easier to use it on unmanaged files

With managed files, I'm afraid I would be forced to use

EntityFieldQuery, overly complicated for such simple task or
$conditions in file_load_multiple, marked as deprecated.

So what's the proper course of action, if I want to avoid both deprecated functionality and overly complicated code?
Answer: I'd definitely go with EntityFieldQuery, not a really complicated solution:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'file')
      ->propertyCondition('filename', '<filename>%', 'LIKE');
$result = $query->execute();
if (!empty($result['file'])) {
  $files = entity_load('file', array_keys($result['file']));
}

Use of conditions is not really recommended on any load multiple function anymore, the method above would be more standard and "future proof" as EntityQuery is the way to go in Drupal 8.
Installing file entity module would add much more value on what you can do regarding managed files.
Comment: Small improvement would be to use `db_like()` to prepare the string, but yeah EFQ is the way forward


Are there functions that are not of exponential order for which you can define a Laplace transform?

Question: I'am in a course of Introduction to Linear Differential Equations and teacher made us this question in class.
we work in $\mathbb{R}$, and any help to answer this is welcome
Comment: Yes. Look at the second counterexample I describe here (in reference to a different question): http://math.stackexchange.com/questions/1264766/improper-integral-from-1-to-infinity-integrated-function-converges-towards-zer/1264769#1264769

That function will not be of exponential type, as it is unbounded as $x \to \infty$. However the Laplace transform integral of it converges.
Comment: What do you mean by define a Laplace transformation? A function having a Laplace transformation not being of exponential order?
Comment: @SimonS, you are right!, also $f(x)=0$ iff $x\in\mathbb{Z}$ and $f(x)=0$ otherwise. thanks
Answer: $\newcommand{\dd}{\mathrm{d}}$A prime example that you find in many textbooks is
$$
f(t) = 2te^{t^2}\cos(e^{t^2})
$$
We may observe that $f(t)=\frac{\dd}{\dd t}\sin(e^{t^2})$, therefore,
\begin{align}
(\mathscr{L}f)(s)
{}={}&
\int_0^\infty e^{-s\tau} \frac{\dd}{\dd \tau}\sin(e^{\tau^2}) \dd \tau
\\
{}={}& \left.e^{-s\tau}\sin(e^{\tau^2})\right|_0^\infty
- \int_0^\infty (-s)e^{-s\tau}\sin(e^{\tau^2})\dd\tau
\\
{}={}& -\sin 1 - \int_0^\infty (-s)e^{-s\tau}\sin(e^{\tau^2})\dd\tau
\end{align}
The last integral converges because
\begin{align}
\int_0^\infty (-s)e^{-s\tau}\sin(e^{\tau^2})\dd\tau
{}\leq{}&
\left|\int_0^\infty (-s)e^{-s\tau}\sin(e^{\tau^2})\dd\tau\right|
\\
{}={}&\int_0^\infty s e^{-s\tau}|\sin(e^{\tau^2})|\dd\tau
\\
{}\leq{}& \int_0^\infty s e^{-s\tau}\dd\tau
{}={} \frac{1}{s},
\end{align}
so the integral is defined for $s\in \mathbb{C}$ with $\Re(s) > 0$.
There are several other examples such as the one mentioned by @SimonS in a comment (see here).
Yet another example is the following function
$$
f(t) = \begin{cases}
e^{n^2}, &\text{if } t\in [n, n+e^{-n^2})
\\
0,&\text{otherwise}
\end{cases}
$$
It is not difficult to show that the Laplace transform of $f$ exists.
Answer: A good example is $\ln x$ .
Its laplace transform is $-\dfrac{\gamma+\ln s}{s}$ .
Comment: $lnx$, is of exponential order 1.


Qual a interface evento que é recebido pelo evento beforeinstallprompt?

Question: Bom adicionei um botão de instalação do site para facilitar o acesso dos usuários. Estou usando o Angular 15.
O lint está me manda o seguinte erro de tipagem:
 Unexpected any. Specify a different type

O erro acontece pois declarei a variável deferredPromptcomo any, o problema é que não faço ideia de como tipar ela.
Vou postar o código que esta funcional, porém quero resolver esse erro.
  public deferredPrompt: any;

  ngOnInit(): void {
     window.addEventListener('beforeinstallprompt', (event) => {
        event.preventDefault();
        this.deferredPrompt = event;
      });
    }

    installPwa(): void {
      this.deferredPrompt.prompt();
      this.deferredPrompt.userChoice.then((choiceResult: { outcome: string }) => {
        if (choiceResult.outcome === 'accepted') {
          this.sucess();
        } else {
          this.error();
        }
        this.deferredPrompt = null;
      });
    }

Comment: https://stackoverflow.com/questions/51503754/typescript-type-beforeinstallpromptevent Acredito que a dúvida seja a mesma, pelo menos me ajudou.
Answer: Em vez de any, use unknown ou never
unknown
Forçará você a afirmar explicitamente e com segurança que o tipo está correto.
never
É útil ao instanciar parâmetros de tipo genérico dos quais você não precisa saber o tipo.
Você pode também desligar o aviso do any editando o arquivo .eslintrc.* (exemplo: .eslintrc.cjs, .eslintrc.json), que contêm as regras, deve estar semelhante a isto:
module.exports = {
  "rules": {
    "@typescript-eslint/no-explicit-any": "warn"
  }
};

Remova a linha "@typescript-eslint/no-explicit-any": "warn" que você não irá mais ter essa regra no seu lint ou apenas troque "warn" por "off".
Mesmo existindo a possibilidade de desabilitar o erro globalmente, ainda o ideal é usar unknown ou never conforme cada caso.
Respondendo ao titulo da pergunta:

Tipagem da variável que recebe o prompt do Pwa;
Qual a interface evento que é recebido pelo evento beforeinstallprompt?

O BeforeInstallPromptEvent é a interface do evento disparado pelo beforeinstallprompt, você pode experimentar usar essa interface no seu código, não cheguei a testar se isso faz parte dos tipos do typescript, mas por não está documentado provavelmente vai causar erro no seu código, já que beforeinstallprompt é experimental ainda (2023-02-25).
Comment: Optei por desligar `"@typescript-eslint/no-explicit-any": ["off"]` no `.eslintrc.json`.
Comment: @HugoBorges ok, adicionei o [detalhe a resposta na revisão](https://pt.stackoverflow.com/posts/577891/revisions).


MEF Directory catalog

Question: i have a solution with the following Structure:
project.Model
project.Builder
project.Unit Tests
in the builder project it should create a Model instance using MEF.
so in the Builder class constructor i want it to have a container to hold the parts related to building the model only(as a separation of concerns) .
currently i am using the directory catalog as follows:
var path = Environment.CurrentDirectory;
var catalog = new DirectoryCatalog(path + @"\Builder\bin\Debug");

so that in the unit test project i can use this container in writing the unit tests functions.
is there a better way to make the builder container have only the dlls that resides in the builder project output directory (bin\debug).
I have tried using:
var directory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var catalog = new DirectoryCatalog(directory);

bu this have make the catalog to scan the output directory of the unit tests projects which have made a lot of problems other than being not where I want the catalog to scan.
is there a more correct way than what I'm currently doing ?
thanks in advance.
Answer: I would rather use and AssemblyCatalog - and add a static reference from Builder project to Model project, so you can avoid all problems with folders - scanning the whole folder, directory structure change during deployment, different versions of assembly in the same folder, etc.
The code would look something like
var catalog = new AssemblyCatalog(typeof(YourModelType).Assembly);

MEF Directory catalog


How to call function after call api in angular?

Question: I want to call the second function after the first function is executed.
In other words, I want the second function to be executed only when the output of the first function is a certain value
Is there an optimal way?
func1() {
this.apiService.getData().subscribe(val=>{
  if(val.status ==1) {
     this.func2();
  }
})
}

func2() {
this.apiService.getData2().subscribe(val=>{
  //code
})
}

Comment: I dont think there is any better way, this approach seems to be fine
Comment: What do you mean with _"better"_? Asking for opinions is off-topic.
Comment: @jabaa I want to know if there is a more optimal way
Comment: Optimal is a superlative. Something is either optimal or not. It can't be **more** optimal. What do you mean with _"optimal"_? Optimal regarding, performance, regarding readability, regarding code length, or something else?
Answer: One possible way to chain observables in Angular is to use the switchMap operator, which maps one observable to another and unsubscribes from the previous one when a new value arrives. This way, you can avoid nested subscriptions and memory leaks. For example, you could write something like this:
func1() {
  this.apiService.getData().pipe(
    // switch to the second observable if the status is 1
    switchMap(val => val.status == 1 ? this.func2() : of(null))
  ).subscribe(result => {
    // handle the result of the second observable or null
  })
}

func2() {
  // return the second observable without subscribing
  return this.apiService.getData2();
}

Check this for more info: https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap


Tarski's conception of truth and Satisfaction

Question: I am trying to understand whether or not I should use Tarski's concept of satisfaction when defining truth for propositional languages.
More precisely, suppose that I have a denumerable set of propositional variables, and that my language consists of the two propositional connectives $\neg$ and $\vee$ only. Do I need to introduce the concept of satisfaction to define truth for this language? (My hesitation lies in the fact that I have a denumerable set of propositional variables.)
I am under the impression that satisfaction is necessary for first order languages, but not for propositional languages. I would like to know if I am correct.
Answer: The truth definition for a propositional language is base on compositionality, using (for classical logic) the well-known truth table for the logical connectives.
We write $1$ and $0$ instead of "true" and "false" and we write $v(\phi) = 1$ for "$\phi$ is true".
We have that : $v(ϕ ∨ ψ) = 1$ iff $v(ϕ) =1$ or $v(ψ) = 1$ and and $v(¬ϕ) = 1 −v(ϕ)$.
Let $\text{At}$ the collection of atoms, i.e.  of proposition symbols: $p_0,p_1,p_2,\ldots$.
We can extend a truth assignment $v : \text{At} \to \{ 0,1 \}$ to the collection $\text{Prop}$ of all propositional formulas with the following defintion:

$v(⊥) = 0$
$v(¬ϕ) = 1− v(ϕ)$
$v(ϕ ∨ ψ) = \max (v(ϕ), v(ψ))$.

Now we have the usual defintions :

$v \vDash \phi$, meaning : "truth assignment $v$ satisfies formula $\phi$";
$\vDash \phi$, meaning : "formula $\phi$ is a tautology, i.e. it is satisfied by every truth assignment";
$\Gamma \vDash \phi$, meaning : "$\phi$ is a semantical (or : logical) consequence  of the set of formulas $Γ$, i.e. $\phi$ is satisfied by every truth assignment that satisfies every formulas in $Γ$".


How to access fields from a goal when creating a node with Rules?

Question: I'm trying to create a rule with the Rules module that posts a node when users achieve a goal (using the Goals module 7.x-1.3). I want to get fields from the goal like the goal image and other fields, but there's no data selector for the goal completed.
I can't find a way to fetch the completed goal entity. I've tried using a data comparison condition, but it'll only give "goal" data selector without any fields.
Any hints?
Comment: Have you tried the 'entity has field', or 'entity is of bundle' conditions on the goal? Sometimes that is required to have the desired fields show up.
Comment: Yeah, but it only gives me site and awarded-user selectors.
Answer: Have a look at this rule (in Rules export format), which is an example of how to get this to work:
{ "rules_show_a_message_after_goal_completion" : {
    "LABEL" : "Show a message after goal completion",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "goals", "rules" ],
    "ON" : { "goal_awarded" : [] },
    "IF" : [ { "goals_goal_condition" : { "goal_id" : "2" } } ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "goal", "id" : "2" },
          "PROVIDE" : { "entity_fetched" : { "goal_fetched" : "Fetched goal" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about the \u0022[goal-fetched:ftitle\u0022 goal which you just completed:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Description\u003C\/strong\u003E = [goal-fetched:field-goal-description]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Category\u003C\/strong\u003E = [goal-fetched:field-goal-category]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Level\u003C\/strong\u003E = [goal-fetched:field-goal-level]\u003Cbr \/\u003E" } }
    ]
  }
}

Some details about this rule:

Rules Event: "A goal is completed by a user", as in your question.
Rules Condition: "The goal completed by a user", a Rules Condition provided by the Goals module (disclosure: I'm its maintainer). In my case, I used the goal with goal id = "2" (replace with the goal id that matches your case).
Rules Actions:

"Fetch entity by id", whereas the entity is a goal, and the id of it is (also) "2" (replace with the goal id that matches your case).
"Show a message on the site", which is just to demo / test some of the field values related to that goal (adapt the machine names of those fields to match your field names).

So by adding the Rules Condition "The goal completed by a user", and by also adding the Rules Action to "Fetch entity by id", in any subsequent Rules Action you should have access to all fields of the goal (with the goal id that matches your case).
Comment: Is there a way to do fetch the goal that was completed and triggered the rule? Seems like I would have to create a rule for each goal (and there are many of them).
Comment: @zoom-ping The question in your last comment here is actually a NEW question. Would you agree that my answer here DOES answer your original question, which is about "*find a way to fetch the completed goal entity*"? If so, how about marking this answer as "accepted", and then post a new question as a followup-question (with a link to this one)? After you do, I might also answer that new question (like "there is no out-of-the box answer with only the Goals module, but I can think of at least 1 alternative to create a single rule to cover all goals in it, provided you use an extra module also").
Comment: Ok, thanks! I'll try to phrase my question better.


Need to Extract only Date from HTML format file to XLSx using Perl

Question: Kindly Help me in extracting only date from the HTML format to XLSX format using Perl.
In HTML format the date is having with time in the format of "2005-08-16 15:23:13.933"
I want to extract it as 2005-08-16.
This is what I have written so far
<code># General format date

my $date_format = $workbook->add_format();
$date_format->set_align('left');
$date_format->set_num_format('mm/dd/yyyy');

if ( $col_format ) {

    print "Col Type : $col_format\n";

    if ( $col_format eq "date_format2" ) {
        $date_format->set_num_format('mm/dd/yyyy');
    }
    else {
        $date_format->set_num_format('mm/dd/yyyy');
    }
}
</code>
Comment: Show some work. What have you tried?
Comment: # General format date

my $date_format = $workbook->add_format();

$date_format->set_align('left');
$date_format->set_num_format('mm/dd/yyyy');

if ($col_format) {

 print "Col Type    : $col_format\n";

  if ($col_format eq "date_format2") {

   $date_format->set_num_format('mm/dd/yyyy');

      }else{

   $date_format->set_num_format('mm/dd/yyyy');

      }

   }
Comment: Please show the html and  script in the question.
Answer: I have given a sample code which converts the cell format. It would be better if you share the HTML and the code you are trying to achieve.
<code>$worksheet = $workbook->add_worksheet();
$date_format = $workbook->add_format();
$date_format->set_num_format('mm/dd/yy');
$worksheet->write(0,  0, 36892.521, $date_format);
</code>


the ratio of the derivative of a holomorphic function over itself

Question: Let $h(x)$ be a holomorphic complex function. Is it true that the ratio :$h'(x)/h(x)$ is holomorphic as well? (please explain why)
Answer: It won't necessarily be a holomorphic function. Actually, anywhere $h(x)=0$ it wont be holomorphic.
For example for $h(x)=x$,
$h^{'}(x)/h(x) = 1/x$ which is not holomorphic at $x=0$.
It will be a meromorphic function tho


Deriving autocovariance of time series

Question: Consider the following AR(1) process:
$$
y_{t}=\phi_{1}y_{t-1}+\epsilon_{t}
$$
I am asked to compute the autocovariance betweem $y_{t}$ and $y_{t-s}$.
Write down the DGP for $y_{t-s}$ which is:
$$
y_{t-s}=\phi_{1}y_{t-s-1}+\epsilon_{t-s}
$$
Write down the covariance as:
\begin{alignat*}{1}
cov\left(y_{t},y_{t-s}\right) & =E\left(\left(\phi_{1}y_{t-1}+\epsilon_{t}\right)\left(\phi_{1}y_{t-s-1}+\epsilon_{t-s}\right)\right)\\
 & =E\left(\phi_{1}^{2}y_{t-1}y_{t-s-1}+\epsilon_{t}\epsilon_{t-s}+\phi_{1}\epsilon_{t-s}y_{t-1}+\phi_{1}y_{t-s-1}\epsilon_{t}\right)\\
 & =\phi_{1}^{2}E\left(y_{t-1}y_{t-s-1}\right)
\end{alignat*}
Where the last expression follows from the white-noise properties
of $\epsilon.$ I know that the correct answer is in fact $\sigma_{y}^{2}\phi_{1}^{s},$
but I am unable to get to it. Any tips are much appreciated.
Comment: The issue might become obvious by considering the smallest non-trivial case where $s=2$ and writing everything out: $$y_t=\phi y_{t-1}+\epsilon_t=\phi\left(\phi y_{t-2}+\epsilon_{t-1}\right)+\epsilon_t.$$ Use the basic algebraic rules of covariance along with what you already know.  Notice the factor of $\phi^2$ lurking there: that will guide you.
Answer: Just a first tip:
In $y_{t} =\phi_1y_{t-1} +\epsilon_t$ replace $y_{t-1}$ by $\phi_1 y_{t-2}+\epsilon_{t-1}$, then replace $y_{t-2}$ and so on until you have an expression with $y_{t-s} $ on the right hand side.
Hope this helps, otherwise let us know.

Deriving autocovariance of time series


Getting TypeError: Object(...) is not a function error when trying to change a state property

Question: I am very new to React and trying to implement the Rating feature in the code. Can anyone tell, why I am Getting TypeError: Object(...) is not a function error when trying to change a state property
when the Rating component onChange property is set.
My code
export default function Details(props) {

const [movie_detail, set_movie_detail] = useState({
    poster_url:"",
    artists:[],
    title:"",
    genres:[],
    duration:0,
    release_date:"",
    rating:0,
    storyline:"",
    id:"",
    wiki_url:"",
    trailer_url:"",
    censor_board_rating:""
  });

    async function data(){
        const data = await fetch(props.baseUrl + "movies/"+props.match.params.id ,
        {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "Cache-Control": "no-cache"
            }
        });
        const rawData = await data.json();
        set_movie_detail(rawData);
    }

    const handleRatingChange = (value) =>{
        console.log(value);
        setState({rating:value});
    }

    useEffect(() => {
        data();
    }, []);

  return (
    <>

        .........

          <Typography>
            Rate this movie
          </Typography>
          <Rating
            name="rating"
            value={movie_detail.rating/2}
            max={5}
            onChange={handleRatingChange}
            icon=
                {
                    <StarBorderIcon
                    style={{color:"black"}}
                    />
                }
            />

    </>
  );
}

Comment: Where does setState come from?
Answer: You should be using the correct name of the function that updates the state. In this case set_movie_detail instead of setState.
You should also merge the update with the previous state instead of overwriting it.
Your function should be as follow:
const handleRatingChange = (value) => {
  console.log(value);
  set_movie_detail((prevState) => { ...prevState, rating: value });
}

Comment: he should also merge with the previous state, as this is a functional component
Comment: This would remove anyhting else from the state, though.
Comment: I updated my answer to add merging with the previous state instead of overwriting it.
Answer: You should be using set_movie_detail instead of setState whilst trying to update the state value.
const handleRatingChange = (value) =>{
        console.log(value);
        set_movie_detail(prev=>{...prev,rating:value});
}

set_movie_detail is the function that updates the state of movie_detail.
Here, we are making use of the spread operator ... to ensure that only the desired attribute(s) (rating here) is overwritten and the rest of the values remain the same.