Can not save permanent login state?

Question: This is the code where I check whether user already Login or not .
But whenever I ran this code I always get this error .
I tried to solve it but I cannot .
Here is my error
12-09 18:19:43.640: E/AndroidRuntime(832): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
12-09 18:19:43.640: E/AndroidRuntime(832):at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:371)
12-09 18:19:43.640: E/AndroidRuntime(832): at   ndroid.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:366)
12-09 18:19:43.640: E/AndroidRuntime(832):  at   com.example.totallyfinish.MainActivity.saveLoggedIn(MainActivity.java:98)
12-09 18:19:43.640: E/AndroidRuntime(832):  at         com.example.totallyfinish.Login$4.onClick(Login.java:295)
12-09 18:19:43.640: E/AndroidRuntime(832):  at android.view.View.performClick(View.java:3480)
12-09 18:19:43.640: E/AndroidRuntime(832):  at android.view.View$PerformClick.run(View.java:13983)
12-09 18:19:43.640: E/AndroidRuntime(832):  at android.os.Handler.handleCallback(Handler.java:605)
12-09 18:19:43.640: E/AndroidRuntime(832):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-09 18:19:43.640: E/AndroidRuntime(832):  at android.os.Looper.loop(Looper.java:137)
12-09 18:19:43.640: E/AndroidRuntime(832):  at android.app.ActivityThread.main(ActivityThread.java:4340)
12-09 18:19:43.640: E/AndroidRuntime(832):  at java.lang.reflect.Method.invokeNative(Native Method)
12-09 18:19:43.640: E/AndroidRuntime(832):  at java.lang.reflect.Method.invoke(Method.java:511)
12-09 18:19:43.640: E/AndroidRuntime(832):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-09 18:19:43.640: E/AndroidRuntime(832):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-09 18:19:43.640: E/AndroidRuntime(832):  at dalvik.system.NativeStart.main(Native Method)

Help me finding it please .
 public class MainActivity extends Activity {

ImageButton Imagebtn_start;
Boolean isInternetPresent = false;
ConnectionDetector conDetector;
private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
SharedPreferences prefsNagSetting;
private static final String NAG_PREFS = "socially_you_nag_prefs";
/* THE EDITOR */
Editor editor;

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

    jsonen();
     Imagebtn_start = (ImageButton) findViewById(R.id.image_btnstart);
     conDetector = new ConnectionDetector(getApplicationContext());
     Imagebtn_start.setOnClickListener(new OnClickListener() {
     Intent intentfromLogin = getIntent();
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            isInternetPresent = conDetector.isConnectingToInternet();
            Boolean value=true;

             if (isInternetPresent){

                    if (isLoggedIn()){
                       Intent team= new Intent(MainActivity.this,Team.class);
                       startActivity(team);
                    }
                    else{

                    Intent goLogin=new Intent(MainActivity.this,Login.class);
                    startActivity(goLogin);
                    }
             }
             else{
                 showAlertDialog(MainActivity.this, "No Internet Connection",
                            "You don't have internet connection.", false);
             }
        }
    });
}

private boolean isLoggedIn() {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    //The false represents the default value, if the variable is not stored
    boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
    return isLoggedIn;
}

public  void  saveLoggedIn(boolean value) {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    Editor editor = sharedPreferences.edit();
    editor.putBoolean("isLoggedIn", value);
    editor.commit();
}
public void jsonen()
{
    int status=2;
    JSONObject json=null;
    String response = null;
    String teamID=null;

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    //postParameters.add(new BasicNameValuePair("email",edit_txt_EmailAddress.getText().toString()));//// define the parameter
    postParameters.add(new BasicNameValuePair("userID","396797666"));

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
       .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
       .penaltyLog().build());

    try {
          response=CustomHttpClient.executeHttpPost("http://10.0.2.2/football365/notification.php", postParameters);
         // json=new JSONObject(response);
        //  teamID=json.getString("teamID");
         // Log.i("Team ID",teamID+"");
        }
   catch (Exception e) {

        e.printStackTrace();
    }

    JSONObject jsonobj = null;
    String alerttime=null;
    String beforematch=null;
    JSONArray jArray = null;
    String starttime=null;
try{

    jsonobj = new JSONObject (response);
    jArray=jsonobj.getJSONArray("notifications");

    Log.i("Current Time",jArray+"");
    Log.i("Current Time",getCurrentTime());
    String currentTime="2013-12-07 14:03";
    for(int i=0;i<jArray.length();i++){

        jsonobj=jArray.getJSONObject(i);

        alerttime=jsonobj.getString("alert");
        starttime=jsonobj.getString("startTime");
        beforematch=jsonobj.getString("beforeMatchTime");

        if(alerttime.equals(currentTime)){

                Notification(starttime);
                Log.i("Wintal", "wint");
        }
    }

}
catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
}

Log.i("RESULT", jsonobj+"");
Log.i("time", alerttime+"");
Log.i("before Match",beforematch+"");
}

public void showAlertDialog(Context context, String title, String message, Boolean status){
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    alertDialog.setTitle(title);

    alertDialog.setMessage(message);

    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });
    alertDialog.show();

}

public String getCurrentTime(){
    Calendar c= Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
    String strDate = sdf.format(c.getTime());
    return strDate;
}

public void alert()
{
    Calendar calendar = Calendar.getInstance();

      calendar.set(Calendar.MONTH, 12);
      calendar.set(Calendar.YEAR, 2013);
      calendar.set(Calendar.DAY_OF_MONTH, 4);

      calendar.set(Calendar.HOUR_OF_DAY, 1);
      calendar.set(Calendar.MINUTE, 13);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.AM_PM,Calendar.PM);

      Intent myIntent = new Intent(MainActivity.this, myReceiver.class);
      PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}

public void Notification(String s)
{
        String ns = Context.NOTIFICATION_SERVICE;

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        int icon = R.drawable.notification_icon;
        CharSequence tickerText = "Ready for Play time."; // ticker-text
        long when = System.currentTimeMillis();
        Context context = getApplicationContext();
        CharSequence contentTitle = "Play Time";
        CharSequence contentText = "Your match is at "+s;
        Intent notificationIntent = new Intent(this,ScheldueNotification .class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification notification = new Notification(icon, tickerText, when);
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        // and this

        mNotificationManager.notify(MY_NOTIFICATION_ID, notification);

        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.vibrate = new long[] { 0, 100, 200, 300 };
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

This is the code where I save a boolean to Editor
                        try {
                            Log.i("noTeam Win tal","Log in hmar");

                            userName=jsonobj.getString("userName");
                            userID=jsonobj.getString("userID");

                            noteamSaving[0]=userName;
                            noteamSaving[1]=userID;

                            Log.i("USerNameNN", userName+"");
                            Log.i("UserIDNN",userID+"");

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        Intent noteamshi=new Intent(Login.this,NoTeam.class);
                        noteamshi.putExtra("NoTeamSaving", noteamSaving);
                        startActivity(noteamshi);
                        MainActivity m=new MainActivity();
                        m.saveLoggedIn(true);

Comment: Can you post your full `LogCat` error. It is incomplete.
Comment: Are you initializing some values at class level?
Comment: @ Abishek . I already  updated :) thanks for concern
Comment: @ Agarwal which value you want to say ?
Comment: can you mark line 98 of MainActivity
Comment: I mean variables which are using context.
Comment: SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this); this is line no 97 & 98
Comment: There's no @ Agarwal :)
Comment: try using getApplicationContext() instead of this.
Comment: can u post whole mainactivity code
Comment: wait a minute @ anand
Comment: I put Mainactivity... :)
Answer: MainActivity m=new MainActivity();

This probably doesn't do what you think it does. Instantiating an activity like this bypasses the normal activity life cycle. The error is because the activity object doesn't know what the package name for the application is. Move isLoggedIn() and saveLoggedIn(boolean value) inside the activity that is foreground when you want to call them so that the "this" reference refers to a properly initiated context.
If you need to access those methods from several activities you could change the methods like this:

class LoginHelper {
     public static boolean isLoggedIn(Context context) {
         SharedPreferences sharedPreferences = PreferenceManager
             .getDefaultSharedPreferences(context);
         //The false represents the default value, if the variable is not stored
         boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
         return isLoggedIn;
     }

     public  void  saveLoggedIn(Context context, boolean value) {
         SharedPreferences sharedPreferences = PreferenceManager
             .getDefaultSharedPreferences(context);
         Editor editor = sharedPreferences.edit();
         editor.putBoolean("isLoggedIn", value);
         editor.commit();
    }
}

