Can i use a chord scale in key signature like CDEFGABC: A CHORD SCALE

Question: To play a song in key is there a possibility of playing a scale of chord in key signature. For example c major key CDEFGABC: In this A is the major 6, can i use A major scale A,B,C#,D,E,F#,G#,A with chord progression C,E,A
Answer: Well, it's going to be quite dissonant, because there are going to be a lot of notes clashing. The A major scale has C# and G# whereas the chord C has C and G natural.* So, those notes are going to create a dissonance. It will sound smoothly over the E and A chords, because E is the V of A, so the notes are the same.
Keep in mind that the chord progression C,E,A isn't part of the C major scale. It borrows chords from other scales (or secondary dominants, I'm not sure where the progression is going). So, you wouldn't stick to the C major scale to play over.
*If you like this kind of dissonance, go for it. Also, it depends on the style of music you're going to be playing this. Not all of them want this dissonance, but if it's your composition, you are free to try them out.
Comment: @Y07 I updated my answer a bit. The A major scale will sound nice over the E and A chords, but not so nice over the C chord
Comment: I am beginner i need some guidance. so usually do i have to select only of signature notes rather chord scales.
Answer: When you are on a certain chord for a bar, then, yes, it'll work. I presume a bar of C, using C scale notes, then a bar of E (dominant of A), where you could use E scale notes, leading to a bar of A, where A scale notes will work. What you need to bear in mind is that all these keys have some common notes, but they may not be chord notes. For example,all 3 have an E note, which happens to be a note from each chord triad too. So, the tune could actually stay on the one note E for all 3 bars! However, the C# for instance,really fits the A chord, not too bad over E, but awful over the C.
In the final reckoning, though, it's pointless asking anyone what'll fit. Ears usually tell the story better. If it sounds good, etc.
Incidentally, yes the A is the major 6th note of C, but this in itself has no bearing on the fact of using the A MAJOR scale. In fact, the A MINOR scale fits just about perfectly - because it's the relative minor of C.
Answer: You mentioned that you are just in the beginning stages of grasping music theory and that's perfectly alright.  We have all been there.
I think you might be confusing major intervals with major and minor chords that go with a given key.  It is true that the note A natural is the 6th scale degree of the C major scale (key of C).  It is also true that A natural is a "major sixth" because there are 9 semitones between the root and the 6th scale degree.  In this context the term "major sixth" refers to the interval and has nothing to do with chords in the key of C major.
The chords used in C major are C Major, D minor, E minor, F Major, G Major, A minor and B diminished.  All of these chords use notes from the C major scale.  If you played the notes from the scale corresponding to the 6 chord (vi chord) of the C major scale (which is A minor) you will be playing the same notes as the C major scale.
So in this case, as a beginner, I think you might find that it sounds best to play the notes from the scale of the sixth chord of the C major scale (which is A minor) - instead of the notes from the A major scale.
It's interesting to note that in any major key, the six chord (vi chord) will always be the relative minor of the major key and the relative minor key shares the same notes and same key signature as it's related major key.
Each chord in a given key will not always contain all the exact same notes as the root key (as does the vi chord discussed above), but all of the chord tones (notes used in the chord) will be in the root key (C major in the example).
I still refer to the chart below to help figure out which chords go with all the major keys.  I have included it here because as a beginner, you might find it particularly useful.

Have fun learning about music theory and becoming a better guitar player.
Comment: Can you suggest me a MUSIC THEORY book .
Comment: Y07 Actually most of what I know about music theory I learned here on Music Stack Exchange.  I have never read a book.  Sorry


Salvar preferências de uso - Android

