Splashscreen activity is not killed when clicking on backbutton

Question: Here is my code. Pretty simple..But when I click on the back button,the second activity appears..
 public class MainActivity extends ActionBarActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread t = new Thread(){
        public void run(){
            try{
                sleep(3000);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                Intent i = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(i);
            }
        }
    };
    t.start();
 }

 @Override
 protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    this.finish();
  }

}

I have also put in the manifest file but again I still have the same problem..
        android:noHistory="true"

Answer: } finally {
   Intent intent = new Intent();
   intent.setClass(SplashActivity.this, MainActivity.class);
   intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   startActivityForResult(intent, 0);
   finish();
}

Answer: I would suggest you switch to an AsyncTask that sleeps for 3 seconds during doInBackground() and starts the new activity + kills the current one in onPostExecute(), but only if isCancelled() is not true.
Then override the onBackPressed() of your splash activity and:

Cancel the current async task (hold a reference to it in a local variable).
Finish the current activity.

This way the AsyncTask will still sleep in the background for 3 seconds, but when its onPostExecute() comes it will know that it was cancelled by checking isCancelled() and not start the second activity.
See: AsyncTask documentation
Answer: use Handler like this for making Splash screen
private static final int SPLASH_TIME_OUT = 3000;
    private Handler mHandler = new Handler();
    private Runnable mRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        mRunnable = new Runnable() {

            @Override
            public void run() {
                openLandingActivity();
            }
        };
        mHandler.postDelayed(mRunnable, SPLASH_TIME_OUT);//
    }

    protected void openLandingActivity() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            mHandler.removeCallbacks(mRunnable);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

Comment: Why the complext `onKeyDown()` instead of `onBackPressed()`?
Comment: both doing the same thing its basically the choice of coder
Comment: Yes using the postDelayed method is another way which works as well. Actually I going to use post() later on for my app:). Thank you again my friend.
Answer: Try this Hope it will help you..
private final int SPLASH_DISPLAY_LENGHT = 5000;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);
    /* New Handler to start the Menu-Activity
     * and close this Splash-Screen after some seconds.*/
    new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
            /* Create an Intent that will start the Menu-Activity. */
             Intent i = new Intent(MainActivity.this,SecondActivity.class);
            startActivity(i);
            splash.this.finish();
        }
    }, SPLASH_DISPLAY_LENGHT);
}

}
Answer: I had to use the onKeyDown() method which makes the problem to disappear..Here is the fixed code..
  public class MainActivity extends ActionBarActivity {
  private boolean isBackPressed = false;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread t = new Thread(){
        public void run(){
            try{
                sleep(3000);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if(!isBackPressed){
                Intent i = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(i);

                }
            }
        }
    };
    t.start();
 }

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        isBackPressed = true;
        finish();
    }
    return super.onKeyDown(keyCode, event);

}

}


Group Determinant Independent of Labeling of Elements