And pass a pointer to the current activity for the context perimeter.
                    try {
                        Log.i("noTeam Win tal","Log in hmar");

                        userName=jsonobj.getString("userName");
                        userID=jsonobj.getString("userID");

                        noteamSaving[0]=userName;
                        noteamSaving[1]=userID;

                        Log.i("USerNameNN", userName+"");
                        Log.i("UserIDNN",userID+"");

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    Intent noteamshi=new Intent(Login.this,NoTeam.class);
                    noteamshi.putExtra("NoTeamSaving", noteamSaving);
                    startActivity(noteamshi);

                    LoginHelper.saveLoggedIn(this, true);

This is assuming the above block comes from an activity that android launched rather than one you manually instantiated.
Comment: LoginHelper.saveLoggedIn(this,true) . In this line this is not working
Comment: Did you create the LoginHelper class that I posted and import it in the file were you called it? What is the error you're getting?

Can not save permanent login state?


Weak convergence of measures implying almost sure convergence of random variables

Question: Suppose $\mu,\mu_n$ are Borel probability measures on $\mathbb{R}$ with $\mu_n$ converging weakly to $\mu$. I am asked to find some probability space $(\Omega,\mathcal{F},\mathbb{P})$ and random variables $X,X_n$ such that $X$ has law $\mu$, $X_n$ has law $\mu_n$ and $X_n \to X$ almost surely as $n \to \infty$.
So far I tried to let $(\Omega,\mathcal{F},\mathbb{P}) = ((0,1),\mathcal{B}_{0,1},\text{Lebesgue})$ and defined $X_n$ as for $\omega \in (0,1)$ we let $X_n(\omega) = \inf\{x \in \mathbb{R}: \omega \in \mu_n((-\infty,x])\}$. Then $\mathbb{P}(X_n \in (-\infty,x]) = \mathbb{P}(X_n^{-1}((-\infty,x])) = \mu_n((-\infty,x])$ so $X_n$ has law $\mu_n$ and similarly for $X$.
However I am not able to prove that $X_n \to X$ almost surely. I have tried using contradiction, if $X_n \not\to X$ almost surely then we have that $|X_n-X| \geq 0$ and this does not converge to 0 almost surely. So the integral of this does not converge to $0$ as $n \to \infty$. However at this point I get stuck. I can't see where I should bring in the fact that $\mu_n \to \mu$ weakly.
How should I proceed?
Comment: This is a special case of Skhorohod Representation Theorem. You can search Wikipedia for this theorem.
Answer: Let $\mu_n$, $\mu$ be probability measures on $\mathbb{R}$ such that $\mu_n$ converges weakly to $\mu$. The associated cumulative distribution functions $$F_n(x) := \mu_n((-\infty,x]) \qquad F(x) := \mu((-\infty,x])$$ then satisfy $$F_n(x) \to F(x) \tag{1}$$ for any continuity point $x$ of $F$.

Lemma Denote by $$\begin{align*} F_n^{-1}(t) &:= \inf\{x \in \mathbb{R}; F_n(x) \geq t\} \\ F^{-1}(t) &:= \inf\{x \in \mathbb{R}; F(x) \geq t\} \end{align*}$$ the generalized inverse functions of $F_n$ and $F$, respectively. If $t \in (0,1)$ is a continuity point of $F^{-1}$, then $$\lim_{n \to \infty} F_n^{-1}(t) = F^{-1}(t). \tag{2}$$

Once we have proved the result, we find immediately that the sequence of random variables defined in your question $$X_n(t) = F_n^{-1}(t) \qquad X(t) = F^{-1}(t)$$ satisifies $X_n(t) \to X(t)$ for any continuity point $t$ of $F^{-1}$; as $F^{-1}$ has at most countably many discontinuies, this shows $X_n \to X$ almost surely.
Proof of the lemma: Let $t \in (0,1)$ be a continuity point of $F^{-1}$. Since $F$ has at most countably many discontinuities, we can find for any $\epsilon>0$ a continuity point $x$ of $F$ such that $$F^{-1}(t)- \epsilon< x < F^{-1}(t).$$ As $$x < F^{-1}(t) \implies F(x) < t$$ and $\lim_n F_n(x) = F(x)$, we have $F_n(x)<t$ for large $n \in \mathbb{N}$, and the definition of the inverse yields $x \leq F_n^{-1}(t)$. Consequently, $$F^{-1}(t) - \epsilon < x \leq F_n^{-1}(t)$$ implying $$F^{-1}(t) \leq \liminf_{n \to \infty} F_n^{-1}(t).$$ It remains to show that $$\limsup_{n \to \infty} F_n^{-1}(t) \leq F^{-1}(t). \tag{3}$$ To this end, we note that for any $u>t$ and $\epsilon>0$ we can find a continuity point $y$ of $F$ such that $$F^{-1}(u) < y < F^{-1}(u)+\epsilon.$$ This implies $$F(y) \geq u > t.$$ As $y$ is a continuity point of $F$, this means that $F_n(y) \geq t$ for large $n \in \mathbb{N}$. Hence, $y \geq F_n^{-1}(t)$, and so $$F^{-1}(u)+\epsilon > y \geq F^{-1}_n(t)$$ for large $n$. Thus, $$\limsup_{n \to \infty} F_n^{-1}(t) \leq F^{-1}(u).$$ Letting $u \downarrow t$ we find from the (right)continuity of $F^{-1}$ at $t$ that $(3)$ holds.
Reference: Theorem 8.3.2 in S.I. Resnick: A probability path, Birkhäuser 2013.


Random no switch statement, por que não funciona?

Question: Seguindo o código abaixo, a minha intenção era randomizar o switch para escolher entre o case 1 e 2, após receber a palavra "gamble". Acontece que quando escrevo gamble, só é ativado o case 1 (somar 10 ferros), ao invés de ser aleatório entre somar 10 ou subtrair 10. O que fiz de errado ?
<code>            int ferros;
            string gamble;
            gamble = Console.ReadLine();
            Random rnd = new Random();
            int luck = rnd.Next(1,3);
            bool loop = true;
            while (loop)
            {
              if (gamble == "gamble")
              {
                  switch (luck)
                  {
                    case 1:
                        ferros = ferros + 10;
                        break;
                    case 2:
                        ferros = ferros - 10;
                        break;
                  }
              }
            }
</code>
Comment: O código é só esse ou você simplificou? Se está testando num _loop_, tem que tirar o new Random() de dentro (usar uma instância só), senão pode ter uma inicialização com _seed_ repetido. Seria legal por a classe da forma que testou na realidade e explicar como fez pra executar.
Comment: Boa noite Bacco, eu realmente estava fazendo dentro de um loop, e o meu erro na verdade foi não colocar int rng = rnd.Next(1, 3); e gamble = Console.ReadLine(); dentro do loop. Acabei percebendo este erro após ler o seu comentário, mesmo sendo sem querer, foi de grande ajuda hahaha. E obrigado pela dica da seed repetida :)
Comment: Sugiro postar **no campo de respostas** o código resolvido explicando qual era o erro (e marcando sua resposta como aceita), ou remover a questão, só pra não largar pendente.
Comment: Já foi postado no campo de respostas, porém só é possível marcar a minha resposta como "aceita" após 2 dias.
Answer: O erro foi não ter introduzido o "sistema" para randomizar dentro do loop. A resolução para o problema é implementar o gamble = Console.ReadLine(); e a váriavel int luck = rnd.Next(1,3); dentro do loop, para que o "sistema" de randomização seja sempre repetido.
<code>        int ferros;
        string gamble;
        Random rnd = new Random();
        bool loop = true;
        while (loop)
        {
         gamble = Console.ReadLine();
         int luck = rnd.Next(1,3);

            if (gamble == "gamble")
            {
              switch (luck)
              {
                case 1:
                    ferros = ferros + 10;
                    break;
                case 2:
                    ferros = ferros - 10;
                    break;
              }
            }
        } //Code
</code>


First Fundamental Theorem of Calculus question regarding F'(x)

Question: The first fundamental theorem is defined:
$F(x) = \int^x_c f(t) dt$ where $c$ is constant.
The corollary:
$\int^b_a f(t) dt = F(b) - F(a)$
My question is how can the integral $[c, x]$ in the first theorem be calculated without the corollary?  Otherwise would $c$ be assumed to be $0$?
As an example:
$f(t) = t^2$,
$F(t) = \int^x_c f(t) dt = \int^x_c t^2 dt$
Antiderivative:
$F(t) = \frac {t^3} 3$
However, my understanding is the antiderivative is the area under the curve from $t = 0$.
Appreciate any guidance.
Comment: Are you sure the first theorem shouldn't be  $F(x)=\int f(x)~dx$?
Comment: In all generality $F(x)=\int_c^x f(t)dt+C$ since trying with f being 0 gives only 0 else for the area under f.
Comment: The antiderivative is not unique. $F(t) = \frac{t^3}{3}+5$ is also an antiderivative of $f(t)$. (adding any constant also gives an antiderivative).  And in this case $F(b)$ does not give the area under $f(t)$ from $t=0$ to $t=b$. $F(b)-F(0)$ gives that area.
Answer: You are skipping a step. The corollary can be stated:
For a function $F'(x)=f(x)$ (such a function is called an antiderivative)
$$\int_{a}^{b}f(t)dt=F(b)-F(a)$$
Hence it tells you that in order to calculate the definite integral you need to find an antiderivative $F$.
Comment: I'm following the steps at Wiki https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus.  $F'(x) = f(x)$ where as I state above $F(x) = \int^x_a f(t) dt$.  My concern is regarding lower bound in the definite integral, $c$ in the first part.  For example if called $F(a)$.
Comment: @Nick, a is just a constant. The point is that a is fixed, whereas x is a variable.


Proving $(1+a)^n\ge 1+na+\frac{n(n-1)}{2}a^{2}+\frac{n(n-1)(n-2)}{6}a^3$ for all $n\in\mathbb N$ and all $a\ge -1.$

Question: I was asked to prove the the following without induction. Could someone please verify whether my proof is right? Thank you in advance.

For any real number $a\ge -1$ and every natural number n, the statement, $$(1+a)^n\ge 1+na+\frac{n(n-1)}{2}a^{2}+\frac{n(n-1)(n-2)}{6}a^3,$$ holds.

Proof. From the binomial theorem we can see that, $$(1+a)^n\ge 1+na+\frac{n(n-1)}{2}a^{2}+\frac{n(n-1)(n-2)}{6}a^3,$$ becomes, $$\sum^{n}_{k=0}\binom{n}{k}a^{k}\ge\sum^{n}_{k=0}\binom{n}{k}a^{k}-\sum^{n}_{k=4}\binom{n}{k}a^{k}.$$ Also, if $a\lt b$, let us define $\sum^{a}_{i=b}f(i)=0$, by convention. Then for n=1 we have,\begin{align}\sum^{1}_{k=0}\binom{n}{k}a^{k}&\ge\sum^{1}_{k=0}\binom{n}{k}a^{k}-\sum^{1}_{k=4}\binom{n}{k}a^{k}\\ \sum^{1}_{k=0}\binom{n}{k}a^{k}&\ge\sum^{1}_{k=0}\binom{n}{k}a^{k}-0,\end{align} which is true, since both remaining sums are equal to each other. It is similarly the case for $n=2$ and $n=3$. More generally, \begin{align}\sum^{n}_{k=0}\binom{n}{k}a^{k}&\ge\sum^{n}_{k=0}\binom{n}{k}a^{k}-\sum^{n}_{k=4}\binom{n}{k}a^{k}\\ 1+\binom{n}{1}a^{1}+...+\binom{n}{k}a^{k}+...+\binom{n}{n}a^{n}&\ge1+\binom{n}{1}a^{1}+\binom{n}{2}a^{2}+\binom{n}{3}a^{3}\\ \binom{n}{4}a^4+\binom{n}{5}a^5+...+\binom{n}{k}a^{k}+...+\binom{n}{n}a^{n}&\ge0.\end{align}

To determine whether this last statement is true, we first consider $a\ge0$, and we see that it is trivially true. Next we consider the case where $-1\le a\lt0.$ We let $a=-b$, so $0\lt b\le 1$ and notice that, $$\binom{n}{4}a^4+\binom{n}{5}a^5+...+\binom{n}{k}a^{k}+...+\binom{n}{n}a^{n}$$ then becomes, $$\binom{n}{4}b^4-\binom{n}{5}b^5+...+(-1)^{k}\binom{n}{k}b^{k}+...+(-1)^{n}\binom{n}{n}b^{n}.$$
Also from the binomial theorem we can see that,
  \begin{align}
(1+(-1))^{n}-(1+(-1))^{3}+(1+(-1))^{1}\\
=\sum^{n}_{k=0}\binom{n}{k}1^{n-k}(-1)^{k}-\sum^{3}_{k=0}\binom{n}{k}1^{n-k}(-1)^{k}+\sum^{1}_{k=0}\binom{n}{k}1^{n-k}(-1)^{k}\\
0=1-\binom{n}{1}+\binom{n}{4}-\binom{n}{5}+\binom{n}{6}+...+(-1)^{k}\binom{n}{k}+...+(-1)^{n}\binom{n}{n}\\
n-1=\binom{n}{4}-\binom{n}{5}+\binom{n}{6}+...+(-1)^{k}\binom{n}{k}+...+(-1)^{n}\binom{n}{n}\ge0,
\end{align}
  and by noticing that $b^4\ge b^5\ge b^6\ge ...\ge b^k$, we can see that each binomial term $\binom{n}{k}$ is multiplied by a factor of $b^k$, making each term smaller than the term before.
Thus,
  \begin{align}