Question: Gostaria de saber qual a melhor maneira de salvar as preferências de uso de um aplicativo, como por exemplo um checkBox marcado ou a ordenação de uma listView. se puderem passar algum exemplo de código agradeço.
Comment: pode usar o [shared preferences](https://developer.android.com/training/basics/data-storage/shared-preferences.html) ou a APi [Preference](https://developer.android.com/guide/topics/ui/settings.html?hl=pt-br) ai depende do que e como quer fazer. Faz tempo que nao mexo com android entao nao tenho codigo.
Comment: Seja bem vindo ao Stackoverflow em Português! Faça um [tour](http://pt.stackoverflow.com/tour) para aprender como o site funciona. Em relação a sua pergunta me parece que falta mais informações, mostrar o que vc já fez e quais as dificuldades esta a enfrentar, edite ela e acrescente mais informações do problema.
Answer: Cria o objeto SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MinhasPreferencias", MODE_PRIVATE);
Editor editor = pref.edit();

Salvando os dados em pares KEY/VALUE
editor.putBoolean("nome_da_chave1", true);      // Salvando valor booleano - true/false
editor.putInt("nome_da_chave2", "int value");   // Salvando valor inteiro integer
editor.putFloat("nome_chave3", "float value");  // Salvando float
editor.putLong("nome_chave4", "long value");    // Salvando long
editor.putString("nome_chave5", "string value");  // Salvando string

// Salva as alterações no objeto SharedPreferences
editor.commit();   // valida as alterações

Lendo os dados de SharedPreferences
boolean estachecado = pref.getBoolean("nome_chave1", true);  // lendo o  boolean
int qualaidade = pref.getInt("nome_chave2", 0);             // lendo o valor inteiro
float total =pref.getFloat("nome_chave3", null);        // lendo o valor  Float
long distancia = pref.getLong("nome_chave4", null);     // lendo o valor Long
String email=pref.getString("nome_chave5", null);       // lendo a String

Excluindo valores da SharedPreferences
editor.remove("nome_chave3"); // excluindo a chave nome_chave3
editor.remove("nome_chave4"); // excluindo a chave nome_chave4

// Salva as alterações em SharedPreferences
editor.commit(); // valida as mudanças

Elimina todos os dados de SharedPreferences
 editor.clear();
 editor.commit(); // Salva as alterações

Comment: Perfeito Reginaldo, muito obrigado mesmo!

Salvar preferências de uso - Android


Eloquent: Get pages based on user role

Question: I have a User, Role & Page setup, all with many-to-many relationships and the pivot tables setup in the usual fashion (role_user, page_role), along with the eloquent methods to attach a model to the pivot tables.
My idea is to allow a user to have many roles, and a page can be accessed by many roles.
However now I'd like to return a collection where I have my users details and then the pages they're allowed to access.
The closest I have got is:
return User::find( Auth::user()->id )->with('roles.pages')->first()->roles;

Now this returns each role the user has, and each page that the role can access. Which is correct, however I have duplication on the pages part.
How would I go about getting only a list of pages the user is able to access with no duplication?
Cheers
Answer: Read that answer to get you on the track: HasManyThrough with one-to-many relationship
Only for your setup you need to adjust the query - join 2 pivot tables (and make sure they represent real data, ie no rows referencing non-existing models):
// User model

// accessor so you can access it like any relation: $user->pages;
public function getPagesAttribute()
{
    if ( ! array_key_exists('pages', $this->relations)) $this->loadPages();

    return $this->getRelation('pages');
}

// here you load the pages and set the collection as a relation
protected function loadPages()
{
    $pages = Page::join('page_role as pr', 'pr.page_id', '=', 'pages.id')
           ->join('role_user as ru', 'ru.role_id', '=', 'pr.role_id')
           ->where('ru.user_id', $this->id)
           ->distinct()
           ->get(['pages.*', 'user_id']);

    $hasMany = new Illuminate\Database\Eloquent\Relations\HasMany(Page::query(), $this, 'user_id', 'id');

    $hasMany->matchMany(array($this), $pages, 'pages');

    return $this;
}

One more thing: I hardcoded tables and columns names for sake of simplicity, but in real life I suggest you rely on the relationships and their getters, like: $relation->getTable(), $relation->getForeignKey() etc.

Now suggestion about your code:
return User::find( // 2. query to get the same user
     Auth::user()->id  // 1. query to get the user and his id
   )->with('roles.pages')
     ->first() // 3. query to get ANOTHER user (or the same, luckily..)
     ->roles;

Use Auth::id() instead of Auth::user()->id (for Laravel ver 4.1.25+) to avoid redundant query
find() and first() are methods that execute the query, so you just returned the user with id = Auth::user()->id and moment later you fetch another one, who comes first() from the users table..
You don't need to use User::whatever for authenticated user, use Auth::user() instead.

So the code with suggested solution would look like this:
Auth::user()->pages; // collection of Page models with unique entries

Comment: Awesome cheers for the heads up, works great :) EDIT: Is it correct to load the `Page` model from inside the `User` model directly?
Comment: What do you mean by correct? Isn't it what you needed :) It is just adjusting what framework offers to match your needs.
Comment: Would it be possible to show me the above how it's properly supposed to be implemented? Also if the user isn't logged in I need to check if there is any pages which have the role "guest". Logic is working in this paste, but doesn't seem the "best" way of doing it... http://laravel.io/bin/QqlnD
Comment: Check the edit, you have everything concerning `User` model there. And here's the paste for you http://laravel.io/bin/mlqzq
Comment: Ahhh I see! Another thing though, surely "User" will never have the relation with pages, so it will always execute the "loadPages()" method?
Comment: Not at all. Check the accessor, last action there: `matchMany` is going to set the relation on `$this`. This is how the relations are attached to the model. You can always play with this and see what queries are run etc. with `artisan tinker` in cli. It is great source to learn how Eloquent works.
Comment: Hey @deczo, any idea how i'd go about getting specific coulmns from the pages table. For example just the name and ID rather than everything (including the timestamps etc)
Comment: I suppose you want to output only certain fields to the user, so check model's `hidden`/`visible` properties. Otherwise simply use `select` on the query

Eloquent: Get pages based on user role


Non similar to orthogonal Matrix

Question: Give an example of a 3-by-3 matrix with determinant 1 which is not similar to an orthogonal matrix.
I know that a matrix is orthogonal if $AA^T=I$ and a matrix $A$ is similar to a matrix $B$ if there exists an orthogonal matrix $P$ such that $B=PAP^{-1}$.
But I can't think of any matrix that is not similar to an orthogonal matrix basing from their definitions.
Can you help me? Any hints will also do. Thanks.
Comment: Similar matrices have the same eigenvalues; any eigenvalue of an orthognal matrix has modulus $1$.
Comment: So does that mean there doesn't exist such matrix that is not similar to an orthogonal matrix?
Comment: No. But from the above, all you need to do is find a matrix with determinant $1$ that has $1/3$ (e.g.) as an eigenvalue.
Answer: Take an upper triangular matrix of all $1$'s on the diagonal and above with $0$'s below the diagonal.
Comment: @hardmath The proof is rather simple. If $1$ are on diagonal   then 1's are also eigenvalues and the eigenvalues of a similar matrix. But the only orthogonal matrix with eigenvalues = 1 ( with algebraic multiplicity $ = 3$) is the identity matrix, which is different from the proposed by CF.
Comment: This would be more interesting if a proof of non-similarity were added, even in outline.
Comment: Is it similar to a JCF with the diagonal equal to 1s?
Comment: @Widawensen:  There are various ways to prove non-similarity, such as noting that [orthogonal matrices are normal, and hence diagonalizable](https://math.stackexchange.com/a/1738794/3111).  But for the omission of a sketch of the proof of non-similarity I would have upvoted that Answer.

Non similar to orthogonal Matrix


How to analyze this dataset with 2 between-, two within- factors using lme4?

Question: This post is a follow up on my previous post (which was interested in lme) and uses the same dataset. Now I would like to know how to analyze it using lme4.
The data
The data is from a behavioral experiment in which participants in 6 groups (based on two crossed factors) worked on 16 trials (two crossed 4-level factors). That is, we have a dataset d with two between-subject factors, group and condition, and two within-subject factors (i.e., repeated-measures factors), topic and problem (I uploaded the data to pastebin, so everybody should be able to obtain it), the participant id is code, the dv is mean:
> d <- read.table(url("http://pastebin.com/raw.php?i=4hRFyaRj"), colClasses = c(rep("factor", 6), "numeric"))
> str(d)
'data.frame':   2928 obs. of  6 variables:
  $ code     : Factor w/ 183 levels "A03U","A08C",..: 1 1 1 1 1 1 1 1 1 1 ...
  $ group    : Factor w/ 2 levels "control","experimental": 2 2 2 2 2 2 2 2 2 2 ...
  $ condition: Factor w/ 3 levels "alternatives",..: 3 3 3 3 3 3 3 3 3 3 ...
  $ topic    : Factor w/ 4 levels "1","2","3","4": 1 1 1 1 2 2 2 2 3 3 ...
  $ problem  : Factor w/ 4 levels "AC","DA","MP",..: 3 4 1 2 3 4 1 2 3 4 ...
  $ mean     : num  94.5 94.5 86.5 84.5 80 46.5 73.5 43.5 51 39 ...

The usual way to analyze this data would to fit an ANOVA on this data (note how the error term is constructed for the within-subject factors):
m1 <- aov(mean ~ (condition*group*problem*topic) + Error(code/(problem*topic)), d)

The Question
My main interest in the data is the following:

Is there an effect of the group factor on any level (i.e., main effect or interaction)? I hope there is not.
Is there an interaction of condition with problem ? Or even an interaction of condition with problem and topic?

I have two questions regarding the analysis in lme4:

How can I specify these questions using lme4?
As lme4 does not provide p-values, how do I determine whether a variable (e.g., group) has any effect (I imagine using some kind of likelihood ratio test) and what is the critical value above which I need to accept effect to be 'significant'?

As is probably obvious from the above description I am no expert in lme4 neither a statistician, so both Venables & Ripley and the lme4 Book by Bates gave me a hard time. Leaving me kind of clueless as before.
Comment: Have you read Baayen, Davidson, Bates (2008), "Mixed-effects modeling with crossed random effects for subjects and items"? It can be found at http://www.ualberta.ca/~baayen/publications/baayenDavidsonBates.pdf
Comment: To be honest, I am reading it right now. But so far I have problems understanding what type of slopes I need or not. I hope with the help of the text and here, I can sort this out.
Comment: You might try to get help in-person too; it's very difficult to fully understand the details of the study over email.  Perhaps http://portal.uni-freiburg.de/imbi/StatConsult/details might be a resource?
Answer: I believe that lmer won't be able to duplicate what comes out of aov because it does not have the capability of restricting the variance-covariance matrix of the random components to compound symmetry as done in aov. However, you can still try something like
require(lme4)
# assuming a simple symmetric positive-definite structure of variance-covariance matrix
anova(m2 <- lmer(mean ~ condition*group*problem*topic + (0+problem | code) + (0+topic | code), data = d))

or a simple model
anova(m3 <- lmer(mean ~ condition*group*problem*topic + (1|code), data = d))

Then you can compare the two models:
anova(m2, m3)

Models:
m3: mean ~ condition * group * problem * topic + (1 | code)
m2: mean ~ condition * group * problem * topic + (0 + problem | code) +
m2:     (0 + topic | code)
    Df   AIC   BIC logLik Chisq Chi Df Pr(>Chisq)
m3  98 24985 25572 -12395
m2 117 24899 25599 -12332 124.4     19  < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The above result indicates the complicated model (the 1st one) is much better. In terms of model complexity, m1 with aov in your OP fits between m2 and m3.
To obtain p-values and confidence intervals for specific effects, do this
require(languageR)
set.seed(101)
# It will take a long time to run the MCMC simulations due to the huge number of effects in the model
mcmc2 <- pvals.fnc(m2, nsim=10000, withMCMC=TRUE)
mcmc2$fixed

The last line will show you the confidence levels and two p-values (one from MCMC simulations, and one from fitted t-statistic) for all the possible fixed effects specified in the model. I am not copying the result here because it's a long table.
If you want to know if the those groups have different variance-covariance structure, you may try
anova(m20 <- lmer(mean ~ condition*group*problem*topic + (0+problem|code/group) + (0+condition|code/group), data = d))

or,
anova(m21 <- lmer(mean ~ condition*group*problem*topic + (0+problem|code/condition) + (0+topic|code/condition), data = d))

And then compare the above two models with the simple one:
anova(m2, m20, m21)

Comment: Thanks for your very interesting answer. And I know, that I cannot duplciate the results from `aov` (there is a reason I want to go away from it). What I want is a `lme4` model that mimics the general structure (i.e., the nesting of problem and topic within code). I just do not understand how to probably convert the structure with the two within-subject factors to `lme4` syntax. But from your answer I get that it is not that easy to decide on the "correct" random terms.
Comment: Can you explain what is the difference between models `m2`, `m20`, and `m21` regarding the within-subject factors? And is there a way to specify something like `(problem*topic)/code` (cf. the the `aov` call) that would make sense?
Comment: @Henrik: What do you mean by converting "the structure with the two within-subject factors to lme4 syntax"? The m3 model in my response exactly handles the possible correlation structure among those levels for each of those two within-subject factors. The only difference here is that, your aov command assumes spherecity which may or may not be reasonable while the m3 model does not put such a strong constraint on the correlation structure. You may argue that m3 might be over-fitting, but, with enough amount of data, this should not be a big issue.
Comment: Thanks for the clear clarification. It improves my understanding drastically. m3 actually is what I wanted. So what is the difference between m3 and m2? Different random factors or different slopes (i.e., a different slope for topic within code and problem within code with code remaining the only random effect)? Btw, I would upvote more if I could.
Comment: @Henrik: Sorry I meant m2 instead of m3 in my previous comment. m3 has a simple random intercept while m2 models the pair-wise correlation among those levels of each within-subject factor. With a continuous variable, that would be a model with a random slope. If you feel that my response answers your OP, you can accept it by clicking the check mark.


Java: how to allow choose a variable depending on parameter passed?

Question: This is my class:
class StockQuote {

Float[] high, low, close, open;

public float GetMax(String choose_data_type) {
    if data_type="high" {
        Routine_Searchmax(high)
    } elseif strdata_type="low" {
        Routine_Searchmax(low)
    }
}
private float Routine_Searchmax(float[] variable) {
   // here i search max value into my array
}
}

My Question is: it is possible to pass a string variable with the name of a variable array, then .. work on that specific variable ?
Is there a way to do that ?
Thanks
Comment: Well you normally don't want to closely couple input data to your internal objects without validation. But you could turn to reflection to retrieve a field dynamically. Have a look at BeanUtils from apache for an idea http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/PropertyUtils.html#getSimpleProperty(java.lang.Object, java.lang.String)
Comment: Your question is unclear. While your syntax is not correct, what you are sketching out here is easily done in Java, just as you outline. Can you explain your statement, "as you know .. I can't do it," because it seems to me that you can do it.
Comment: I fail to see how having four different routines is any different than four sections of a single routine, except that it is easier to verify it's correctness at compile time...
Comment: I think I'd have to see your working code first to see what you're trying to do and then suggest how to improve it.
Comment: I am probably not understanding the question correctly but you are definitely missing a return statement from your method. What is Searchmax()? class? method? if it is a class then you need to use "new" to instantiate the class. If it is a method, what does it return?
Comment: Why not have a map with the data type as the key, and a collection as the value?
Answer: Implement one single private method that take the name of the variable as parameter and return the corresponding float array. Then you can use this helper method in all the methods that implement you calculation.
If your parameter to identify the variable is an string, then the easyest way to "transform" it to the float array is an kind if-cascade.
if(name.equals("high") return this.high;
if(name.equals("low")...
throw new IllegalArgumentExeption();

If you have many of this Variables (high, low, ...) then you may should use reflection instead of this if-cascade.
An impovent would be to use an ENUM instead of the string!

But im my oppinion a much better solution would be using object orientation! Make high, low, ... instances of an class that implements getMax only for its own valus. So you can do this:
 MyClass high = new MyClass;
 ...
 float higgMax = high.getMax();

Answer: A better way is to do it by using enum
Enum Declaration
public enum Float
{
    HIGHT("high"), LOW("low"), CLOSE("close"), OPEN("open");

    String code;

    Float(String code)
    {
        this.code=code;
    }

   // add getter and setter for string code here
}

Class Dec
public class StockQuote {

    public Float getMax(String chooseDataType) {

        return routineSearchmax (Float.valueOf(chooseDataType));
    }

    //This float is now enum
    private Float routineSearchmax(Float variable) {
           // here i search max value into my array
        }
}

But like these guys are saying you could just do it with out it as well but neater this way in my opinion also notice no if statement.
Comment: By the way forgot mention that you variable and function name were not following JAVA standard conventions of using camel case.


Android map basic app crashes

Question: I am trying to build a Google map application .... I am doing the same as shown in https://developers.google.com/maps/documentation/android/  (hello map). But when i run the app it crashes. I dont know what is causing the problem. My code is :
package com.googlemaps;
import java.io.IOException;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity {

private GoogleMap maps;

final static String URL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Get a handle to the Map Fragment
   maps = ((MapFragment) getFragmentManager() .findFragmentById(R.id.map)).getMap();
   maps.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
   LatLng as = new LatLng(141.0819,37.092);
   maps.setMyLocationEnabled(true);
    maps.moveCamera(CameraUpdateFactory.newLatLngZoom(as, 13));
   maps.addMarker(new    MarkerOptions().title("PlaceName").snippet("Magnitude").position(as));

  }

XML::
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<fragment
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:name="com.google.android.gms.maps.MapFragment"/>

</LinearLayout>

LOGCAT:
02-09 06:46:04.940: W/GooglePlayServicesUtil(1308): Google Play services out of date.  Requires 4132500 but found 4033530
02-09 06:46:04.960: W/GooglePlayServicesUtil(1308): Google Play services out of date.  Requires 4132500 but found 4033530
02-09 06:46:04.970: W/GooglePlayServicesUtil(1308): Google Play services out of date.  Requires 4132500 but found 4033530
02-09 06:46:05.050: W/GooglePlayServicesUtil(1308): Google Play services out of date.  Requires 4132500 but found 4033530
02-09 06:46:05.120: W/GooglePlayServicesUtil(1308): Google Play services out of date.  Requires 4132500 but found 4033530
02-09 06:46:05.210: W/GooglePlayServicesUtil(1308): Google Play services out of date.  Requires 4132500 but found 4033530
02-09 06:46:05.210: D/AndroidRuntime(1308): Shutting down VM
02-09 06:46:05.210: W/dalvikvm(1308): threadid=1: thread exiting with uncaught exception (group=0xb4aceba8)
02-09 06:46:05.240: E/AndroidRuntime(1308): FATAL EXCEPTION: main
02-09 06:46:05.240: E/AndroidRuntime(1308): Process: com.googlemaps, PID: 1308
02-09 06:46:05.240: E/AndroidRuntime(1308): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.googlemaps/com.googlemaps.MainActivity}: java.lang.NullPointerException
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.os.Looper.loop(Looper.java:136)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at java.lang.reflect.Method.invokeNative(Native Method)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at java.lang.reflect.Method.invoke(Method.java:515)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at dalvik.system.NativeStart.main(Native Method)
02-09 06:46:05.240: E/AndroidRuntime(1308): Caused by: java.lang.NullPointerException
02-09 06:46:05.240: E/AndroidRuntime(1308):     at com.googlemaps.MainActivity.onCreate(MainActivity.java:52)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.app.Activity.performCreate(Activity.java:5231)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-09 06:46:05.240: E/AndroidRuntime(1308):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-09 06:46:05.240: E/AndroidRuntime(1308):     ... 11 more
02-09 06:47:02.900: I/Process(1308): Sending signal. PID: 1308 SIG: 9

I think the problems are in some of these lines:
     maps.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
     LatLng as = new LatLng(141.0819,37.092);
     maps.setMyLocationEnabled(true);
    maps.moveCamera(CameraUpdateFactory.newLatLngZoom(as, 13));
     maps.addMarker(new MarkerOptions().title("PlaceName").snippet("Magnitude").position(as));

The app loads the map just fine if all these codes are removed.. but  rashes if not.
Answer: Do you have the latest version of google services? Is the setMapType() causing a problem? It says null pointer at line 52 in oncreate. What's that?
Comment: The setMapType() is not the porblem .. The app still crashes if it is removed
Comment: i dont know much about programming >>> Please help me out... What is null pointer?

Android map basic app crashes


Requesting REST-GET gives me 403 but works fine in DHC

Question: I am stuck for hours now with a JSON REST problem:
I have a simple REST endpoint in my Drupal 8 App. If I call it with the DHC Chromium REST Extension like GET http://proreos/api/v1/checklawyer/1?_format=json, I get
127.0.0.1 - - [07/Jul/2016:15:03:54 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 200 477 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/51.0.2704.79 Chrome/51.0.2704.79 Safari/537.36"

That's wonderful. Also Drupal does all the requested processing.
But if I call it from curl like
curl 'http://proreos/api/v1/checklawyer/1?_format=json'
I get the bad 403 response:
127.0.0.1 - - [07/Jul/2016:15:10:27 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 403 409 "-" "curl/7.35.0"

Well actually, I want to call it from a JS plugin like:
function checkLawyer() {
  var server = drupalSettings.bootasde.proreos_server;
  var id = drupalSettings.bootasde.asdeid;
  var jUrl = server+'api/v1/checklawyer/'+id+'?_format=json';
  console.log('Q: '+jUrl);
  jQuery.getJSON(jUrl);
}

It works fine, but unfortunately, it also gives me a 403 without any further Drupal backend processing:
127.0.0.1 - - [07/Jul/2016:15:06:03 +0200] "GET /api/v1/checklawyer/1?_format=json HTTP/1.1" 403 464 "http://proreos/asde/anwalt/1" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"

Console says:
15:17:22.973 "Q: http://proreos/api/v1/checklawyer/1?_format=json"
XHR HTTP/1.1 403 Forbidden

Any idea would be great! Thanks.
Comment: It's a [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) failure (the clue is the `XHR` part of your response)  - either the site hosting the JS needs to be on the domain `proreos`, or you need a cross origin access header on the Drupal site
Comment: It's even more crazy: If I paste the URI into chromium it works, in firefox it does not work - while the request headers are totally ident (except from the UA).
Comment: Not crazy at all - a normal HTTP request will work, an XHR won't...
Comment: Oh, not sure about the FF thing. That's why I stopped using it. Chrome always just works like it should
Comment: But there is no CrossOrigin, everything is localhost with proreos alias.
Comment: So just to confirm, `drupalSettings.bootasde.proreos_server` contains `http://proreos/` and nothing else?
Comment: Yes. Think it's a pure FF problem. In Chromium the complete end2end processing is totally fine.
Comment: Yeah, you're probably right. FF does things like this; in their defence, they're usually complying with some part of a spec that no one else is. But it produces inconsistent behaviour and confuses people. Not sure whether it should be judged as right or wrong to be honest
Comment: I am fairly certain this is not a CORS issue because the response would be valid, but you would not be able to access the content (or content body is 0 bytes in firefox). This is an authentication issue. Ninja edit: As I was thinking about it, @Rainer Feike confirmed my suspicions in his answer.
Comment: @mradcliffe Yeah you're right, I obviously only read half the question. Just saw the JS and response containing `XHR`, jumped to a conclusion
Answer: Doomed, I am so stupid. Chrome had the admin cookie, FF had a simple user cookie. I forgot to permit the GET on the new endpoint in the user permissions!!!
So stupid. @Clive: Thanks a lot for your help and sorry for that waste of time.


Power analysis with R

Question: I have two questions regarding the R script.
If I want to know the size of the sampling when I do a t-test with R, I can use this R script :
power.t.test(delta=1,sd=1.5,sig.level=0.05,power=0.8)

If I want to know the size of the sampling when I do the test of Pearson correlation coefficient, what is the R script?
And for a chi-square test what is the R script?
Comment: You can look at the pwr package for one approach to these problems.
Comment: The question could be migrated to SO, it has already received a full answer anyway.
Answer: For correlation:
pwr.r.test(n = , r = , sig.level = , power = )

and for chi-square
pwr.chisq.test(w =, N = , df = , sig.level =, power = )

For others, see here

Power analysis with R


What's the deal with current thread busy from Tomcat Status?

Question: I have deployed a pretty big application that is used all across the country (Canada), meaning lots of concurrent connections.
Recently we have reached the maximum amount of concurrent threads as our jBoss was configured to 40 maximum threads. Now it is 250 so we are fine.
Every now and then I am looking at the Tomcat status page, and I see threads to javascript files, css files, struts (java) actions, etc.
How could a thread on a javascript or css file be alive for my than a few seconds? I thought the thread was only during the page load (when the client downloads the javascript file to cache). Am I right?
Example entry
<code>Stage: S
Time: 1127110823 ms
B Sent: 0 KB
B Recv: 0 KB
Client: client's ip address...
VHost: server's vhost...
Request: GET /que/2715/jsp/common/js/jquery/jquery.maskedinput.js HTTP/1.1
</code>
This one is always here.. I don't understand why...
I would like to understand all these information and then change the way I code in order to free up some current threads.
Thank you for help
Charles
Answer: A misbehaving HTTP client may not be ack'ing your TCP packets, even for very small files, and Tomcat is waiting for the acks because it doesn't want to close the connection until it is sure the client got all the info.  Check the timeout values for your HTTP Connectors in server.xml (especially connectionTimeout) and make sure they are not set to very large values or -1 (wait infinitely).
See http://tomcat.apache.org/tomcat-7.0-doc/config/http.html for more info on timeout settings in the configuration.
<code> -Larry
</code>
Comment: None of the server.xml timeouts affect this behaviour. What you describe is done by the TCP stack, not by Tomcat.
Comment: Looks like the environment where we are hosted uses mod_jk in front of jBoss. See: http://1.bp.blogspot.com/_y8SmAu6cJZ4/TTpexxSN10I/AAAAAAAAAH4/lYekuJOxwMQ/s1600/Tomcat-cluster-diagram.png
Comment: The thing is that we were not having that kind of problem before on our Windows environment (jBoss running as a service on Windows, using the HTTP protocol directly). Is there any configuration that could be done to solve that problem on the new environment (apache & mod_jk)? Thanks for help
Comment: @EJP - Recent versions of tomcat have several timeout options (e.g., keep alive and connection timeouts) which may not allow you control over the lower level TCP behavior, but is good enough to close hanging connections.
Comment: @CharleyDC5 - I'm not a mod_jk expert, but reviewing the docs, it appears like there may be a few cases that would have the symptoms you describe, in particular if there is a firewall between mod_jk and Tomcat.   See http://tomcat.apache.org/connectors-doc/generic_howto/timeouts.html for the JK connector docs and see if you can get more information from your hosting service.


See all nodes where user profile entity reference matches the same entity reference on the node

Question: I have the Profile 2 module where a user selects a zip code (which is an entity reference to the content type ZipCode)
The ZipCode content type has an entity reference to a Region content type.
Finally, there is a content type called Schools which has an entity reference to the ZipCode content type.
I would like to display all schools that match the region of the logged in user. Logically this means finding the user's region, and then all schools with the same region, through the zip code...
I can't for the life of me figure out how to do this. Any help would be appreciated.
Answer: The easiest way is creating a view for the School content type and add the fields you want to display on your list. Then add:

A reference to the entity that is common between the School content type and the ZipCode content type. If there is no connection between the two, you will also need to add a reference to the Region content type and then to the ZipContent type.
Add an argument or contextual filter for the user ID of the currently logged-in user and limit the number of nodes displayed.

Note: I have sometimes achieved the same result by creating a view (for users) referencing the content types and adding the desired fields.
This is a video about view arguments: http://mustardseedmedia.com/podcast/episode39.


Significant figures during intermediate steps in a calculation

Question: If I have some values to use in a calculation, which all have 3 significant digits, then I know that the result will also have no more than 3 significant digits.
Am I allowed to round up/down to 3 digits during intermediate steps in the calculation? If not (which it seems is the case), then why not? Isn't any more digits just "random" inaccurate digits anyways since we started off with only 3-digit values? I do not see how these extra digits will make a difference.

If the question is not entirely clear, here is the reason I ask.
I am looking at an easy vector problem from a university physics book. My result is exactly the answer given, BUT is off by $1$ at the last (third) digit.
The question:

Follow a path $180\,\mathrm{m}$ straight west ($\vec A$), then $210\,\mathrm{m}$ in a direction $45 ^\circ$ east of south ($\vec B$), and then $280\,\mathrm{m}$ at $30^\circ$ east of north ($\vec C$). A fourth displacement $\vec D$ brings you back to start. Determine the magnitude of $\vec D$.

My answer for the magnitude is $D=144\,\mathrm{m}$. The answer in the book says $D=143\,\mathrm{m}$.
My procedure is to set up the vectors' coordinates:
$$\vec A=(-180,0)\,\mathrm{m}\\
\vec B=(B\sin 45^\circ,B\cos 45^\circ)\,\mathrm{m}=(148,-148)\,\mathrm{m}\\
\vec C=(C\sin 30^\circ,B\cos 30^\circ)\,\mathrm{m}=(140,242)\,\mathrm{m}$$
then to add them:
$$\vec D=-(\vec A+\vec B+\vec C)=-((-180,0)+(148,-148)+(140,242))\,\mathrm{m}\\
=\underline{-(108,94.0)\,\mathrm{m}}$$
and then to find the magnitude:
$$D=\sqrt{(-180\,\mathrm{m})^2+(94.0\,\mathrm{m})^2}=\underline{\underline{144\,\mathrm{m}}}$$
The issue is that I have messed with an intermediate step: I have rounded the coordinates for $\vec B$ and $\vec C$ up/down to 3 digits. If I don't and instead keep all digits in my calculator all the way and don't remove it until the end, it is correct.
Comment: @ADG Sure, it doesn't matter much. But do you know that feeling of frustation that you should know such a simple rule but apparently don't? If my kidbrother ever asks, I will not know what to say... *That* scares me.
Comment: why do you mind the 1 last digit? IMO it doesn't even matter unless you are dead serious about significant digits.
Comment: the young fredman one?
Comment: @ADG Yes, that is the physics book.
Comment: Generally I keep all intermediate calculations one digit more accurate than    my required accuracy for the final answer (in this case 4 significant figures  during intermediate steps). It's really hard to introduce an error this way, so it's worked for all my classes. Essentially, the idea is that rounding the value during intermediate steps will cause an error that can compound as you do things to it. For example, $10^{440}$ is very different from $10^{400}$, even though you're only rounding down a digit.
Comment: if you're allowed to use a calculator use variables storage if you have casio fx990 or such
Comment: Given an expression, you could keep doing the algebra until you come to the point where it's all numbers. Then you plug it in to the calculator, giving you as much accuracy as the calculator.
Answer: So, you would not be able to round it. It is a good rule of thumb to always let the original number limit your certainty.
Example:
Add $3.1416+(2/7)$:
$3/7 = 0.4285714$
The correct way to solve would be:
$3.141(6) + .428571(4)$, making sure all other numbers are certain past the original numbers certainty (by at least 1 digit, but the more you keep the better).
Then add to give you: $3.570171$
Now if you did not do that, you would get the following:
 $3.1416+(2/7)$
= $3.1416+(.4286)$
= $3.5702$
which are not equivalent to each other. Generally, significant figures are prevalent in science than math . But again, just keep the rule of thumb in the beginning in mind when you  do problems like that.


Theory of scales in piano improvisation

Question: I'm learning the piano and just learned two scales, A and C (and the theory as to how to make the other keys: WWHWWWH).
Other than learning how to make major/minor/dim etc chords how else can I use the scale?
For example:
On youtube I saw guys talking about improvisation on the piano and they hit a C chord with their left (bass) hand and the right hand they pick certain notes that "go well" with that chord, I'm guessing there is some theory there as to what would sound good (eg: a 1 and 3 or a 1 and 6 etc) but I can't really find it.
As you might have guessed, I am very much a beginner so feel free to throw in any pointers to anything else.
Answer: There is a jazz scale theory, coming mainly from the modal period, with contributions from the jazz theorist George Russell, that approaches improvisation by viewing "every chord as having one or more scales that can be played over it" (www.jazzstandards.com/theory/modal-jazz.htm).
Here's a possible chords-scales correspondence (this chart is my attempt at summarizing lessons from the course Jazz Improvisation by Gary Burton; any mistake is my own fault):

Approaches by other performers and theorists may vary from this chart in some details and consider additional scales, like pentatonic and so on.
So in principle, selecting a scale as per this chart will provide, for each chord, notes that sound "good". I suppose this may answer strictly the question asked, but of course it's an over simplification and anyway only a small part of the improvisation process. And it's a rather complex subject in it self, requiring many hours of study to understand the theory behind these chords and scales and master all the different scales in all (or at least most) of tonalities.
Anyway, studying the major (= the Ionian) and minor (the natural minor = the Aeolian) scales is always the place to start, so you're on a good track by beginning to understand and play the major scales.
Comment: You may want to have a look at Gary Burton's course, it's freely available in the Coursera MOOC platform (https://www.coursera.org/learn/jazz-improvisation). I really recommend it, even if at first you may not be able to completely apply everything (I'm still working on it :-) it will for sure give you a boost in the understanding of this subject and the process of improvisation.

Theory of scales in piano improvisation


Can we compute bivariate from marginal distributions?

Question: Can we do that? If yes, then what are the conditions which should be met?
Answer: Just knowing the marginal distributions of two variables isn't sufficient to specify their bivariate distribution. You need more information about their joint relationship. Simple example: two random normals can have any particular correlation with each other, but still have the same marginal distributions.
It sounds like you may want to consider copulas.
Comment: @Harpreet If you make it to section 3 of @Hong's Wikipedia reference you will see that Sklar's Theorem answers your question affirmatively (http://en.wikipedia.org/wiki/Copula_%28statistics%29#Sklar.27s_theorem ).
Comment: @cardinal, the point is that copulas are a way of specifying the additional information you need to obtain the bivariate distribution, if you already have the marginals.
Comment: @Hong, That's fine, I know what a copula is. My point is that they don't help here. If all you have is the marginal distributions and, not, say, the $(X,Y)$ pairs, all a copula will do is let you make up whatever dependence you'd like. They have no utility in terms of inference because you have no information about the joint distribution.
Comment: @Hong, and how are copulas supposed to help if you only have the marginal distributions?
Comment: @Harpreet, even if the marginals are normal, the joint distribution can be non-normal. You can use copulas, but as @cardinal said, you need additional information.


Como não usar tantas Activities?

Question: Olá, estou começando a programar algo no android faz alguns dias (um programinha de identificação de conchas, bem simples, porém extenso, nele você tem 5 opções, dentro dessas 5 mais algumas dependendo da especie, e dentro mais opções até chegar em uma concha específica com todas as informações dela), então eu fui criando layouts e activities pra cada espécie, classe, etc... acabou que deu umas 200 layouts e activities e ainda não cheguei no fim do programa kkkk e só aí que eu pensei "tem algo errado nisso" hehe. Então gostaria de saber se tem algum outro jeito de fazer um programa desse tipo com opções dentro de opções, totalmente offline, sem usar tantas activities e layouts.
Comment: voce pode usar fragments... dialogs personalizados... não necessariamente sempre activities... a forma de voce adaptar o codigo que vai dizer... se cada opção abrir uma pagina por exemplo e voce quizer apenas uma activity voce cria dialogs...  cada um abre uma "tela" diferente mas na realidade só tem 1...
Comment: A solução é utilizar Fragments, no limite, uma Activity pode ser suficiente para toda a aplicação.
https://developer.android.com/training/basics/fragments/index.html
Os layouts poderás re-aproveitar, já a lógica poderá ter que ser reescrita.
Answer: Cara se eu intendi direito você tem um catálogo com várias conchas, e quer exibir elas em uma lista onde o usuário possa selecionar uma e ver os detalhes, certo? Se sim, você está indo pelo caminho mais errado fazendo uma activity/fragment para cada concha, pense comigo se voce tiver um objeto "Concha", você não poderia fazer um fragment para a listagem e um para o detalhe? Esse fragment de detalhe seria genérico e exibiria as informações de um objeto concha. Me corrija se eu não intendi a sua ideia, mas se a ideia for essa: "Exibir lista e detalhes de conchas" então você está na direção errada, se a ideia for: "Para cada concha eu quero criar uma certa logica diferente por exemplo espécie X faz uma determinada ação, espécie Y faz uma ação completamente diferente da X" ai sim voce deve criar um fragment para cada espécie. E se você não souber como armazenar essas conchas que não seja fixo em um fragment dá uma estudada sobre o banco de dados do Android. NO HARD CODE!
Comment: é mais ou menos isso, só que são opções dentro de opções. Por exemplo, pra Gastropoda eu tenho 3 opções Marinho, Terrestre e Agua doce, dentro de Terrestre tenho mais 19 opções que são as famílias, dentro de Marinho tenho 102 opções, e dentro de Agua doce mais 8 kkkk e ainda pra completar tenho mais uma média de 5 especies por família totalizando umas 500 espécies só em Gastropodas kkkk Teria um jeito de fazer tudo isso ser offline? ou seria um app muito grande?
Comment: Se você precisa de uma estrutura de hierarquia em árvore, pode usar um banco noSQL, ou guardar um JSON com essas informações. Eu aconselho criar uma aplicação para atualizar o banco de dados (ou JSON), se não você vai ficar maluco na hora de atualizar as informações. Tem como fazer em banco relacional também, mas aí sai do escopo da pergunta.
Comment: Sim Vanjura, você tem ai um erro de modelagem, você não precisa criar uma activity ou fragment para cada uma das 500 espécies de Gastropodas, e sim, você consegue manter isso até em um banco de dados relacional que é o caso do SQLite que o android usa, claro que isso gera um pouco mais de trabalho do que se você usar o banco noSQL como o Daniel sugeriu, mas pelo que vejo você está iniciando no desenvolvimento, então pra simplificar você poderia usar o banco relacional (SQL) e repensar a sua modelagem
Comment: repensar a modelagem seria tipo: Uma concha é uma entidade, quais atributos todas elas (as conchas no geral) tem? alguma tem algum atributo especifico(Só essa tem esse atributo)? eu preciso fazer uma herança? por exemplo: classe pai: Concha, classe filha: Gastropodas, entendeu? se fizer assim você vai acabar provavelmente com 1 activity e umas porção pequena de fragments que poderiam ser usados genericamente para todas as mais de 500 especies de conchas e ainda de quebra vai ter um codigo mais elegante e facil de se manter :)

Como não usar tantas Activities?


Confidence interval for a constrained fit to Gaussian-like data

Question: I'm working with data from an instrument which is expected a priori to produce Gaussian (normally) distributed data:
\begin{equation}
G = A\exp\left(-\dfrac{(x - \mu)^2}{\sigma} \right)
\end{equation}
The data are normally sparse, with only about 2-3 measurements representing each $G$. In this question, I'm focussing on a single $G$, but in reality, we often have analyte signals causing overlapping $G$ that are then fitted simultaneously as described below.
To fit $G$ to our measurements, we calibrate for $\mu$ and $\sigma$ a priori using reference signals, then use these calibrations to constrain all parameters except $A$. So the fit reduces to
\begin{equation}
G = AG_0
\end{equation}
which is then fitted by least-squares minimization to determine $A$.
My main question is: what is the uncertainty ($\sigma_A$) in the fitted $A$?

My initial approach was to estimate $\sigma_A$ as the RMSE of the fit.  But since the RMSE is essentially the standard deviation of the residuals, this seems like an overestimate: I want the confidence interval of the fitted parameter.
Can I safely use the following textbook equation for the confidence interval of a linear-regression slope in this context? (the $x_i$ are the predictor variables, $\bar{x}$ is the mean of the predictor variables, the $e_i$ are fit residuals, and 2 degrees of freedom were consumed by the 1 fitted variable and the fact that the residuals sum to zero)
\begin{equation}
\sigma_A = \dfrac{s_e}{\Sigma _i (x_i - \bar{x})^2 } = \dfrac{\frac{1}{n- 2}\Sigma_i e_i^2}{\Sigma _i (x_i - \bar{x})^2 }
\end{equation}
I think "yes": all I have done is transform my $x$ before fitting a linear parameter. I also think "no" because I'm not sure of the meaning of $x_i - \bar{x}$ in this equation -- is it specific to linear regression?

To give you a visualization, my data are almost as bad as these simulated data (but often the signal ontains one or two data points more):

Note: I am aware that Bayesian analysis would be a better method for passing information about $\mu$ and $\sigma$ to my fit, but I am not at liberty to change the analysis software right now. I need to limit myself to an estimate of $\sigma_A$.
edit: Another note that might exclude some solutions: I am analyzing thousands of measurements in bulk with no known true value.
Answer: Jeff,
Two comments.
1) The steps you described correspond to fitting the model:
\begin{equation}
G_i = AG_0(x_i) + \epsilon_i
\end{equation}
with {epsilon_i} iid, normally distributed, with mean 0 and variance sigma, which is a standard linear model (linear in the way the observations are assumed to depend on the un-known parameter A), without intercept.
The least-square estimator is
\begin{equation}
\hat A = \dfrac{\Sigma _i G_i G_0(x_i)}{\Sigma _i G_0(x_i)^2 }
\end{equation}
whose variance can be estimated by
\begin{equation}
se^2(\hat A) = \dfrac{\frac{1}{n- 1}\Sigma_i e_i^2}{\Sigma _i G_0(x_i)^2 }.
\end{equation}
There would be an \bar{x} if the model had an intercept.
2) It seems, from what you say, that to reflect the uncertainty in A, a model of the form:
\begin{equation}
ln(G_i) = a + ln(G_0(x_i)) + \epsilon_i
\end{equation}
would be better. One could fit the constant a, taking the ln(G_0(x_i)) term as a fixed offset, and translate the uncertainty in the estimator of a into uncertainty in A.
Comment: Thank you! So (if I understand correctly) it was true that any transformation of the $x$ variable, followed by a linear fit, can be afterwards analyzed by standard least-squares approach.

However, I don't understand why you suggest switching from my physically-based Gaussian approach, to your log-transformation approach?  Why have you chosen a logarithmic function? To represent a more general form of the exponential Gaussian function?
Comment: The log transformation is just a suggestion. Ordinary least squares in the original scale would assume that {epsilon_i} have the same variance, but G0 and G_i decrease very fast; the assumption that errors for observations in the tails are of the same size as around \mu would not hold. You can still work in the scale of the G's; the estimator would be the BLUE estimator; use of the least-squares machinery (p-value computations, confidence intervals, etc) would not be justified since a key assumption underlying those results (equal variance of the remainders) would not be true.
Comment: Note that the log transformation also effectively changes the weighting of the data points in the least-squares minimization. Equal weights in linear scale correspond to equal absolute uncertainty, while equal weights in log scale correspond to equal _relative_ uncertainty in linear scale.


Home Folders showing as My Documents

Question: I have seen some similar questions for this
I know i can just delete desktop.ini for each folder manually
Is there a working powershell or batch file thats safe to use for this?
I have tried GPO workaround without success
User Configuration > Preferences > Windows Settings > Files (set to delete) and then put in desktop.ini
Suppress errors on individual file actions' > Common Tab > Tick 'Run in logged-on-users's security context (user policy option)' > Apply > OK
Would prefer either a script or gpo than a file screen if possible, most of our customers use One Drive, haven't seen this for a while thanks
Answer: The best solution to the issue of seeing lots of folders called "My Documents" because of desktop.ini on your file server, is to store them in a subfolder of the username.
If you redirect "My Documents" folders to \\svr\users$\%username% this causes the problem.
The path may be \\svr\users$\IrishGuy101 but when you browse the users$ share, even on the local file system of svr, it will display as "My Documents" because of desktop.ini.
A better practice is to redirect "My Documents" folders to \\svr\users$\%username%\Documents.
Now your path becomes \\svr\users$\IrishGuy101\Documents and it shows as "My Documents" only after you've browsed from the users$ share one level deeper into the IrishGuy101 folder.
You can also redirect other folders into this user folder, such as Desktop and have Documents and Desktop in the same user folder.
If for some reason doing this differently isn't an option right now, you can use a powershell command to do a recursive delete in the users share. (That sentence should be terrifying.)
Get-ChildItem * -Include "desktop.ini" -Recurse should display all the desktop.ini files from each user share. Once that looks good to delete, you can pipe the output to Remove-Item
Get-ChildItem * -Include "desktop.ini" -Recurse | Remove-Item
Comment: Thanks very much for that didnt realise I could add subfolder called documents (take everything from username folder and copy it into that and it would work) I only have 10-15 people affected so I could just delete it one by one, i would use the powershell code if it was 100% ok to use, thanks for the response :)

Home Folders showing as My Documents


Search a table based on the value of more than one cell per row

Question: I am trying to find a previous value of a unit ( the data for the unit being an entire row) entered into a table. Over time the value in one of the columns in the unit grows and I am attempting to use a loop to analyze each row based on two values in each row and return the previous value in that specific unit when a new value is entered for that specific unit.
'My Variables

    Dim current_size As Integer
    Dim last_size As String
    Dim joint_number As Integer

    Dim tool_sizes As Range: Set tool_sizes = drill_log.Range("Drill_Log[Tool Size]")
    Dim joints As Range: Set joints = drill_log.Range("Drill_Log[Joint '#]")
    Dim pass_types As Range: Set pass_types = drill_log.Range("Drill_Log[Pass Type]")
    Dim row As Range

    'Finds the current pass size and last pass size and assigns it to the current pass size variables
        If pass_type = ream Then
            current_size = drill_log.Range("W" & last_ream_range.row)
            joint_number = drill_log.Range("C" & last_ream_range.row)

        ElseIf pass_type = intersect_ream Then
            current_size = drill_log.Range("W" & last_intersect_ream_range.row)
            joint_number = drill_log.Range("C" & last_intersect_ream_range.row)
        Else
            Exit Sub
        End If

    'Finds the previous pass size for the last joint entered

        For Each row In drill_log.Range("Drill_Log")

'Line that Errors
          If pass_types.Value = pass_type And joints.Value = joint_number Then
          If tool_sizes < current_size Then
                    last_size = tool_sizes
                Else
                    last_size = "NONE"
                End If
            Else
            End If

        Next row

My goal is to have it examine the specified columns in each row and if it is a match then assign it to the variable if the cell in the column containing the information is less that the current.
Right now it is telling me that I have a type mismatch and I cant solve it.
Thanks for the help.
Comment: Which line errors?
Comment: Sorry the "If pass_types.Value = pass_type And joints.Value = joint_number Then" Line.  9th from he bottom
Comment: You don't appear to have defined (or declared) `pass_type`. Are they both single-cell ranges?
Comment: there is about 200 lines of code outside of this. The variables that aren't defined are assigned elsewhere. pass_type is a string.
Comment: I am assuming that the ranges declared in my variables are automatically assumed by the program to be referencing the row it is currently on. right?
Comment: I don't think so. I'm not really sure what you mean.
Comment: If you have a procedure that's over 200 lines of code, consider splitting it up into smaller chunks. e.g. anytime you have a comment that says "this code does XYZ", you should have a separate procedure/function *named* `DoXYZ` - comments say *why*, the *code* says *what*.
Answer: A type mismatch error on an instruction that compares Range.Value against a string or number or anything, is almost certainly due to Range.Value containing an error value.
Either fix the data and ensure there can never be an error in these cells:
=IFERROR([whatever formula you have here], "")

Or change the code so that it no longer assumes there can't be errors in the cells:
If Not IsError(pass_types.Value) And Not IsError(joints.Value) Then
    If pass_types.Value = pass_type And joints.Value = joint_number Then
        '...
    End If
End If

...or play safe, and do both wherever possible.

The reason for the type mismatch is that when IsError(Range.Value) is True, then the type of Range.Value is Variant/Error, and VBA doesn't know how to compare an Error value to anything.
Repro:
Debug.Print TypeName(CVErr(xlErrNA))       'prints "Error"
Debug.Print IsError(CVErr(xlErrNA))        'prints "True"
Debug.Print CVErr(xlErrNA)) = vbNullString 'type mismatch
Debug.Print CVErr(xlErrNA)) = 0            'type mismatch


Global access to view for using headlink plugin Zend Framework 2

Question: How can I access the headLink view helper from a global perspective, maybe for example here:
        public function onBootstrap(MvcEvent $e)
        {
            $eventManager        = $e->getApplication()->getEventManager();
            $moduleRouteListener = new ModuleRouteListener();
            $moduleRouteListener->attach($eventManager);
            $app          = $e->getTarget();
            $locator      = $app->getServiceManager();
            $view         = $locator->get('Zend\View\View');
            $view->plugin()->headLink()->appendStylesheet('img.css');
        }

Another great example would be if I used an Event that fired off a custom class which could access the view helper as well. I imagine Id need access to the application class.
Please assist any way possible.
Answer:         public function onBootstrap(MvcEvent $e)
        {
            $serviceManager = $e->getApplication()->getServiceManager();
            $headLinkHelper = $serviceManager->get('ViewHelperManager')->get('HeadLink');
            $headLinkHelper->appendStylesheet('img.css');
        }


Why does $\pm$ mean two different things in statistics?

Question: In statistics, why do we sometimes use the symbol $\pm$ to mean interval of numbers, for example in confidence intervals, and sometimes to mean two numbers, for example in the formula $x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}$?
Comment: In both cases the meaning is the same "+ or -"
Comment: Hint: An interval is fully defined by its endpoints, which is two numbers.
Comment: One can say that the confidence *interval* for an estimate is $(\hat{b}+Z_{\alpha/2} \hat{\sigma}, \hat{b}+Z_{1-\alpha/2} \hat{\sigma})$ xor the confidence *limits* for an estimate are $\hat{\beta} \pm Z_{1-\alpha/2}\hat{\sigma}$. But the latter is not an interval! That's the only case where I've seen the language abused in probability and statistics.
Answer: It doesn't mean two different things. The meaning is the same, $\pm$ means "the $\pm$ symbol may be used to indicate a symbol that may be replaced by either the plus and minus signs, $+$ or $−$, allowing the formula to represent two values or two equations". "$a \pm b$" means "$a + b$ or $a - b$". Same with $x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}$, you could replace $\pm$ symbol with $+$ or $-$ to get the two possible answers from the formula.
When defining the interval, this is shorthand for defining its bounds, $x \pm c$ means the $[x - c, x + c]$ interval bounds. Obviously, this makes sense only for an interval that is symmetric and centered around the origin, it wouldn't make sense for an asymmetric interval (think of skewed distribution).