Question: Let $G$ be a finite group with elements $g_1, g_2, \ldots, g_n$. We define the group matrix by $$X_G = [x_{g_ig_j^{-1}}].$$
We then can define the group determinant as $$\det X_G = \Theta_G.$$
$\Theta_G$ will be a polynomial over the $x_{g_k}$. It seems like the group determinant would be independent (perhaps just up to sign $(\pm)$) from the indexing of the elements of $G$ since any renumbering of the elements would just cause row and column swaps.
Is this a proper way to think of this?
Comment: Maybe [this way](http://en.wikipedia.org/wiki/Determinant#n.C2.A0.C3.97.C2.A0n_matrices) $(\det(A) = \sum\limits_{\sigma \in S_n} \hbox{sgn}(\sigma) \prod\limits_{i=1}^n a_{i,\sigma_i})$ is more useful here, imho.
Answer: The determinant is indeed independent from the indexing of the elements.
One way to see this is the following.  Suppose you index your elements in a different way; this means you take an element $\sigma$ of the symmetric group $S_n$, and you order your element as $g_{\sigma(1)}, g_{\sigma(2)}, \ldots, g_{\sigma(n)}$.  With this new ordering, the matrix becomes
$$X^\sigma_G=[x_{g_{\sigma(i)}g_{\sigma(j)}^{-1}}]. $$
Now, let $P$ be the permutation matrix associated to $\sigma$, that is, $P=[\delta_{\sigma(i), j}]$, where $\delta_{k, \ell}$ is $1$ if $k=\ell$ and $0$ else.  If $M$ is any $n\times n$ matrix, then the matrix $PM$ is obtained by reordering the rows of $M$ by applying $\sigma$; similarly, $MP^{-1}$ is obtained by reordering the columns of $M$ by applying $\sigma$.  Combining these two observations, you get that $X^\sigma_G = PX_G P^{-1}$.  Taking the determinant, you have $det(X^\sigma_G) = det(X_G)$.
Note that the determinants are exaclty equal, not up to a sign.


Using Sequelize load data of every hour of a day

Question: how to load record of transactions of every hour.
if (ExpenseGraphTimeSeries === 'today') {
        let date = new Date(Date.now());
        let createdAt = {
          [Op.lt]: new Date(date),
          [Op.gte]: new Date().setHours(0, 0, 0, 0)
        };

        ExpenseGraphCondition.createdAt = createdAt
        ExpenseGraph = await model.Expense.findAll({
          where: createdAt,
          attributes: [
            [model.sequelize.fn('sum', model.sequelize.col('Amount')), 'expense'], 'createdAt'
          ],
        });
      }

Current out put is
| Amount |    createdAt |
| -------- | -------------- |
| 2349   | 01-01-2020 00:00:00           |
| 2349   | 02-01-2020 00:00:00         |
i need record of every hour with amount of that hour. how to do this?

Answer: group:[] is use in sequelize to return data by groups.
your code will be like this
    if (ExpenseGraphTimeSeries === 'today') {
        let date = new Date(Date.now());
        let createdAt = {
          [Op.lt]: new Date(date),
          [Op.gte]: new Date().setHours(0, 0, 0, 0)
        };

        ExpenseGraphCondition.createdAt = createdAt
        ExpenseGraph = await model.Expense.findAll({
          where: createdAt,
          attributes: [
            [model.sequelize.fn('sum', model.sequelize.col('Amount')), 'expense'], 'createdAt'
          ],
          group: [model.sequelize.fn('hour', model.sequelize.col('createdAt'))],
          order: [['id', 'asc']], //optional
        });
      }


Prove that $f(x)=x^2$ is uniformly continuous in [a,b]

Question: I'm expanding this question, this time supposing that the inverval in which the uniform continuity of the function has to be proved is the more general closed interval $[a,b]$.
I'm asking this because in my book there is a proof of this sort:
For $|x_1-x_2| < \delta$, we have $|f(x_2)-f(x_1)| = |x_2^2-x_1^2| = |x_2-x_1||x_2+x_1| \leq 2|x_2-x_1|(|b|+|a|) \lt 2 \delta (|b| + |a|) = \epsilon $. So $\delta = \epsilon/(|a|+|b|)$.
I just don't understand why $|x_2-x_1||x_2+x_1|$ should be $\leq 2|x_2 - x_1|(|b|+|a|)$.
In fact, if you apply the triagle inequality  to $|x_2-x_1||x_2+x_1|$, that is to $|x_2-x_1||2x_1+(x_2-x_1)|$you have that this is $ \leq |x_2-x_1|(2|x_1|+|x_2-x_1|)$.
But now, since you only know that the distance between $x_1$ and $x_2$ is less than the one between $a$ and $b$, even if you apply the triangle inequality again to write that $|x_2-x_1| \leq |a-b| \leq |a| + |b|$ (thus substituting the $|x_2-x_1|$ in the brackets with $|a| + |b|$, since the one outside is needed as $\delta$), you could never get rid of that $2|x_1|$ remaining, and even if you write it as $2|x_2+(x_1-x_2)|$, applying the triangle inequality again, you will end up forever with either $x_1$ or $x_2$ which don't seem to suggest that the function is uniformly continuous on $[a,b]$.
In an answer to the question I'm expanding, the chosen $\delta$ is $\epsilon/2b$, which seems basically the $\delta$ chosen in my book, given that $a=0$ and $b>0$. The problem is that in this particular case, where both $a$ and $b$ are nonnegative, one could simply write $|x_2-x_1||x_2+x_1| \leq |x_2-x_1|(|x_2|+|x_1|) \leq |x_2-x_1|(|b|+|b|)$, thus choosing $\delta = \epsilon/2|b|$; I, instead, can't get rid of either $|x_1|$ or $|x_2|$, since I can't know wheter these are less than or greater than $ |a|$ and $|b|$, because they can be either positive or negative.
Am I missing something important here? I hope so, since I can't really figure out this problem.
One last additional thing: my book says that $[a,b]$ must be a "fixed finite closed set" and then says "The restriction to bounded intervals is essential as the example of the function $x^2$ shows." However, I don't actually feel such an urgence to specify the precence of bounds in the closed interval $[a,b]$: isn't it just bounded by definition, since it's a closed interval on the real line, whose bounds are therefore $a$ and $b$?
Maybe some clarification on this may help in solving the problem above.
Thanks.
Comment: $|x_1+x_2| \leq |x_1|+|x_2| \leq 2 \max \{|a|,|b|\} \leq 2(|a|+|b|)$.
Comment: Isn't $|x_1 + x_2| \le 2||a|+|b||$ obvious?
Comment: No, sorry, not so obvious... Can you explain better?
Comment: Regarding your last question, the reason why restriction to bounded intervals is necessary is because $x^2$ is not uniformly continuous over unbounded sets like $\mathbb{R}$ or $[0,\infty)$.
Comment: @angryavian Yes, I know, but wouldn't just be sufficient to restrict to closed intervals? What is the main difference between "closed" and "bounded" here?
Comment: The OP is asking why not just use $2|b|$ rather than the larger $2(|a|+|b|)$, assuming $b>a>0$.  The form expressed in the book covers all cases, including negative values of $a$ and or $b$,
Comment: @RiccardoDelMonte My previous comment shows that we need to restrict to bounded sets. To see why being closed is needed, we unfortunately need to consider a different example. The function $f(x)=1/x$ is not uniformly continuous on $(0,1]$.
Comment: @angryavian Yes, and in this example, if you take the interval $[0,1]$, this interval is bounded, but $0$ isn't in the domain of $f$, so here it's again not uniformly continuous. Instead, if we take an interval of the type $[a,b]$, with, say, $a,b > 0$, then you have an uniformly continuous function with modulus of continuity $\delta = a^2\epsilon$. But, anyway, what I was actually asking you was wheter this interval $[a,b]$, even in this other example, must be called "bounded", "closed", or "closed and bounded", as my book does. I actually don't get the difference between these terms
Comment: @RiccardoDelMonte: The interval $[a,\infty)$ is closed and unbounded. "Closed" means containing its endpoint(s) (in this case the interval has only one endpoint, namely $a$), while "unbounded" means going out to $\infty$ and/or $-\infty$. The same for $(-\infty,b]$. And $(-\infty,\infty)$ is closed (vacuously, since it has no endpoints) *and* open and unbounded!
Answer: $$a \le x_i \le b \Longrightarrow |x_i| \le \max \{ |a|,|b|\} \le |a|+|b|$$
so
$$|x_1|+|x_2| \le 2 (|a|+|b|)$$


Minimize MS Access Window Leaving POPUP Form

Question: I have the below code to minimize MS access but the pop up forms disappear with the background...
Global Const SW_HIDE = 0
Global Const SW_SHOWNORMAL = 1
Global Const SW_SHOWMINIMIZED = 2
Global Const SW_SHOWMAXIMIZED = 3

Private Declare Function apiShowWindow Lib "user32" _
Alias "ShowWindow" (ByVal hWnd As Long, _
ByVal nCmdShow As Long) As Long

Function fSetAccessWindow(nCmdShow As Long)

Dim loX As Long
Dim loForm As Form
On Error Resume Next
Set loForm = Screen.ActiveForm

If Err <> 0 Then
    loX = apiShowWindow(hWndAccessApp, nCmdShow)
    Err.Clear
End If

If nCmdShow = SW_SHOWMINIMIZED And loForm.Modal = True Then
    MsgBox "Cannot minimize Access with " _
    & (loForm.Caption + " ") _
    & "form on screen"
ElseIf nCmdShow = SW_HIDE And loForm.PopUp <> True Then
    MsgBox "Cannot hide Access with " _
    & (loForm.Caption + " ") _
    & "form on screen"
Else
    loX = apiShowWindow(hWndAccessApp, nCmdShow)
End If
fSetAccessWindow = (loX <> 0)

End Function

does anyone have any idea how i can leave the popup form and just minimize access background?
Comment: From where do you call that function in your project ?
Comment: from a module so it looks like this from a button click ( call fSetAccessWindow(SW_SHOWMINIMIZED)
Answer: The only way I know of to do this is to put the call fSetAccessWindow(SW_SHOWMINIMIZED) in the form_load event. This works reliably for me
Answer: The trick is to use the Form.SetFocus cmd afterwards. As the main screen minimizes the SetFocus cmd after will keep the form up:
Private Sub cmdMinimize_Click()
        Call fSetAccessWindow(SW_SHOWMINIMIZED)
        Form.SetFocus
End Sub


SQL statement for getting user rank in proper order?

Question: I am looking for an SQL statement that returns users rank by score, but does so in order, which is not happening with the code below:
$sql = "SELECT COUNT(*) AS rank FROM users WHERE points>=(SELECT points FROM users WHERE uid='$uid')";

Instead, each user has the same rank depending on how many users there are.  So if there are 25 users, each of their ranks will display as 25 but this is not actually the case, as surely there must be an individual rank for each user.
I have tried a couple of different of different solutions, but I can't quite put the logic together.  I thought this would work:
$sql ="SELECT COUNT(*)-1 AS rank FROM users WHERE points>=(SELECT points FROM users WHERE uid='$uid' ORDER BY DESC)";

But I've had no success.
TLDR; How could I change my SQL statement to reflect users rank in order by score, without multiple users having the same rank?
Comment: Please show sample data and the expected output.
Comment: I didn't know if this was supposed to be tagged php or sql, I apologize if I have misplaced this!
Comment: `SELECT user, points as rank order by rank desc` ?  `COUNT(*)` just returns the number of rows in the result, has nothing to do with the points, or user.
Comment: SELECT * FROM users WHERE uid='$uid' ORDER BY points DESC
Answer: If you are trying to order the data in the table using the points and give them individual rank you can use ROW_NUMBER()
SELECT *,ROW_NUMBER() OVER (ORDER BY points DESC) AS RANK FROM users

ROW_NUMBER() is not available in MYSQL. You can do following for MYSQL
SELECT
@r:=@r+1 Rank,tbl.*
FROM users tbl, (select @r:=0) as r
ORDER BY users.points DESC;

Consider you have data
Points
3
7
8

Using Select statement with ROW_NUMBER() you will get result as follows
Result:
Points Rank
8       1
7       2
3       3


How to covert labels array into one vector of letters

Question: I have the labels as the following:
array([[1., 0., 0., 0.], [1., 0., 0., 0.], [1., 0., 0., 0.], ..., [1., 0., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]], dtype=float32)
How can I turn this into one vector that has for example a letter representing each class
[a,
a,
a,
b,
c,
d]
Comment: You can traverse through the array and save those float values into a mapping to other characters. Is it only for `0.0` and `1.0`, or for a lot of them? What code do you have right now?
Answer: You can use np.argmax() with map():
list(map(lambda x: chr(ord('a') + x), np.argmax(arr, axis=1)))

This outputs:
['a', 'a', 'a', 'a', 'c', 'd']


Does the definition of distribution and Dirac delta function capture the physicists' idea?

Question: I read on a physics textbook by Griffiths that the Dirac delta function is defined by $\delta(x)=0$ if $x\not=0$ and $\int_{-\infty}^{\infty}\delta(x)dx=1$. As a distribution, the Dirac delta function is defined by $\delta(f):=f(0)$, where $f:\Bbb R\to\Bbb R$ is infinitely differentiable and has compact support. However, I feel like the latter definition does not capture the idea of the former definition for several reasons:
$1.$ A relation is given in the textbook as $$\delta(kx)=\frac{1}{|k|}\delta(x)$$ for nonzero constant $k$. This concept is only captured by using change of variable, but not by defining Dirac delta explicitly as a distribution.
$2.$ The author gives several problems on evaluating integrals involving Dirac delta, with an example (after changing some numbers, I don't know if there are copyright issues) being $\int_{-8}^{8}x\delta(x-5)dx$. It is obvious that $x$ is not a test function. But several expressions similar to this are written in the book anyway.
$3.$ The author gives several problems on evaluating integral involving Dirac delta function over a compact set (like a region bounded by a cube or sphere), just like the above example. We can use case-defined functions or step functions to simulate integration over a compact set, but the result is that we get a function that is not a test function.
Could it be that definition of Dirac delta function as a distribution didn't really capture physicists' idea? Or is the definition already good enough for all practical applications in physics and other fields (that is, good enough for solving real problems in their fields rather than calculating an integral that comes out of nowhere)?
Answer: I think you are completely correct that the more definitional/formal, super-careful version of Dirac's $\delta$ (and other related notions) does not immediately capture the sense or use of it by physicists, although it is a good approximation. Further, with some sophistication, rigorous mathematical rationalizations for some seemingly glib physicists' tricks can be found, although often these rigorizations require a level of sophistication that's hard to anticipate.
For example, $\int_{-8}^8 x\,\delta(x-3)\;dx$ is not immediately legitimate, since the function $f(x)$ that is $x$ on $[-8,8]$ and $0$ outside is not a test function, nor is it a Schwartz function. There are at least two ways to make this "ok". First, we can use the notion of support of a distribution, and the support of $\delta$ is $\{0\}$. Then (making a choice) we can modify $f(x)$ by multiplying by a smooth cut-off function that is identically $1$ near $0$... thus creating a test function out of $f$. This is a bit of a kludge, because we must show that the outcome is independent of the smooth cut-off... and, anyway, far more importantly, how would we know that this process is compatible with all our other expectations? :)
A second, slightly fancier, approach is to observe that $f(x)$ and $\delta$ have disjoint _singular_support_, so can be multiplied, as distributions. They have compact support, so can be applied to the smooth function $1$. (One should prove that the dual of the space of all smooth functions on $\mathbb R$, suitably topologized, is compactly-supported distributions.)
And there are more rationalizations available... From a strict mathematical viewpoint, one would want to know that they are all inevitably the same. Well, one approach is to once-and-for-all determine a very large space of functions on which $\delta$ is indeed a continuous functional, and prove some uniqueness results... For example, spaces of functions which are continuous on a neighborhood of $0$ will suffice... but without more information this is too self-referential. Further, without more information, the seminorm $\nu(f)=|f(0)|$ is not separating on many interesting spaces of functions... so there is considerable latitude in choosing a topology on a more-global space of functions... to make $\delta$ legit.
Partly because various uniqueness theorems are provable, much of the time the naive form of a computation does yield the correct outcome... whether or not we know why. A miraculous idiot-proof-ness of this bit of mathematics. But, yes, it is still possible to create/find seeming paradoxes if one presses too hard from a naive viewpoint (in effect disconnecting from physical intuition, for example).
Answer: both definitions lead to exactly the same properties. but you must recognise how are they related.
$$
\delta[f]=f(0)
$$
$$
\int_{\mathbf{R}}\delta(x)f(x)\,\textrm{dx}=f(0)\int_{\mathbf{R}}\delta(x)\,\textrm{dx}=f(0)
$$
So the distribution and the delta function are related this way:
$$
\delta[f]=\int_{\mathbf{R}}\delta(x)f(x)\,\textrm{dx}
$$
and since they are equivalent in both settings you can derive the same properties
Comment: You didn't read all the details I have given...
Comment: i've read them and maybe i didn't understand where your problem lies, physicists prefer the integral representation since it directly leads to useful computations, mathematicians prefer the distribution definition since it's more rigourous.
Comment: The problem is that I found something that seems to be used by physicists, and those may not be accurately represented in terms of distributions.
Comment: Look here and you'll see that it can be done. https://en.wikipedia.org/wiki/Distribution_(mathematics)


MySql changing date format

Question: I got a lot of customers data who did put their birthday in wrong format.
0000.00.00
00-0000-00
0000-00-00
0000/00/00
etc..
mainly 6-7 variations
How can I fix it so that all have year-month-day format, using some query? The field type is varchar(255).
Comment: Hard to do 100% correctly since for example 1/2/3 can be Jan 2 2003, Feb 1 2003, Feb 3 2001, ... If you manage to clean them up, you should _really_ consider using a `DATE` datatype instead of a `VARCHAR`.
Answer: Using the DATE_FORMAT() function. http://www.w3schools.com/sql/func_date_format.asp

MySql changing date format


Ignoring case sensitivity

Question: I have to count how many times each word from given input text appears in it.
And the thing where I'm stuck: The character casing differences should be ignored.
For example: "You are here.You you" -> the output :
are=1
here=1
You=3

What I've done:
string text = "You are here.You you";
IDictionary<string, int> wordsCount = new SortedDictionary<string, int>();
string[] words = text.Split(' ',',','.','-','!');

foreach (string word in words)
{
    int count = 1;
    if (wordsCount.ContainsKey(word))
        count = wordsCount[word] + 1;
    wordsCount[word] = count;
}
var items = from pair in wordsCount
            orderby pair.Value ascending
            select pair;
foreach (var p in items)
{
    Console.WriteLine("{0} -> {1}", p.Key, p.Value);
}

There is a chance to make this possible without checking manually every word from the given text? For example if I have a very long paragraph to not check every word using the specific method?
Answer: Just add
for(i = 0; text[i] != '\0'; i++){
    text[i] = text[i].ToLower();
}

But as text is a string, just do :
text = text.ToLower();

Just before the string[] words = text.Split(' ',',','.','-','!'); line.
And then enjoy !
Comment: Sorry, what should I put in front of toLower to work?
Comment: You wrote: text[i] = tolower(text[i]). What's this "tolower"?
Comment: toLower must be applied to a string. `text[i] = text[i].toLower()`
Comment: Sorry I confounded with C, I apologize !
Answer: How about linq?
var text = "You are here.You you";
var words = text.Split(' ', ',', '.', '-', '!');

words
    .GroupBy(word => word.ToLowerInvariant())
    .OrderByDescending(group => group.Count())
    .ToList()
    .ForEach(g=> Console.WriteLine(g.Key + "=" + g.Count()));

Ignoring case sensitivity


Derivation of E step in EM algorithm

Question: While im going through the derivation of E step in EM algorithm for pLSA, i came across the following derivation at this page. Could anyone explain me how the following step is derived.
$\sum_z q(z) log \frac{P(X|z,\theta)P(z|\theta)}{q(z)}  = \sum_z q(z) log \frac{P(z|X,\theta)P(X,\theta)}{q(z)} $
Comment: It's all to do with Bayes Rule: I've explained it in this video https://www.youtube.com/watch?v=-q0KFRaPuvc
Answer: It looks like Bayes' formula :
$\Pr[A \mid B] = \frac{\Pr[B \mid A] \Pr[A]}{\Pr[B]}$
Here, it gives:
$\Pr[X \mid z, \theta] = \frac{\Pr[z \mid X, \theta] \Pr[X \mid \theta]}{\Pr[z \mid \theta]}$
Comment: @Learner: Well... I have not read the document, but $\theta$ is the standard notation for a parameter. Now, a parameter is a fixed quantity, not a random variable, and it does not make sense to compute $P(\theta)$... Could it be a typo ?
Comment: if we substitute your $P[X|z,\theta)$, we will end up $P(z|X,\theta)P(X|\theta)$ but not = $P(z|X,\theta)P(X,\theta) $.

Derivation of E step in EM algorithm


Basic C Questions. fprintf and fgets failures

Question: I've got some basic c questions that are driving me insane. Let me post my code, and I'll tell you about what's going wrong.
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

static int GetLine();

int main() {
char* sourceFile;
char* destinationFile;
int error, bytesRead;
char* sourceFD;
char* destinationFD;
char buffer[100];

error = GetLine("Please enter a source file name: \n", sourceFile, 100);
if (error == 1) {
    printf("A source file was not inputted.\n");
    return 0;
}
else if (error == 2) {
    printf("Source file is too long.\n");
    return 0;
}

error = GetLine("Please enter a destination file name: \n", destinationFile, 100);
if (error == 1) {
    printf("A destination file was not inputted.\n");
    return 0;
}
else if (error == 2) {
    printf("Destination file is too long.\n");
    return 0;
}
}

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int GetLine (char *prmpt, char *buff, unsigned int sz) {
int ch, extra;

// Get line with buffer overrun protection.
if (prmpt != NULL) {
    printf("%s", prmpt);
    fflush(stdout);
}
}

if (fgets (buff, sz, stdin) == NULL) {
    fprintf(stderr, "fgets returned NULL");
    return NO_INPUT;
}

printf("logging input: %s", buff);

// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
    extra = 0;
    while (((ch = getchar()) != '\n') && (ch != EOF))
        extra = 1;
    return (extra == 1) ? TOO_LONG : OK;
}

// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}

The errors are occurring in the the GetLine function, which was largely provided by another StackOverflow post. Here are my issues.

No matter what I do, I cannot get debug print statements to work properly. basic printf will often fail. Calling fflush(stdout) immediately after does not help, nor does setbuf(stdout, NULL). Right now I am trying fprintf(stderr), also to no avail. The LOC that continually fails (regardless of the method I try) is fprintf(stderr, "fgets returned NULL"). Note that the application still gives me the error that "A source file was not inputted." It doesn't matter if I target stdout or stderr.
fgets is returning NULL every time. I have no idea why. No, the input I'm providing is not large.

EDIT: I just noticed the missing brackets on that if statement (the fgets one). let me see what that fixes.
Comment: And, *if your question is answered, don't fix the code in the question* because then it looks like you never had that problem. If you've accepted an answer, and your code has other unrelated problems, post another question.
Comment: Hint: when you call `GetLine("Please enter a source file name: \n", sourceFile, 100);`, what value does `sourceFile` have? (the pointer itself)
Answer: if (fgets (buff, sz, stdin) == NULL)
    fprintf(stderr, "fgets returned NULL");
    return NO_INPUT;

Here return NO_INPUT; is always executed no matter what fgets() returns. Use {} to enclose the two statements.
Comment: hahah I just saw that as well. Thank you. That explains both errors perfectly
Comment: That's what I get for programming in Python so much. This looks normal
Comment: Alright, one more error now. The second time we call GetLine, the fgets still fails with a bus error. It doesn't return NULL. It just crashes the program. ideas?
Answer: if (prmpt != NULL) {
    printf("%s", prmpt);
    fflush(stdout);
}
}