\binom{n}{4}b^4-\binom{n}{5}b^5+...+(-1)^n\binom{n}{n}b^n\ge0\\
\binom{n}{4}a^4+\binom{n}{5}a^5+...+\binom{n}{n}a^n\ge0,\tag{by substitution}
\end{align} as desired.
Working backward, \begin{align}\binom{n}{4}a^4+\binom{n}{5}a^5+...+\binom{n}{k}a^{k}+...+\binom{n}{n}a^{n}&\ge0\\ 1+\binom{n}{1}a^{1}+...+\binom{n}{k}a^{k}+...+\binom{n}{n}a^{n}&\ge1+\binom{n}{1}a^{1}+\binom{n}{2}a^{2}+\binom{n}{3}a^{3}\\ \sum^{n}_{k=0}\binom{n}{k}a^{k}&\ge\sum^{n}_{k=0}\binom{n}{k}a^{k}-\sum^{n}_{k=4}\binom{n}{k}a^{k}\\ (1+a)^n&\ge 1+na+\frac{n(n-1)}{2}a^{2}+\frac{n(n-1)(n-2)}{6}a^3.\ \ \ \blacksquare\end{align}
Comment: I find a bit unfair to take Newton's binomial formula for granted. I would prove that statement by induction. For $n = 0$ it's trivial. Suppose it holds for $n \in \mathbb{N}$, then
$(1+a)^{n+1} = (1+a)(1+a)^n \geq 1+na+\frac{n(n-1)}{2}a^2+\frac{n(n-1)(n-2)}{6}a^3 + a+na^2+\frac{n(n-1)}{2}a^3+\frac{n(n-1)(n-2)}{6}a^4 = ...$
Comment: @Gibbs I'm sorry, I forgot to add I was asked to do it without induction, otherwise I would agree with you, induction is my first choice.
Comment: When you say "Also, from the binomial theorem we can see that (...)" I don't see how you get $1+\binom{n}{1}+...$. How do you find all those $+$?
Comment: You're right, I made a mistake. I meant $$(a+b)^{n}=\sum^{n}_{k=0}\binom{n}{k}a^{n-k}b^{k}=a^{n}+\binom{n}{1}a^{n-1}b+\binom{n}{2}a^{n-2}b^{2}+...+\binom{n}{k}a^{n-k}b^{k}+...+\binom{n}{n}b^{n}$$ Let $a=1$ $$(1+b)^{n}=\sum^{n}_{k=0}\binom{n}{k}1^{n-k}b^{k}=1+\binom{n}{1}b+\binom{n}{2}b^{2}+...+\binom{n}{k}b^{k}+...+\binom{n}{n}b^{n}$$Let $b=-1$ $$(1+(-1))^{n}=\sum^{n}_{k=0}\binom{n}{k}1^{n-k}(-1)^{k}=1-\binom{n}{1}+\binom{n}{2}+...+(-1)^{k}\binom{n}{k}+...+(-1)^{n}\binom{n}{n}$$ Fixed.
Answer: This is not an answer to the question about your proof.  I am offering an alternative proof,using Taylor's Theorem.  Note that, for integers $n$ and $k$ with $n> k\geq 0$,
$$(1+a)^n-\sum_{r=0}^k\,\binom{n}{r}\,a^r=(k+1)\binom{n}{k+1}\,\int_{0}^a\,(1+x)^{n-k-1}\,(a-x)^k\,\text{d}x\,.$$
Your question is a particular case where $k=3$, which leads to
$$(1+a)^n-\sum_{r=0}^3\,\binom{n}{r}\,a^r=4\binom{n}{4}\,\int_{0}^a\,(1+x)^{n-4}\,(a-x)^3\,\text{d}x\geq 0\,,$$
and the equality holds iff $a=0$.  You can also use the derivative form:
$$(1+a)^n-\sum_{r=0}^3\,\binom{n}{r}\,a^r=\binom{n}{k+1}\,(1+\zeta)^{n-k-1}\,a^4\geq0\,,$$
where $\zeta$ is a number between $0$ and $a$.
Answer: proof-verification:

Proof. From the binomial theorem we can see that,
  $$
(1+a)^n\ge 1+na+\frac{n(n-1)}{2}a^{2}+\frac{n(n-1)(n-2)}{6}a^3,
$$
  becomes ("is equivalent to"),
  $$
\sum^{n}_{k=0}\binom{n}{k}a^{k}\ge\sum^{n}_{k=0}\binom{n}{k}a^{k}-\sum^{n}_{k=4}\binom{n}{k}a^{k}.
$$
  Also, if $a\lt b$ (I would use other notations here so that I would not mess up with the "a" in the inequality), let us define $\sum^{a}_{i=b}f(i)=0$, by convention.