How can I scrape a website for the nav menu only

Question: I'm building a program that scrapes a website.  It looks at the entire website and takes only the header and footer navigation menus from that website, then inserts new html tags (div, p, table, etc.) in between the header and footer menus.
I'm looking for some ideas on how to strip only the header and footer nav menus, as well as add code in between the two.
I'm using HTML Agility Pack and have worked on a few methods.
Method 1:

In most cases, the header and footer navigation menus are mostly
  links, and have very little text.  I used a threshold variable that
  was a ratio of text to links.  If the ratio text:links for a node is
  less than the threshold, the node would be considered a menu node, and
  it would be saved.  Any node whose text:links ratio was greater than
  the threshold value would be removed.

Method 1 worked for some sites, but not for others, so I ditched it.
Method 2:

I searched each node for an id or class attribute that included "nav"
  or "menu".  "n","a","v", "m","e","n","u" could have been upper case or
  lower case, and "nav" and "menu" could have been surrounded by any
  combination of characters.  That way, it would include id's and
  classes such as "bottomNav", "navRight1", "LeftMenu2", etc.  If the id
  or class contained either "nav" or "menu", the node would be saved.
  If the node's attributes did not contain either of those terms, or any
  of the node's descendants did not contain either of those terms, the
  node would be deleted.