Here you are closing GetLine but your code continues


bind9: Disabling error logging for recursive queries

Question: inadvertedly, a bind9 server I ran was an open resolver. Whoops.
Now it's been months and the recursive queries for isc.org are still incoming. I would not mind if my /var/log/syslog did not look like this:
Jul  6 01:10:23 servername last message repeated 6 times
Jul  6 01:10:23 servername named[2580]: client YYY.YY.YYY.YYY#25345: query (cache) 'isc.org/ANY/IN' denied
Jul  6 01:10:23 servername named[2580]: client ZZZ.ZZ.ZZZ.ZZ#25345: query (cache) 'isc.org/ANY/IN' denied
Jul  6 01:10:23 servername last message repeated 7 times
Jul  6 01:10:23 servername named[2580]: client AAA.AAA.A.AAA#25345: query (cache) 'isc.org/ANY/IN' denied
Jul  6 01:10:23 servername named[2580]: client BBB.BB.BB.BBB#25345: query (cache) 'isc.org/ANY/IN' denied
Jul  6 01:10:23 servername last message repeated 6 times

(One might find it funny that the above messages all appear within one second... I no longer don't.)
This really, REALLY makes it hard to catch any real errors that another service on the system may report.
I'd like to make bind9 no longer log these messages. And I'm crossing my fingers that it is possible to make only these messages disappear from the logs.
In what way can I disable messages that recursion is disallowed from appearing in the syslog (or other logs)?
servername:/etc/bind9# named -V
BIND 9.8.4-rpz2+rl005.12-P1 built with '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--sysconfdir=/etc/bind' '--localstatedir=/var' '--enable-threads' '--enable-largefile' '--with-libtool' '--enable-shared' '--enable-static' '--with-openssl=/usr' '--with-gssapi=/usr' '--with-gnu-ld' '--with-geoip=/usr' '--enable-ipv6' 'CFLAGS=-fno-strict-aliasing -DDIG_SIGCHASE -O2'
using OpenSSL version: OpenSSL 1.0.1c 10 May 2012
using libxml2 version: 2.8.0

servernane:/etc/bind9# uname -a
Linux servername 3.2.0-4-686-pae #1 SMP Debian 3.2.35-2 i686 GNU/Linux

To clarify:
I'm interested in more detailed example on how to silence just the 'recursion denied'-type messages.
Comment: @Ivan If someone is referring to your nameserver by `ns1.foobar.com`, changing the IP doesn't help if `ns1.foobar.com` still gets someone to your nameserver. Changing the scheme (example: `ns1.east.foobar.com`) breaks the robots but doesn't break your actual clients, since the servers that are behaving correctly are tracing their way to your domains from the root nameservers.
Comment: What distribution are you running? If you are using rsyslog, and named is logging to rsyslog, you may be able to use a regexp pattern to exclude it?
Comment: @fukawi2 My distribution is Debian, as visible from `uname -a`. If you need more information than that, I'll check in greater detail.
Comment: Those queries are attempts to use you as an amplification attack relay (`ANY?` is always your first hint, and `isc.org` is the classic query). You've made it into a list of known open recursors that bots are using. While this isn't the answer that you're looking for, you might want to change the IP address of these DNS servers and give the IPs to something where you can safely drop port 53. You'd probably want to change the glue record naming scheme as well.
Comment: @AndrewB I'm aware of what's going on :-) and I've thought of changing the IP. I'll probably do it. I'm however interested in what exactly you mean by 'changing the glue record naming scheme'?
Answer: Regarding disabling all the bind error logging for recursive queries such as
"query (cache) 'theswat.net/ANY/IN' denied"
The below in /etc/named.conf redirect these to /var/named/data/named.security
with a total size limit of 15mbytes of rolling over logs.
Note that category security is only "Approval and denial of requests."
logging {
        channel default_debug {
                    file "data/named.run";
                severity dynamic;
        };
        // Redirect all of those 'denied' logs for non-existing domains or external ones (we are 'recursion no;')
        //   logs to /var/named/data/named.security, up to 3 files of 5mbytes each
        //   independent hack_detect processes can then scan for flooders and known abusers and block their IPs
        channel hd_security {
                file "data/named.security" versions 3 size 5m;
                print-time yes;
                print-severity yes;
                print-category yes;
        };
        category security { hd_security; };
};

Comment: Thanks! On Debian, I did `mkdir /var/log/named`, `chown bind /var/log/named` and changed the path to an absolute one, `/var/log/named/named.security`. I also skipped `channel default_debug` section. On a side note, I seem to be getting no requests logged, though, except when explicitly requesting a test. So the server must have went off some lists! Hooray! ;)
Answer: See the BIND Administrator's Reference Manual (aka "the ARM", which is included with your source distribution, or consult the link tables in the ISC Knowledge Base to find the version specific to your BIND version) and go to section 6.2.10, which covers logging.
BIND error messages are emitted in various categories and you can specify their destination based on category.  While I don't know offhand and would have to check the source to know exactly in which category is the error message you want to suppress, once you have identified the category (either by checking the source or by trial and error) you can suppress error messages for that category using the sample syntax shown in the ARM, i.e.:
To discard all messages in a category, specify the null channel:
category xfer-out { null; };
category notify { null; };