I would not bother with the cases n=1,2,3: one can just claim that one can just do it by direct substitution.
More generally Suppose $n\geqslant 4$. Then it suffices to show that (you don't need to write so much here. I have tailored some of your steps.)
  $$
\sum^{n}_{k=4}\binom{n}{k}a^{k}\geq 0
$$
  which is
  $$
\binom{n}{4}a^4+\binom{n}{5}a^5+...+\binom{n}{k}a^{k}+...+\binom{n}{n}a^{n}\ge0.
$$

To determine whether this last statement is true, We first consider $a\ge0$, and we see that it is trivially true. Next we consider the case where $-1\le a\lt0.$ We let $a=-b$ (I would write b=-a instead. When defining something new, it is clearer to write it on the left.), so $0\lt b\le 1$ and notice that,
  $$
\binom{n}{4}a^4+\binom{n}{5}a^5+...+\binom{n}{k}a^{k}+...+\binom{n}{n}a^{n}
\\
=\binom{n}{4}b^4-\binom{n}{5}b^5+...+(-1)^{k}\binom{n}{k}b^{k}+...+(-1)^{n}\binom{n}{n}b^{n}.
$$
Also from the binomial theorem we can see that (A possible big gap here: this step is mysterious to me and totally unmotivated: how do you suddenly get rid of the a and b in the equality above and jump to the following one? I would stop reading here.),
  \begin{align}
(1+(-1))^{n}-(1+(-1))^{3}+(1+(-1))^{1}\\
=\sum^{n}_{k=0}\binom{n}{k}1^{n-k}(-1)^{k}-\sum^{3}_{k=0}\binom{n}{k}1^{n-k}(-1)^{k}+\sum^{1}_{k=0}\binom{n}{k}1^{n-k}(-1)^{k}\\
0=1-\binom{n}{1}+\binom{n}{4}-\binom{n}{5}+\binom{n}{6}+...+(-1)^{k}\binom{n}{k}+...+(-1)^{n}\binom{n}{n}\\
n-1=\binom{n}{4}-\binom{n}{5}+\binom{n}{6}+...+(-1)^{k}\binom{n}{k}+...+(-1)^{n}\binom{n}{n}\ge0,
\end{align}
  and by noticing that $b^4\ge b^5\ge b^6\ge ...\ge b^k$, we can see that each binomial term $\binom{n}{k}$ is multiplied by a factor of $b^k$, making each term smaller than the term before.
Thus (Assuming the above is correct, I don't understand this step either.),
  \begin{align}
\binom{n}{4}b^4-\binom{n}{5}b^5+...+(-1)^n\binom{n}{n}b^n\ge0\\
\binom{n}{4}a^4+\binom{n}{5}a^5+...+\binom{n}{n}a^n\ge0,\tag{by substitution}
\end{align} as desired.
Working backward(the rest is redundant. Writing could be precise without sacrificing any rigorousness.)
Answer: Also, we can use the following reasoning.
For $n\in\{1,2,3\}$ it's an identity.
Let $n\geq4$ and $$f(a)= (1+a)^n-1-na-\frac{n(n-1)}{2}a^{2}-\frac{n(n-1)(n-2)}{6}a^3.$$
Thus,
$$f'(a)=n(1+a)^n-n-n(n-1)(n-2)a-\frac{n(n-1)(n-2)}{2}a^2,$$,
$$f''(a)=n(n-1)(1+a)^{n-2}-n(n-1)-n(n-1)(n-2)a$$ and
$$f'''(a)=n(n-1)(n-2)(1+a)^{n-3}-n(n-1)(n-2).$$
We see that $f''$ gets a minimal value for $a=0$.
Thus, $$f''(a)\geq f(0)=0,$$
which gives that $f'($ is an increasing function and $f'(0)=0$.
Thus, since $f'$ has an unique root on $[-1,+\infty)$, we see that $x_{min}=0$,
which gives $f(x)\geq f(0)=0$ and we are done!


Inconclusive results in non-inferiority design

Question: I am interested in how an inconclusive result occurs given the formal null and alternative hypotheses required for non-inferiority testing.
I have pre-specified a noninferiority design comparing accepted and experimental treatments. The design tests the null hypothesis that experimental treatment is harmful and alternative hypothesis that treatment is noninferior to accepted treatment. The noninferiority margin was prespecified as a difference of not more than 2.9% mortality (experimental - accepted). I obtained the result of a mortality difference of 0.9% (95% CI of -2.5%,13.6%).
I am reading here that this result is inconclusive. I cannot reconcile the inconclusive result in the setting of the hypothesis tests. It seems that I can neither reject my null hypothesis nor accept the alternative based on my result. From a conservative standpoint, it seems that if the upper boundary of the 95% CI exceeds the prespecified noninferiority margin that the null hypothesis cannot be rejected.
How can an inconclusive result be possible given the formal null and alternative hypotheses? Is a third hypothesis necessary for these types of studies?
This has been tangentially addressed here, as  a matter of lack of power. In my case, I understand that a lack of power exists.
Answer: In the example you show, you fail to reject the null hypothesis. This is like any other case, where you fail to reject it. This does not mean that you accept it - i.e. it is entirely possible that the null hypothesis is false, but you cannot reject it at the one-sided 2.5% signignificance level with the present data. So the result is inconclusive.
This is not different from any other case of null hypothesis testing, the only difference is that your null hypothesis is $\delta \leq 2.9$%, while very often we look at $\delta \leq 0$ or for two-sided testing at $\delta = 0$. What would be your interpretation of the data you obtained, if that had been your null hypothesis?
It is certainly true, that your example may look like a case of low power. Especially, if up-front it was believe that the two treatments are approximately equivalent, then clearly the study was too small or short to observe enough deaths to have any reasonable power with this non-inferiority margin.
Comment: Why is failure to reject the null inconclusive in this case? Failure to reject seems like a valid result of the noninferiority design. In a standard 2-sided test of H0 = 0 we don't claim an inconclusive result if the confidence interval crosses 0.
Comment: It's a valid result. If we fail to reject the H0 for a standard 2-sided test of H0=0, that is also inconclusive (we do not really know whether the H0 is true or not, we just could not reject it). In addition, with non-inferiority, there is the possibility that you get another kind of conclusive result: You may fail to find non-inferiority and infact demonstrate inferiority (i.e. the standard treatment is clearly superior to the new treatment). I assume that might be what such a comment refers to. One might also get both non-inferiority & superiority to the accepted treatment.


How should I backup pillar data for SaltStack?


TabActivity not starting activity when tab widget touched

Question: <code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_uicreate_session);
TabHost tabHost = getTabHost();
TabSpec sessionTab = tabHost.newTabSpec("Sessions");
sessionTab.setIndicator("Sessions");
Intent i = new Intent().setClass(this, TabSessions.class);
sessionTab.setContent(i);
tabHost.addTab(sessionTab);
}
</code>
When I click on 'Sessions' nothing happens, no stacktrace, nothing.
I am not using fragments because I want to target devices on as low as sdk version 8.
Comment: But if that is the only tab, what do you expect to happen? I think that tab is already displayed.. try to add one more tab at least
Answer: Issue was fixed by moving to the fragment layout.


Solving a sum using the hypergeometric function

Question: While answering this question I came across this curious sum:
$$S_k=\sum_{n=0}^{\infty}\frac{x^n(n+k+1)!}{n!}$$
Which Wolfram Alpha effortlessly evaluates as
$$S_k=\frac{(k+1)!(1-x)^{-k}}{(x-1)^2}$$
The partial sum formula it spat out involved the hypergeometric function ${}_2F_1$, shown below:
$$\sum_{n=0}^{N}\frac{x^n(n+k+1)!}{n!}$$
$$=\frac{(1-x)^{-k-2}}{(N+1)!}\big[(k+1)!(m+1)!-(1-x)^{k+2}x^{N+1}(k+N+2)!{}_2 F_1(1,k+m+3;m+2;x)\big]$$
I did some research on Wolfram Mathworld and Wikipedia about the properties of the hypergeometric function, but didnt get very far. Indeed, the terms in the sequence satisfy the property that the ration between two terms is a rational function of $n$, but the first term isn't $1$ as requested on Mathworld...
Does anyone know how I can connect this sum to a hypergeometric function and thus derive the formula Wolfram Alpha gives?
Comment: If your ultimate quest is to evaluate $S_k$, then we do not need its partial sum. Indeed, using the formula $$\int_{0}^{\infty}t^ne^{-st}\,\mathrm{d}t=\frac{n!}{s^{k+1}}$$ valid for $k >-1$ and $s > 0$, for $|x|<1$ we have $$S_k=\sum_{n=0}^{\infty}\frac{x^n}{n!}\int_{0}^{\infty}t^{n+k+1}e^{-t}\,\mathrm{d}t=\int_{0}^{\infty}t^{k+1}e^{xt}e^{-t}\,\mathrm{d}t=\frac{(k+1)!}{(1-x)^{k+2}}.$$ Alternatively, this formula can be derived recursively from $$S_{-1}=\frac{1}{1-x},\qquad\frac{\mathrm{d}}{\mathrm{d}x}S_k=S_{k+1}.$$
Comment: Alternatively, but along the same line as SangchulLee's comment, note that $$S_k = (k+1)! \sum_{n=0}^\infty \binom{n+k+1}{n} x^n = (k+1)! \sum_{n=0}^\infty \binom{-k-2}{n}(-x)^n$$ and then use the binomial theorem.
Comment: @Sangchul Lee Fantastic work! However, I'm a bit confused as to how you got rid of the summation and simply put an $e^{xt}$ into the integral on your second to last line. The recursive definition is perfectly clear though.
Answer: $$S_k=(k+1)!\sum_{n=0}^{\infty} {n+k+1 \choose k+1}~ x^n$$ $$S_k=(k+1)! \sum_{n=0}^{\infty} {-k-2 \choose n} (-1)^n x^n= (k+1)!~(1-x)^{-k-2},~ |x|<1. $$
Here we have used $${-p \choose m}=(-1)^m {p+m-1 \choose m}$$
and $$(1-x)^{-p}=\sum_{m=0}^{\infty} {-p \choose m} (-1)^m x^m, |x|<1.$$


Business Layer structure, how do you build yours?

Question: I am a big fan of NTiers for my development choices, of course it doesnt fit every scenario.
I am currently working on a new project and I am trying to have a play with the way I normally work, and trying to see if I can clean it up. As I have been a very bad boy and have been putting too much code in the presentation layer.
My normal business layer structure is this (basic view of it):

Business

Services

FooComponent

FooHelpers
FooWorkflows

BahComponent

BahHelpers
BahWorkflows

Utilities

Common
ExceptionHandlers
Importers
etc...

Now with the above I have great access to directly save a Foo object and a Bah object, via their respective helpers.
The XXXHelpers give me access to Save, Edit and Load the respective objects, but where do I put the logic to save objects with child objects.
For example:
We have the below objects (not very good objects I know)

Employee
EmployeeDetails
EmployeeMembership
EmployeeProfile

Currently I would build these all up in the presentation layer and then pass them to their Helpers, I feel this is wrong, I think the data should be passed to a single point above presentation in the business layer some place and sorted out there.
But I'm at a bit of a loss as to where I would put this logic and what to call the sector, would it go under Utilities as EmployeeManager or something like this?
What would you do? and I know this is all preference.
A more detailed layout
The workflows contain all the calls directly to the DataRepository for example:
public ObjectNameGetById(Guid id)
{
    return DataRepository.ObjectNameProvider.GetById(id);
}

And then the helpers provider access to the workflows:
public ObjectName GetById(Guid id)
{
    return loadWorkflow.GetById(id);
}

This is to cut down on duplicate code, as you can have one call in the workflow to getBySomeProperty
and then several calls in the Helper which could do other operations and return the data in different ways, a bad example would be public GetByIdAsc and GetByIdDesc
By seperating the calls to the Data Model by using the DataRepository, it means that it would be possible to swap out the model for another instance (that was the thinking) but ProviderHelper has not been broken down so it is not interchangable, as it is hardcode to EF unfortunately.
I dont intend to change the access technology, but in the future there might be something better or just something that all the cool kids are now using that I might want to implement instead.
projectName.Core
projectName.Business
    - Interfaces
        - IDeleteWorkflows.cs
        - ILoadWorkflows.cs
        - ISaveWorkflows.cs
        - IServiceHelper.cs
        - IServiceViewHelper.cs
    - Services
        - ObjectNameComponent
            - Helpers
                - ObjectNameHelper.cs
            - Workflows
                - DeleteObjectNameWorkflow.cs
                - LoadObjectNameWorkflow.cs
                - SaveObjectNameWorkflow.cs
    - Utilities
        - Common
            - SettingsManager.cs
            - JavascriptManager.cs
            - XmlHelper.cs
            - others...

        - ExceptionHandlers
            - ExceptionManager.cs
            - ExceptionManagerFactory.cs
            - ExceptionNotifier.cs

projectName.Data
    - Bases
        - ObjectNameProviderBase.cs
    - Helpers
        - ProviderHelper.cs
    - Interfaces
        - IProviderBase.cs
    - DataRepository.cs

projectName.Data.Model
    - Database.edmx

projectName.Entities (Entities that represent the DB tables are created by EF in .Data.Model, this is for others that I may need that are not related to the database)
    - Helpers
        - EnumHelper.cs

projectName.Presenation
(depends what the call of the application is)
projectName.web
projectName.mvc
projectName.admin

The test Projects
projectName.Business.Tests
projectName.Data.Test

Answer: +1 for an interesting question.
So, the problem you describe is pretty common - I'd take a different approach - first with the logical tiers and secondly with the utility and helper namespaces, which I'd try and factor out completely - I'll tell you why in a second.
But first, my preferred approach here is pretty common enterprise architecture which I'll try to highlight in brief, but there's much more depth out there. It does require some radical changes in thinking - using NHibernate or Entity framework to allow you to query your object model directly and let the ORM deal with things like mapping to and from the database and lazy loading relationships etc. Doing this will allow you to implement all of your business logic within a domain model.
First the tiers (or projects in your solution);
YourApplication.Domain
The domain model - the objects representing your problem space. These are plain old CLR objects with all of your key business logic. This is where your example objects would live, and their relationships would be represented as collections. There is nothing in this layer that deals with persistence etc, it's just objects.
YourApplication.Data
Repository classes - these are classes that deal with getting the aggregate root(s) of your domain model.
For instance, it's unlikely in your sample classes that you would want to look at EmployeeDetails without also looking at Employee (an assumption I know, but you get the gist - invoice lines is a better example, you generally will get to invoice lines via an invoice rather than loading them independently). As such, the repository classes, of which you have one class per aggregate root will be responsible for getting initial entities out of the database using the ORM in question, implementing any query strategies (like paging or sorting) and returning the aggregate root to the consumer. The repository would consume the current active data context (ISession in NHibernate) - how this session is created depends on what type of app you are building.
YourApplication.Workflow

Could also be called YourApplication.Services, but this can be confused with web services
This tier is all about interrelated, complex atomic operations - rather than have a bunch of things to be called in your presentation tier, and therefore increase coupling, you can wrap such operations into workflows or services.
It's possible you could do without this in many applications.

Other tiers then depend on your architecture and the application you're implementing.
YourApplication.YourChosenPresentationTier
If you're using web services to distribute your tiers, then you would create DTO contracts that represent just the data you are exposing between the domain and the consumers. You would define assemblers that would know how to move data in and out of these contracts from the domain (you would never send domain objects over the wire!)
In this situation, and you're also creating the client, you would consume the operation and data contracts defined above in your presentation tier, probably binding to the DTOs directly as each DTO should be view specific.
If you have no need to distribute your tiers, remembering the first rule of distributed architectures is don't distribute, then you would consume the workflow/services and repositories directly from within asp.net, mvc, wpf, winforms etc.
That just leaves where the data contexts are established. In a web application, each request is usually pretty self contained, so a request scoped context is best. That means that the context and connection is established at the start of the request and disposed at the end. It's trivial to get your chosen IoC/dependency injection framework to configure per-request components for you.
In a desktop app, WPF or winforms, you would have a context per form. This ensures that edits to domain entities in an edit dialog that update the model but don't make it to the database (eg: Cancel was selected) don't interfere with other contexts or worse end up being accidentally persisted.
Dependency injection
All of the above would be defined as interfaces first, with concrete implementations realised through an IoC and dependency injection framework (my preference is castle windsor). This allows you to isolate, mock and unit test individual tiers independently and in a large application, dependency injection is a life saver!
Those namespaces
Finally, the reason I'd lose the helpers namespace is, in the model above, you don't need them, but also, like utility namespaces they give lazy developers an excuse not to think about where a piece of code logically sits. MyApp.Helpers.* and MyApp.Utility.* just means that if I have some code, say an exception handler that maybe logically belongs within MyApp.Data.Repositories.Customers (maybe it's a customer ref is not unique exception), a lazy developer can just place it in MyApp.Utility.CustomerRefNotUniqueException without really having to think.
If you have common framework type code that you need to wrap up, add a MyApp.Framework project and relevant namespaces. If your're adding a new model binder, put it in MyApp.Framework.Mvc, if it's common logging functionality, put it in MyApp.Framework.Logging and so on. In most cases, there shouldn't be any need to introduce a utility or helpers namespace.
Wrap up
So that scratches the surface - hope it's of some help. This is how I'm developing software today, and I've intentionally tried to be brief - if I can elaborate on any specifics, let me know. The final thing to say on this opinionated piece is the above is for reasonably large scale development - if you're writing notepad version 2 or a corporate phone book, the above is probably total overkill!!!
Cheers
Tony
Comment: Thats a great, I will post the full outline for the structure I use as I have only shown the business layer above, I also do not just call it business ;) a lot of what you have said above is great, but the reason for Utilities it where I put generic classes such as XML Serialisers as they dont directly link to anything. Anyway I will post a better structure outlay, as you have covered all other layers not just the business.
Comment: Your XML Serialisers probably belong in your data layer. For instance, I have some XML serialisation stuff that is responsible for pulling in data from 3rd party suppliers. It lives in MyApp.Data.Repositories.Integration - I'm yet to find a need to name anything generic like "Utilities"
Comment: take your SettingsManager for instance - to me that just lives in projectName.SettingsManager - the .Utilities.Common isn't quite as intuitive. It's a matter of preference of course! :)
Comment: Maybe Im being brain washed with what I 'think' the data layer is, but I thought it was for communication with the database?
Comment: It's the persistence layer, where you implement your repository patterns plus anything else that might do to and from persistence. Database is one form of persistence - XML may well be another.
Comment: Right ok, thanks for the information helps a little.
Anyone else wish to share their way?
Comment: +1 @deepcode.co.uk has got a point that developers in general tend to have a Utils or whatever namespace to helps us with something in parts of the application. The XML thing is a good example of something that doesn't need to be in a Utils namespace. However, what if you have some expression builder that the client generates as XML and you need your XML serialise and deserialise methods in there? You certainly have a good point but the possibilities here are endless so we should have an open mind about those things.
Answer: There is a nice diagram and a description on this page about the application layout, alhtough looks further down the article the application isnt split into physical layers (seperate project) - Entity Framework POCO Repository
Comment: the link to Entity Framework POCO Repository is dead, anyway you have an updated link?
Comment: This post of 5yrs ago, but I've managed to find it through WaybackMachine

https://web.archive.org/web/20120605012315/http://blog.keithpatton.com/2009/05/30/Entity+Framework+POCO+Repository+Using+Visual+Studio+2010+Net+40+Beta+1.aspx


What file or data I should NOT give outsourcing developer for security when they need a copy site of my site?

Question: I'm asking a outsourcing developer to modify some part of my site and then he needs the copy of my site as a test site.
My site is already working site and has users registered. What comes in mind first is deleting user table from database to protect the personal information.
And the what else I should NOT give the developer? I trust the one who works on my site of course. But in generally is there any files or database table that can be harmful if the third party obtains?
Answer: Deleting the user table might break features that rely on node authors or some other user information. Try setting every user's email to firstname.lastname@example.com and their password to 'password'. You shouldn't give the settings.php file, since it has your database credentials and the cryptographic salt Drupal uses to hash users' passwords.
Answer: There are two places I would look:

Any credentials stored in places like the settings.php file which has database credentials and potentially other sensitive information. If it's not in settings.php (e.g. some sites use settings.local.php that is included into settings.php) then just be aware of that and who has access to it. There may be other credentials stored in other .php files.
Your database has a lot of potentially sensitive information in it. See this article about sanitizing the Drupal database backup for advice on what you may want to remove.

Also, if you trust them to write module or tpl files then you should trust them with your data. After all: they could make a mistake or add a back-door to the site to steal this information if they want it. I see both of the above suggestions as "best practices" regardless of who is doing the work. Everyone should remove credentials and sensitive database information prior to giving out copies of the information.


Remove TABLE, TR, TD tags through jquery

Question: Is it possible to remove "TABLE, TR, TD" tags through jquery but content shouldn't be deleted inside the table.
i.e. Below is my table code contained images and I want to remove only table, tbody, tr and td tags around the images.
Code before jquery

Code should be after jquery

Thanks in advance!
Answer: Try:
var gallery = $("#Gallery");
var contents = gallery.find("td, th").contents().detach();
gallery.find("table").remove();
gallery.append(contents);

DEMO: http://jsfiddle.net/Ydsg9/
Answer: $('#Gallery table').replaceWith(function(){
     return $(this).find('td *');
});

http://jsfiddle.net/ec46T/
Answer: $("#Gallery img").each(function(){
    $("#Gallery").append($(this));
});
$("#Gallery table").remove();

http://jsfiddle.net/hescano/jGT5b/
Answer: Working Fiddle
var img = "";
$("td").each(function(){
  img = img + $(this).html();
});

$("#Gallery").append(img);
$("table").remove();

Comment: Using `.html()`, all jQuery event handlers and data are lost
Comment: you're missing a `{` after `each(function()` and if corrected it prepends `undefined` to the images
Answer: Try this:
$('#Gallery img').unwrap().unwrap().unwrap().unwrap();

Comment: Interesting aproach, although not as flexible for other structures.
Answer: If you are solely expecting content within the  elements as you should be, you can use the following:
 $(function(){
    var g = $('#Gallery'),
    f = '';

    $('td', g).each(function(){
        f += $(this).html();
    });

    g.html(f);

});

Answer: Another way of doing it
        var gallery = $("#Gallery");
        var imgs = $("img", gallery).clone();

        $("table", gallery).remove();
        gallery.append(imgs);

the selector is optimized and the imgs variable still has a reference to the images inserted in #Gallery
Answer: Here it is
var list = $('#Gallery table td *');
$('#Gallery').html(list.get());

You can play with it in here: http://jsfiddle.net/cockypup/Dehgf/2/
The CSS is just to make evident the table is disapearing.


Date from multiple date columns

Question: I am using Tableau and I would like to combine two different date columns
1. purchase_date
2. revenue_date
My case is that there is a delay between purchase creation date and revenue creation date. We sell products and we take the revenue a few days later.
We would like to have a field that the amount dimension to be calculated using revenue date and the number of purchases dimension to be calculation using purchase date. So the desired result is the one displayed below (Expected Tableau result).
Exptected tableau example
Comment: Are you using the Tableau API to write code to do this? If so, show your [mcve]. Otherwise, it is likely off-topic for SO.
Comment: Sounds like you a mixing cash basis and accrual basis views of the data
Answer: This task would be easier if you reshape your data (or revise your query) to have two tables. The first describing Orders_Placed with a Purchase Id and Date and Amount Columns
The second table describing Received_Payments with Payment_Id, Order_Id, Date and Amount columns.
If you model your data separately in this case, you can represent situations like - orders that have no payments yet, orders that have a series of partial payments, even overpayments. So there are benefits to not mixing two different types of objects in your data representation. And payments are still tied to orders by the shared Order_Id
Finally, to get the chart you want, you can make two separate connections in Tableau and then use data blending to build your chart. Linking on the date field. Use the Order data source as the primary data source.

Date from multiple date columns


df -h shows 100% usage but sizes don't add up

Question: I have a situation where my root filesystem is supposed to have plenty of free space, but Debian behaves as if it had no free space left. Non-root users even refute to write anything complaining about the lack of free space. I.e. for example:
~$ echo "qwertyu" > test
-bash: echo: write error: Spazio esaurito sul device

(Sorry about the language, I didn't install the server myself. The error reads "ran out of free space on the device").
But root writes to the same directory without complaints. Also if I do df -h as root I get this:
/# df -h
File system                                             Dim. Usati Dispon. Uso% Montato su
rootfs                                                   48G   46G       0 100% /
udev                                                     10M     0     10M   0% /dev
tmpfs                                                   397M   88M    310M  23% /run
/dev/disk/by-uuid/8063903c-80ad-4f72-81b0-cd67dbd48fc7   48G   46G       0 100% /
tmpfs                                                   2,0G     0    2,0G   0% /dev/shm
tmpfs                                                   2,0G     0    2,0G   0% /sys/fs/cgroup
tmpfs                                                   5,0M     0    5,0M   0% /run/lock
tmpfs                                                   100M     0    100M   0% /run/user
/dev/sdb1                                                99G  9,6G     84G  11% /disk2

But du entries don't add up:
/# du -sh /* | sort -hr
du: impossibile accedere a "/proc/12905/task/12905/fd/4": File o directory non esistente
du: impossibile accedere a "/proc/12905/task/12905/fdinfo/4": File o directory non esistente
du: impossibile accedere a "/proc/12905/fd/4": File o directory non esistente
du: impossibile accedere a "/proc/12905/fdinfo/4": File o directory non esistente
9,4G    /disk2
3,8G    /var
3,2G    /data
1,6G    /usr
277M    /opt
130M    /root
129M    /lib
88M /run
45M /home
18M /boot
7,6M    /bin
6,0M    /sbin
5,2M    /etc
28K /tmp
16K /lost+found
8,0K    /media
4,0K    /srv
4,0K    /selinux
4,0K    /mnt
4,0K    /lib64
0   /vmlinuz
0   /sys
0   /proc
0   /initrd.img
0   /dev

(Error says "Cannot access yada yada: No such file or directory").
Be aware that /disk2 is a mount for an another partition.
Checking the filesystem didn't help either:
/# e2fsck -n /dev/sda1
e2fsck 1.42.5 (29-Jul-2012)
Warning!  /dev/sda1 is mounted.
Attenzione: essendo un controllo a sola lettura, il journal non verrà ripristinato.
/dev/sda1: clean, 86568/3145728 files, 11666588/12563712 blocks

("Being it a read-only check, the journal will not be recovered", but I guess the "clean" just below rules out this possibility).
Any idea what might be going on here? Consider the system runs on a VM somewhere and I can only access it via SSH.
Comment: Ended up being a big deleted log file was being kept open by mongoDB. Kudos to the guy from the other question.
Comment: Also note that the ext[2-4] filesystems reserve 5% of their space for the root user by default (so root can still login and fix things when the disk fills up).
Answer: The only reasonable explanation would be, that the file system is mounted read-only.  dmesg | grep -i "\-fs" should show some errors, if so.
If you are on a VM, the fs may not be fully accessible from within your VM, thus rendering you impossible to fix fs errors from within your VM. Consider contacting your provider to get this fixed.
Comment: `/# dmesg | grep -i "\-fs"`
`[    0.942564] EXT4-fs (sda1): mounted filesystem with ordered data mode. Opts: (null)`
`[    3.872319] EXT4-fs (sda1): re-mounted. Opts: errors=remount-ro`
`[  394.339307] EXT3-fs (sdb1): using internal journal`
`[  394.339310] EXT3-fs (sdb1): mounted filesystem with ordered data mode`
I don't know if this is significant to the case...
Comment: No, seems ok to me. I guess the underlying host/storage is to blame.
Comment: This is not true, I have rw rights on my partition and it has the same problem


Printing out Matrix values in OPENCV does not work

Question: I started working with OPENCV and I firstly test some basic
commands. At the moment I try to print out a particular value of a jpg image. I already read several posts and constructed the following C++ program.
<code>#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;

int main()  //(int argc, char** argv)
{
    Mat image;
    image = imread("Desert.jpg", IMREAD_COLOR);
    cout << image.at<Vec3b>(1, 1)[0] << std::endl;
    cout << image.at<Vec3b>(1,1) << std::endl;
    image.at<Vec3b>(1, 1)[0] = 10;
    cout << image.at<Vec3b>(1, 1) << std::endl;
    return 0;
}
</code>
The output in the terminal is
<code>▒
[205, 123, 51]
[10, 123, 51]
</code>
So I get a strange value when printing out the first channel of pixel (1,1). Contrary to that I can print all three at once. I can even change the value of pixel (1,1) in channel 1 using the same syntax.
I use visual Studio and Vesion 3.4.1 of OPENCV. Any suggestions or comments why this happens?
Answer: It is printing a value that looks bad, but it is actually correct.
The type Vec3b is a vector with 3 byte entries, where those bytes are stored as unsigned char values to represent the 0 -> 255 color range. You are seeing the byte value of 205 in the console.
The Vec3b object most likely has the << overridden to deal with printing out the values for the user to read.
Try type casting the byte to an int to see the value:
<code>cout << (int)image.at<Vec3b>(1, 1)[0] << std::endl;
</code>


Apache AddType directive for .js files does not work

Question: I run YSlow in a couple of sites of mine and it reports that one .js file is not compressed. mod_deflate is enabled of course (other html and text files are compressed):
AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml application/javascript application/ecmascript text/javascript text/x-javascript
DeflateCompressionLevel 6
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary

# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary

I used Firebug to see the html headers sent by Apache when directly requesting this .js file and it seems that Apache does not send any Content-type header directive. I suppose this is the reason it does not go through the deflate filter for compression. Then, I added
AddType application/javascript .js

in the corresponding config file in Apache, restarted it and it still does not work. No Content-Type header is sent when requesting the file.
Apache runs in Linux, with PHP enabled (if this helps). mod_mime module is also enabled.
Answer: Apparently, the file was served from the browser's cache, I did not see the 304 status response in the Firebug window. After emptying the cache, the js file was indeed returned with the application/javascript content type and was gzipped.


How to check feature relevance and representativeness?

Question: How to check whether features from one domain are relevant in other domain?
How to evaluate whether features are representing that domain?
Comment: This is too vague. Can you give an example?
Comment: What do you understand by domain?
Answer: It depends on your application. For example, if you have a classification problem (It means you have labels for your data), you can classify your data using only one specific feature and check how representative is that specific feature. Or, you can do classification with and without a specific feature and see how much difference a specific feature can make.


Retornar todos dados do primeiro ao último dia do mês com mysql

Question: estou fazendo uma busca em uma tabela na minha base que precise que retorne todos os dados que foram criados no mês corrente (irei rodar um cron no último dia do mês às 23:00). Tenho na minha tabela um campo created_at que guarda o data inserida na base o registro.
O que fiz foi o seguinte:
SELECT *
FROM minha_tabela
WHERE created_at >= date_add(last_day(date_sub(curdate(), interval 1 month)), interval 1 day)
AND created_at <= last_day(curdate());

Esta funcionando, só que gostaria de saber se é melhor eu deixar assim mesmo ou se tem alguma forma melhor para se fazer, pensando em performance e manutenção.
Answer: Você pode só selecionar o mês e o ano, ao invés de selecionar por um intervalo de dias.
SELECT * FROM minha_tabela
WHERE MONTH(created_at)=MONTH(CURDATE()) AND YEAR(created_at)=YEAR(CURDATE())

Dessa forma, você seleciona todos os registros no mês atual.
Comment: Uma forma que pelo menos já facilita na manutenção, e pelo que vi melhora nem piora a performance. Valew
Comment: Não posso dizer no mysql, mas no sql server existe uma perda de performance caso o campo utilize índices, pois eles são desconsiderados quando o `where` é calculado através de uma expressão (`month()` e `year()` nesse caso)
Answer: Fazendo da forma que você explicou, você esta com uma janela de uma hora, e os registros criados nesse período nunca vão passar por este processo...
Sugiro que você crie a cronjob no primeiro minuto de todo dia primeiro do mês, e a query seleciona todos os registros do mês anterior:
SELECT *
FROM minha_tabela
WHERE YEAR(created_at) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(created_at) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)

Veja funcionando no SQL Fiddle


javascript functions available via javascript_include_tag but not asset pipeline and application.js

Question: My apologies if this has been posted somewhere else, but I'm not exactly sure how to even phrase a search for this problem.
Basically, I've got fullcalendar.js sitting in app/assets/javascripts/. Within my application.js file (in the same folder of course) I've got the following...
//= require jquery
//= require jquery_ujs
//= require foundation
//= require_tree .

So, as expected the fullcalender.js gets swept up in the asset compiling process and ends up in the application.js that is then served to the user.
The problem comes in when I try to reference a function defined in fullcalendar.js (and thus defined in application.js after compiling the assets) it throws an error stating TypeError: $(...).fullCalendar is not a function in the js console of firebug, and of course full calendar doesn't render.
Now, however, if I include <%= javascript_include_tag "fullcalendar.js" %> in the layout file after all of the other scripts and stylesheets have been pulled in, it works as expected.
Baffled, I looked into the js in each file and compared them and can't see a difference. Is there something going on with the asset pipeline that I'm not aware of or is this some freaky DOM issue? I just have no idea at this point.
For reference, here are the contents of both the application.js and fullcalendar.js that are linked to in the page source of the site. I've only included the relevant full calendar portion of each, as it's too large for gist or pastebin if I include everything.
What baffles me is that both the sources come from the same file, one is just linked to directly, the other flows through the asset pipeline process.
application.js - http://pastebin.com/byyNErB8
fullcalendar.js - http://pastebin.com/k4p29YmP
Any insight or help would be GREATLY appreciated.
Answer: Maybe a dependency error. I'll suggest you to use a better practice for such lib.

Put the fullcalendar scripts into vendor/assets/javascripts
Require this script manually in application.js before the tree and after jquery and any other lib it depends.
/=require 'fullcalendar`

Add
Check the loaded Javascript files in header, if application.js is the last, you have dependency error. The lib must be there before calling it.
Comment: Yeah, so, I did have it in my `vendor/assets/javascripts` section but to remove any further moving parts I temporarily moved it to the `app/assets/javascripts` section. I get the same results whether I leave the file in the vendor or app section :(

But yes, to be clear, you are totally correct in that they are best placed in the vendor folder.
Comment: @detectivist, I think the problem is you load the lib before the calling script. You can try remove `require tree` and require each file manually, putting your own scripts at the last.
Comment: Let's say I've got a little script that references a function that is defined in the lib. Don't I need to have that lib loaded before my script attempts to call that function? Right now, my own script, which calls to that lib is loaded after the lib itself is loaded. I assume this is what you mean.
Comment: @detectivist, yes, you are totally right. But I have not seen such custom code in application.js http://pastebin.com/byyNErB8
Comment: the addition to your comment got me thinking. It turns out the problem was that I was loading my script before jquery was loaded. So, just moving around the javascript_include_tags so that jquery loaded before the compiled application.js fixed the issue.

Thanks for getting me down the right path!


Linear programming with reuse of services

Question: I came across some questions of this style and was not sure what the minimization function would be.
A hotel requires a known number of hand towels for guests to be given during the week and the goal is to meet the demand at minimum cost. Suppose the towels required are 100,80,120,150 and 130 for Monday through Friday respectively. New towels can be purchased for \$0.12 each and used towels can be washed. Towels that are washed for the next-day service have a cost of \$0.06 each, for use on the second day at \$0.03 each and for the third day at \$0.03 each. At the end of the week, all used towels can be sold for \$0.01 each.
I assumed the following:
$$x_i = \text{the # of new towels purchased for day } i, \text{where } i = 1,2,3,4,5$$
$$x_{ij} = \text{the # of towels used on day } i, \text{and washed to be used again on day } j,  = i+1,...,5$$
My constraints are:
$$x_{ij} \geq 0$$
$$x_1 \geq 100$$
$$x_2 + x_{12} \geq 80$$
$$x_3 + x_{13} + x_{23} \geq 120$$
$$x_4 + x_{14} + x_{24} + x_{34} \geq 150$$
$$x_5 + x_{15} + x_{25} + x_{35} + x_{45} \geq 130$$
I am not sure how to develop the cost function fully. I reached this far but not sure what to do with the selling of the towels:
$cost = 0.12 (x_1 + x_2 + x_3 + x_4 + x_5) + 0.06 (x_{12}+ x_{23}+ x_{34}+ x_{45}) + 0.04 (x_{13} + x_{24} + x_{35}) + 0.03 (x_{14} + x_{25})$
Comment: Ok deleted my old comments to avoid confusion. I think you need to subtract off $0.01(\sum_{i=1}^{4}x_{i5})$ from your cost function.
Comment: On second thought, maybe it's -$0.01(x_5 + \sum_{i=1}^{4} x_{i5})$. Hmm LP formulation is confusing, what do you think? Basically you want to treat that profit as a "negative-cost".
Answer: Your model looks correct, though it's also important to have the non-negativity constraint for $x_i \ge 0$ for $i = 1,2,...5$. The rest of your constraints are correct. Your objective function is almost correct, but you need to take account the 'profit' from the used towels on the final day. Note: what I suggested in the comments is incorrect, there is a simple fix in which you just replace the 0.12 with 0.12 - 0.01.
objective function:
min $0.12\sum_{i=1}^{5} x_i + 0.06(x_{12}+x_{23}+x_{34}+x_{45}) + 0.04(x_{13}+x_{24}+x_{35}) + 0.03(x_{14} + x_{25}) - 0.01(\sum_{i=1}^{5} x_i)$ =
min $0.11\sum_{i=1}^{5} x_i + 0.06(x_{12}+x_{23}+x_{34}+x_{45}) + 0.04(x_{13}+x_{24}+x_{35}) + 0.03(x_{14} + x_{25})$
Where the term $\sum_{i=1}^{5} x_i$ represents the number of towels bought in the week, and also the number of used towels remaining at the end of week (i.e., all the towels you bought are considered used at the end of week).
Comment: Thank you, I understand what needs to be done now. I too initially thought it was 0.01 by the whole of the last row. This makes much more sense and yes LP formulation can become confusing.


Find Taylor series and radius of convergence of $\frac{1}{1-z}, z_0 = i$

Question: I cannot find a comparable series. What am I supposed to compare this to?
$$\frac{1}{1-z}, z_0 = i$$
So I guess this is the geometric series but $z_o = i$. So what's the Taylor series then? Is it just:
$$ \frac{1}{1-z} = 1 + x + x^2 ... = \sum_{n=0}^{\infty} x^n$$
z
I think not... but how do I incorporate the $z_0$
Comment: Hint: $$
\frac{1}{{1 - z}} = \frac{1}{{1 - i - (z - i)}} = \frac{1}{{1 - i}}\frac{1}{{1 - (z - i)/(1 - i)}}.
$$
Answer: You have\begin{align}\frac1{1-z}&=\frac1{1-i-(z-i)}\\&=\frac1{1-i}\frac1{1-\frac{z-i}{1-i}}\\&=\frac1{1-i}\sum_{n=0}^\infty\frac{(z-i)^n}{(1-i)^n}\text{ (if $|z-i|<\sqrt2$)}\\&=\sum_{n=0}^\infty\frac{(z-i)^n}{(1-i)^{n+1}}.\end{align}
Comment: From$$\left|\frac{z-i}{1-i}\right|<1\iff\frac{|z-i|}{\sqrt2}<1\iff|z-i|<\sqrt2.$$
Comment: The radius of convergence of a power series is **always** a number $R\in[0,\infty)$ or $\infty$. In this case, it is $\sqrt2$.
Comment: where did $\sqrt{2}$ come from?
Comment: So then is the radius of convergence... $\sqrt{2}$? or is it $\sqrt{2} + i$? by adding i to both sides
Answer: Hint: $$\frac{1}{1-z}= \frac{1}{1-i} \cdot \frac{1}{1-\frac{z-i}{1-i}}.$$
Geometric series !


Probability density function and distribution from samples to population

Question: Heya got a small doubt here
most of the discrete random variables utilize simple examples of situations like 3 coin toss or 2 dice rolls or girl/boys born. These examples are simple in the sense that we can chart out the entire sample space and discrete values of the random variable. We can then have a complete frequency or probability distribution.
but what happens in situations when it is not possible to prepare the complete sample space. say I note down childbirths in a hospital for 30 days. Can I use this sample and convert it to proportions and give out the probability of no of childbirths on a given date? (stupid example I know)
Answer: Hey hopefully I'm understanding your question correctly and this helps. It sounds like this is a general theory question about how to model a real-world event when we don't have access to the full population. This is the case most of the time, which is why we rely on probability distributions.
The long answer:
In your example, you want to predict either the number of childbirths on a given date or the probability of a certain number of childbirths on that date. The simplest way (that I can think of) to model this would be to assume that the number of childbirths a day follows a Binomial distribution:
i.e. Let X be the random variable "the number of childbirths a day", following a Binomial distribution with unknown n and p parameters: X ~ Binomial(n, p)
The question is how to estimate the values n (number of women who could give birth a day) and p (probability of giving birth that day). This is known as statistical inference and there are many available frequentist and Bayesian methods for performing this.
The short answer:
We cannot generalise a small sample to a population easily but we can make an assumption about which distribution the model may follow and then use statistical inference to estimate the shape of the distribution.
Comment: hi, yes got the problem right. Can you please explain on what basis did you select that the distribution will be binomial? @BigBowlOfXoop
Comment: Great! Well first of all, there is no right or wrong distribution to use. It's all about the question you want to answer. The Binomial distribution is used to model the "number of successful outcomes from a known number of trials", hence in this case we are modelling ."the number of pregnancies out of a known number of pregnant women in a given hospital".  We also could have used the Beta distribution to directly predict the proportion of pregnancies, and then used statistical inference to estimate the shape parameters. The Beta distribution is very common in inference for this reason.
Comment: Poisson or negative binomial models might be more suitable If you don''t have a known N.
Comment: Hm but are the Poisson assumptions not violated? e.g. Childbirths occurring single is violated depending on how common twins are. Doesn't neg bin have same problem if unknown N?


Theme "seven" – how to allow regular users edit content with this theme?

Question: please instruct me how to allow regular users (non-admins) to use Seven theme to edit content. Now users are forced to edit content using the default drupal theme which wasn't designed for this purpose (looks ugly).
Is it matter of some permission? Admins are editing with Seven theme without problem.
I've found some topics about more complex cases with module recommendations like this:
http://drupal.org/project/themekey . As my case is pretty simple, I decided to ask!
Cheers!
Answer: Checking the permissions "View the administration theme" fixed my problem.
Answer: You can try the Administration Theme module to control which pages are rendered with the admin theme (in your case: Seven).
Comment: Ok, so I checked again permissions table (which got pretty complex thanks to a lot of modules and content types) and search one more time for "theme" (few results, confusing similar titles) ... ended up turning on "View the administration theme" which did the trick! :)
Comment: Aha, good catch, I forgot that that's a separate permission. Did you can add your own solution as answer and mark it as accepted (in a day or two)?
Comment: sure. I will do that!


Calculus : Plug in value into a derivative?

Question: $$ f(x) = x^3-2x^2-6x $$
after derivative
$$ 3x^2-4x-6 $$
If u plugin x=1,2,3,4,5
as a result:
$$ 3(1)^2-4(1)-6=-7 $$
$$ 3(2)^2-4(2)-6=-2 $$
$$ 3(3)^2-4(3)-6=9 $$
I know it means the slope of the current point on the curve or instantaneous rate of change
Look at the answer 9 what is it actually mean?Is there any relationshiop between x=3 and x=4? an increment?
Comment: Note that $f'(x)=3x^2-4x-6$ and so $f'(3)=9$. This means that at $x=3$, the gradient of the tangent to $f(x)$ is $9$.
Comment: The value $25$ is incorrect.
Comment: $x=3 ; (3)^3-2(3)^2-6(3)=1$ how this answer related to the slope 9?
Answer: For $x=1$ :
$$f(1)=(1)^3-2(1)^2-6(1)=-7$$
$$f'(1)=3(1)^2-4(1)-6=-7$$
This means that at point $(1\:,\:-7)$ the slope of the tangent is $=-7$ .
For $x=2$ :
$$f(2)=(2)^3-2(2)^2-6(2)=-12$$
$$f'(2)=3(2)^2-4(2)-6=-2$$
This means that at point $(2\:,\:-12)$ the slope of the tangent is $=-2$ .
For $x=3$ :
$$f(3)=(3)^3-2(3)^2-6(3)=-9$$
$$f'(3)=3(3)^2-4(3)-6=9$$
This means that at point $(3\:,\:-9)$ the slope of the tangent is $=9$ .
For $x=4$ :
$$f(4)=(4)^3-2(4)^2-6(4)=8$$
$$f'(4)=3(4)^2-4(4)-6=26$$
This means that at point $(4\:,\:8)$ the slope of the tangent is $=26$ .
Comment: Finally I get the answer by myself. The slope mean if x change in a very small amount and y value will change in multiplier of the slope
$x^2$ if u put 2 and 2.000001 into x. The slope of 2 is $2(2)=4$ and $2.000001^2=2+0.000001(slope);slope=4$


Cox regression latex output equation explanation

Question: After fitting a Cox model when I export the equation using
w <- latex(f, file='f.tex')
The XB contains a constant which is not one of the beta co-efficient of the predictors in the model. Is this the baseline hazard?
Do I have to include this while calculating the survival probability using the equation S(t)=S(0)exp(βpredictor1predictor1 + βpredictor2predictor2 etc.)?
Thank you very much in advance.
Comment: It's going to be hard to answer this unless you show the output from the `latex` output. A Cox model has no intercept and only provides an empirical baseline hazard.
Answer: After some searching found out that the latex output of a Cox model equation includes the centering constant, equal to overall mean of X beta.


How to send the post values while pagination links call in laravel

Question: I would like to pass the post values while clicking the links in pagination..
I wrote the pagination even if ajax calls..BUT,I'm unable to send all the values through pagination..
And Finally I got appends()->render();
So there I send all my POST values by using appends($_POST)->render();
It shows the link as localhost/example.com/hotel/hotelresults?MY_POST_VALUES&page=2
But,It seems to be an error like that

Here,I send the search_city with several values through my post action.
But I don't know why doesn't works for me..
Please someone help me.
Answer: I got it..
Hopes it might be helpful for someone else..So I posted my answer here..
Controller
public function postHotelresults()
    {
    .
    .
    .
    $sqlCond = 'WHERE 1 '.$this->getAreaCondition($_POST['search_city']);
    .
    .
    $query = "SELECT `h`.*,".$countquery.",".$minquery." FROM `abserve_hotels` as `h`";

    $query1 = DB::select($query.$sqlCond);

    $perPage = 2;
    $currentPage = Input::get('page', 1) - 1;
    $pagedData = array_slice($query1, $currentPage * $perPage, $perPage);
    $query1 =  new Paginator($pagedData, count($query1), $perPage);
    $query1->setPath('hotelresults');
    .
    .
    return view('hotel.list', $this->data,compact('query1'));
    }

public function getHotelresults()
    {
            $this->postHotelresults();
    }

Here,When we click the links in the pagination it pass its all values to the get method..
So,as I already said I use appends($_POST)->render(); in view But instead of this I gave it like appends($_REQUEST)->render();.
Since $_REQUEST is used to get both the POST and GET values
According to this my view is like
View
<?php
if(!empty($query1)){
?>
@foreach($query1 as $aHotelRoom)

{{$aHotelRoom->hotel_id }}
{{$aHotelRoom->logo}}

@endforeach
<?php
echo $query1->apends($_REQUEST)->render();
}

And in the controller I use to call the post method inside the get Which leads to call the all the functionalities in get.
And an important thing is Routing in my
routes.php
Route::get('hotel/hotelresults', 'HotelController@postHotelresults');

I gave like this.
Thanks,


How to display files in a web browsers?

Question: I have a new OA site spun up and have some content available for the few users I have. One of the requests from the user's is to be able to view (and most likely edit) the documents via the web browser.
I was able to open a Word document in the browser when using IE, however I was unable to edit the document. Also, opening project files was a no go.
I am pretty new to Drupal, however any research I did on this issue just brought me different file manager modules.
Is it possible to view/edit files in the browser with Drupal/Open Atrium?  I know it is possible with SharePoint but that utilizes a back end office.
Or is it possible to have it so people can open files automatically in their client side applications (Project, Word etc.) and have it save to the OA file system?
Answer: I'm not aware of any web based file browser that "opens files in the client site applications" like Project, Word, etc. and saves them.
Some ideas:
However, this could be possible if you open your files with a FTP manager, as they will be opening from your client's computer, therefore using its applications.
Another option might be the download / re-upload approach, for what you could use a module like elfinder, which does allow you to edit text based files (note that we are not talking about propietary software like Microsoft Word).
Disclaimer: I'm not endorsing any of these methods, just offering alternative ideas.
Comment: Thank you for your input, I will look into the methods you laid out.

How to display files in a web browsers?


Is this a good candidate for using Asynchronous controllers in ASP.NET MVC

Question: All the images in my site are served by a controller action. This action checks to see if the image exists on disk and can do some manipulations (resizing etc.).
Considering that a page may contain 50 or so images, resulting in 50 requests, is this a good candidate for using ASP.NET MVC Async controllers?
Answer: You should read measure-the-performace-of-async-controllers first.
From the article

Asynchronous requests are useful, but only if you need to handle more concurrent requests than you have worker threads. Otherwise, synchronous requests are better just because they let you write simpler code.
(There is an exception: ASP.NET dynamically adjusts the worker thread pool between its minimum and maximum size limits, and if you have a sudden spike in traffic, it can take several minutes for it to notice and create new worker threads. During that time your app may have only a handful of worker threads, and many requests may time out. The reason I gradually adjusted the traffic level over a 30-minute period was to give ASP.NET enough time to adapt. Asynchronous requests are better than synchronous requests at handling sudden traffic spikes, though such spikes don't happen often in reality.)
Even if you use asynchronous requests, your capacity is limited by the capacity of any external services you rely upon. Obvious, really, but until you measure it you might not realise how those external services are configured.
It's not shown on the graph, but if you have a queue of requests going into ASP.NET, then the queue delay affects all requests – not just the ones involving expensive I/O. This means the entire site feels slow to all users. Under the right circumstances, asynchronous requests can avoid this site-wide slowdown by not forcing the other requests to queue so much.


GestureRecogniser and disabling drag gesture of a UIView in a UIScrollView

Question: Recently I had a problem. How to disable scrolling in a particular area of a UIScrollView, particularly the area occupied by a UIView or subview.
I've readen a lot about subclassing and other long approaches to solve this.
But recently I solved this problem in a simplier manner without subclassing:
<code>UIPanGestureRecognizer *panrecognizer = [[UIPanGestureRecognizer alloc] init];
</code>
and then
<code>[panrecognizer setCancelsTouchesinView:NO];
[mySubViewInScroll addGestureRecognizer:panrecognizer];
</code>
I created the UIPanGestureRecognizer without an Action passed to it and then added the recognizer to the view in the scroller. In such way the gestures on the view will be captured but expressly not handled by the view or by the superviews because we passed to the object no Action.
The question is this. Is this a correct approach to handle this type of prolem or it's better to do otherwise. I mean Apple will accept this kind of application with this approach ?
Comment: Can you clarify your question please: do you mean that you want a UIView laid over the top of the UIScrollView, i.e. not a child view of the UIScrollView, but just over the top (i.e. a sibling of the UIScrollView)?
Comment: Of course apple will accept this kind of app.  So long as you don't start digging through their mountain of frameworks to find an undocumented (and most likely worthless) API for a scrollview, it'll be fine.
Comment: No..The UIView is a child of the UIScrollView. I wanna the UIview to not let his parent UIScrollView to scroll when we start to drag with fingers on the UIView itself, but when we drag in another part of the scrollview it scrolls normally and even the UIView moves with the rest of the scroll.
Answer: In effect I think that this, even if not the best is the most practical solution..since messing around with the classes and subclassing to achieve only a partial scroll lock of the screen seems to be very odd. So let-s see if Apple will accept this kind of solution...
Comment: Claudio, I'm looking at a similar situation. What was the outcome with Apple? Thanks David
Answer: try rewrite ScrollView's
<code>-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
</code>
to return chi
Comment: To improve the quality of your answer, please include how/why your post will solve the problem.


Como programar em java e python junto

Question: Vejo vários programas e sistemas que são programados em várias linguagens, como por exemplo o android. Eu estou tentando programar em java junto ao python, mas não acho nada sobre isso. Ja tentei juntar as informações em json para trabalhar, mas não parece algo muito bom para se usar. Alguém consegue me ajudar
Comment: Maniero: "Python é bom em IA" - quando 90% dos frameworks para IA disponiblizam suas APIs e documentação primariamente em Python. A premissa de Python sempre foi facilitar a interface, e deixa o que é computacionalemtne intensivo ser executado em código nativo.
Comment: Se lhe for útil, eu votei para fechar porque acho vago demais uma pergunta do tipo "como uso X e Y juntos". Dependendo o objetivo, a resposta variará ou até a recomendação será "não use". Abordar todos os contextos possíveis na resposta costuma ser inviável e há uma grande chance da resposta ser um "chute" sobre o contexto da pergunta. Se o chute for errado, será uma resposta inválida, que só o autor da pergunta poderá avaliar. Por isso comentei questionando quais eram os objetivos e se a pergunta for editada complementando isso eu reavaliarei meu voto de fechamento.
Comment: Considero ser uma pergunta completamente válida, mas não no formato atual. Discordo dela receber três votos negativos, pois ela não é, na totalidade, ruim; mas também discordo dela receber três votos positivos, pois na sua forma atual a pergunta não é suficiente.
Comment: É bem simples de entender o problema até. Da forma como foi feita podem surgir inúmeras respostas usando Java e Python, todas com cenários, pressupostos e finalidades completamente sem relação entre si.
Comment: Por exemplo, uma forma melhorada poderia ser "*Eu gostaria de fazer ... em Java porque ..., mas gostaria de fazer ... em Python porque ..., como eu posso integrar essas duas linguagens para que isso seja possível?*"
Comment: @Woss como você deve saber as pessoas votam por ser engraçadinha, curioso, também queria a opinião, normalmente enviesada, de alguém sobre o assunto porque eu quero fazer igual já que não tenho capacidade de tomar as próprias decisões. Então a pergunta é fora de escopo, é baseada em opinião, não clara e ampla. E de fato a resposta dada não responde a pergunta, mesmo que curiosa, dar o que as pessoas **querem ouvir**. Em geral só acha bom esse tip ode pergunta quem só responde e não participa da comunidade e não vê o monte de problema que iso costuma gerar ,mesm oque algum caso não gere.
Comment: "Como programar em java e python junto?" a pergunta é esta e ele quer que ajude ele fazer algo não descrito. Isto nem dá para responder, no mínimo precisa de um capítulo de um livro. Dizer que tem uma ferramenta que pode ser usada não responde a pergunta feita. Ainda mais que depois a resposta diz "para o seu caso não dá para usar o que eu falei que dá para usar no começo". Isto é um bom comentário, não é resposta. Nós temos uma definição do que é resposta e do que é um comentário, por isso uma pergunta assim é fechada, ela não é adequada para uma resposta, para um comentário é.
Comment: Aceitar resposta é justamente o que eu disse, a pessoa ouviu o que ela queria ouvir, mesmo que a prejudique, mesmo que a leve para um caminho ruim. Por isso essas respostas não são boas. Não estou entrando no mérito da resposta específica porque estou julgando a pergunta, e ela dá muita margem para ter uma resposta que leva a pessoa para o caminho errado, o caminho que é do interesse de alguém. Muitas vezes a pessoa aceita porque é o que tem, ou até pra fazer birra, acontece muito quando tem alguém que diz o contrário do que ela quer ouvir.
Comment: Responder ou aceitar algo ruim acontece quando a pessoa não conhece bem o funcionamento do site. A pergunta é uma das piores já postadas no site, não é uma questão de estar em uma linha tênue. Claro que ela pode ser refeita e ter um propósito, claro, objetivo, que leve a algum lugar, e aí mereça uma resposta. Este caso não merece, e o fato da resposta ter sido postado burlando o fechamento não colabora. Foi um "vai na marra".
Comment: O que exatamente precisa fazer em Java e o que precisa fazer em Python?
Comment: Como java tem vários recursos achei melhor colocar ele como gerenciador de input, e python como é bom para IA estou usando para output. Pois acho difícil fazer IA em java
Comment: Sua pergunta parece ter alguns problemas e sua experiência aqui no Stack Overflow em Português poderá não ser a melhor por causa disto. Queremos que você se dê bem aqui e consiga o que quer, mas para isso precisamos que você faça sua parte. Veja algumas orientações que vão te ajudar: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045) ([versão curta](https://pt.meta.stackoverflow.com/q/8089/101)). Se a ajuda for muito simples ainda é possível fazer nos comentários.
Comment: Python não é bom em IA, nada. Python pegou fama de ser bom em IA, é diferente. Java pode tudo o que Python pode fazer em IA. Achar difícil é outra questão. Tudo é mais difícil fazer em Java. É uma linguagem que afasta amadores, exige um pouco mais que a pessoa realmente aprenda programar.
Comment: É que estou familiarizado com IA em python diferente de java
Comment: Ok - só me ajude a entender como esta resposta "não responde a pergunta"? As primeiras duas linhas dela já respondem a pergunta. O restante vai além, incluindo outros casos de uso, inclusive o uso no mercado, em larga escala.  O AP aprovou como respondida. O que poderia ser mais objetivo que "o projeto Jython (link incluso) permite o uso de Python e Java no mesmo programa." ?
Answer: Existe uma implementação de Python 2 chamada "Jython" - ela permite que você execute código Python dentro do ambiente da JVM, importando e instanciando classes em Java normalmente.
Isso é o que normalmente se entende por "programar Python e Java junto".
Agora, há a abordagem sistemas distribuídos - em que sistemas independentes compartilham dados e eventos por meios de comunicação como requisições web, gerenciadores de fila (redis, Amazon SQS, etc...)  para trabalhar em conjunto. O uso do "JSON" entraria aí: ele é um protocolo de serialização comum para troca de dados entre os sistemas nesses casos. Normalmente essas aplicações que trabalham junto são o que empresas fazem para realizar seus negócios - é comum uma empresa ter um eco-sistema com aplicativos em várias linguagens diferentes.
Tem bastante mais informação e detalhes dessas abordagens nesta resposta:
É possível mesclar Java com JavaScript?
Agora, dado seu esclarecimento:

Como java tem vários recursos achei melhor colocar ele como
  gerenciador de input, e python como é bom para IA estou usando para
  output. Pois acho difícil fazer IA em java

FIca claro que suas premissa sobre as vantagens do Java nesse caso estão incorretas. O que seriam "vários recursos"?
Dá para garantir com tranquilidade que quaisquer "vários recursos" para interface, e entrada e saída de dados, seja num sistema Web, seja no terminal, e até mesmo num aplicativo desktop, são mais fáceis em Python (e isso pode até mesmo ser demonstrado objetivamente: o número de detalhes da linguagem, classes, interfaces que você vai ter que saber pra criar seu app em Python, em relação a Java, vai  ser quase uma ordem de grandeza menor).
Se o seu interesse é chegar a um aplicativo para sistemas Android, a escolha óbvia é fazer uso do PyQT5, com pyqtdeploy para criar o APK. Não sei quanto bem as bibliotecas de IA em si vão funcionar no Android, e se o pyqtdeploy vai conseguir empacota-las corretamente. Uma alternativa é ter a parte de IA em um servidor remoto, como backend, e aí você cria o App Android ou iOS na tecnologia que achar melhor (esse já é um caso de sistema distribuído, como acima)
Por outro lado, a sua premissa em relação a linguagem Python - de que nesse momento do tempo, a maior parte das ferramentas e frameworks para desenvolvimento de IA tem interfaces, exemplos, e documentação em Python está correta.
A solução para você então é: esqueça o Java por agora. Se em algum ponto você tiver uma razão objetiva para usar Java (por exemplo, integrar uma parte de IA em um sistema grande já existente), você volta se procupar com isso.
E, por fim, o Jython não tem um eco-sistema em que as ferramentas de IA do Python estão replicadas - alguns provavelmente até podem funcionar, mas vão perder eficiência - e vai ter pouca documentação. Além do quê ele usa Python 2. A abordagem para esse caso seria de sistemas distribuídos mesmo.
Comment: Criticaram para melhorar o conteúdo da pergunta e entender o que quer, não há problema em receber críticas, o problema é não melhorar com elas
Comment: @Denis: não - de acordo com a interpretação rígida que tem sido dadas as orientações pra perguntas aqui pelo moderador (e segundo ele, é a vontade dos "participantes mais efetivos"), essa pergunta não teria como ser feita aqui, não importa o quanto fosse melhorada - a nao ser que o AP trouxesse vários exemplos já quase funcionando, de sistemas em Python e Java se comunicando.
Comment: @jsbueno não sei se vc não entendeu mesmo quando fala certas coisas do outro moderador, que não procedem sobre o que o autor teria que fazer para reabrir o post (vou presumir boa fé, como obrigação de moderador). O quadro azul é bem claro, um convite a melhorar o post. O fechamento para perguntas que não tem como ser recuperadas é outro.
Comment: @jsbueno "essa pergunta não teria como ser feita aqui, não importa o quanto fosse melhorada - a nao ser que o AP trouxesse vários exemplos já quase funcionando, de sistemas em Python e Java se comunicando" – isso não é verdade. Mas a pergunta precisa ser melhorada para ser reaberta. Por que você não colabora e edita você mesmo? A sua resposta já foi meio caminho andado na salvação da pergunta.
Comment: O primeiro comentário a sua pergutna, nao foi uma crítica. Já o fechamento da pergunta pelo moderador, eu já tentei conversar com ele - não adianta. Ou é uma pergunta com exemplo de código e só uma dúvida pontual, ou é fechada.  A rede em inglês do stackeschange tem outros sites sem ser o stackoverflow, que permitem perguntas mais genéricas sobre t.i.  e aprendizado - a única forma de essa pergutna estar 100% alinhada seria achar o site exato aqui (https://stackexchange.com/sites), e nem eu sei dizer qual - prefiro ser um pouco mais tolerante no que são dúvidas válidas.
Comment: Dá uma lida no manual que colocaram nos comentários, é muito importante entender como o site funciona para se dar bem aqui
Comment: Obrigado por responder minha pergunta. Diferente de algumas pessoas que só criticaram. Muito obrigado. Provavelmente não vou me dar bem por esse comentário.

Como programar em java e python junto


How to spot and remove unimportant columns in a dataframe?

Question: I have a pandas dataframe with several columns, for example let's say:
<code>   A   B   C   D(labels)
   45  88  44  0
   62  34   2  1
   85  65  11  1
   74  43  42  1
   90  38  34  0
        ...
    0  94  45  1
   58  23  23  0
</code>
How can I detect which columns are useless and which columns are useful to a machine learning model?. I all ready tried several methods like PCA, removing features with low variance, univariate feature selection with a chi criteria, etc. However none of them seems to work since the performance of my classifier still is low. I also tried to create more features (add more columns to the feature matrix) and they decreased the performance of my classifier, thus is there anyway to spot which columns are useless?.
Comment: It could also just be that there isn't sufficient information for the classification to perform well.  A couple other approaches you could try though would be to find and remove correlated features if they exist, which can through off some methods, or (depending on the dimensions of your data), try something like Lasso regression which will down-weight unimportant features without removing them entirely, or random forests which has the ability to assign an importance score to each feature.
Comment: Thanks for the help @KeithHughitt, which is the approach to check the correlation between to columns?
Answer: I'm assuming all training/CV/test performance is bad and thereby that the problem is not overfitting. In a nutshell, you then could try the following to meaningfully reduce your features:

Use feature correlation to reduce correlated features,
Feature selection techniques such as feature filters and feature wrappers,
Feature reduction with using techniques like PCA, or
Models that internally "weight" features themselves.

Things you should consider:

As @KeithHughitt mentioned, the problem might be that the relation you seek is simply not present in your data. In such a case it might be impossible for models to perform and generalize well. The "one perfect" solution for those cases does not exist, but, as you already mentioned, deriving features (same information but differently processed) and/or adding information (new information, e.g. with recording more features) might help.
Another explanation for bad predictive performance with big data/many features might be: the feature-target relation is too complex to be represented accordingly by your model (e.g. trying to model circular data with a linear model). In such cases, another option besides adding preproceesing/feature derivation would be to employ more complex models. But those usually come at the cost of increased calculation power, such as with deep learning.
Comment: I am using gradient tree boosting and I all ready used PCA, SVD and other dimentionality reduction methods. Could you provide some approaches to model feature target relation?.... Do you think Fp-Growth or an association rule algorithm can work for this case?