Again, method 2 worked for some sites, but not for others.
For the sites where either of these methods worked, I still wasn't able to put new html code in between the two menus, because I had no way of telling where the header menu ended, and where the footer menu began.
I'm just looking for other ideas on how to scrape only the header and footer navigation menus from a website, and insert new html code in between the two.
Answer: Other than looking for specific elements or element classes (header, nav, ...), you can try to look at the problem in a different way:

first, fetch and parse two (or more) pages from each website, preferably checking that they vary substantially (but not totally);
then, do a diff (of the DOM, preferably), and retain only the common structure.

This common structure should consist mostly of headers, footers, navbars and other elements more or less constant across each website.
A final step might be to look in this common structure for small gaps caused by headers/footers that vary depending on context, as opposed to large gaps caused by different (main) content, and scrape their possible values from the largest set of pages you can fetch from each website.
Comment: Nice approach.   Would love to see an example of this.  I assume you would use python's difflib [link](https://docs.python.org/2/library/difflib.html)?  Also, not sure what you mean "preferably of the DOM."
Comment: @leeprevost, I'm not sure what I'd use these days (nor do I remember what particular tools came to mind at the time), but difflib seems like a perfectly reasonable (text diff) alternative.  By diffing the "DOM, preferably" I meant doing a diff of the DOM tree, instead of a simple text diff of HTML: make it operate on the structure of the document (rather than necessarily on the textual contents), and also make it tolerant to sites where the entire structure might be dynamically created from JS.