I would start with the "resolver" category, although because it's a denial message it might belong to "security" -- actually the area you have described kind of sits between several possible categories (which is why I can't say off the top of my head which is correct..)  "resolver" sounds like messages you don't expect to find useful anyway, if you are not trying to perform recursion for clients.
Comment: Oh, and good job closing your open resolver!
Answer: Yes, it is possible to silence bind.  Check your configuration for category and channel definitions.  If this is showing up in your syslog, then find the channel(s) mentioning syslog.  There is also a default_syslog channel built in.  Then find the categories logging to these channels.  Comment out the category or redirect it to a different channel.  You may want to redirect to a log while you test.
More detail can be found here: http://www.zytrax.com/books/dns/ch7/logging.html
Comment: @IvanVučica Don't send all errors to null, only those types you don't want.  Alternatively, send them to their own log with a small size and limited rotation.
Comment: That's why I accepted Lynn Slater's answer. :-)
Comment: Thanks. I silenced bind entirely by redirecting everything to null. I'm however unsure how to go about disabling just this error about recursion? This server will never be a recursive one, so these errors are not important for me; but others might be. So, any tips?
Answer: For those using syslog and don't want to discard everything. Technically you don't want to send everything to NULL.
Here WARNING's and CRITICAL's are still being logged.
logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
        channel syslog {
                syslog;
                severity warning;
                print-severity yes;
                print-category yes;
        };
        category default{
                syslog;
        };
};


Prove if a language is infinite

Question: Given M = (Q,Σ,δ,q0,F) a DFA with n states. Prove:
The languge T(M) is infinite iff contains a string with lenght t, where n ≤ t < 2n.
Ok, it's intuitive for me, I can understand to get a string with length > number of states I need a loop, but how to prove it formally?
Using $\delta$-hat, could be an idea?
Comment: @NormalHuman: That comment really isn't appropriate here.
Comment: Hint: the pumping lemma (/pumping theorem) for regular languages is your friend here.
Comment: @BrianO, yes. I'll try it. Thanks
Answer: HINT: Consider the sequence of states visited when $M$ reads a word $w$ of length $n$ or more: it must intersect itself. That is, there must be some state that it visits twice. That means that the path contains a loop. Now you can modify the input word so that the DFA goes around that same loop any number of times while still ending in the same state as it does for $w$. Thus, if it accepts $w$, it accepts infinitely many other words. This is the basic idea; you should try to make it a bit more formal.
All that remains at that point is to show that if $|w|\ge 2n$, you can shorten $w$ to a word whose length is between $n$ and $2n-1$ inclusive that sends $M$ to the same end state. You can do this by showing that some subsequence of $w$ sends $M$ around a loop, so that this subsequence can be removed without changing the end state. As long as you have at least $2n$ symbols in the word, you can continue doing this. Finally, show that the substring sending $M$ around a loop once can have length at most $n$, so that removing it cannot drop the total length of the word below $n$.

Prove if a language is infinite


What is the simplest proof of the pythagorean theorem you know?

