The "Multiple Error Terms" notation for hierarchical models

Question: I'm seeking clarification regarding notation for Bayesian hierarchical models, specifically the mixed effects model. Consider the following hierarchical model for the outcome of unit $i \in N$ in group $j \in J$ from Gelman and Hill (p.265):
$$y_i \sim Normal(X_i\beta + \eta_{j[i]}, \sigma_y^2) \\
\eta_j \sim Normal(0, \sigma_\alpha^2)$$

$X_{(0)}$ is a constant.
$X_{(1)}$ is a unit/level-1 predictor.
$X_{(2)}$ is a group/level-2 predictor.

The authors call this the "regression with multiple error terms" notation but I find this confusing for several reasons.

In this model isn't there only one error term ($\sigma_y^2$) that captures the total unexplained error in $y$? What then is the other error term in the name "multiple error terms?"

If each group is supposed to have its own error, why is $\eta_j$ part of the model for the mean of $y_i$ rather than the error of $y_i$? I read this to imply a heteroskedastic model in which the error is decomposed into group-level terms and individual terms like $\sigma_y^2 = \sigma_\eta^2 + \sigma_i^2$.

What, if anything, is multivariate here? Would it be more appropriate to write $\eta_j \sim MVN(0, \Sigma)$? If so, would $\Sigma$ have a single parameter $\sigma_\alpha^2$ on the diagonal and zeroes elsewhere or does each element of the diagonal vary (i.e. is its own parameter)?
Answer: Let's consider a simplification of your model with only a constant in the $X_i \beta$ part, i.e.,
$$\left\{
\begin{array}{l}
y_{ji} \mid \eta_{j} \sim N(\eta_j, \sigma_y^2),\\
\eta_{j} \sim N(\beta, \sigma_\eta^2).
\end{array}
\right.$$
Note that I have explicitly conditioned on $\eta_j$ in the first line. That is, the first line represents the model at a given level $j$ $(j = 1, \ldots, n)$. The variance parameter $\sigma_y^2$ denotes the variance of the outcome $y_{ij}$ around the mean at the $j$-level denoted by $\beta + \eta_j$. The second line is the model for the means $\eta_1, \ldots, \eta_{n}$ that has a mean $\beta$ and variance $\sigma_{\eta}^2$.
From the above formulation, you can derive the marginal model for $y_j$, i.e., $$y_j \sim N(\beta, \Sigma),$$ where $\Sigma$ has a compound symmetry structure, with diagonal elements equal to $\sigma_{\eta}^2 + \sigma_y^2$, and off-diagonal elements equal to $\sigma_{\eta}^2$. This marginal model does not presume the existence of the latent variable $\eta_j$. That is, a hierarchical model implies a marginal model but not vice versa.  For example, you could define a marginal model that does not correspond to a hierarchical one, or you could have that two different hierarchical models imply the same marginal model. You may have a look at Section 3.3 of my course notes for additional explanation.


XSLT1.0 distinct list of attributes across several nodes

Question: I'm stuck on XSLT1.0 with no extensions.
I need to get a list of nodes whose attributes are distinct. From the XML below below, the result should be 1,2,3,5 for the first post_press_version (25) and 1,2,3,6 for the second (26)
<order>
<post_press_version>
    <post_press_version_id>25</post_press_version_id>
    <hopper_allocations>
        <hopper_sequence>
            <sequence_id>2</sequence_id>
            <sequence_part_produced_id>37</sequence_part_produced_id>
            <sequence_part_produced_name>96854-12WS10</sequence_part_produced_name>
            <sequence_qty>2</sequence_qty>
            <hopper number="0" id="" is_insert="False"/>
            <hopper number="1" id="23" is_insert="False">96854-6FL</hopper>
            <hopper number="2" id="13" is_insert="False">96854-8FL003</hopper>
            <hopper number="3" id="15" is_insert="False">96854-10FL004</hopper>
            <hopper number="4" id="" is_insert="False"/>
            <hopper number="5" id="" is_insert="False"/>
            <hopper number="6" id="" is_insert="False"/>
        </hopper_sequence>
        <hopper_sequence>
            <sequence_id>3</sequence_id>
            <sequence_part_produced_id>38</sequence_part_produced_id>
            <sequence_part_produced_name>96854-12WS20</sequence_part_produced_name>
            <sequence_qty>250</sequence_qty>
            <hopper number="0" id="" is_insert="False"/>
            <hopper number="1" id="24" is_insert="False">96854-6FL10</hopper>
            <hopper number="2" id="29" is_insert="False">96854-8FL</hopper>
            <hopper number="3" id="" is_insert="False"/>
            <hopper number="4" id="" is_insert="False"/>
            <hopper number="5" id="31" is_insert="False">96854-10FL</hopper>
            <hopper number="6" id="" is_insert="False"/>
        </hopper_sequence>
    </hopper_allocations>
</post_press_version>
<post_press_version>
    <post_press_version_id>26</post_press_version_id>
    <hopper_allocations>
        <hopper_sequence>
            <sequence_id>2</sequence_id>
            <sequence_part_produced_id>37</sequence_part_produced_id>
            <sequence_part_produced_name>96854-12WS10</sequence_part_produced_name>
            <sequence_qty>2</sequence_qty>
            <hopper number="0" id="" is_insert="False"/>
            <hopper number="1" id="23" is_insert="False">96854-6FL</hopper>
            <hopper number="2" id="13" is_insert="False">96854-8FL003</hopper>
            <hopper number="3" id="15" is_insert="False">96854-10FL004</hopper>
            <hopper number="4" id="" is_insert="False"/>
            <hopper number="5" id="" is_insert="False"/>
            <hopper number="6" id="" is_insert="False"/>
        </hopper_sequence>
        <hopper_sequence>
            <sequence_id>3</sequence_id>
            <sequence_part_produced_id>38</sequence_part_produced_id>
            <sequence_part_produced_name>96854-12WS20</sequence_part_produced_name>
            <sequence_qty>250</sequence_qty>
            <hopper number="0" id="" is_insert="False"/>
            <hopper number="1" id="24" is_insert="False">96854-6FL10</hopper>
            <hopper number="2" id="29" is_insert="False">96854-8FL</hopper>
            <hopper number="3" id="" is_insert="False"/>
            <hopper number="4" id="" is_insert="False"/>
            <hopper number="5" id="31" is_insert="False"/>
            <hopper number="6" id="" is_insert="False">96854-10FL</hopper>
        </hopper_sequence>
    </hopper_allocations>
</post_press_version>

I tried the XSL below, but it only returns 1,2,3: the results of the first hopper node in the first hopper_sequence
   <xsl:template match="order">

                <xsl:for-each
                    select="/order/post_press_version/hopper_allocations/hopper_sequence/hopper[node() and not(@number = preceding::hopper/@number)]]">

                        <xsl:value-of select="../../../post_press_version_id"/>-<xsl:value-of select="@number"/>

                </xsl:for-each>

    </xsl:template>

I'm struggling to figure out where I'm goign wrong. I laso tried the Meunchen method with this key, but get similar results
<xsl:key name="unique_post_press_version_hoppers" match="/order/post_press_version/hopper_allocations/hopper_sequence/hopper" use="concat(../../../post_press_version_id, @number)"/>

Any suggestions?
Thanks
Mark
Answer: I updated and used your XML and find the proper output as you want. please look again it is correct. Only zero is coming.
Comment: Thanks for the reply. I updated the post to have a more complete XML. I also forgot to mention (and include in original code, that it should only select non-empty hopper nodes


Google app script OnEdit to run only on one cell in one sheet

Question: I'm new and playing around with Google sheet app script.
i'm trying to sheet on onEdit trigger for only one cell (B5). It contains a dropdown list. When staff selects the month (eg. May), it runs the May() script.
The below code works. But when i add an if() it suddenly stops.
Any help will be appreciated!
function onEdit(e) {
  let ss = SpreadsheetApp;
  let activeSheet = ss.getActive().getActiveSheet();
  let dropDownCell = activeSheet.getRange('B5').getValue();
  if (dropDownCell == 'January'){ return Jan() };
  if (dropDownCell == 'February'){ return Feb() }
  if (dropDownCell == 'March'){ return Mar() };
  if (dropDownCell == 'April'){ return Apr() };
  if (dropDownCell == 'May'){ return May() };
  if (dropDownCell == 'June'){ return Jun() };
  if (dropDownCell == 'July'){ return Jul() };
  if (dropDownCell == 'August'){ return Aug() };
  if (dropDownCell == 'September'){ return Sep() };
  if (dropDownCell == 'October'){ return Oct() }
  if (dropDownCell == 'November'){ return Nov() };
  if (dropDownCell == 'December'){ return Dec() };
  }```

Answer: I believe your goal is as follows.

You want to run the script when the cell "B5" is edited.

In this case, how about the following modification? In this modification, the event object e is used.
From:
function onEdit(e) {
  let ss = SpreadsheetApp;

To:
function onEdit(e) {
  const { range } = e;
  const sheet = range.getSheet();
  if (range.getA1Notation() != "B5") return;
  let ss = SpreadsheetApp;

Or, if you want to also check the sheet name, you can also the following modification.
function onEdit(e) {
  const sheetName = "Sheet1"; // Please set the sheet name.
  const { range, value } = e;
  const sheet = range.getSheet();
  if (range.getA1Notation() != "B5" || sheet.getSheetName() != sheetName) return;
  let ss = SpreadsheetApp;

Note:

When I saw your showing script, I thought that your script might be able be simpler. So, how about the following modification?
  function onEdit(e) {
    const sheetName = "Sheet1"; // Please set the sheet name.
    const { range, value } = e;
    const sheet = range.getSheet();
    if (range.getA1Notation() != "B5" || sheet.getSheetName() != sheetName) return;
    const obj = { 'January': Jan, 'February': Feb, 'March': Mar, 'April': Apr, 'May': May, 'June': Jun, 'July': Jul, 'August': Aug, 'September': Sep, 'October': Oct, 'November': Nov, 'December': Dec };
    if (!obj[value]) return;
    obj[value]();
  }

In this modification, the event object e is used. So, please edit the cell "B5" of the sheet. By this, the script is run by the onEdit trigger. If you directly run the script, an error like TypeError: Cannot destructure property 'range' of 'e' as it is undefined. occurs. Please be careful about this.

And, this modified script supposes that your functions of Jan(), Feb() and so on have no methods which cannot be used by the simple trigger. Please be careful about this. If an error related to the permission occurred, please consider using the installable trigger.

References:

Simple Triggers
Event Objects
Comment: whoa. this is my very first post on stackoverflow, and you did not disappoint. Thank you for the alternative suggestion too, it makes the code a lot more tidy.

i was actually able to copy-and-paste the newer code. Didn't need to change (e) to (B5) too
Comment: @Bosty Chan Thank you for replying and testing it. I'm glad your issue was resolved. Thank you, too.


Fragment - 'on navigate back' not bahave the same way as back button

Question: I'm writing android app, using fragments.
There are two main ways to navigate up or back.
picture of the screen

The first is to use the arrow on the navigation bar (marked with the number 1 in the picture)

The second use the system back button (marked with the number 2)

I wrote:
override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
...
        requireActivity().onBackPressedDispatcher.addCallback(this) {
                findNavController().navigate(R.id.action_updateFragment_to_listFragment)
...
}

and it works just fine, but only for system back button(2).
How can I override action caused by click on the back arrow from navigation bar(1)?
thanks!!!
Answer: Ok, I've got this.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if(item.itemId == android.R.id.home) {
            Toast.makeText(requireContext(), "the answer", Toast.LENGTH_SHORT).show()
        }
        return super.onOptionsItemSelected(item)
    }

I hope this post will help someone in the future.


Fast scroll thumb disappears while scrolling AlphabetIndexer

Question: I have a ListView with fastScrollAlwaysVisible and fastScrollEnabled both set to true. After implementing SectionIndexer to my Adapter and an AlphabetIndexer, my fast scroll thumb will disappear while I scroll, then reappear once I reach the top or bottom of the list. I'm pretty clueless about why this happens. I haven't experienced it before.
Everything below works as far as AlphabetIndexer is concerned. My question is why does my fast scroll thumb disappear while I scroll and how can I stop it from disappearing?
Whether or not the fast scroll is always visible doesn't matter. Whenever the fast scroll is visible, the fast scroll thumb is not there, it's simply gone and that's my problem. Also, when I remove the AlphabetIndexer the fast scroll thumb works like I intend for it to. Everything works successfully in an Activity, but when I load my ListView in a Fragment things end up like I explain.
This is my Adapter for my ListView:
private class AlbumsAdapter extends SimpleCursorAdapter implements
        SectionIndexer {

private AlphabetIndexer mIndexer;

// I have to override this because I'm using a `LoaderManager`
@Override
    public Cursor swapCursor(Cursor cursor) {

        if (cursor != null) {
            mIndexer = new MusicAlphabetIndexer(cursor, mAlbumIdx,
                    getResources().getString(R.string.fast_scroll_alphabet));
        }
        return super.swapCursor(cursor);
    }

    @Override
    public Object[] getSections() {
        return mIndexer.getSections();
    }

    @Override
    public int getPositionForSection(int section) {
        return mIndexer.getPositionForSection(section);
    }

    @Override
    public int getSectionForPosition(int position) {
        return 0;
    }
}

MusicAlphabetIndexer helps sort through music correctly:
class MusicAlphabetIndexer extends AlphabetIndexer {

public MusicAlphabetIndexer(Cursor cursor, int sortedColumnIndex,
        CharSequence alphabet) {
    super(cursor, sortedColumnIndex, alphabet);
}

@Override
protected int compare(String word, String letter) {
    String wordKey = MediaStore.Audio.keyFor(word);
    String letterKey = MediaStore.Audio.keyFor(letter);
    if (wordKey.startsWith(letter)) {
        return 0;
    } else {
        return wordKey.compareTo(letterKey);
    }
  }
}

Comment: I am doing something similiar HERE http://stackoverflow.com/questions/10224233/alphabetindexer-with-custom-adapter-managed-by-loadermanager
Comment: I took at your post and didn't see anything wrong. My `SectionIndexer` works and doesn't show as you scroll and it seems you're having the opposite problem, weird. I'm starting to think `Fragments` are the culprit, but I'm unsure how right now. I think they are because my `SectionIndexer` works in a `ListActivity`.
Comment: I'll try to see if I can recreate your issues.
Answer: I had similar issue with fast scroller's thumb icon. I was investigating Android source code and found a commit which introduced this problem and other (ArrayIndexOutOfBoundsException). I built even Android system without this commit and it worked then.
I submitted the issue in June: https://code.google.com/p/android/issues/detail?id=33293
When I'm reading it know I see I could describe the issue better :)
This is the commit which is making problems: https://github.com/android/platform_frameworks_base/commit/32c3a6929af9d63de3bf45a61be6e1a4bde136d3
Unfortunately I haven't found any solution, except revert the commit, and I left it.
I hope someone will find how to fix it.
Comment: Yeah, I suspected that it was a framework bug. I've also seen other apps in the Play Store experience the same thing. I"m glad you posted this.
Answer: Do you have both fastScrollEnabled and fastScrollAlwaysVisible set to true? There is no fastScrollAlwaysEnabled attribute of a ListView, so I'm thinking maybe you just have fastScrollEnabled set to true but fastScrollAlwaysVisible is set to its default value, which is false.
Comment: Oh, wow. That's actually a typo. I did mean `fastScrollAlwaysVisible`. I also have `fastScrollEnabled` set to true. I actually updated my OP a little more. Thanks for commenting, I never would have noticed I made a typo.
Answer: You can check this code:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion <= android.os.Build.VERSION_CODES.FROYO){
    // Do something for froyo and above versions
    list.setFastScrollEnabled(true);

} else if(currentapiVersion > android.os.Build.VERSION_CODES.HONEYCOMB){
    // do something for phones running an SDK before froyo
    list.setFastScrollEnabled(true);
    list.setFastScrollAlwaysVisible(true);
}

Comment: Wow, [that](https://stackoverflow.com/a/30370154/1677912) [code](http://stackoverflow.com/a/29958384/1677912) [gets](http://stackoverflow.com/a/34332188/1677912) [around](http://stackoverflow.com/a/3940823/1677912)! Suggest you provide attribution for code you've found. (The basic structure is from docs, right?)
Comment: [setFastScrollAlwaysVisible](http://developer.android.com/intl/es/reference/android/widget/AbsListView.html#setFastScrollAlwaysVisible(boolean)) -> Set whether or not the fast scroller should always be shown in place of the standard scroll bars.
Answer: Activity
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.AlphabetIndexer;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.SimpleCursorAdapter;

public class TestAct extends Activity {
    /** Called when the activity is first created. */
    ListView test_listView;
    Cursor myCursor;
    String[] proj;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_app_test);

        TestDummyData cTestDummyData = new TestDummyData(
                getApplicationContext());
        cTestDummyData.open();
        cTestDummyData.insertRandomNames();
        myCursor = cTestDummyData.fetchAllData();

        test_listView = (ListView) findViewById(R.id.pager_list_test);
        test_listView.setFastScrollEnabled(true);

        test_listView.setAdapter(

        new MyCursorAdapter(getApplicationContext(),
                android.R.layout.simple_list_item_1, myCursor,
                new String[] { TestDummyData.KEY_NAME },// names
                new int[] { android.R.id.text1 })

        );

        cTestDummyData.close();

    }

    class MyCursorAdapter extends SimpleCursorAdapter implements SectionIndexer {

        AlphabetIndexer alphaIndexer;

        // HashMap<String, Integer> alphaIndexer;
        // String[] sections;
        public MyCursorAdapter(Context context, int layout, Cursor c,
                String[] from, int[] to) {
            super(context, layout, c, from, to);

            alphaIndexer = new AlphabetIndexer(c,
                    myCursor.getColumnIndex(TestDummyData.KEY_NAME),
                    " ABCDEFGHIJKLMNOPQRSTUVWXYZ");
            // ======optional way to get alphaindexer from data
            // alphaIndexer = new HashMap<String, Integer>();
            // int size = items.size();
            //
            // for (int x = 0; x < size; x++) {
            // String s = items.get(x);
            //
            // String ch = s.substring(0, 1);
            //
            // ch = ch.toUpperCase();
            //
            // alphaIndexer.put(ch, x);
            // }
            //
            // Set<String> sectionLetters = alphaIndexer.keySet();
            //
            // ArrayList<String> sectionList = new ArrayList<String>(
            // sectionLetters);
            //
            // Collections.sort(sectionList);
            //
            // sections = new String[sectionList.size()];
            //
            // sectionList.toArray(sections);

        }

        @Override
        public int getPositionForSection(int section) {
            // TODO Auto-generated method stub
            return alphaIndexer.getPositionForSection(section);
        }

        @Override
        public int getSectionForPosition(int position) {
            // TODO Auto-generated method stub
            return alphaIndexer.getSectionForPosition(position);
        }

        @Override
        public Object[] getSections() {
            // TODO Auto-generated method stub
            return alphaIndexer.getSections();
        }

    }

}

Class To use Dummy Data For listing
import java.util.Random;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class TestDummyData {

    static final String KEY_ID = "_id";
    static final String KEY_NAME = "name";

    private static final String DB_NAME = "tutorial";
    private static final String TABLE_NAME = "names";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE = "create table " + TABLE_NAME
            + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME
            + " varchar not null);";

    private Context context;
    private DatabaseHelper dbHelper;
    private SQLiteDatabase db;

    public TestDummyData(Context context) {
        this.context = context;
        this.dbHelper = new DatabaseHelper(this.context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DB_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.v("DBUTIL", "Upgrading database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

    public void open() {
        db = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    public void insertRandomNames() {
        db.execSQL("DELETE FROM " + TABLE_NAME);
        String s = "ANDROIDDEVELOPER";
        Random r = new Random();

        ContentValues values = new ContentValues();
        for (int i = 0; i < 200; i++) {
            values.clear();
            values.put(KEY_NAME, s.substring(r.nextInt(s.length())));
            db.insert(TABLE_NAME, null, values);
        }
    }

    public Cursor fetchAllData() {
        return db.rawQuery("SELECT * FROM " + TABLE_NAME + " ORDER BY "
                + KEY_NAME + " ASC", null);
    }

}

the above class is dummy data clss for common task...
list_app_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<ListView
android:id="@+id/pager_list_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>

</LinearLayout>

you have just give test_listView.setFastScrollEnabled(true);
gvn ans whter i cn understand from ur quest.
Comment: This isn't helpful. I know how to implement a `SectionIndexer`. What I don't know is why the fast scroll thumb disappears while I scroll.
Comment: This is possibly the least useful answer I've ever come across.


Comparison of CPH, accelerated failure time model or neural networks for survival analysis

Question: I am new to survival analysis and I've recently learned that there are different ways to do it given a certain goal. I am interested in actual implementation and appropriateness of these methods.
I was presented with the traditional Cox Proportional-Hazards, Accelerated failure time models and neural networks (multilayer perceptron) as methods to get survival of a patient given their time, status and other medical data. The study is said to be determined in five years and the goal is to give survival risks each year for new records to be given.
I found two instances where other methods where chosen over the Cox PH:

I found "How to get predictions in terms of survival time from a Cox PH model" and it was mentioned that:

If you are particularly interested in obtaining estimates of the probability of survival at particular time points, I would point you towards parametric survival models (aka accelerated failure time models). These are implemented in the survival package for R, and will give you parametric survival time distributions, wherein you can simply plug in the time you are interested in and get back a survival probability.

I went to the recommended site and found one in the survival package - the function survreg.
Neural networks were suggested in this comment:

... One advantage of neural net approaches to survival analysis is that they do not rely on the assumptions that underlie Cox analysis...

Another person with the question "R neural network model with target vector as output containing survival predictions" gave an exhaustive way of determining survival in both neural networks and Cox PH.
The R code for getting the survival would be like this:
mymodel <- neuralnet(T1+T2+T3+T4+T5~covar1+covar2+covar3+..., data=mydata, hidden=1)
compute(mymodel,data=mydata)

I went to the R forums and found this answer in the question "predict.coxph and predict.survreg":

Indeed, from the predict() function of the coxph you cannot get
  directly "time" predictions, but only linear and exponential risk  scores. This is because, in order to get the time, a baseline hazard has to be computed and it is not straightforward since it is implicit in the Cox model.

I was wondering if which of the three (or two considering the arguments over Cox PH) is best for getting survival percentages for time periods of interest? I am confused which of them to use in survival analysis.
Answer: It depends on why you are making models. Two main reasons to construct survival models are (1) to make predictions or (2) to model effect sizes of covariates.
If you want to use them in a predictive setting in which you want to obtain an expected survival time given a set of covariates, neural networks are likely the best choice because they are universal approximators and make less assumptions than the usual (semi-)parametric models. Another option which is less popular but not less powerful is support vector machines.
If you are modelling to quantify effect sizes, neural networks won't be of much use. Both Cox proportional hazards and accelerated failure time models can be used for this goal. Cox PH models are by far the most widely used in clinical settings, in which the hazard ratio gives a measure of effect size for each covariate/interaction. In engineering settings, however, accelerated failure time (AFT) models are the weapon of choice.
Comment: thank you for the answer! You've said it exactly - "_to obtain an expected survival time given a set of covariates_". I'll have to go with the neural networks and SVMs in my study.
Comment: @Marc Claesen I assume neural networks cannot be directly applied to survival analysis problem but the survival analysis problem should be 1st converted to a classification or regression problem. So can you please explain how survival analysis problem can be converted to a classification or regression problem so that neural networks can be applied? Please answer here if possible http://stats.stackexchange.com/questions/199549/how-can-machine-learning-models-gbm-nn-etc-be-used-for-survival-analysis
Comment: @Marc Claesen: The Cox PH model does provide P(survival time > t). Isn't is possible to get the pdf of survival time from there and sample from the pdf?


How to grant sudo rights only to specific script files?

Question: I would like a user to have sudo rights (without password check) to a couple of shell scripts under a specific directory (in my case, /usr/local/tomcat7/bin), and to nowhere else. What's the simplest way to accomplish this?
Something like this in /etc/sudoers didn't seem to work:
jsmith ALL=(ALL) NOPASSWD: /usr/local/tomcat7/bin

Comment: Someone hopes these scripts and the directory are writable only by root since otherwise it's a huge security vulnerability.
Comment: I was searching for this, as I want a user to be able to execute a script using `sudo`, but NOT update the script. Making sure that the directory is writable only via sudo achieves this?
Answer: I think you are almost there. put a / at the end of your directory spec
jsmith ALL=(ALL) NOPASSWD: /usr/local/tomcat7/bin/

From the sudoers man page

A directory is a fully qualified path name ending in a '/'. When you
  specify a directory in a Cmnd_List, the user will be able to run any
  file within that directory (but not in any subdirectories therein).
Comment: Thanks (to both answerers), got it working! Note to self: need to invoke the scripts directly (e.g. `sudo catalina.sh stop`) - this doesn't work: `sudo sh catalina.sh stop`.
Answer: Add a slash '/' to the end of the path.
jsmith ALL=(ALL) NOPASSWD: /usr/local/tomcat7/bin/


GridView and CheckBoxList with UpdatePanel in asp.net (C#)

Question: I have an CheckBoxList within UpdatePanel which has onselectedindex change event on this event i have to update my gridview by fetching data from database. Event perform well but GridView not showing updated data may be because of GridView not in updatepanel.
Actually my problem is data not updated in gridview after firing onselectedindexchanged of Checkboxlist, and i cannot put gridview inside the updatepanel(its mandatory for me).
onselectedindexchanged event working fine i am already checked it out. So how can i update my gridview data.
Here is my code
<asp:UpdatePanel ID="MonthUpdatePanel" runat="server">
    <ContentTemplate>
       <asp:CheckBoxList ID="MonthCheckBoxList" runat="server" AutoPostBack="True"
         onselectedindexchanged="MonthCheckBoxList_SelectedIndexChanged"
       Width="195px"  onclick="updateviewmore()" >
       <asp:ListItem Value="1">1 Month</asp:ListItem>
       <asp:ListItem Value="2">2 Month</asp:ListItem>
       <asp:ListItem Value="6">6 Month</asp:ListItem>
       <asp:ListItem Value="12">1 Year</asp:ListItem>
       </asp:CheckBoxList>
   </ContentTemplate>
 </asp:UpdatePanel>

 <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false"  Width="100%"
     GridLines="None" onrowdatabound="GridView2_RowDataBound"
     ShowHeader="False">
      <Columns>
          <asp:TemplateField>
            <ItemTemplate>

                 <asp:Label ID="BookImageName" Text='<% #"../BookImages/"+ Eval("BookImage") %>'           CssClass="BookImage" runat="server" Height="180px" Width="135px" />

       </ItemTemplate>
     </asp:TemplateField>
    </Columns>
 </asp:GridView>

Answer: Unfortunately, you can't do that. Not if the GridView is outside the UpdatePanel. Your options are:

Remove the UpdatePanel and use full postbacks
Add a PostbackTrigger to the UpdatePanel and specify the CheckboxList as triger element...this is similar to the above...it'll always cause a full postback
Put the GridView inside the UpdatePanel and everything will be done in an async postback
Move the CheckboxList outside of the UpdatePanel, then put the GridView inside the UpdatePanel and add an AsyncPostbackTrigger for the CheckboxList so the UpdatePanel gets update asynchronously when and item is checked

The bottom line is, if you want to re-bind the GridView asynchronously then you'll have to move it inside the UpdatePanel or else you'll have to go with full postback approach
A Hardcore Solution
You can still do everything manually with the help of the jQuery plugin, a UserControl and an http handler that you could create to serve the necessary html. That is, intercept the html requests from client-side, make an async request to the handler passing some parameters so that the handler knows how to tell the UserControl how to bind the GridView...of course, the GridView will be inside a UserControl
The handler can write the output of a UserControl to the response using Execute method of the HttpServerUtility class instance which is available in the current HttpContext. For example...
public class YourHandler: IHttpHandler {
    public void ProcessRequest(HttpContext ctx){
        StringWriter writer = new StringWriter();
        ctx.Server.Execute("~/UserControl.ascx", output, false);
        ctx.Response.Write(writer);
    }
}

This method effective works as if the UserControl was passing through all the ASP.NET pipeline cycles during a normal request and its context will be exactly the same context of the http handler...so, if you're using built-in asp.net membership features make sure to use a generic handler (.ashx) which plugs into the ASP.NET pipeline by itself with no further effort from your side


Executar jQuery para selecionar Solicitante

Question: Tenho o seguinte jQuery:
function clienteChange() {
    var id = $('#idCliente').val();
    $.ajax(
    {
        url:"/Administrar/clientes.endereco.php?id=" + id,
        dataType : 'json',
        success:function(result) {
            $('[name^="cham_endereco[]"]').val(result.endereco);
            $('[name^="cham_numero[]"]').val(result.numero);
            $('[name^="cham_bairro[]"]').val(result.bairro);
            $('[name^="cham_cidade[]"]').val(result.cidade);
        }
    });

    var selectSolicitante = jQuery(id).parents('tr').find('select.selectSolicitante');
    selectSolicitante.html('<option value="0">Carregando...</option>');
    $.post("/Administrar/clientes.solicitante.php?idCliente=" + id,
        {solicitante:jQuery(id).val()},
        function(valor){
            selectSolicitante.html(valor);
        }
    );
}

O primeiro bloco funciona corretamente, exibe certinho os dados no endereço, número... Queria que ao selecionar o cliente, executasse esse primeiro bloco mas também executasse o segundo bloco, buscando os solicitantes précadastrados... Fiz o teste, mas não funciona.
Segue o PHP também:
    mysql_query("SET NAMES 'utf8'");
    mysql_query('SET character_set_connection=utf8');
    mysql_query('SET character_set_client=utf8');
    mysql_query('SET character_set_results=utf8');

    echo "<option>teste</option>";

A tela de cadastro é esta:
Comment: Qual teste você fez?
Comment: Selecionei o cliente normal... E no console não retornou nada de erros também... Mas não exibe também as opções do campo. Coloquei um print do formulário para entender melhor.
Comment: Teria que retornar o teste...
Comment: Em que momento você executa a função `clienteChange()`?
Comment:
Comment: Mas qual é esse `select` na sua tela?
Comment: Neste momento, eu executo ele... tipo, ele exibe certinho o endereço do cliente, quando seleciona, mas queria que ao selecionar o cliente, carregasse também o solicitante
Comment: Este select que eu te passei, é o "Cliente"
Comment: O código `$.post("/Administrar/clientes.solicitante.php?idCliente=" + id,` é executado? Outra dúvida, porque é um método `POST` e você passa a variável na `URL`?
Comment: Verdade, posso tirar o GET, mas ele executa a url sim.
Comment: Você consegue verificar utilizando `console.log(valor)` antes de `selectSolicitante.html(valor);`? Você já verificou se esta enviando o `id`?
Comment: teste Retornou este no console, mas, no campo não
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/26743/discussion-between-andre-baill-and-gerep).
Answer: Verifique se o seu comando var selectSolicitante = jQuery(id).parents('tr').find('select.selectSolicitante'); esta realmente retornando o elemento que você procura.
Minha sugestão é, se possível, dar um id ou uma class ao seu elemento, deixando seu código assim:
    $(".selectSolicitante").html('<option value="0">Carregando...</option>');
    $.post("/Administrar/clientes.solicitante.php?idCliente=" + id,
        {solicitante:jQuery(id).val()},
        function(valor){
            $(".selectSolicitante").html(valor);
        }
    );

É importante deixar o html(valor) porque desse modo, quando o seu post retornar os valores que você precisa, ele vai remover o Carregando da sua select
Comment: Deu certo, fico grato pela ajuda!


Como comparar mais de uma coluna numa clausula IN?

Question: Existe uma maneira de comparar >= 2 colunas em uma cláusula IN tipo como se fosse comparar objetos?
Por exemplo(Vai dar erro por isso a pergunta)
SELECT * FROM Usuarios1 WHERE Nome,Sobrenome IN(SELECT Nome,Sobrenome from Usuarios2);

ou seria algo do tipo
SELECT * FROM Usuarios1 WHERE Nome,Sobrenome IN(('Leo','Bonetti'),('José','Silva'));
Answer: Infelizmente, não há como usar o IN para comparar registros por mais de uma coluna. Porém, você pode criar uma tabela anônima a partir de uma subquery e fazer um join nas colunas equivalentes:

SELECT *
FROM Usuarios1 este
INNER JOIN (
  SELECT Nome, Sobrenome
  FROM Usuarios2) outro
ON este.Nome = outro.Nome AND este.Sobrenome = outro.Sobrenome


Override host in TinyMCE (or CKEditor) Rich Text Edit

Question: I am currently trying to integrate a RIch Text Editor in an application I am working on. So far, I have tested CKEditor and TinyMCE editor. Assume my application is hosted at http://example.com. I have a constraint in my deployment environment that makes it impossible to serve static assets. For this reason, static assets use a different host which is http://assets.example.com.
I have realized that TinyMCE (as well as CKEditor) dynamically appends


Knapsack problem with values per item and limited items

Question: I'm trying to solve a variant of knapsack problem that i haven't seen before.
in this variant we have a vector v consist of values per gram for each item and we also have a limited weight of each item and our goal is to find the maximum value that can be gain if we have a pack of size M.
I tried greedy approached but haven't found any solution. i think the most difficult part is to do it in O(n) because we shouldn't sort anything.
anyone has any idea?
Comment: If the value per gram has reasonably narrow bounds, you can counting-sort or radix-sort or bucket-sort it in linear time by the value per gram, and then just fill up the bucket in order of most valuable substances. Are there reasonable limits on the value per gram?
Comment: Possible duplicate of [Knapsack Algorithm using decimal values?](https://stackoverflow.com/questions/36502507/knapsack-algorithm-using-decimal-values)
Comment: @Patrick87 It seems that your answer is correct please post it as an answer so i can mark it as correct,thanks!
Answer: If the value per gram has reasonably narrow bounds, you can counting-sort or radix-sort or bucket-sort it in linear time by the value per gram, and then just fill up the bucket in order of most valuable substances. What do I mean by reasonable limits? Specifically, I mean that there are asymptotically fewer meaningful "values per gram" than there are kinds of substances.


Is $X_\tau$ measurable wrt $\mathcal F_\tau$? Even without any measurability assumption on $X_\infty$?

Question: Let

$(\Omega,\mathcal A)$ be a measurable space;
$(\mathcal F_t)_{t\ge0}$ be a filtration on $(\Omega,\mathcal A)$ and $$\mathcal F_\infty:=\sigma(\mathcal F_t,t\ge0);$$
$\tau$ be an $(\mathcal F_t)_{t\ge0}$-stopping time on $(\Omega,\mathcal A)$
$(E,\mathcal E)$ be a measurable space;
$(X_t)_{t\ge0}$ be an $(\mathcal F_t)_{t\ge0}$-progressive $(E,\mathcal E)$-valued process on $(\Omega,\mathcal A)$;
$X_\infty:\Omega\to E$.

Am I missing something or is $X_\infty$ always $\mathcal F_\tau$-measurable; without any measurability assumption on $X_\infty$?
In fact, this should be true, since $(\tau\wedge t)_{t\ge0}$ is $(\mathcal F_t)_{t\ge0}$-adapted, we easily see that $(X_{\tau\wedge t})_{t\ge0}$ is $(\mathcal F_t)_{t\ge0}$-adapted as well.
By introduction of $X_\infty$, $X_\infty$ is a well-defined function; even on $\{\tau=\infty\}$. And the former adaptedness result shows that $$\{X_\tau\in B\}\cap\{\tau\le t\}=\{X_{\tau\wedge t}\in B\}\cap\{\tau\le t\}\in\mathcal F_t\;\;\;\text{for all }t\ge0\tag1$$ and hence $$\{X_\tau\in B\}\in\mathcal F_\tau\tag2$$ for all $B\in\mathcal E$.
(the natural assumption would clearly be that $X_\infty$ is $\mathcal F_\infty$-measurable, since then $(X_t)_{t\in[0,\:\infty]}$ is $(\mathcal F_t)_{t\in[0,\:\infty]}$-adapted)
Comment: I don't see any definition of $X_\infty$, what is it?
Comment: @Ilya It is defined in the list; it is a function $\Omega\to E$.
Comment: There it looks just like it's any function. That's your point? You're asking whether any function will be $\mathcal F_\tau$-measurable? The answer is of course: no
Comment: No, I don't claim that any function is $\mathcal F_\tau$-measurable, but that it doesn't matter what $X_\infty$ is. However, I think I've noticed what my mistake was. See my comment below [John Dawkins' answer](https://math.stackexchange.com/a/4443262/47771).
Answer: You have argued that the restriction of $X_\tau$ to $\{\tau<\infty\}$ is $\mathcal F_\tau\cap\{\tau<\infty\}$ measurable. But you have shown nothing about $X_\tau$ ($=X_\infty$) on $\{\tau=\infty\}$.
Comment: But $$\mathcal F_\tau=\{A\in\mathcal A:A\cap\{\tau\le t\}\in\mathcal F_t\text{ for all }t\ge0\}.$$ I guess the crucial thing I've missed is that I sitll need to verify $\{X_\tau\in B\}\in\mathcal A$ for all $B\in\mathcal E$, right? But wouldn't it then be enough to assume that $X_\infty$ is $\mathcal A$-measurable (instead of even $\mathcal F_\infty$-measurable)?
Comment: You need to verify that $\{X_\tau\in B\}\cap\{\tau=\infty\}$ is $\mathcal F_\infty$ measurable. That is, to show that $\{X_\infty\in B\}\cap\{\tau=\infty\}\in\mathcal F_\infty$.


What is the degrees of freedom of a linear model when some of the variables sum to 1?

Question: If I have a linear model
$$ y_i = \beta_0 +\beta_1 X_{1i} + \beta_2X_{2i} + \beta_3X_{3i} + \beta_4X_{4i}+ \beta_5X_{5i}+\beta_6X_{6i} + \epsilon_i$$
the degrees of freedom is $n-(6+1)$ because I have intercept + six parameters.
However, I have a model where part of the model sums to 0, e.g. $X_{1i}+X_{2i}+X_{3i} = 0$ and $X_{4i}+X_{5i}+X_{6i} = 0$.
Since in this case when $\beta_1 X_{1i}$ and $\beta_2X_{2i}$ are estimated $\beta_3X_{3i}$ is not free anymore,
does this change my degrees of freedom to be $n-5$?
Comment: https://stats.stackexchange.com/questions/418181 answers your questions in terms of "dropping columns."
Answer: You describe a strict linear dependence among your predictors, which is dangerous and won't provide a unique solution for all the coefficients. As you describe it you only have 4 linearly independent predictors, not 6.
If you are succeeding in fitting your data with this model, your software might be arbitrarily (maybe even silently) removing predictors from your model to allow a solution. For example, perhaps $X_{3t}$ and $X_{6t}$ and their coefficients were removed, as they were the last offending predictors entered into your model. Yes, then you are only fitting 4 predictor coefficients plus the intercept, for $n-5$ degrees of freedom.
The best idea here is not to specify a model where you know that the predictors are linearly dependent, as with linearly dependent predictors you won't necessarily get the same coefficients with different software or with a different order of predictors in your model or data set, even if the model fits at all. Unexpected near-dependence arising from predictor multicollinearity can be bad enough; there's no need to compound the problem with deliberate linear dependence.


Need help for turn this form $\neg ((p \Rightarrow q) \Rightarrow r)$ into DNF

Question: How can I turn this form

$\neg( ( p \Rightarrow q ) \Rightarrow r )$

to  disjunctive normal form  and to the disjunctive normal form fully developed ?
I have done the truth table see below

I arrived to this form :   $(\neg p \vee q) \wedge r$   but I am not sure if it is correct and if I had developed enough
Thanks for your help !
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Please ask only one question per post. Having multiple questions in the same post is discouraged and such posts may be closed, see [meta](https://math.meta.stackexchange.com/q/6464).
Answer:
I arrived to this form :   $(\neg p \vee q) \wedge r$   but I am not sure if it is correct and if I had developed enough

This is not correct. Hint: $\sf~\neg(A\to B) \equiv A\wedge\neg B~$ by implication negation.


React native camera detecting face

Question: Does anyone know how to enable the React-native-camera face detection feature?
I've followed the guide on https://github.com/react-native-community/react-native-camera such as importing and changing the line on package.json but still don't see anything happening to my camera when it is in front of a face
Answer: react-native-camera doesn't do anything on its own to let you know that the face detection is working. It is up to you to do something with the data it provides.
This code snippet would show some text when a face is detected, for example:
<code>constructor(props) {
    super(props);
    this.state = { isFaceDetected: false };
}

handleFaceDetected = faceArray => {
    this.setState(state => { ...state, isFaceDetected: true });
};

// ...

<RNCamera
    faceDetectionMode={RNCamera.Constants.FaceDetection.Mode.fast}
    onFacesDetected={this.handleFaceDetected}
/>
{this.state.isFaceDetected && (<Text>I saw a face</Text>)}
</code>
See the react-native-camera face-detection documentation for more details.
Comment: undefined is not an object (evaluating '_reactNativeCamera.RNCamera.Constants.FaceDetection.Mode.accurate')

Which is odd because my camera works just fine and i take photo's using the library the constants exists I just don't know why adding this line of code breaks it and it shouldn't.

React native camera detecting face


The field is ambiguous while it is clearly hidden

Question: I know and fully agree that sharing constants through interfaces is considered as a bad practice, but I didn't choose this implementation. Whatever:
interface SuperClassConstants {
    public static final String CONSTANT = "super";
}

interface SubClassConstants extends SuperClassConstants {
    public static final String CONSTANT = "sub";
}

class SuperClass implements SuperClassConstants {
}

class SubClass extends SuperClass implements SubClassConstants {
    public SubClass() {
        System.out.println(CONSTANT);
        // The field CONSTANT is ambiguous
    }
}

Why ambiguous? Isn't the constant hidden? I thought Java would have understood I was expecting "sub"...
Comment: But your `SubClass` class can access to both interfaces...
Answer: As per the JLS 9.3:

If two fields with the same name are inherited by an interface because, for example, two of its direct superinterfaces declare fields with that name, then a single ambiguous member results. Any use of this ambiguous member will result in a compile-time error.

The field CONSTANT in SubClassConstants has hidden the CONSTANT of SuperClassConstants. But the class SubClass has access to both the CONSTANT as it virtually implements both the interfaces.
You can remove the ambiguity by specifying the Interface name :
System.out.println(SubClassConstants.CONSTANT);

Also read JLS 188.8.131.52:

If an expression name consists of a single Identifier, then there must be exactly one declaration denoting either a local variable, parameter, or field visible (§6.4.1) at the point at which the Identifier occurs. Otherwise, a compile-time error occurs.


Central limit theorem when the mean is not constant

Question: I've heard that there is a soft version or interpretation of the CLT that says —in summary— that it can be applied also to a sequence of independent real-valued random variables that share the same distribution shape but not the mean (for instance, a sequence of $n$ normal variables $X_i \sim N(\mu_i, \sigma)$ where $\mu_i$ can be different for each $i$).
Is that right? Where can I find it (textbook or article)?
And, a last one: In this case (where $X_i$ are independently and equally distributed except for their means), what would the distribution of $Y=\frac{1}{n}\sum_{i=1}^n{X_i}$ approximately be, according to CLT?

EDIT:
I want to stress that $X_i\sim N(\mu_i,\sigma)$ was just an example.
What I have is $X_i \sim F_i$, where $F_i$ stands for the CDF of $X_i$, and where all $F_i$'s are equal to the same distribution (with a known constant variance $\sigma^2$) except for the fact that they have different averages $\mu_i$.

EDIT:
Just to make it clearer, what I would like to know is whether or not it is correct to state this:
$Y=\frac{1}{n}\sum_{i=1}^n{X_i}$ is approximately distributed as $N(\mu_Y,\sigma_Y)$, where

$\mu_Y$ can be estimated as $\bar{x} = \frac{x_1+ \cdots + x_n}{n}$ and
$\sigma_Y$ can be estimated as $\frac{s}{\sqrt{n}}$, $s$ being the sample (quasi)standard deviation,

using a random sample $(x_1, \dots, x_n)$ of $(X_1, \dots, X_n)$.
Comment: What do you know about $\mu_i$?
Comment: You don't need a CLT for independent normal variables; $X_1 + X_2 \sim N(\mu_1 + \mu_2, \sigma_1 ^2+ \sigma_2^2)$ and so on.
Comment: Google "Lindeberg Feller central limit theorem"
Comment: See these Wikipedia links [1](https://en.wikipedia.org/wiki/Central_limit_theorem#Lyapunov_CLT) [2](https://en.wikipedia.org/wiki/Central_limit_theorem#Lindeberg_CLT)
Comment: @Emre, that is a good question. All what we know about $\mu_i$ is that it is not constant. We can assume that there is a kind of *underlying central* $\mu$ which could be estimated as the average $\bar{x}=\frac{x_1+\dotsc+x_n}{n}$, where $x_i$ is an observation from $X_i$.
Comment: @Student001, see my edit above.
Comment: The distributions don't need to be the same shape.
Answer: A precise reference for the Lindeberg-Feller CLT is Theorem 4.12 in Foundations of Modern Probability by Olav Kallenberg.  I paraphrase it below:

Let $(\xi_{n,j}; j = 1,\ldots,n)_{n=1}^\infty$ be a triangular array
  of row-wise independent random variables with mean $0$ and
  $\sum_{j=1}^n \mathbb{E}[\xi_{n,j}^2] \to 1$ as $n\to\infty$.
Suppose that for any $\epsilon > 0$ we have
  $\sum_{j=1}^n \mathbb{E}[\xi_{n,j}^2; |\xi_{n,j}|>\epsilon] \to 0$.  (*)
Then $\sum_{j=1}^n \xi_{n,j} \overset{d}{\to} N(0,1)$.

Suppose the $X_i$ are arbitrary independent random variables. Let $\mu_j = \mathbb{E}[X_j]$ and $\sigma_j^2 = Var[X_j]$.
Take $\xi_{n,j} = \frac{X_j - \mu_j}{\sqrt{\sum_{i = 1}^n \sigma_i^2}}$.  Then the theorem says
$$
\frac{1}{\sqrt{\sum_{i = 1}^n \sigma_i^2}} \sum_{j = 1}^n (X_j - \mu_j) \overset{d}{\to} N(0,1),
$$
and thus
$$
\frac{1}{\sqrt{n}} \sum_{j=1}^n (X_j - \mu_j) \overset{d}{\to} N(0,\sigma^2)
$$
if the limit $\sigma^2 = \lim_{n\to\infty}\sum_{i=1}^n \sigma_i^2 / n$ exists.  To put in another way, the sample mean $Y_n = \frac{1}{n} \sum_{i=1}^n X_i$ satisfies
$$
\sqrt{n}(Y_n - \frac{1}{n}\sum_{i=1}^n \mu_i)  \overset{d}{\to} N(0,\sigma^2),
$$
i.e. $Y_n$ has approximate distribution $N(\frac{1}{n}\sum_{i=1}^n \mu_i, \sigma^2/n)$.  However, be warned that the theorem does not say exactly what the rate of convergence is!
I leave it as an exercise for you to see what the Lindeberg condition (*) is.
Comment: More or less- see expanded answer.
Comment: Therefore, just to be sure, does this mean that the distribution of $Y=\frac{1}{n}\sum_{i=1}^n{X_i}$ asymptotically tends to a normal distribution with mean $\mu=\frac{1}{n}\sum_{i=1}^n{E[X_i]}$ and standard deviation $\sigma= \frac{\sqrt{\sum_{i=1}^n{Var[X_i]}}}{n} $? See also my last edit above, please.
Comment: Your $\mu$ and $\sigma$ here are not limiting values...  do you mean $\mu = \lim_{n\to\infty} \frac{1}{n} \sum_{i=1}^n \mathbb{E}[X_i]$? (assuming the limit exists, and similar for $\sigma$)
Comment: So, $\mu_Y = \lim_{n \rightarrow +\infty}{\frac{1}{n}\sum_{i=1}^n{E[X_i]}}$ and $\sigma_Y = \lim_{n \rightarrow +\infty}{\frac{1}{n}\sqrt{\sum_{i=1}^n{Var[X_i]}}}$ would be right, in case those limits exist. Isn't that?
Comment: And, about my last edition in the original question, could $\mu_Y$ and $\sigma_Y$ be approximated by $\bar{x}$ and $\frac{s}{\sqrt{n}}$ from a sample $(x_1,\dots,x_n)$ of $(X_1,\dots,X_n)$ ??
Comment: OK.  Just for a moment consider the simpler case that the $X_i$ are i.i.d.  Then what is the limit of $Y_n = \frac{1}{n} \sum_{i=1}^n X_i$? [Apologies if it seems I'm making you jump through hoops here, and I also fixed a minor typo in my answer with $\sqrt{n}$ scaling! :)]
Comment: Next consider the case that the variances are all equal, i.e. $\sigma_i = \sigma$ for every $i$.
Comment: I know what you mean... If $X_i$ are i.i.d. with $E[X_i]= \mu$ and $E[X_i]= \sigma^2$ , then for $Y_n=\frac{1}{n} \sum_{i=1}^n{X_i}$ it would be true that $E[Y_n]= \frac{1}{n} \sum_{i=1}^n{E[X_i]} = \mu$ and $Var[Y_n] = \cdots = \frac{1}{n}\sigma^2$...
Comment: yes, I know what you mean, but you also mentioned that "The random variables can have different distributions". In that case (the most general case, let us say), how would you estimate or approximate the mean and the standard deviation of $Y_n$ using a sample? I just want to be sure I am not wrong about my guesses...
Comment: So $Var[Y_n] = \sigma^2/n \to 0$ and $Y_n \to \mu$ by the LLN.  To get the fluctuations of $Y_n$ around $\mu$ you need $\sqrt{n}$ scaling, i.e. $\sqrt{n}(Y_n - \mu) \to N(0,\sigma^2)$.
Comment: In your last comment, would it be equivalent to say that $(Y_n-\mu) \rightarrow$ Normal with mean $\mu$ and standard deviation $\sigma/\sqrt{n}$?
Comment: And therefore I am right... I can estimate or approximate the mean of $Y_n$ using $\bar{x}$ and can approximate the standard deviation of $Y_n$ using $\frac{s}{\sqrt{n}}$, from a sample $(x_1, \dots, x_n)$ of $(X_1, \dots, X_n)$. Am I right???
Comment: thank you for your effort in answering my question and explaining me everything! As a final conclusion, although the convergence rate is unknown, I can apply Lindeberg-Feller CLT to state that ("more or less"), $\bar{x}$ and $s/\sqrt{n}$ are valid approximations for the mean and the standard deviation of $Y_n$, can't I?
Comment: A last comment/question:  In my concrete case, $n=15$ or so, and the $X_i$ variables are known to follow a Beta distribution, but are not i.i.d. I think I can apply this theorem. I don't know how to estimate an upper bound for the error for $n=15$. Also, I don't know if there is a better approximation for the concrete case of the sum of not i.i.d. Betas.

I can open a new question for this, if your think it is better.
Comment: I would like to draw your attention to the second part of the question, which can be found here:  http://stats.stackexchange.com/questions/157428/approximating-the-distribution-of-a-linear-combination-of-beta-distributed-indep


Error 400: Bad request in Amazon SageMaker Ground Truth text Labeling task

Question: I am trying to use Amazon AWS to annotate my text data. It's a csv of 10 rows include header : "orgiginalText, replyText" and text data. I put my data in s3 bucker, create IAM with S3, sageMaker FullAccees. When I want to 'Create labeling job', it gave me error 400 Badrequest to connect to S3. is there anything else to be considered? I stucked 2 days in this small task and can't go forward.
Answer: Few things to check:

Can you access the S3 bucket from other means? Like AWS CLI from your local machine or from an EC2 instance?
Can you access the S3 bucket from a SageMaker notebook instance using the same execution role you created for SageMaker GroundTruth?
Does this issue persist with a particular bucket? Did you try creating another bucket, copy the data there and point to this S3 bucket instead?
Are you using the S3 bucket and Groundtruth labeling job in the same AWS region?

The 400 error can be due to variety of reasons. From S3 perspective, it may happen due to the bucket being in a transitioned state like creating/deleting etc.
From SageMaker's point, it can be due to many reasons few of which are listed here: https://docs.amazonaws.cn/sagemaker/latest/APIReference/CommonErrors.html
Please try the above approaches and let me know your findings.


Squid proxy not caching anything

Question: squid.conf:
http_access allow all

# Squid normally listens to port 3128
http_port 3128 accel defaultsite=localhost no-vhost

cache_peer localhost parent 80 0 no-query originserver name=myAccel
cache_peer_access myAccel allow all

# Uncomment and adjust the following to add a disk cache directory.
cache_dir ufs /usr/local/var/cache/squid 100 16 256

# Leave coredumps in the first cache dir
coredump_dir /usr/local/var/cache/squid

Squid 3.2.9, installed on OSX via Homebrew
localhost: ~ $ squid -v
Squid Cache: Version 3.2.9
configure options:  '--disable-debug' '--disable-dependency-tracking' '--prefix=/usr/local/Cellar/squid/3.2.9' '--localstatedir=/usr/local/var' 'CC=cc' 'CXX=c++' 'PKG_CONFIG_LIBDIR=/usr/lib/pkgconfig'

Started squid with squid -f squid.conf -d 2 -N
The upstream is returning valid Cache-Control headers, which I've verified are correct by visiting the page in Google Chrome 26 and watching in Chrome Dev Tools.
localhost: ~ $ curl -s -o /dev/null --dump-header /dev/stdout  http://localhost/test.php
HTTP/1.1 200 OK
Date: Tue, 16 Apr 2013 21:29:33 GMT
Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.3.15 with Suhosin-Patch mod_ssl/2.2.22 OpenSSL/0.9.8r
X-Powered-By: PHP/5.3.15
Cache-Control: max-age=60, public
Content-Length: 16
Content-Type: text/html
X-Pad: avoid browser bug

But when I query the page via the Squid reverse proxy, I always get a cache miss.
localhost: ~ $ curl -s -o /dev/null --dump-header /dev/stdout  http://localhost:3128/test.php
HTTP/1.1 200 OK
Date: Tue, 16 Apr 2013 21:29:34 GMT
Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.3.15 with Suhosin-Patch mod_ssl/2.2.22 OpenSSL/0.9.8r
X-Powered-By: PHP/5.3.15
Cache-Control: max-age=60, public
Content-Length: 16
Content-Type: text/html
X-Cache: MISS from localhost
Via: 1.1 localhost (squid/3.2.9)
Connection: keep-alive

localhost: ~ $ curl -s -o /dev/null --dump-header /dev/stdout  http://localhost:3128/test.php
HTTP/1.1 200 OK
Date: Tue, 16 Apr 2013 21:29:38 GMT
Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.3.15 with Suhosin-Patch mod_ssl/2.2.22 OpenSSL/0.9.8r
X-Powered-By: PHP/5.3.15
Cache-Control: max-age=60, public
Content-Length: 16
Content-Type: text/html
X-Cache: MISS from localhost
Via: 1.1 localhost (squid/3.2.9)
Connection: keep-alive

What's wrong with my configuration?
Comment: The cache-control header sets max-age to 60, which is the same as squid's default `minimum_expiry_time` - try tweaking this value in squid.
Answer: Oh, crap, I figured it out.
Squid ignores cache headers less than OR EQUAL TO one minute. So max-age=60 is ignored, but max-age=61 works like a charm.
<?php
Header('Cache-Control: max-age=61');

?>hi

Comment: `minimum_expiry_time`, yes. (You got it right in the comment to the question.)
Comment: Or you can tweak `maximum_expiry_time` in squid - which is recommended for this type of environment. :-)

Squid proxy not caching anything


Blocking an IP in Webmin

Question: I've been checking my /var/log/secure log recently and have seen the same bot trying to brute force onto my Centos server running webmin.
I created a chain + rule in Networking -> Linux Firewall:
Drop    If source is 188.8.131.52

But I'm still seeing the attempted logins in the log:
Jun  6 10:52:18 CentOS5 sshd[9711]: pam_unix(sshd:auth): check pass; user unknown
Jun  6 10:52:18 CentOS5 sshd[9711]: pam_succeed_if(sshd:auth): error retrieving information about user larry
Jun  6 10:52:19 CentOS5 sshd[9711]: Failed password for invalid user larry from 18.104.22.168 port 49328 ssh2

Here is the contents of /etc/sysconfig/iptables:
# Generated by webmin
*filter
:banned-ips - [0:0]
-A INPUT -p udp -m udp --dport ftp-data -j ACCEPT
-A INPUT -p udp -m udp --dport ftp -j ACCEPT
-A INPUT -p udp -m udp --dport domain -j ACCEPT
-A INPUT -p tcp -m tcp --dport 20000 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 10000 -j ACCEPT
-A INPUT -p tcp -m tcp --dport https -j ACCEPT
-A INPUT -p tcp -m tcp --dport http -j ACCEPT
-A INPUT -p tcp -m tcp --dport imaps -j ACCEPT
-A INPUT -p tcp -m tcp --dport imap -j ACCEPT
-A INPUT -p tcp -m tcp --dport pop3s -j ACCEPT
-A INPUT -p tcp -m tcp --dport pop3 -j ACCEPT
-A INPUT -p tcp -m tcp --dport ftp-data -j ACCEPT
-A INPUT -p tcp -m tcp --dport ftp -j ACCEPT
-A INPUT -p tcp -m tcp --dport domain -j ACCEPT
-A INPUT -p tcp -m tcp --dport smtp -j ACCEPT
-A INPUT -p tcp -m tcp --dport ssh -j ACCEPT
-A banned-ips -s 22.214.171.124 -j DROP
COMMIT
# Completed
# Generated by webmin
*mangle
:FORWARD ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
# Completed
# Generated by webmin
*nat
:OUTPUT ACCEPT [0:0]
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
# Completed

Comment: Your chain *banned-ips* doesn't seem to be linked to the INPUT chain. Try `iptables -I INPUT -j banned-ips`
Comment: Any reason you put both "-m tcp" and "-p tcp"? One of them should be enough, shouldn't it?
Answer: I would :
1.doublechechk if it's the same ip
2.allow only from your IP
3.change webmin port to a random one
Comment: 1: Yes - you can see yourself the log IP is the same as the rule IP
2: Not something I'd like to do - I access my server from multiple machines, one of which is a dynamic IP
3: Webmin GUI is currently running on port 10000 - the bot is trying 3~ ports none of which are that port

Ideally I just want to lock a host out after 5 - 10 failed attempts for a day. I know cPanel had better brute force protection. This is just a temporary stopgap till I find something similar
Comment: 2. You could allow a hole range of ip's that you currently use on the specific port , and deny all others (-A INPUT -p tcp -m tcp --dport ssh -j ACCEPT 193.x.x.x and drop all others on the webmin port . It's a good general rule to have the firewall on deny all and allow only the ports that you are using from specific IP ranges - like country / provider specific if you can't give only one IP . . Then he can test all the ports that he wants :) .
Answer: I went and installed ConfigServer Firewall - the bot got banned within minutes of installing it.
http://www.configserver.com/free/csf/install.txt
@ripat You may be correct in why my rule was not being picked up - I think Webmin's UI is at a disjoint to what iptables requires.

Blocking an IP in Webmin


Offensive rebounding % on missed 3FG vs 2FG (NBA)

Question:
Amongst missed 3FG, what % are rebounded by the offensive team?
Amongst missed 2FG, what % are rebounded by the offensive team?

Is there a significant difference between these two percentages?
Answer:
The great Kirk Goldsberry included this graphic in his (in)famous article on the "Kobe Assist."1 It looks like 2-point field goals are more likely to be rebounded by the offensive team than are 3-point field goals, but this depends on team and precise location.
Comment: Can you link to the original article/source?
Comment: That is a good answer.  Of course if you shoot 2 feet from basket there is a really good chance you would get your miss.  Also most blocked shots happen closer to the basket.  If you get your own shot that was blocked you get an offensive board.


Run a for loop over a list, save each list object in output matrix

Question: I want to run a for loop over a list. I have 3 questions:

I wonder how I select  each list in "i in 1:list", when doing the same for a data frame it can be for(i in 1:ncol(df)), but how should this be written for a list?
I also wonder how I could "add on" the values for each loop to the " output" matrix?
How to convert a list to a data frame. When doing it like data.frame(df3) they will be added column wise, number of rows will always be 3.

Many thanks if someone has suggestions!
    name <- rep("gg",3)
id <- LETTERS[1:3]
emmeans <- runif(1:3)
SE <- runif(1:3)
p <- rep(c(0.001),3)
df <- data.frame(name,id, emmeans,p)
df
df  <- list(df)

name <- rep("ff",3)
id <- LETTERS[1:3]
emmeans <- runif(1:3)
SE <- runif(1:3)
p <- rep(c(0.003),3)

df2 <- data.frame(name,id, emmeans,p)
df2 <- list(df2)

df3 <- list(df,df2)
df3
> df3
[[1]]
[[1]][[1]]
  name id   emmeans     p
1   gg  A 0.2248491 0.001
2   gg  B 0.4213938 0.001
3   gg  C 0.3671521 0.001

[[2]]
[[2]][[1]]
  name id   emmeans     p
1   ff  A 0.2561801 0.003
2   ff  B 0.1705811 0.003
3   ff  C 0.9714178 0.003

output <- matrix(nrow=2, ncol=5)

for(i in 1:list){ # what could be written here?
  d <- as.data.frame(df3[[i]])
  for(j in 1:nrow(d)){
    output[i,1] <- d[1,3]
    output[i,2] <- d[2,3]
    output[i,3] <- d[3,3]
    output[i,4] <- d[1,4]
    output[i,5] <- d[1,1]
  }
}

#Wanted outcome:
output
     [,1]                [,2]                [,3]                [,4]    [,5]
[1,] "0.224849119782448" "0.421393777942285" "0.367152112303302" "0.001" "gg"
[2,] "0.256180095253512" "0.170581063022837" "0.971417842432857" "0.003" "ff"

Comment: 1. `length(df3)`, 2. `cbind`, 3. `dplyr::bind_rows(df3)`
Comment: But (2) is terribly inefficient - set up so that your output matrix is the right size from the start, and then replace the default values with your actual results in your loop, rather than "growing" your matrix by making it bigger every iteration.
Comment: @Gregor Thomas thanks fro your response! Do you have a suggestion on how to do this?
Comment: I'm having trouble understanding what your actual goal is. You have `output <- matrix(nrow=6, ncol=2)`, so you are already initializing `output` to some size - just make sure that size is the final size you want it to be.
Comment: It's also hard to tell what's going on with your set-up. E.g., you have `df <- data.frame(name,id, q1,q2)`, so `df` is a data frame. Then you do `df <- list(df)`, so now `df` is a list that contains only a data frame. And then ditto for `df2`. Then when you do `df3 <- list(df, df2)` you have a list that has 2 items, and each item is a list that contains a single data frame - a relatively complex data structure.
Comment: Why did `df` and `df2` become list themeslves *and* be put into `df3` - there doesn't seem to be any purpose to `df <- list(df)` and `df2 <- list(df2)` - is this inefficient code we should change, or is it a simplification of your actual data that requires this extra step for some reason?
Comment: And back to your actual goal - your code doesn't run as-is, and you don't show or describe your desired output, so I don't really know what you are trying to achieve, so I really can't help get you there. Your specific questions have been addressed...
Comment: @Gregor Thomas yes the code is wierd Im just trying to recreate the problem I have in my actual data. Therefore i made a data frame to a list.  In my real data I have a list with several items (or what to call it, as exemplified in df3), and I want to iterate over these and extract some data from each item and put it in another matrix, "output". Thats my goal! How would you do this?
Comment: How I would do it would depend on what I'm trying to extract and what format I want the result in. If you (**a** - best!) put your expected result in the question, or (**b** - second best) describe your exact goal in words, or (**c** - okay) comment the not-working code to make it's goals clear, then maybe I'd understand your goal and could help with it. (**a**) and (**b**) together would be preferable.
Comment: @Gregor Thomas Now I have updated the code! I realize there were some error. So I want to extract information from the items in the list (df3) into a new matrix (output) in another order. Now the code is not working. So, I wonder how to run a loop of the list to extract the information I want from each item and then how to store it in "output". Many thanks!
Comment: Okay, so based on the input you show and the output, it looks like you want your output to be a matrix with 1 row per element in `df3`. For each list item in `df3`, which is a sub-list, we will look at the *first* item of the sub-list (? is this right? What do we do if `df3[[1]]` includes multiple items? Multiple data frames?). For this data frame, we will extract the `emmeans` column as a vector, append the *first value from the `p` column* (is "first" right? In your example, all the p column values are equal. Is this always the case? Should we check? Take the first? The mean?...)
Comment: Then we also append the *first value in the `name` column* (same questions about `name` as `p` column - is *first* value right?). As the `name` column is non-numeric, this vector will be `character` class, and will form a row in the output.
Comment: This also assumes that all the data frames have the same number of rows - is this a safe assumption? Do we need to check the number of rows, fill missing rows with `NA`, truncate extra values?
Comment: @ Gregor Thomas The column "p" and "name" will have the same value in the three rows, it will always be like this. It is the effect of gg on id A,B,C. p= overall pvalue of the id A,B,C (yes, should have named id differently, like treatment or something). I just made it like this to make the same number of all columns and rows, so yes it will always be the same numbers of rows and columns
Comment: @ Gregor Thomas What do we do if df3[[1]] includes multiple items? Answer: The data structure will always be the same!
Answer: This data is weirdly structured enough, and the extraction is unique enough, that I think a for loop is the easiest way. Something like this:
output <- matrix(nrow = length(df3), ncol=5)
for(i in seq_along(df3)) {
  output[i, ] = with(df3[[i]], c(emmeans, p[1], name[1]))
}
output
#      [,1]                 [,2]               [,3]                [,4]    [,5]
# [1,] "0.0101301828399301" "0.21454192395322" "0.913734979229048" "0.003" "ff"
# [2,] "0.0101301828399301" "0.21454192395322" "0.913734979229048" "0.003" "ff"


Convert List to List in windows phone 8

Question: how to convert List to List in c# windows phone 8 app?
obj_1 and obj_2 are lists.
I have Following code:
List<obj_1> list = new List<obj_1>();
obj_1 = new List<obj_1>(obj_2.Of Type<obj_1>().To List());

OR
List<obj_1> list = new List<obj_1>();
obj_1 = new List<obj_1>(obj_2.Cast<obj_1>().To List());

while debugging the code, count in obj_1 is 0 and obj_2 is 10.Please suggest any solution.Thank You
Comment: Is there any hierarchical relationship between the two types `obj_1` and `obj_2`?
Comment: No there is no Hierarchical Relationship.
Answer: To convert from List<> of type obj1 to List<> of type obj2 then List<T>.ConvertAll
 List<obj2>  resultList= List<obj1>.ConvertAll(x => new Obj2 { Property = x.SomeValue });

or
List<obj_2> resultList = new List<obj_2>(List<obj_1>.Cast<obj_1>());

Comment: Your code sample isn't using the `ConvertAll` method though.

Convert List to List in windows phone 8


Is there a subset of $\mathbb{R}^2$ that is bounded but not compact?

Question: How to find a subset of $\mathbb{R}^2$ that is bounded but not compact. Does the open disk satisfies this?
Comment: In any Euclidean space, compact is the same as **closed** and bounded. If you want a noncompact set that is bounded, what can you conclude?
Answer: The open unit disk
$$D=\{(x,y):x^2+y^2<1\}$$
is such a set. Indeed, it is covered by the open disks
$$U_n=\{(x,y):x^2+y^2<(1-1/n)^2\},$$
of radius $1-1/n$, but there is no finite subcollection of $\{U_n\}_{n=1}^\infty$ which covers $D$.
Comment: Doesn't $U_1$ cover the open disk?
Comment: @Nishant Thank you, I meant $1-1/n$. See edit.


Endless loop in onSensorChanged

Question: Help! I've fallen into an endless loop and I can't get up!
RESULTS
**** MisbehavingActivity onCreate.
**** MisbehavingActivity onResume Register.
**** MisbehavingActivity onAccuracyChanged.
**** MisbehavingActivity Accelerometer onSensorChanged.
**** MisbehavingActivity onPause Unregister.
**** MisbehavingActivity Accelerometer onSensorChanged.
**** MisbehavingActivity onPause Unregister.
**** MisbehavingActivity Accelerometer onSensorChanged.
**** MisbehavingActivity onPause Unregister.
**** MisbehavingActivity Accelerometer onSensorChanged.
**** MisbehavingActivity onPause Unregister.
**** MisbehavingActivity Accelerometer onSensorChanged.
**** MisbehavingActivity onPause Unregister.
etc. etc. until:
"Unfortunately, Amiok has stopped"
Here's the code:
<code>package com.apackage.amiok;

import android.content.Context;
//import android.content.Intent;
import android.hardware.Sensor;
import static android.hardware.Sensor.TYPE_ACCELEROMETER;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MisbehavingActivity extends AbstrActivity  implements OnClickListener, SensorEventListener {

    private static final String TOAST = "**** MisbehavingActivity ";
    SensorManager sensorManager;
    Sensor accelerometer;
    Button aButton;
    //SensorEventListener sensorListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        logStuff( TOAST + "onCreate. ");

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(TYPE_ACCELEROMETER);

        setContentView(R.layout.activity_main);

        aButton = ((Button) findViewById(R.id.buttonToStop));
        aButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        logStuff( TOAST + "onClick.");
        onPause();
        finish();
    }

    @Override
    public void onResume() {
        logStuff( TOAST + "onResume Register.");
        super.onResume();
        // register the listener
        accelerometer = sensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void onPause() {
        logStuff( TOAST + "onPause Unregister.");

        // unregister the listener for all sensors
        sensorManager.unregisterListener(this);
        super.onPause();
    }

    // SensorEventListener stuff

        @Override
        public void onSensorChanged(SensorEvent event) {
            logStuff( TOAST + "Accelerometer onSensorChanged.");
            onPause();
            finish();

        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            logStuff( TOAST + "onAccuracyChanged.");
            // Not sure I need to do anything here...
        }
}
</code>
Answer: You are registering the Activity instance as SensorEventListener twice, on onCreate and onResume method, leave only one registration, on onResume method and delete registration on onCreate method. As good practice call first super methods onPause and onResume. Look a example code on SensorManager.
Comment: Thanks, Joseph!  I actually had it that way in the first place, but I got the exact same results, so I changed it.  The real question is why isn't my "unregisterListener" statement working?
Comment: Hmm. I made those "good practice" changes you suggested, Joseph, and also replaced all the calls to logStuff (which is in my AbstrActivity) with makeNotification, and that helped somewhat, but it still seems like the onSensorChanged method is getting called at least twice before I can unregister!  At least it's not crashing now. Thanks!

Endless loop in onSensorChanged


Finding distribution function

Question: Let $X_1,X_2,...$ denote iid random variables such that $X_1$ is continuously distributed with density $p(x)$ and distribution function $F(x)$ where $F(0) = 0, F(x) > 0$ for all $x > 0$, and $p(0) > 0$. Let
$\hspace{15mm}Y = n\cdot  \min \{X_1,...,X_n\}$.
Then there exists a random variable Y such that:
$\hspace{15mm} Y_n \xrightarrow{D}Y$ as $n \xrightarrow{} \infty$.
What is the distribution function of $Y$?
I'm not sure how to proceed with this question. Any insight would be much appreciated.
Answer: Notice that for $t\geqslant 0$,
$$\mathbb P\{Y_n\leqslant t\}=\mathbb P\{\min_{1\leqslant j\leqslant n} X_j\leqslant t/n\}=1-\mathbb P\{\min_{1\leqslant j\leqslant n} X_j>t/n\}=
1-\mathbb P\left(\bigcap_{1\leqslant j\leqslant n}\{X_j\gt t/n\}\right).$$
Using the fact that $(X_j)$ is iid, we get
$$\mathbb P\{Y_n\leqslant t\}=1-(1-F(t/n))^n.$$
Now, we have to use the fact that $X_1$ has a density in order to compute the limit.

Finding distribution function


How to make a transition sound so "in your face"?

Question: I can't really describe well with words what I mean, but this transition in Touch off by Uverworld (01:07) is sort of very "in your face". I feel like some techniques from electronic music are used here that I don't have to background to recognize (I'm also curious about many other sections in the song...).
What techniques used here, or how can I recreate a similar effect?
Comment: Is it possible to not move comments that are actual comments to chat? My actual comment (clarifying the question) is/was to ask for the time stamp of the transition in question to be added in text form to the answer because following the link I don't hear a clear transition.
Comment: @ToddWilcox it's all or nothing for comment export to chat. You can delete your own comment in chat and flag things that do not belong, but it wont typically affect the flow of a chatroom as long comment threads will typically be at most half a page of a chatroom.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/138814/discussion-on-question-by-stefan-perko-how-to-make-a-transition-sound-so-in-you).
Comment: @Dom - it's not "all or nothing" according to [this post](https://meta.stackexchange.com/questions/305628/move-comments-to-chat-failed).
Comment: @ElementsinSpace he's asking about the other way. I can pick comments not to be deleted, but I can't pick comments to not be moved to chat.
Comment: @Dom - I don't have access to these tools, so I can only piece together what's possible.  But it seems like you could "move comments to chat" but not "also delete the moved comments from the post". Then, from the post manually delete the noisy comment and leave the useful comments.
Comment: @ElementsinSpace unless I'm misunderstanding, Todd is asking about things in the chat not comments here. The comments were also resolved so should be deleted anyway. The way only way not to export the comment to chat is to delete the comment first which in a long comment thread can be hard to do first.
Answer: Well, I'll start with the obvious- all sound cuts out for 2 whole beats before the downbeat.  It's hard to get any more jarring than that.  And then the music comes back all at once.  You hear a sudden unmute, not natural instrument attacks.
Aside from that, electronic music often does transitions by using what people call "transition effects".  There's two parts to it- a riser, which is a sound that builds leading up to the downbeat, and an impact, which is a percussive burst of sound that happens on the downbeat.
The traditional simple riser is made by playing white noise and slowly opening up a resonant low pass filter.
The traditional impact would probably be a crash cymbal... I'm not sure.
There's plenty of ways to spice up your transition effects, but in practical terms, what most producers will do is purchase effects packs from sound designers who specialize in making weird and wonderful sounds.
I'd recommend finding some stems for a song in this genre (or, you can listen to the stems for Pendulum-Granite here).  Listen to the "effects" stem.  See how they use noises to support the song.


Prove that $T:c \to c_0$ is continuous bijection

Question: Let $c$ be the vector space of all real convergent sequences, with the norm
$$\|(a_n)_{n\in \mathbb N}\|_\infty = \sup\{|a_n|:n\in \mathbb N\}$$
Let $c_0$ be the subspace of $c$ of sequences with limit $0$, with the standard $\sup$-norm.
Define $T:c \to c_0$ by
$$T((a_n))=(a,a_1-a,a_2-a,\dots)$$
where $a=\lim_{n \to \infty}a_n$.
Question: How do I prove that $T$ is a bijection (1-1 and onto), and also continuous?
Comment: For continuity, if $a_n\to a$ does there exist any relation between $\|a_n\|_\infty$ and $|a|$? $T(a_n)$ has norm $≤\|a_n\|_\infty +|a|$, can you use the previous result to get a Lipschitz constant? For injectivity, if you suppose two sequences are sent to the same vector, what follows for the limit of the sequences? Can you see how this implies all terms of the sequences must be the same (start with the first term)?
Comment: Either $T ((a_n)) = (a, a_0-a, a_1-a, \dots) $ or your sequences are indexed on  $\mathbb N ^*$, otherwise T is not a bijection.
Answer: Presumably you are using $\mathbb N = \{1,2,3,\dots\}$.
The first thing is to prove that the function $(l,a_1-l,a_2-l,\dots)$ actually converges to $0$. This is easy.
Now prove it is injective. suppose $f((a_n))=f((b_n))$. Then we must have that both limits $l_a$ and $l_b$ are equal, we also have $l_a-a_k=l_b-b_k$ for all $j\in \mathbb N$. Since $l_a=l_b$ we have $a_k=b_k$ for all $k$. So the two sequences are equal.
To prove it is surjective. suppose you have a sequence $(a_1,a_2,\dots )$ that converges to $0$. Then the sequence $(a_1+a_2,a_1+a_3,a_1+a_4,\dots)$ converges to $a_1$ (because $a_n$ converges to $0$).
It follows that $f(a_1+a_2,a_1+a_3,\dots)=(a_1,a_2,a_3,\dots)$. So it is surjective.


how to modify the confirmation email in Ubercart?

Question: I'm trying to modify the format and text of the confirmation email in Ubercart and I don't know from where....can anyone give me hint?
for example including some images or custom links in some parts of the email, quit the horrible yellow background of the site name , etc, etc...
I'm using Drupal 6
Here's what I'm receiving at the moment...
Answer: You'll want to override the file 'uc_order-customer.tpl.php' found in the ubercart module. The way you do this is:
You need to copy two files from sites/all/modules/ubercart/uc_order/templates
The files to copy are uc_order.tpl.php and uc_order-customer.tpl.php
Then just edit uc_order-customer.tpl.php to your liking.
Comment: Thanks! I just copied uc_order-customer.tpl.php file to my template and wondered why it didn't worked.
Comment: Glad to help ;)
Answer: Additionally if you want to build multiple templates you can copy the uc_order.tpl.php to your theme's templates directory and create a new template called something like uc_order-customer2.tpl.php where customer2 can be any name you choose.
Then implement a hook to identify the new templates:
<code>function hook_uc_invoice_templates() {
  return array('customer2');
}
</code>
Make sure the 'customer2' is the same as that part of the template file name.
This way you can make unlimited e-mail templates and keep the original customer template intact.
Also note that you can choose the template you want sent in the conditional actions predicate.


Using a looper with the 4-cable-method (4CM)

Question: My Equipment:

Engl Powerball 2
Boss GT-100 Effektboard
Boss RC-300 Looper

What works:

4-Cable-Method with Engl and GT-100. it's great!

Short explanation of the 4-Cable-Method:

The 4 cable method is a way to hook up a pedalboard to an amp in a way that allows you to control which pedals or effects are placed before the pre-amp and which pedals or effects are placed after the pre-amp in the amp's effects loop.
  This is achieved using four cables hence the name.
source: http://guitargearfinder.com/guides/use-four-cable-method/

What I want:

Integrating the Looper will bring much more fun
I could also use the RC-300-Pedal as a volume pedal of the guitar signal
I could also use the Sub-Output of the RC-300 (see manual) to go into the PA for backing sounds
...

What I did:

my idea was to bring it to the end of the chain, like this:

The Problem:

If I record a loop on the RC-300, I can see it (there is a red blinking light for it) but I can't hear it.
Just my guitar signal is coming out. it's like the looper is 'invisible'
Comment: What exactly happens when you try to loop?
Comment: nothing! There is no output. I can see, that the loop is on the rc-300 track (there is a red blinking light for it). But just my guitar signal is coming out. it's like the looper is 'invisible'. (<- added this text to the question)
Comment: So with the looper bypassed you can hear the guitar (like the last sentence in your question) but as soon as you start recording a loop the sound goes away?
Comment: I play and here my actual play. I record and still hear my actual play. I stop recording and begin to loop. I don't hear the loop.
Comment: What happens if you connect the looper between the guitar and the amp with just two cables and don't use the GT-100?
Comment: I will try this as soon I am in our rehearsal room. By the way: both Boss-boards are in successful use at home, in the order: Guitar->Multieffekt->Looper->Monitor.
Answer: I don't have the answer but I know what is not the answer. It has nothing to do with the 4CM. The looper has no idea that you are using the 4CM. If you are producing sound through your GT output on all patches you are using to record, it is going into your looper. The issue is with the looper settings to the output, maybe channeled to stereo and you are using the mono out only. To note, if you record ambient effects from your GT, it will be messy coupled with new ambient effects from your overdub. Either use ambient effects from your looper so it will sync or move the looper to before the GT return (assuming your ambient effects are after the loop as should be). Then your loop playback AND your live play will get the same treatment.
Answer: Why no fun?  Likely because the 4cm puts effects in front of the amp and also between the pre-amp and final power amp stage.  If you wanted the ENGL output to go to the RC-300, then you would need another amp output to send a signal from the ENGL power amp.
If the ENGL Fireball II amp had a line-out, such as an emulated headphone jack, then you could send that signal to the RC-300 and loop away.  However, you could have more fun by instead by sending the line out from the Boss GT-100 to the auxilliary input of the RC-300 looper and then send the looper's line out (headphone output) to a separate line-level audio, such as the Roland KC60 or a PA or a hi-fi system etc.  This way, you can record separate loops using different effects and/or channels on the ENGL each time and the looped playback won't be coloured by the sound of the amp.  See picture.
FYI - I struggled with this issue using the Blackstar TVP 260, Boss GT8, Digitech JamMan Stereo and Roland KC60 but the set up just described works well.  (The old GT8 still has excellent modulation and compression effects and can do midi channel switching for the  TVP 260 across 128 banks).
Answer: To capture the signal from the amp channels as well as the multi effects board on a looper pedal use the 4 cable method for connecting the multi effects then a separate link from the emulated line out of the amp into the looper and out from the looper into a mixing desk.
If you have the boss rc500 you can also split the outputs from the looper so that right goes to one channel on the mixing desk playing recorded loops only and the left goes to a second channel on the mixer playing the bypass live sound. This can then be muted if you only want to hear the live sound through the amp or vice verca.
This is the 7 cable method. Took a while to work out but simple when you know how. Simple always works. This arrangement also allows good level control over each channel as well as the amp so can be balanced nicely.


Use only verified addresses in production AWS SES

Question: I have AWS SES in production mode, but now want to limit sending to only verified addresses (as it did in sandbox mode).  Is there any way to configure this?
Answer: First of all, AWS SES has built-in email reputation checks and other filtering checks. Your application should decide which emails you are planning to send using the API. Otherwise, it'll anyway hit the API with a request perform that you are willing to block.
However, you can control your various AWS SES actions in many ways using AWS Identity and Access Management. Refer to the official doc https://docs.aws.amazon.com/ses/latest/DeveloperGuide/control-user-access.html
Look for the section "Restricting Email Addresses" in that doc.
If it's not the answer you are looking for, please comment with more information. I'll try my best to help. Take care.

FYI, long story short: log in to your AWS console to create an IAM policy for SES service. Add and apply policies to particular SES services. More details  https://docs.aws.amazon.com/ses/latest/dg/control-user-access.html#iam-and-ses-examples-recipients
Comment: When the application was in development, SES restricted email sent to a small number of verified addresses.  When the app went into production, the request to move SES into production removed these restrictions.  For various reasons, I want to run it with those same restrictions.  I was hoping to do this without code changes.  Basically, change it back to pre-production mode with respect to email.  In the meantime, I DID make the needed code changes, but would still be curious to know if this is possible.
Comment: You can do that without programming. I made some updates in the original post. please review.