How to supress a notification pop-up?

Question: There are some notifications on Android, like the Spotify playback notification or charging notifications from the Android-System that don't visually pop up. I'm looking for the parameter inside those notifications which determines this behaviour. Anyone knows how this is done?
Thanks!
Comment: you mean you want a non-dismissable notification?
Answer: Try set the Notification flags to
    Notification.FLAG_NO_CLEAR or Notification.FLAG_ONGOING_EVENT

How to supress a notification pop-up?


Making perfect cube from factors of $20!$

Question: At least how many different factors of $20!$ must we choose so that we can always find some subset whose product is a perfect cube? For example, if we choose $\{2,3,5,7,11,13,17,19,22,26,34,38\}$, then no subset has a product that is a perfect cube, so the answer must be more than $12$.
We can write
$$20!=2^{18}\times 3^8\times 5^4\times 7^2\times 11\times 13\times 17\times 19$$
The total number of factors is $(18+1)(8+1)(4+1)(2+1)(1+1)^4=41040$, but I don't expect we need to use anything close to that.
Comment: Interesting. One can get a bound of $3^8$, but the truth must be far smaller.
Comment: @Qwerty The OP only considers factors of $20!$ Primes larger than $20$ do not occur.
Comment: Can you please provide an example to make your question more clear?
Comment: Hope it's clearer.
Comment: Find out the total number of primes $<41040$. The answer must be greater than that!
Comment: Where did you get the question?????????????????????????????
Comment: @AndréNicolas The bound can be further reduced to $3^4\cdot 2^4=1296$ because the squares of the primes $11,13,17,19$ are no factors anymore.
Answer: Seventeen.
There are sixteen factors that are primes or $2^3$ multiplied by a prime, and no non-empty product of these numbers is a perfect cube.
In the other direction, given a sequence of $17$ factors of $20!,$ we can map each factor $x_i=2^{n_{i,1}}3^{n_{i,2}}5^{n_{i,3}}\cdots 19^{n_{i,8}}$ to the tuple $n_i=(n_{i,1},\dots,n_{i,8})$ in the group $G=(\mathbb Z/3\mathbb Z)^8.$ By Olson's theorem (J.E. Olson, "A combinatorial problem on finite abelian groups I–II" J. Number Th. , 1 (1969) pp. 8–10; 195–199) $G$ has Davenport constant 17, which means some non-empty subsequence has total zero. This corresponds to a non-empty product of the factors being a perfect cube.