Question: Maybe enough so to explain it to children.
Comment: Related: [Pythagorean Theorem Proof Without Words (request for words)](http://math.stackexchange.com/q/103758/264) and [What is the most elegant proof of the Pythagorean theorem?](http://math.stackexchange.com/q/803/264)
Comment: Any explanation of the Pythagorean Theorem that can be understood by children cannot be called a 'proof' in the strictest sense of the word. It is at best a 'demonstration'.
Answer: I wouldn't call  this a proof, but it's a convincing argument good demonstration of what the theorem means, and I thought it was pretty cool. Hopefully should help with explaining it to kids, as you asked.
Comment: I don't see how it's even a convincing argument.  It just shows that for this particular triangle, it happens to be true that $a^2 + b^2 = c^2$.  It doesn't show why it's true, and it doesn't give us any reason why it would be true for other triangle.
Comment: @KeshavSrinivasan resize the gif; the proof will quickly follow with the help of some fairly trivial theorems from linear algebra
Comment: The best I've seen so far
Comment: I can easily imagine an animated gif like this showing that $a^2 + b^2$ is less than or greater than $c^2$.
Comment: @KeshavSrinivasan moreover it's easy to create a contraption like that in real life that proves $a^2+b^2$ is greater or less than $c^2$ by adjusting the depth
Comment: @Keshav, I agree with you completely. How can nsanger call this a convincing argument, when it's not even an argument?
Comment: @enthdegree: You missed Keshav's point. If the big square is _thicker_ (in the z-dimension, if you like) than the small squares, then the water won't fill it. Likewise, if the big square is thinner, then the water will overflow.
Comment: I apologize for using the word "argument", perhaps a better phrasing would have been "demonstration of what the theorem means." The OP was asking for something that could help explain the theorem to children, so I posted a gif that I thought would help accomplish that. The post was written in 20 seconds -- it wasn't something I put a lot of thought into, so please don't look too deeply into it.
Comment: I don't understand how this demonstration works. How come the $c$ square ends up completely full? Since it's not completely lined up with the ground, shouldn't gravity cause some of its fluid to backwash into the $a$ square? It seems like some sleight-of-hand must be going on . . .
Comment: @enthdegree Can you elaborate on this?  How should the gif be resized, and what theorems of linear algebra are you referring to?
Comment: @TonyK I wasn't talking about the thickness of the squares.  I was just saying that, if you didn't already know that the Pythagorean theorem was true, there's no reason to believe that the water in the two upper squares is going to match the space in the lower square.  So if you just saw this animation, you might think this was just some kind of random coincidence for this particular triangle, and you can just as we'll imagine another right triangle for which $a^2 + b^2$ is less than or greater than $c^2$.
Answer: 'Picture proofs' are particularly elegant. I like this one:
Comment: this one seems to be the best as it avoid the use of formula of area of a triangle. Only requirement is the formula for area of square.
Comment: @pts That's not a big problem, since the second figure has rotational symmetry.
Comment: @ParamanandSingh You don't need the formula for the area of a square. You can see from this that the area of a square of side $c$ is the same as the sum of the areas of squares of sides $b$ and $a$, you don't need to calculate those areas.
Comment: Hm, this argument seems to rely on the area-preserving nature of rotations and translations. Is that trivial? (I'm being sarcastic.) What is trivial or non-trivial depends on one's axioms. Maybe my axioms take the area formula for a square as primitive.
Comment: Fully agree with Jesse Madnick. And Jack M. you do need the area of a square of side $a$ as $a^{2}$. Normally this can be taken as an axiom or we can define the area of unit square as $1$ and then derive this formula by properties of addition of areas.
Comment: You also need to prove that in the figure on the right the large white area is a square. It's obvious that all its sides have the length $c$, but are the angles right angles?
Comment: @ParamanandSingh Oh, I see, you're seeing the pythagorean theorem as stating $a^2+b^2=c^2$. I would just directly state it as "sum of areas of squares equals big area".
Answer: Every time you walk on a floor that is tiled like this, you are walking on a proof of the Pythagorean theorem.

EDIT: Due to popular demand, I have added the grid in red on the right, with some triangle legs in blue.
If you consider say the upper left corner of every small square, you can see that these points lie on a slightly diagonal periodic grid.
Each square in this grid is $c \times c$.
Then you can choose either of two easy proofs:

(1) The $c \times c$ square is clearly a rearrangement of one $b \times b$ square and one $a \times a$ square.
or
(2) Each period of the periodic pattern covers what area of floor?  On the one hand there is one $a \times a$ square and one $b \times b$ square per period, while on the other hand there is one $c \times c$ square per period.

(The second proof is my favorite, since unlike most proofs it requires neither dissection nor algebra.  Once you see that the tiling's periodicity is $c \times c$, you are done!)
Comment: A picture that proves Pythagoras but contains no obvious triangle simply doesn't *feel* right for me :D .
Comment: If you are allowed to draw on the floor, you can draw the $c \times c$ grid.  You will see the relevant triangle all over the place.  If you are not allowed to draw on the floor, you will have to visualize the hypotenuses on your own.  That is the fun part.  The triangles are there.
Comment: I have drawn some lines on the floor now so that you can see the triangles more easily.  But I still recommend practicing seeing the triangles in your head even when they are not marked, so that you can enjoy the proof embedded in such floors whenever you walk on them.
Comment: This is great.  I think it would be even better if the lengths were chosen so that `b` is not `2 a`; e.g. lengths 1 and 3 instead of 1 and 2.  That would have prevented my initial confusion due to the two little triangles being identical, leading to me regrouping them what turned out to be the less helpful
of the two possible ways.
Comment: @DonHatch I agree, it was just the first such picture I found. A picture "in general position" would of course be better. Also, I find it easiest to see the CxC grid in terms of the small squares being the grid points. This way the CxC grid is actually visually recognizable as a grid (without drawing lines on the floor). Placing the red grid this way (with grid points at the centers of the small squares) results in more tile shards but it is more symmetric, and a bunch of little triangle equivalences of the type you spotted are sufficient to fix the corners of the big square.
Comment: I see what you're saying; yes, that's now my favorite way of looking at it.  Oh wait-- actually, try putting the grid points in the the centers of the *large* squares.  Very few pieces, and no ambiguity on how to put them back together!  The little square doesn't even need to be carved up.  Now *this* is my favorite way of looking at it :-)
Answer: I liked Garfield's Proof. It is simple and intuitive.
Here, https://www.khanacademy.org/math/cc-eighth-grade-math/cc-8th-geometry/cc-8th-pythagorean-proofs/v/garfield-s-proof-of-the-pythagorean-theorem
Comment: I would be interested in seeing the cat's proof as well.
Comment: Note: The president's, not the cat's. :)
Comment: Ask Odie: Garfield copied the proof from him
Answer: For geometric proof using rearrangment there are few quite good example on the Wikipedia page. A beginner likely will not understand this quite well, because all those triangles in the picture can be confusing, so I recommend to start first with this "counting proof"

Then introduce the rearrangment pictures and animations, and at last introduce the actual formula $a^2 + b^2 = c^2$. It would be nice to lead them and help them to derive the formula by themselves, rather than just writing it on a board.
Comment: I would consider this to be more of a demonstration than a proof. Such demonstrations would be undermined if the student has seen [disappearing square](http://en.wikipedia.org/wiki/Missing_square_puzzle) puzzles.
Comment: Also, how do you know that with squares of those sizes you end up with a right angle between A and B (without already knowing the pythagorean theorem)?
Answer: You can cut up a square of sides $a+b$ into $a^2$, $b^2$ and four triangles of sides $a,b,c$.
You can also cut up the same square into a square of side $c$, and the same four triangles.
Answer: Consider the right figure and ignore the left one!

The area of the square of side $a+b$ is
\begin{align*}
(a+b)(a+b)
&= a^2 + ab + ab + b^2\\
&= a^2 + 2ab + b^2
\end{align*}
It is equal to the sum of 4 triangles and 1 square. This sum is
\begin{gather*}
4\times \frac{ab}{2} + c^2\\
2ab+ c^2
\end{gather*}
By equating both, we have
\begin{align*}
a^2 + 2ab + b^2
&= 2ab +c^2\\
a^2+b^2=c^2
\end{align*}
Now consider a single triangle so you have proven that $a^2+b^2=c^2$. Done!
Comment: "You've got to know that the area of a rectangle is the product of its sides."  That's a non-trivial fact?  That's practically my definition of area.
Comment: This relies on loads of non-trivial facts about area. You've got to know that the area of a rectangle is the product of its sides, and then you've got to consider that those sides might be real numbers, so you've got to know how to do arithmetic with real numbers.
Comment: @JackM Euclid proved that area is length times width, and he did it without assuming anything about the arithmetic of real numbers.  See my comment to you here: http://math.stackexchange.com/questions/803/what-is-the-most-elegant-proof-of-the-pythagorean-theorem/10867#comment1152889_10867 He did, however, use Eudoxus' theory of proportions, which basically says that two ratios are equal if and only if the same rational numbers are less than, greater than, or equal to them, so there is a reliance on something equivalent to our modern idea of real numbers, but not the arithmetic of real numbers.
Comment: @JesseMadnick Not mine. I define area using a unit shape (like a square with a side of unit length) and counting the number of that shape you'd need to cover the shape whose area you'd want to measure.
Comment: @JackM: Right, so by that definition, isn't the area of a rectangle equal to its length times its width, then? After, say, a 1-line argument?
Comment: @JesseMadnick For integer sides, yeah.
Comment: @JackM: Oy, ok, I suppose that's fair.
Comment: @JesseMadnick The point is that I'm not being pedantically formal, I'm just being practical. I'm thinking about how you would convince a hypothetical *complete* layman. Someone totally uninitiated wouldn't understand the motiviation behind a definition like "the area of a rectangle is the product of its sides", or that you can multiply lengths that aren't ratioanl numbers, but they would agree that (my definition of) area is invariant under rotation.
Comment: @JackM Euclid's proof of the area of a rectangle doesn't involve the notion of multiplying irrational numbers at all.
Comment: @JackM I found a proposition of Euclid that seems to demonstrate even more directly that area = length times width: http://aleph0.clarku.edu/~djoyce/java/elements/bookVI/propVI1.html
Answer: I think that one of the simplest proofs is that attributed to US President James Abram Garfield.
The Cut the Knot page on the Pythagorean lists it as Proof #5.

This proof, discovered by President J. A. Garfield in 1876 [Pappas],
  is a variation on the previous one. But this time we draw no squares
  at all. The key now is the formula for the area of a trapezoid - half
  sum of the bases times the altitude - $(a + b)/2·(a + b)$. Looking at
  the picture another way, this also can be computed as the sum of areas
  of the three triangles - $ab/2 + ab/2 + c·c/2$. As before,
  simplifications yield a² + b² = c².

For more of this story, see: A Mathematician for President, Let's Play Math.

PS
I just noticed that this proof was already given as an answer. I'll leave my response here as it contains more details.
PPS
My next favourite proof is probably the one based on a construction of similar triangles (Proofs #6 and #7). I think it cuts to the heart of the idea as seen by Euclid.
Then probably the simple picture proofs #3, #4, #9 - the latter already being posted as an answer to this question.
The original Euclidean proof constructed from the "Bride's Chair" always seemed a little convoluted to me.
Answer: What I will say will be the worst in terms of beauty but you need to ask yourself what is a square triangle. How is it defined ?
Well, the answer is that 2 vectors are square when their scalar product is 0, which leads (after 1 or 2 lines) to the Pythagore Theorem
Edit :
Vectors are A and B ; C = A - B to "complete the triangle"
In the general case, ||C||2 = (A-B).(A-B) = ||A||2 + ||B||2 - 2 A.B
We see that ||C||2 = ||A||2 + ||B||2 if and only if A.B == 0 (i.e are square by definition of being square)
Comment: Would you mind showing those 1 or 2 lines?
Comment: see update/edit
Comment: In other words, don't explain Pythagore's formula with the area of the squares around the triangle. It does not make any sense. The formula says that the length of a "shortcut" is derived from the length of 2 legs of a path, it has nothing to do with areas


Multiple objects waiting for the same API response

Question: I have an API code, which loads a data necessary for my application.
It's as simple as:
<code>- (void) getDataForKey:(NSString*) key onSuccess:(id (^)())completionBlock
</code>
I cache data returned from server, so next calls of that functions should not do network request, until there is some data missing for given key, then I need to load it again from server side.
Everything was okey as long as I had one request per screen, but right now I have a case where I need to do that for every cell on one screen.
Problem is my caching doesn't work because before the response comes in from the first one, 5-6 more are created at the same time.
What could be a solution here to not create multiple network request and make other calls waiting for the first one ?
Answer: You can try to make a RequestManager class. Use dictionary to cache the requesting request.

If the next request is the same type as first one, don't make a new request but return the first one. If you choose this solution, you need to manager a completionBlock list then you will be able to send result to all requesters.
If the next request is the same type as first one, waiting in another thread until the first one done. Then make a new request, you API will read cache automatically. Your must make sure your codes are thread-safe.

Or you can use operation queues to do this. Some documents:
Apple: Operation Queues
Soheil Azarpour: How To Use NSOperations and NSOperationQueues
Comment: I'm using AFNetworking - do you know if they have anything ready to use for that maybe ?
Comment: @GrzegorzKrukowski If you are using AFNetworking, have a look at AFHTTPRequestOperationManager. If you create request via AFHTTPRequestOperationManager, request will be add into [AFHTTPRequestOperationManager manager].operationQueue automatically. By the way, this operationQueue is a NSOperationQueue, you can setup it as you like.
Answer: May be there will be so many time consuming solutions for this. I have a trick. Create a BOOL in AppDelegate, its default is FALSE. When you receive first response, then set it TRUE. So when you go to other screen and before making request just check value of your BOOL variable in if condition. If its TRUE means response received so go for it otherwise in else don't do anything.
Comment: Sorry but that's not gonna solve my problem. I want to do something even if there is another request made, but I want to wait for the first to be finished, and return same response to others


Google Analytics configuration setting for Drupal multisite (domain and submain)

Question: I am working on a Drupal mulsite project (using single database) and using Google Analytics module for this.
I have follow the below steps for GA configuration:

Created a domain name example1.com and a sub-domain name example2.com.
Create an account on GA and create property for both of this domain name in GA account. Both property give me two different Tracking ID (same as below screenshot).

Into the configuration setting of GA from drupal admin section I have added Web Property ID of example1.com and into domain setting added both the domain name example1.com and example2.com into the section of List of top-level domains (a same as attached screenshot).

Now this configuration is only working for emample1.com, not for example2.com. So can anyone please tell me how can I use Web Property ID of domain exmaple2.php to get the result?
Comment: I take it doesn't work because those domains have two different UAs, while the module allows you to enter just one.
Answer: As Kiamlaluno states, this is likely caused by the fact that the module only allows one UA, while you are trying to track two domains. According to the GA module documentation it can be overridden using code like this in settings.php:
<?php
// Override Google Analytics Web Property ID per hostname.
// Hostnames need to be lower-case!
switch ($_SERVER['HTTP_HOST']) {
  case 'www.example.com':
  case 'www.example.net':
  case 'forum.example.net':
    $conf['googleanalytics_account'] = 'UA-123456-2';
    break;

  case 'www.example.org':
    $conf['googleanalytics_account'] = 'UA-123456-3';
    break;

  default:
    $conf['googleanalytics_account'] = 'UA-123456-1';
}
?>

Documentation can be found here


In 4/4 time can I insert a half sized bar in the middle of the piece?

Question: I am writing a piece that has a chord structure A, B, A, B,etc. with a melody that is not repeated.
When ending the B part the music wants to hang for an extra two beats before returning to the A part. It then means that my second A part starts in the middle of the bar unlike the first time around.
Can one insert half a bar to keep the uniformity or is there a way of showing a slowing down of the last two quarter notes by half so that in effect they become half notes? Or should I not be worrying about the fact that the part starts halfway through the bar?
As you can no doubt gather I am a novice at music notation.
Comment: Take a look at the image in this question, should be exactly what you want: http://music.stackexchange.com/q/32068/28
Comment: If it can be less measured, I would als look into using a 'ritardando'.
Comment: If you are expecting it to keep exactly the same tempo, then the 2/4 bar is the way to go. Roy Orbison did it in several numbers, notably Pretty Woman. Lots of  people don't even notice the change.
Comment: Bob Dylan just won a Nobel Prize doing this.
Comment: Become famous enough and you can literally do [whatever you want](https://www.youtube.com/watch?v=EkFNdi8gIMY).
Comment: I think Stephen Sondheim once said something to the effect that he learned from Bernstein to prefer an "out of place" measure in a different time signature from the rest of the piece to "padding" the measure to keep it in line with the rest. I can't find the exact quote, though.
Comment: Listen to 'Revolution 1' by the Beatles: almost every line in the verse has a 2/4 bar in the middle of a 4/4 line. There are also two songs by Van der Graaf Generator with a basic line structure of 4/4, 2/4, 4/4, 4/4 (at least the way I count it).
Comment: See Lennon-McCartney "Revolution." It has a 2/4 bar inserted in the middle of a 4/4 passage.
Answer: I'm not totally sure I understand what you are trying to achieve, but this might help:
There is no reason why you cannot change the time signature for just one bar, and then immediately change it back to what it was. For example, after a number of bars of 4/4 music, you can insert one bar of music with a new time signature of 2/4, and after that "half-sized" bar, go back to the previous time signature of 4/4.
Would that solve your problem?
Comment: Personally, I would prefer a time change for  single bar, so that it is then really clear that the A part is the same the second time round. There is also another point: in a 4/4 bar, the first beat has the most stress, and the 3rd beat is a bit less, and the 2nd and 4th beats least stress, so that if you were to start the second occurrence of A halfway through a 4/4 bar, you would be changing the stress pattern at least slightly.
Comment: @alephzero Probably not, they're not interchangeable.  See http://music.stackexchange.com/q/5621/28
Comment: Meh, just total the number of quarter notes in the piece and have a single bar.  136/4 is a perfectly fine time signature.  ;)
Comment: Possibly, yes - unless he wants a strongish stress every 4 beats.
Comment: Thank you @Old John that is what I need to hear. Yes the piece wants to be felt as 4/4  - just at that one place it needs to extend a bit (but not a whole bar).  After reading what you said I realise I must go back and sort out a few old pieces with similar problems where the beginnings of sections land up in weird places. Much appreciated
Comment: Personally, I think a 6/4 would be more natural.
Comment: @PhilMobley: at least in classical music, 3/2 would be more appropriate than 6/4 for this.  6/4 is usually read as two groups of three quarter notes (like a scaled-up version of 6/8), so for three groups of two quarter notes, 3/2 is used.
Comment: Yes. That would help. Thank you. I guess I am a not sure of what a  musician would expect/prefer to see. (The signature changes - or the A part starting half way through the bar). I am writing in Logic Pro using the piano roll and then generating notation for a hypothetical musician so I can't ask them. (I play guitar and am writing melodic parts for cello and oboe)
Comment: The simplest solution might be to use 2/4 for the whole piece.
Comment: Do you mean just one bar of 6/4 (instead of a 4/4 bar and a 2/4 bar), or are you thinking of writing the whole thing in 6/4?
Comment: @OldJohn yes I meant just the one bar at 6/4... it feels like what you want is a 5th and 6th beat, not a short measure.
Answer: This has been said many times already on this site, but here goes...
The answer to all "can I do X"-questions in music is: yes, you can do anything!
Really, these questions have just two subquestions that should be considered:

"Do I want it"? Everything you put in a composition will have a certain effect on the end result. If you decide to put an F♯ in the melody of a piece in F over a D minor chord, nobody can stop you. It just will sound, ahem... Or to take a more relevant example, it's perfectly possible to use parallel fifths, and it won't sound wrong (except perhaps to some overzealous music educators), but it also won't give you quite the full intertwined-harmony sensation that classical composers achieve with their 4-voice counterpoint (which generally avoids parallel octaves and fifths, though even those composers make exceptions when it's musically useful).In your example, this questions reads "will it sound disruptive if I insert a single ²⁄₄ bar in the midst of my ⁴⁄₄ piece"? To which the answer is, possibly, but since ²⁄₄ is still pretty even, it will probably be barely noticable. In fact, if that extra half-metre fits logically in the melody, then it will likely sound less disruptive than the pause that a full ⁴⁄₄ bar would incur†. So by all means don't shy away from that possibility, just be sure that it actually feels right.Whether something feels right is best determined by actually playing it, even if just in a much simplified manner.
"Is it practical"? Some things might theoretically work out great, but it's unrealistic to expect the musicians to be able to accurately render them out. Obviously this includes technically very difficult lines (it's always good to know yourself at least roughly how everything would actually be played, on each instrument), but also parts that are rhythmically or otherwise too hard to get together. And many musicians aren't capable of playing complex metres. But again – ²⁄₄ really isn't that far-out, almost nobody who's musical at all should have trouble with that. As already said, it's not uncommon either.

Is summary: yes, I reckon you should insert a single ²⁄₄ bar in that piece.

†Then again, it can be good to have a bit of space. A rest in the main voice may be an opportunity to give e.g. the cello a bit of a melodic hook, or just to de-clutter everything.
Answer: Instead of changing time signatures, you might consider instead using a pause (fermata) on the last 2 beats worth of the last bar of section B.
I assume you are considering writing something like this at the end of your section B:

Instead you could consider doing this:

This may not be precisely what you want though.  According to the wikipedia entry:

Exactly how much longer it is held is up to the discretion of the performer or conductor, but twice as long is common.
Answer: Yes, you can. For example, take a look at Bring Me To Life by Evanescence. While the main part of the song is in 4/4 notation, the song "hangs" for two extra beats (just like you describe it) before the first chorus, at around 00:50.
Comment: How is it notated, though?
Comment: @Random832 unfortunately I don't have the sheet music for the song. I'll see if i can find it!
Answer: If the piece is in 4/4 time, change measure to 2/2 time and indicate two notes with two half notes.  Then change back to 4/4 time with quarter notes carrying the beat.


grep pattern for getting words having alternate consonants and vowels

Question: I have a text file file1.txt containing the following words

abcdefghis
abacadafag
cdefghijka
bedefegehj
cidifigihi

Question: How will I get the words with alternating consonants and vowels using grep pattern?
My expected output is like this:
abacadafag
cidifigihi

So far I have this code but it only displays words with alternating consonant and vowel on the first 2 characters.
cat file1.txt | grep -i '^[^aeiou][aeiou]'

Any help would be appreciated. Thanks. :)
Answer: Your desired regex is the following:
^[aeiou]?([^aeiou][aeiou])+[^aeiou]?$

^[aeiou]? Matches any vowel 0 or 1 times (?) at the beginning of the string (^)
([^aeiou][aeiou])+ Matches any consonant followed by a vowel 1 or more times (+)
[^aeiou]?$ Matches any consonant 0 or 1 times (?) right before the end of the string ($)
Comment: Nice! this solution is superior to the one that I provided!
Comment: Sorry for the late reply. This solution worked great. Accepted this. Thank you so much :)
Answer: Just remove the first ^, grep -i '[^aeiou][aeiou]'