Cross Tab Query in MySQL

Question: I created a sql select query, but I cannot get the records to display correctly.
Table:
gradeid | usrname | reviewmonth | program | total_score | pae
--------------------------------------------------------------
151     | smithj  |      2      | math    | 100%        | 100%
152     | smithj  |      2      | math    |  95%        | 100%
153     | smithj  |      3      | math    |  80%        | 100%
154     | jonesm  |      3      | math    |  79%        | 79%
155     | jonesj  |      2      | art     |  100%       | 100%

The query that I created to display the information is
SELECT reviewmonth,
ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score)),2) AS January
FROM vwscore
WHERE program = 'Math' AND reviewmonth = 1
UNION ALL
SELECT reviewmonth,
ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score)),2) AS February
FROM vwscore
WHERE program = 'Math' AND reviewmonth = 2
UNION ALL
SELECT reviewmonth,
ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score)),2) AS March
FROM vwscore
WHERE program = 'Math' AND reviewmonth =  3
UNION ALL

The query returns: Unfortunately I need to display the records horizontally.
reviewmonth | January
----------------------
      1     |  91.94
      2     |  94.86
      3     |  89.89

Desired outcome:
January | February | March
--------------------------
   91.94|   94.86  |  89.89

I tried different queries to display the answer. I tried using CASE, but it seemed to only display 1 record. Thanks for all your help!
Comment: http://stackoverflow.com/questions/7674786/mysql-pivot-table
Comment: SELECT
COUNT(CASE WHEN reviewmonth = 1  THEN ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae, total_score)), total_score)),2) ELSE NULL END) AS 'January',
COUNT(CASE WHEN reviewmonth = 2  THEN ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae, total_score)), total_score)),2) ELSE NULL END) AS 'February',
COUNT(CASE WHEN reviewmonth = 3  THEN ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae, total_score)), total_score)),2) ELSE NULL END) AS 'March'
FROM vwscore
WHERE program = 'math'
Comment: I received this error: [Err] 1111 - Invalid use of group function. Thanks for the help. Am I missing something. I follow the sql from the link provided.
Answer: This query fulfills the horizontal demand of your question.
I am not concerned what you are trying to do.
Please make sure if this works for you.
SELECT
CASE WHEN  program = 'Math' AND reviewmonth = 1 THEN
        ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score)),2)
        ELSE 'NULL' END AS January,
CASE WHEN program= 'Math' AND reviewmonth = 2 THEN
        ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score)),2)
    ELSE 'NULL' END AS February,

CASE WHEN program= 'Math' AND reviewmonth = 3 THEN
        ROUND(AVG( IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score)),2)
    ELSE 'NULL' END AS March
FROM vwscore
WHERE program='Math'

EDIT : I was not concerned about what you expected.Now you will get the correct result I hope.
SELECT
ROUND(t.January/t.JanuaryCount,2) AS January,
ROUND(t.February/t.FebruaryCount,2) AS February,
ROUND(t.March/t.MarchCount,2) AS March
FROM
(
    SELECT
            SUM(CASE WHEN reviewmonth=1 THEN IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score) ELSE 0 END) AS January,
            SUM(CASE WHEN reviewmonth=1 THEN 1 ELSE 0 END) AS JanuaryCount,

            SUM(CASE WHEN reviewmonth=2 THEN IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score) ELSE 0 END) AS February,
            SUM(CASE WHEN reviewmonth=2 THEN 1 ELSE 0 END) AS FebruaryCount,

            SUM(CASE WHEN reviewmonth=3 THEN IF(pae = 79, (IF(pae < total_score, pae,total_score)),total_score) ELSE 0 END) AS March,
            SUM(CASE WHEN reviewmonth=3 THEN 1 ELSE 0 END) AS MarchCount

    FROM
    vwscore
    WHERE program='Math'
) AS t

Comment: Thanks for the help. The query works just like you stated. I think there is a problem with my table. The return record set returned: January | Null ; February | 92.19; March | Null. The interesting thing is that it groups everything in the month of February. Thanks again...I am puzzled.
Comment: You are welcome Rob!! Glad to hear that it worked for you. :)
Have a nice day!
Comment: It looks like if all rolls up to February. I know the query makes sense. The rest are NULL
Comment: Hi Rob! Now check the edited query. Please make sure that you got it right!
Comment: The updated answer from Md. Afafat Al Mahmud worked! I'm very impressed on how you came up with the answer. Thanks you so much!!! Thank you all again for all the help!!!!

Cross Tab Query in MySQL


Python vowel check

Question: I know there are a few ways to remove vowels, but when I try the method below, the output I get is the string just being printed len(string) times.  For example:
s="Labido Labidi"
for i in s:
        if i.lower()=='a' or 'e' or 'i' or 'o' or 'u':
            s=s.replace(i,"")
            print(s)

The resultant output is:
Labido Labidi
Labido Labidi
...and so on

What's going on inside the loop ?  It isn't even going through the if statement.
Comment: That's not the actual output. Please edit your post to include the correct output from your code. Also, take a look at [this](https://stackoverflow.com/q/20002503/198633)
Answer: You are using the or statement incorrectly:
s="Labido Labidi"
for i in s:
    if i.lower()=='a' or i.lower()=='e' or i.lower()=='i' or i.lower()=='o' or i.lower()=='u':
        s=s.replace(i,"")
        print(s)