Angular: Performance implication of using object literals in component template for ng-template context with ngTemplateOutlet

Question: What are the performance implications of using an object literal in the template when passing context to ng-template?
<ng-container *ngTemplateOutlet="template;context:{ field: value };"></ng-container>

as opposed to:
<ng-container *ngTemplateOutlet="template;context:context;"></ng-container>

context = { field: value }

Is change detection going to run more often in the first case, since it's (presumably) creating a new object?
https://github.com/angular/angular/blob/c2868de25a0fe4e14e4da4aae6aa2d5867711d05/packages/common/src/directives/ng_template_outlet.ts
  /**
   * We need to re-create existing embedded view if:
   * - templateRef has changed
   * - context has changes
   *
   * We mark context object as changed when the corresponding object
   * shape changes (new properties are added or existing properties are removed).
   * In other words we consider context with the same properties as "the same" even
   * if object reference changes (see https://github.com/angular/angular/issues/13407).
   */
  private _shouldRecreateView(changes: SimpleChanges): boolean {
    const ctxChange = changes['ngTemplateOutletContext'];
    return !!changes['ngTemplateOutlet'] || (ctxChange && this._hasContextShapeChanged(ctxChange));
  }

Judging by this I would say it does make a difference because the function call is more expensive if "ngTemplateOutletContext" is in changes. And it always would be there if it's defined as an object literal in the template. This assumes that a new object is created every cycle. Is this assumption wrong?
Answer: I stumbled against this article explaining that a literal object in templates doesn't imply a new instance on every detect cycle. I checked it out with a modern versions of Angular and its behavior is the same. So, I suppose that construction like in your code snippet is okay and it can be used without any problem.


What's the order of correlation?

Question: What is expressed by the terms zeroth-, first-, second-, third-, etc. order of correlation?
Thanks!
Comment: Hi.  You're more likely to get a useful answer if you indicate what efforts you've made to solve the problem yourself (eg which definitions have you looked at), what is puzzling you about them (so we can help!), and what the context is (eg regression, time series, multivariate analysis).
Answer: Here is a nice resource for understanding these issues.  It's excellent; you should read it thoroughly.
However, I will give a quick introduction.  Imagine you have 3 variables, $x$, $y$ and $z$.  You are primarily interested in the relationship between $x$ and $y$, but you know that $y$ is also related to $z$, and that unfortunately, $z$ is confounded with $x$.  If you simply wanted to know the strength of the relationship, Pearson's product-moment correlation coefficient $r$ is a useful effect size measure.
In this situation, you could simply ignore $z$ and compute the correlation between $x$ and $y$ (this is not really a good idea, as the value would be a biased estimate of the direct correlation).  Since you have controlled for nothing, this is a 'zero-order' correlation.
You might opt instead for a more conscientious approach and control for the confounding with $z$, by partialling out $z$.  (One conceptually clear way to do this, albeit not computationally optimal, is to regress $y$ onto $z$, and $x$ onto $z$, and then compute the correlation between the residuals of the two models.)  Because you have controlled for one variable, this would be a 'first-order' partial correlation.  Another possibility is to partial $z$ out of only one variable, say $y$.  For example, you could regress $y$ onto $z$ and correlate those residuals with $x$.  This would be a 'first-order' semi-partial (or part) correlation*.
I have never seen such a thing in practice, but if you partialled out 17 other variables, you would have a 'seventeenth-order' partial correlation.  The linked website is very informative, with examples, multiple formulas and diagrams; go read it.  To be technical, there isn't really any such thing as a 'first-order' correlation, nor is there such a thing as a 'zero-order' partial or semi-partial correlation.  There are only 'zero-order' correlations, and only 'first-', 'second-', etc., 'order' partial and semi-partial correlations.
* Regarding why you might use a partial vs. semi-partial correlation, it depends on the question you want to answer.  Often, it may have to do with the pattern of causal connections that people believe creates the pattern of correlations that are seen.  For example, a 'first-order' partial correlation between $x$ and $y$ controlling for $z$ of $0$ (i.e., $r_{xy|z}=0$) is consistent with the idea that both $x$ and $y$ are effects of $z$ with no direct connection between them.  Likewise, someone might want to show that $y$ is correlated with $x$ even after controlling for $z$.  Part of what is going on in a Structural Equations Model can be understood as partial and semi-partial correlations.
Comment: Ok. But it seems that the term has another meaning in "For a spatial field, multifractality is associated with the presence of spatial correlations of order higher than two that are not completely determined by the second-order correlations, that is, by the shape of the power spectrum." From: https://journals.ametsoc.org/view/journals/hydr/4/3/1525-7541_2003_004_0544_rmirf_2_0_co_2.xml  Could you explain the meanign here, please?
Comment: @AntonioSerrano, you should ask that as a new question.  It doesn't work well to ask questions in comments.  You can link back to this thread for context, if you like.

What's the order of correlation?


Create a QDockWidget that resizes to it's contents