You need to put your full evaluational statement after the or
Comment: What about 'for i.lower() in s', much shorter
Answer: The problem is your if logic.
After the first or you have to repeat i.lower() == 'e', etc.
Try this:
s="Labido Labidi"
for i in s:
        if i.lower() in 'aeiou':
            s=s.replace(i,"")
            print(s)

Answer: The problem is your if condition.  or connects two boolean expressions; it doesn't work the same as in English.  What you need to check is
if i.lower()=='a' or
   i.lower()=='e' or
   ...

Better yet, just make a single check on a list of vowels this way:
if lower() in "aeiou":

DETAILS
Any expression used as a Boolean value is evaluated according to whether it is "truthy" or "falsey".  Non-Boolean data types are sometimes not obvious.  In general, zero and `None` values are "falsey", and everything else is "truthy".

Thus, each of the single letters is "truthy", so the Python interpreter regards your if statement as if it says
if i.lower()=='a' or True or True or True or True:

In short, this is always True; your program thinks that everything is a vowel.

Python vowel check


Letter recognition feature extraction

Question: I have few thousands letter's images which are all colored black on a white background. I wanted to extract their features so that it was possible to cluster them effectively.
My attempt was to divide an image on 25 parts, calculate black pixels to white pixels ratio in each part (if there were no white ones I assumed the ratio is twice the black pixels) and thus convert an image to a vector of 25 values. I also added a 26th attribute which denoted if an image represents a letter which has a dot/something else outside its 'body'. Then I used a k-centroids algorithm to cluster the data, but the results were highly unsatisfactory.
Is there any simple, yet effective way to do what I'm trying to do?
(Images are of different size, mainly with varying width (from 5 to 30 pixels) and rather stable height (29 to 31 pixels). As I said, they are all black and white.)
Comment: Have you tried exploring the data / features you constructed? I'm not surprised those features don't work well.
Comment: Are you sure you want clustering and not classification?
Comment: No, I'm not sure actually.
Comment: @gung What do you mean by exploring the data?
Comment: Look at the patterns of the features & how they relate to the letters.
Comment: Visualizing the data, maybe in [such a plot](http://i.stack.imgur.com/dXx1A.jpg) might be helpful. Note that you probably won't get such a nice distinction between classes with the current set of features, but it might give you some idea about which features are working good.
Comment: Ok, but do you have any other ideas what features I could add? Little really comes to my mind if all I have are black and white pixels... I could additionally calculate the number of closed loops, I read it is useful in char. recognition but that's it.
Comment: Your 26th feature could be improved with connected component analysis. Other than that, I'm not experienced with digit/letter recognition, so my best bet would be to search for relevant articles and check what features they have used. Or maybe someone will be nice enough to give a summary of such articles :)
Answer: Instead of using hand-tuned features, I'd suggest using some automated form of dimensionality reduction, which will automatically extract features from your data. There are many ways to do this, ranging from the simple, linear case (e.g. PCA) to complex, nonlinear 'manifold learning' algorithms (e.g. t-SNE). Neural networks (particularly variants like autoencoders) could also work well. All of the methods I just mentioned are unsupervised, which means that they don't use labels (in your case, you'd give the images as input, but you wouldn't specify what letters they represent). Unsupervised methods work by attempting to find 'structure' in the data; what this means varies from algorithm to algorithm. There's no guarantee that the images will form clusters around the letters they represent; whether this happens or not depends on the data and how structure is defined.
You'll probably find this blog post interesting. They run various dimensionality reduction methods on the MNIST dataset, which is a set of grayscale images of hand-drawn digits.
If you explicitly want the extracted features to cluster (or at least be separable) in terms of the letters they represent, then it might be better to use a supervised algorithm (i.e. to train a classifier). In your case, you'd give the training algorithm a set of images and a set of labels indicating the letters they represent. The training algorithm will attempt to learn a function (the classifier) that predicts the represented letter from the image. Some classifiers will give you a set of extracted features, and others won't. For example, a k nearest neighbors classifier won't, so it won't be useful for your purposes (assuming that what you want to do is examine the features).
A simple, linear, supervised method is linear discriminant analysis (LDA). It will give you a set of features that are linear combinations of your input pixels. It attempts to find the weights of these linear combinations such that, when the data are projected into the feature space, it's possible to linearly separate the data points in each class (i.e. to find hyperplanes that separate the images representing each letter). Note that it may not be possible to linearly separate the classes in this way, and LDA will try to do the best it can.
A more complicated, non-linear class of methods is supervised neural networks. In this case, the network would take an image as input, and output the predicted letter the image represents (or a probability distribution over possible letters). The network would be trained to correctly classify images of letters. You can think of the units (i.e. 'neurons') in each layer of the network as representing features of the input image. Therefore, if you want to use the network for feature extraction, simply take the vector of unit activations for some layer of the network.
Dimensionality reduction and supervised learning are enormous fields, but hopefully these few examples can help getting started looking for more methods.
Comment: And what do you understand as 'giving an image as an input'? Its pixels' representation? Doesn't it matter the images are differently sized? If I were to use a neural network, I'd need to have the same amount of features and if I use pixels, I don't.
Comment: Certain classes of neural networks can process variable-sized inputs (e.g. recurrent networks). But many methods (neural net or otherwise) require fixed-size inputs. A simple option is to zero-pad the images to the same size, trying to keep your letter roughly centered in the image. Then, use pixels as input.

Letter recognition feature extraction


What is meant when a guitar amplifier does or does not "take" guitar pedals?

Question: I've been researching guitar amps to buy for a first-time electric guitar learner (me). Among the many types available, I've encountered a few described as "modeling" amplifiers, which appear to use digital circuits to recreate the tone and effects of other amplifiers or musicians.
I understand that using a particular pedal in conjunction with an amp that is also applying a bunch of effects could be counter-productive or result in a mess. In a few reviews, more experienced guitar players have said something along the lines of the amplifier not "taking" pedals.
Is this just a recommendation to not use pedals with the amp when applying its internal effects? I can't think of a reason why a pedal (such as an overdrive or delay) wouldn't be compatible with a modeling amp running in otherwise clean-signal mode.
Answer: First, an amp "taking pedals well" has little to do with modeling amps specifically or internal effects of any kind. I don't have much experience with modern modeling amps but I'd guess that they are subject to the same things as real amps. Though, in general, when people use that phrase it's usually a matter of the gain staging when using pedals like overdrives and distortions.
But it's one of those things that can mean different things to different people and whether it does it "well" is of course subjective. I'd say people are usually talking about one of two things though:

The amp is clean and has enough headroom that you can crank gain-based pedals like overdrives and distortions and get the sound from the pedal and not from the amp. So if you use a particular overdrive pedal you'll get the sound of that pedal but a completely different sound when you use a different one. The inverse—amps that don't take pedals well in this way—would be amps that always have a distinct sound even when you're getting most of the gain from a pedal.
The amp is of the variety that you'd crank to get the sound of the overdriven amp itself. But when you add a gain pedal on top of that it sounds even sweeter or still sounds good in some way. Amps that don't take pedals well in this way might crap out on you when adding a pedal on top of amp gain or it doesn't really change the sound much or sounds too muddy or flabby or something.
Comment: I find It's often more about #2, just about any amp set clean lets you do #1 ( or just bypass the preamp and go into the fx loop).  Number 2 is trickier.  Many ultra high gain amps are not meant for this because you are getting the sound of the amp.   Usually boosts and overdrives are there to help push a sweet spot thats just a little more than a given channel that isn't fully over the tip and on verge of breaking up. Dave Friedman states in his amp descriptions (and in person) "this amp loves boosts and overdrives", meaning that they will stack well with the amp distortion.
Answer: It may have to do with the amp having/not having an effects loop.
More info can be found here:
https://www.dawsons.co.uk/blog/how-to-use-an-effects-loop-on-your-amp
"An effects loop is an input/output that allows you to place effects between the pre-amp section of the guitar – where it gets its tone and the power section of the amplifier – where it amplifies the sound. This means that your pre-amp can be put anywhere in the signal chain rather than having to be the last stop. "
Comment: @LaurencePayne That is completely false!  Effects are equally likely to be in FX loop or in front of amp depending on the effect type.  You would generally never put time based effects anywhere BUT the FX loop ( loopers, delay, reverb, chorus ).   Based upon your logic FX Loops wouldn't need to exist...
Comment: A guitar effect is normally connected inline with the input, not in an effects loop.
Comment: For a guitar amp, with a single input channel, I'm not sure they DO have much use.  Remember, delay etc. boxes have a wet/dry control.
Answer: I think its simpler than that. Some amps just sound harsh, or get extra muddy with pedals. They lose their clarity, and tonal quality. Your guitar may get buried in a mix and not cut through well if your jamming with a band. It just sounds bad. there may be one decent combination of settings between the amp and pedals that actually sounds decent.
While others amps have amazing clarity, bringing out all the subtle nuances of a pedal's different parameters incredibly well. They offer a wide range of tonal possibilities that all sound good. The pedals do their job well without too much extra noise or hissing. They don't degrade the amps original tone.
A 10 watt solid state 80s peavy practice amp are harsh and  bad. Those don't take pedals (or guitars in general) well.