Question: I have an application where fixed-size child widgets need to be added programatically to a dock widget at run time based on user input. I want to add these widgets to a dock on the Qt::RightDockArea, from top to bottom until it runs out of space, then create a new column and repeat (essentially just the reverse of the flow layout example here, which I call a fluidGridLayout)
I can get the dock widget to resize itself properly using an event filter, but the resized dock's geometry doesn't change, and some of the widgets are drawn outside of the main window. Interestingly, resizing the main window, or floating and unfloating the dock cause it to 'pop' back into the right place (I haven't been able to find a way to replicate this programatically however)
I can't use any of the built-in QT layouts because with the widgets in my real program, they end up also getting drawn off screen.
Is there some way that I can get the dock to update it's top left coordinate to the proper position once it has been resized?
I think this may be of general interest as getting intuitive layout management behavior for dock widgets in QT is possibly the hardest thing known to man.
VISUAL EXMAPLE:
The code to replicate this is example given below.

Add 4 widgets to the program using the button

Resize the green bottom dock until only two widgets are shown. Notice that the 3 remaining widgets are getting painted outside the main window, however the dock is the right size, as evidenced by the fact that you can't see the close button anymore

Undock the blue dock widget. Notice it snaps to it's proper size.

Re-dock the blue dock to the right dock area. Notice it appears to be behaving properly now.

Now resize the green dock to it's minimum size. Notice the dock is now IN THE MIDDLE OF THE GUI. WTf, how is this possible??

THE CODE
Below I give the code to replicate the GUI from the screenshots.
main.cpp:
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

#endif // MAINWINDOW_H

mainwindow.cpp
#include "mainwindow.h"
#include "QFluidGridLayout.h"
#include "QDockResizeEventFilter.h"
#include <QDockWidget>
#include <QGroupBox>
#include <QPushButton>
#include <QWidget>
#include <QDial>

class QTestWidget : public QGroupBox
{
public:
    QTestWidget() : QGroupBox()
    {
        setFixedSize(50,50);
        setStyleSheet("background-color: red;");

        QDial* dial = new QDial;
        dial->setFixedSize(40,40);
        QLayout* testLayout = new QVBoxLayout;
        testLayout->addWidget(dial);
        //testLayout->setSizeConstraint(QLayout::SetMaximumSize);

        setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
        setLayout(testLayout);
    }

    QSize sizeHint()
    {
        return minimumSize();
    }

    QDial* dial;
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{

    QDockWidget* rightDock = new QDockWidget();
    QDockWidget* bottomDock = new QDockWidget();

    QGroupBox* central = new QGroupBox();
    QGroupBox* widgetHolder = new QGroupBox();
    QGroupBox* placeHolder = new QGroupBox();

    placeHolder->setStyleSheet("background-color: green;");
    placeHolder->setMinimumHeight(50);

    widgetHolder->setStyleSheet("background-color: blue;");
    widgetHolder->setMinimumWidth(50);
    widgetHolder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    widgetHolder->setLayout(new QFluidGridLayout);
    widgetHolder->layout()->addWidget(new QTestWidget);

    QPushButton* addWidgetButton = new QPushButton("Add another widget");
    connect(addWidgetButton, &QPushButton::pressed, [=]()
    {
        widgetHolder->layout()->addWidget(new QTestWidget);
    });

    central->setLayout(new QVBoxLayout());
    central->layout()->addWidget(addWidgetButton);
    rightDock->setWidget(widgetHolder);
    rightDock->installEventFilter(new QDockResizeEventFilter(widgetHolder,dynamic_cast<QFluidGridLayout*>(widgetHolder->layout())));
    bottomDock->setWidget(placeHolder);

    this->addDockWidget(Qt::RightDockWidgetArea, rightDock);
    this->addDockWidget(Qt::BottomDockWidgetArea, bottomDock);

    this->setCentralWidget(central);
    central->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    this->setMinimumSize(500,500);
}

};
QFluidGirdLayout.h
#ifndef QFluidGridLayout_h__
#define QFluidGridLayout_h__

#include <QLayout>
#include <QGridLayout>
#include <QRect>
#include <QStyle>
#include <QWidgetItem>

class QFluidGridLayout : public QLayout
{
public:

    enum    Direction { LeftToRight, TopToBottom};

    QFluidGridLayout(QWidget *parent = 0)
        : QLayout(parent)
    {
        setContentsMargins(8,8,8,8);
        setSizeConstraint(QLayout::SetMinAndMaxSize);
    }

    ~QFluidGridLayout()
    {
        QLayoutItem *item;
        while ((item = takeAt(0)))
            delete item;
    }

    void addItem(QLayoutItem *item)
    {
        itemList.append(item);
    }

    Qt::Orientations expandingDirections() const
    {
        return 0;
    }

    bool hasHeightForWidth() const
    {
        return false;
    }

    int heightForWidth(int width) const
    {
        int height = doLayout(QRect(0, 0, width, 0), true, true);
        return height;
    }

    bool hasWidthForHeight() const
    {
        return true;
    }

    int widthForHeight(int height) const
    {
        int width = doLayout(QRect(0, 0, 0, height), true, false);
        return width;
    }

    int count() const
    {
        return itemList.size();
    }

    QLayoutItem *itemAt(int index) const
    {
        return itemList.value(index);
    }

    QSize minimumSize() const
    {
        QSize size;
        QLayoutItem *item;
        foreach (item, itemList)
            size = size.expandedTo(item->minimumSize());

        size += QSize(2*margin(), 2*margin());
        return size;
    }

    void setGeometry(const QRect &rect)
    {
        QLayout::setGeometry(rect);
        doLayout(rect);
    }

    QSize sizeHint() const
    {
        return minimumSize();
    }

    QLayoutItem *takeAt(int index)
    {
        if (index >= 0 && index < itemList.size())
            return itemList.takeAt(index);
        else
            return 0;
    }

private:

    int doLayout(const QRect &rect, bool testOnly = false, bool width = false) const
    {
        int left, top, right, bottom;
        getContentsMargins(&left, &top, &right, &bottom);
        QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
        int x = effectiveRect.x();
        int y = effectiveRect.y();
        int lineHeight = 0;
        int lineWidth = 0;

        QLayoutItem* item;
        foreach(item,itemList)
        {
            QWidget* widget = item->widget();

            if (y + item->sizeHint().height() > effectiveRect.bottom() && lineWidth > 0)
            {
                y = effectiveRect.y();
                x += lineWidth + right;
                lineWidth = 0;
            }

            if (!testOnly)
            {
                item->setGeometry(QRect(QPoint(x, y), item->sizeHint()));
            }

            y += item->sizeHint().height() + top;

            lineHeight = qMax(lineHeight, item->sizeHint().height());
            lineWidth = qMax(lineWidth, item->sizeHint().width());
        }

        if (width)
        {
            return y + lineHeight - rect.y() + bottom;
        }
        else
        {
            return x + lineWidth - rect.x() + right;
        }
    }

    QList<QLayoutItem *> itemList;
    Direction dir;
};

#endif // QFluidGridLayout_h__

QDockResizeEventFilter.h
#ifndef QDockResizeEventFilter_h__
#define QDockResizeEventFilter_h__

#include <QObject>
#include <QLayout>
#include <QEvent>
#include <QDockWidget>
#include <QResizeEvent>

#include "QFluidGridLayout.h"

class QDockResizeEventFilter : public QObject
{
public:

    QDockResizeEventFilter(QWidget* dockChild, QFluidGridLayout* layout, QObject* parent = 0)
        : QObject(parent), m_dockChild(dockChild), m_layout(layout)
    {

    }

protected:

    bool eventFilter(QObject *p_obj, QEvent *p_event)
    {
        if (p_event->type() == QEvent::Resize)
        {
            QResizeEvent* resizeEvent   = static_cast<QResizeEvent*>(p_event);
            QMainWindow* mainWindow     = static_cast<QMainWindow*>(p_obj->parent());
            QDockWidget* dock           = static_cast<QDockWidget*>(p_obj);

            // determine resize direction
            if (resizeEvent->oldSize().height() != resizeEvent->size().height())
            {
                // vertical expansion
                QSize fixedSize(m_layout->widthForHeight(m_dockChild->size().height()), m_dockChild->size().height());
                if (dock->size().width() != fixedSize.width())
                {
                    m_dockChild->resize(fixedSize);
                    m_dockChild->setFixedWidth(fixedSize.width());
                    dock->setFixedWidth(fixedSize.width());
                    mainWindow->repaint();
                    //dock->setGeometry(mainWindow->rect().right()-fixedSize.width(),dock->geometry().y(),fixedSize.width(), fixedSize.height());
                }
            }
            if (resizeEvent->oldSize().width() != resizeEvent->size().width())
            {
                // horizontal expansion
                m_dockChild->resize(m_layout->sizeHint().width(), m_dockChild->height());
            }

        }

        return false;

    }

private:

    QWidget* m_dockChild;
    QFluidGridLayout* m_layout;

};

#endif // QDockResizeEventFilter_h__

Answer: The problem is, nothing in the code above actually causes the QMainWindowLayout to recalculate itself. That function is buried within the QMainWindowLayout private class, but can be stimulated by adding and removing a dummy QDockWidget, which causes the layout to invalidate and recalcualte the dock widget positions
QDockWidget* dummy = new QDockWidget;
mainWindow->addDockWidget(Qt::TopDockWidgetArea, dummy);
mainWindow->removeDockWidget(dummy);

The only problem with this is that if you dig into the QT source code, you'll see that adding a dock widget causes the dock separator to be released, which causes unintuitive and choppy behavior as the user tries to resize the dock, and the mouse unexpectedly 'lets go'.
void QMainWindowLayout::addDockWidget(Qt::DockWidgetArea area,
                                             QDockWidget *dockwidget,
                                             Qt::Orientation orientation)
{
    addChildWidget(dockwidget);

    // If we are currently moving a separator, then we need to abort the move, since each
    // time we move the mouse layoutState is replaced by savedState modified by the move.
    if (!movingSeparator.isEmpty())
        endSeparatorMove(movingSeparatorPos);

    layoutState.dockAreaLayout.addDockWidget(toDockPos(area), dockwidget, orientation);
    emit dockwidget->dockLocationChanged(area);
    invalidate();
}

That can be corrected by moving the cursor back onto the separator and simulating a mouse press, basically undoing the endSeparatorMove callafter the docks have been repositioned. It's important to post the event, rather than send it, so thatit occurs after the resize event. The code for doing so looks like:
QPoint mousePos = mainWindow->mapFromGlobal(QCursor::pos());
mousePos.setY(dock->rect().bottom()+2);
QCursor::setPos(mainWindow->mapToGlobal(mousePos));
QMouseEvent* grabSeparatorEvent =
    new QMouseEvent(QMouseEvent::MouseButtonPress,mousePos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);
qApp->postEvent(mainWindow, grabSeparatorEvent);

Where 2 is a magic number that accounts for the group box border.
Put that all together, and here is the event filter than gives the desired behavior:
Corrected Event Filter
#ifndef QDockResizeEventFilter_h__
#define QDockResizeEventFilter_h__

#include <QObject>
#include <QLayout>
#include <QEvent>
#include <QDockWidget>
#include <QResizeEvent>
#include <QCoreApplication>
#include <QMouseEvent>

#include "QFluidGridLayout.h"

class QDockResizeEventFilter : public QObject
{

public:
    friend QMainWindow;
    friend QLayoutPrivate;
    QDockResizeEventFilter(QWidget* dockChild, QFluidGridLayout* layout, QObject* parent = 0)
        : QObject(parent), m_dockChild(dockChild), m_layout(layout)
    {

    }

protected:

    bool eventFilter(QObject *p_obj, QEvent *p_event)
    {
        if (p_event->type() == QEvent::Resize)
        {
            QResizeEvent* resizeEvent   = static_cast<QResizeEvent*>(p_event);
            QMainWindow* mainWindow     = dynamic_cast<QMainWindow*>(p_obj->parent());
            QDockWidget* dock           = static_cast<QDockWidget*>(p_obj);

            // determine resize direction
            if (resizeEvent->oldSize().height() != resizeEvent->size().height())
            {
                // vertical expansion
                QSize fixedSize(m_layout->widthForHeight(m_dockChild->size().height()), m_dockChild->size().height());
                if (dock->size().width() != fixedSize.width())
                {

                    m_dockChild->setFixedWidth(fixedSize.width());
                    dock->setFixedWidth(fixedSize.width());

                    // cause mainWindow dock layout recalculation
                    QDockWidget* dummy = new QDockWidget;
                    mainWindow->addDockWidget(Qt::TopDockWidgetArea, dummy);
                    mainWindow->removeDockWidget(dummy);

                    // adding dock widgets causes the separator move event to end
                    // restart it by synthesizing a mouse press event
                    QPoint mousePos = mainWindow->mapFromGlobal(QCursor::pos());
                    mousePos.setY(dock->rect().bottom()+2);
                    QCursor::setPos(mainWindow->mapToGlobal(mousePos));
                    QMouseEvent* grabSeparatorEvent = new QMouseEvent(QMouseEvent::MouseButtonPress,mousePos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);
                    qApp->postEvent(mainWindow, grabSeparatorEvent);
                }
            }
            if (resizeEvent->oldSize().width() != resizeEvent->size().width())
            {
                // horizontal expansion
                // ...
            }
        }
        return false;
    }

private:

    QWidget* m_dockChild;
    QFluidGridLayout* m_layout;
};

#endif // QDockResizeEventFilter_h__


How can I apply interpolation to angle data?

Question: My data is in angles (degrees) and I intend to write a code that is trying to understand if there is a systematic (biased) behaviour in data.
For example, if my data set is (10, 20, 30, 40) then a basic fit can find a relation like y=10*x. However, when it is like (340 350 0 10 20), even though same relation exits, my code cannot find it since there is no way for code to understand 350 to 0 is also a plus 10.
In other words, how can I write an interpolation code that works with modded numbers (in this case, mod360)?
(This is neccesary for a code that outs warnings when there is a systematic behaviour in data. After polynomial and exponential fits, goodness of fit tests are done and warnings are given for detected systematic behaviours. I need to make it work in angle data too, however modded number break the usual approach.)
Comment: have you thought about converting to rectangular coordinates of the unit circle?  I.e. create new columns x=cos(theta) and y=sin(theta)?
Comment: Do you always want the smaller angle?  I.e., between 350 and 10 you want 00, not 180?
Comment: It does not matter if numbers are small or big, It just needs to show if there is a systematic behaviour. I guess converting to rectangle would work, if both coordinates show bias, I could flag that case. I hope there is a cleaner solution though.
Answer: This problem needs additional constraints in order to be identified. Let's look a the set you mention:
$$ x = (340, 350, 0, 10, 20),$$
and let's number the elements $n = (1, 2, 3, 4, 5).$ Then, we can see that a perfect fit is $x = 330 + 10n.$ However, another perfect fit is $x = 330 + 370n.$ In fact, any fit $x = 330 + (360k + 10)n$ is a perfect fit for $k \in \mathbb{Z},$ that is, integer.
This problem is well known in circular regression, and one of the reasons why a linear model is rarely used. The linear model is sometimes called the "barber's pole" regression model.
If you want to use this model, a good approach is to look at the model as $x = \alpha + \beta n, $ and to constrain $-180 < \beta < 180.$ Then, we can optimize  $\alpha$ and $\beta$ to obtain the best fit. Note that this optimization is not convex.


How to set system sound,also change by programatically?

Question: In iPhone/iPad, how to programmatically set system sound? Also how to control system sound programmatically? I went through many web documents but couldn't find exact solution. Please any one help me out. Is it possible to access system configuration through app?
Comment: A slider control used to set the system audio output volume, and a button for choosing the audio output route.

Link: https://developer.apple.com/documentation/mediaplayer/mpvolumeview
Comment: Possible duplicate of [How to change an iOS device volume programmatically?](https://stackoverflow.com/questions/29049699/how-to-change-an-ios-device-volume-programmatically)
Answer: System/Device sounds cannot be set from the App. Custom sounds can be added inside the app and can be played for any of your App's activity. For your App's notifications, custom sounds can be used but that has to be set from the App itself.


Changing views keeps giving me attempt to present vc1 on vc whose view is not in the window hierarchy

Question: I've created a test application to understand how views/viewcontrollers work and how to navigate between them programmatically without a storyboard or a nib.
I've basically set up a rootViewController called Viewcontroller which is set in the AppDelegate.
This view presents view1 on startup which contains a uibutton which calls the notification in the rootViewController to present view2. However when I do this I keep getting the warning:
Warning: Attempt to present <View1: 0x7be66c80> on <ViewController: 0x7be62980> whose view is not in the window hierarchy!

My code for the controlling viewcontroller is as follows:

    #import "ViewController.h"
    #import "View1.h"
    #import "View2.h"
    @interface ViewController ()

    @end

    @implementation ViewController
    -(void) loadView{
        [super loadView];
    }
    -(void)viewDidAppear:(BOOL)animated{
        NSLog(@"View appeared");
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"view1" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(view1:) name:@"view1" object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"view2" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(view2:) name:@"view2" object:nil];
        [self showView1];
    }
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    -(void)view1:(NSNotification*) notification{
        NSLog(@"Showing view1");
        [self dismissViewControllerAnimated:YES completion:nil];
        [self showView1];
    }
    -(void)showView1{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.view.window.rootViewController presentViewController:[[View1 alloc]init] animated:YES completion:nil];
        });
    }
    -(void)view2:(NSNotification*) notification{
        NSLog(@"Showing view2");
        [self dismissViewControllerAnimated:YES completion:nil];
        [self showView2];
    }
    -(void)showView2{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:[[View1 alloc]init] animated:YES completion:nil];
        });
    }

@end

Edit:I forgot to mention that view1 displays initially without any errors or problems.
Edit: the code for view1 and view2 are exactly identical except that they send different notifications:

    #import "View1.h"

    @interface View1 ()

    @end

    @implementation View1

    - (void)loadView {
        [super loadView];
        self.view.frame = [[UIApplication sharedApplication].keyWindow bounds];
        // Do view setup here.
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button addTarget:self
                   action:@selector(touchedLogin:)
         forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:@"Login" forState:UIControlStateNormal];

        button.layer.cornerRadius=1;
        button.frame = CGRectMake(self.view.bounds.size.width/2-100, self.view.bounds.size.height-200, 200, 60.0);
        [button setTitleEdgeInsets:UIEdgeInsetsMake(5.0, 0.0, 0.0, 0.0)];

        //[_window setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:button];
    }
    -(void)touchedLogin:(id*)sender{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"view2" object:nil];
    }

    @end
Comment: If you get the error when you press the button in View1, then you need to show the code you have in that button's action method.
Comment: I've added the code. Both views are the same except the other one sends the notification to show the other view
Answer: You get this error because you're dismissing View1 with animation, then immediately calling showView2 (which actually shows View1, since you have [View1 alloc]init] in that method). Because the animation takes some amount of time, you're trying to present View1 while View1 is still on screen, not ViewController. In general, it's not a good idea to do dismissals and presentations, one right after the other like that. I think it might work (though I never do this) if you do the dismissal without animation.
Comment: @thegalah, that's too broad a question for me to answer. There are many ways to do it, and many structures that your app could take. Often the root view controller would be one of the container controllers like a navigation controller, tab bar controller, or split view controller. I suggest you  read the "View Controller Programming Guide for iOS", and also the "View Controller Catalog for iOS" to get a good overview of the possibilities.
Comment: I've tried removing all animations and the error still comes up. I've also tried using dispatch async on the dismissal and presentation with no success
Comment: @thegalah, yeah, I wasn't sure that would work. Using dispatch_async is unnecessary in your code since everything is on the main thread. Your whole approach is not good. Don't do a presentation right after a dismissal. If you want to go from View1 to View2, have View1 present View2. Also, using notifications like you are isn't the best way to go either. They're best used when you have multiple controllers that need to be notified of some action, not just one like you have here.
Comment: How would I navigate between the views as I wish to. I'm new to ios haha
Comment: I think I've found the proper way to change views. It's not really changing views but it works. Basically I add the initialized viewcontroller as a childviewcontroller and add the viewcontrollers view as a subview using the following:
`UIViewController * vc=[[View2 alloc]init];
        [self addChildViewController:vc];
        [self.view addSubview:vc.view];`


Trying to include file from another account: permissions denied

Question: I have a dedicated server running php with dso handler, I am including a global config.php from one account into all the other accounts. This works fine on apache when opening the sites via browser.
But I also have some cron jobs, and there i get "permissions denied" error when trying to include the config.php file.
The main config.php is in user1 account, so I tried adding user2 (which includes user1 config.php) to the user1 group, but that didn't worked, the error still persist.
How could I fix it without having to modify all the files that include the main config.php file?
UPDATE:
i "fixed" it by adding the user2 to the nobody group. It seems to work fine, but could it generate some other problems?
Answer: Every web server uses Effective uid and gid ,
Definition :
Effective username and group name are defined in /etc/passwd and /etc/group

For example apache on Debian distro uses www-data group and www-data user. You should set your web data to them.Such as :
chown www-data.www-data YOURROOTDIR/ -R

Suggestion :
You should find out to how set your distro its effective uid and gid.Then act to chown.Because each distro uses one effective uid and gid.