What are correlated errors and why are they important?

Question: I am looking for help on correlated systematic errors, and their meaning. I have some quantities $x,y,z$ which determine a function I need to calculate. These 3 quantities are determined by a measurement, and the uncertainties on the measurement translate into an uncertainty on the function they are used to calculate.
I think that somehow, these 3 observables can be varied individually to determine some type of error correlation, or covariance matrix. But I'm not sure I understand the use or meaning of error correlation. Let me be more concrete...
I am calculating a certain function, say $N = \int f(x,y,z) ~dx ~dy~ dz$ using a Monte Carlo, for a certain experiment; so I can sample randomly over $x , y , z$ and calculate $N$.
Now the measured $x,y,z$ have some experimental uncertainties, and I wish to estimate the impact of these uncertainties on $N$; i.e. $N \rightarrow N \pm \delta N$. We can take the systematic errors on $x,y,z$ to be gaussian with widths $\delta x, \delta y, \delta z$.
So I can take my Monte Carlo data set $\{x_i,y_i,z_i\}$ and smear each entry randomly within their widths to produce a new Monte Carlo Data set $\{x_j,y_j,z_j\}$, and then calculate $N_j$. I can repeat this process to produce a set of $\{N\} = \{N_1,N_2...\}$. I can then take $N \pm \delta N = {\rm mean}(\{N\}) \pm \rm{Std. Dev}(\{N\})$.
Now I think this would be a result with fully decorrelated errors. My question: what does error correlation mean, how does it apply in general (or for my problem), and what is the purpose? Am I over/under-estimating the error? If so, how do I properly check if there is correlation and deal with it properly?
If anyone has any good sources that would be greatly appreciated. I can find some useful info (https://arxiv.org/pdf/1507.08210.pdf), but I'm still quite confused. This question (How do I propagate correlated errors numerically?) seems to be related. Thank you in advance
Edit: There may be some confusion on terminology as pointed out in the comments by whuber. The types of measurement errors which I called "systematic errors" may be better called "random errors".
Comment: Are you perhaps using the term "systematic errors" to mean *random* errors?  Systematic errors, by their very definition, would not be modeled with a probability distribution as you propose.
Comment: That's a measurement error.  It is not considered "systematic."  It is one component of the random errors.
Comment: Okay. Thank you for acknowledging a confusion on terminology. I'll add an edit / disclaimer to my question to avoid confusion
Comment: Hi whuber, thanks for your comment. No I don't think I mean random (aka statistical?) errors. In my field I popularly see these errors to be Sqrt{N}, which I think comes from a poissonian distribution (N is counts of a pixel, basically). The systematic errors I am talking about are something like the following: I measure something to be a foot long, but my eyes aren't too good, so I say it's a foot $\pm$ 1 inch.
Comment: Okay fair enough, I see your point. In particle physics we call these systematic errors to distinguish them from statistical errors which occur even for a perfect experiment. Nevertheless, there can be correlations between these measurement errors, that I am trying to understand
Comment: I appreciate that different communities use their own sometimes idiosyncratic terms.  However, this use of "systematic error" does not comport with my own experience in the field nor with authorities such as Bevington & Robinson, *Data Reduction and Error Analysis for the Physical Sciences* (2002): "Systematic errors ... will make our results different from the 'true' values with reproducible discrepancies" (p. 3). Thus, your unusual use of "systematic error" outside your immediate field looks like a risky and unreliable way to communicate with others.
Answer: You can have correlation in two ways in settings like this:

the error in $x_i$ is correlated with the error in $y_i$
the error in $x_i$ is correlated with the error in $x_{i+1}$

In both situations, the effect of correlation is on how the positive and negative errors cancel (or reinforce) each other.  If the errors in $x_i$ and $y_i$ are positively correlated, the error in $x_i+y_i$ is larger and the error in $x_i-y_i$ is smaller than if they were independent.  Similarly, if the errors in $x_i$ and $x_{i+1}$ are positively correlated, the error in the sum (or average) will be higher than if they are independent.
In the real world there are reasons why correlated measurement errors are plausible

$x$, $y$, and $z$ are all measured on the same physical sample, which might not be perfectly representative (air pollution, soil sampling)
$x_i$ and $x_{i+1}$ are measured in the same location at different times, and that location is high/low compared to the average
measured in the same lab (lab drift/batch effects)
negative correlation because $x$, $y$, and $z$ add up to a fixed total (% calories from different sources)
measurements derived from the same imperfectly accurate theoretical model
etc, etc

In your case, then, you have the questions:

are your measurements positively or negatively correlated?
is your function $N$ more like an average or more like a difference? (low-pass or high-pass in engineering terms)

These questions aren't how you calculate -- you do that by simulating appropriately correlated errors -- but they are useful for thinking about what you should expect.
Comment: Thanks for your answer Thomas. Let me ask a follow up. For me the situation is the case that the error on $x$ might be correlated with $y$. But how can I understand if they are correlated? Currently I model this as independent fluctuations around the minima for each variable $x,y,z$ - in other words, the smeared value of $x$ does not depend on what $y$ is. But they could both affect $N$ non-trivially.


Representar coordenadas em vetor de Matlab

Question: Estou com problemas na criação de um vetor de objetos em Matlab, a ideia é que seja um vetor de coordenadas, i.e. as posições x e y.
O objetivo é ter um vetor para acessar as coordenadas nos loops facilmente, e ter atomicidade dos dados para ter consistência de qual posição é x ou y.
Creio que tem que usar construtor.
Dado um n de entrada será construído um array de coordenadas de tamanho n. No qual cada elemento terá seu próprio x e y.
Ex:
n=2;
vetor(n)=coord(0,0);
vetor(1).x=5;vetor(1).y=3;
vetor(2).x=2;vetor(2).y=4;

A questão principal é que quero deixar a instância vetor em uma outra classe, que terá que ter no construtor a alocação desse array de n posições.
Answer: Um vetor único para as posições x e y, acho que o certo seria uma matriz com as posições, mas em todo caso para simplificar já pensou em usar algo parecido com hash ou dicionários (scalar structure), você pode criar um dicionário chamado coordenada, dentro dele crie as coordenadas X e Y correspondentes, você pode usar algo assim:
%coloque os valores correspondentes a suas coordenadas, veja um exemplo
coordenada.X=[1 2 3 4 5]
coordenada.Y=[1 2 3 4 5]
%agora faça um loop para acessar suas coordenadas assim:
for i=1:length(coordenada.X)
     X=coordenada.X(i)
     Y=coordenada.Y(i)
 end

Seguindo o exemplo que você mostrou e que acabou de editar, você pode alocar o tamanho de cada vetor no matlab em memória usando zeros, veja:
n=2;

%alocando o espaço necessário
coordenada.X=zeros(n,1);
coordenada.Y=zeros(n,1);

%agora popule suas coordenadas
coordenada.X(1)=5; coordenada.Y(1)=3
.
.
.

Neste caso é só passar a instancia coordenada para a sua outra classe.
Comment: Não é viável fazer isto no meu caso são muitas coordenadas. Consegui uma solução utilizando a classe java.awt.Point do java num java array em Matlab, mas ainda gostaria de construir o vetor de coordenadas no próprio Matlab sem depender do Java.
Comment: é que não ficou muito claro o seu problema, um vetor de coordenadas da espaço para muitos tipos de implementaçõe,s eu aconselho você demonstrar um exemplo de como você espera que este vetor seje ...
Comment: Certo vou editar.
Comment: da uma olhada se é mais ou menos isso que precisa ..
Comment: Tive que usar um construtor pra cada classe mesmo, e se a outra não tivesse construtor não fazia nada. Contudo pelo esforço vou te pontuar.


Is this sum equal to 1?

Question: Is this function $P:\mathbb{N}\mapsto \mathbb{R}$ such that
$$
P(i)=\frac{1}{m^n}((m-i+1)^n-(m-i)^n), \quad  i\in\mathbb{N}
$$
a probability over natural numbers?
I was trying to calculate if
$$
1=\sum_{i=1}^m\frac{1}{m^n}((m-i+1)^n-(m-i)^n)
$$
Comment: Is $m$ a positive integer?
Comment: Try writing out the full sum for some simple cases ($m=1,2,3$) and see if you can spot a pattern.
Answer: The sum is telescoping
$$  \frac 1 {m^n} \sum_{i=1}^m \left[ (m-i+1)^n - (m-i)^n    \right] = \frac 1 {m^n} \left[ m^n - (m-1)^n + (m-1)^n - (m-2)^n + ... - 1^n + 1^n - 0   \right] = \frac 1 {m^n} m^n =1 $$

Is this sum equal to 1?


Why we need enabled_shared_from_this

Question: I am looking into the boost documentation for shared_ptr and enable_shared_from_this and I can not figure out practical use of enable_shared_from_this.
Below is my understanding of enable_shared_from_this (example copied from What is the usefulness of `enable_shared_from_this`?).
class Y: public enable_shared_from_this<Y>
{
    public:
      Y(): count(3){}
      shared_ptr<Y> f()
      {
         return shared_from_this();
      }
      int count;
}

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q = p->f();
    cout << "\n Count from P is " << p1->count;
    cout << "\n Count from q is " << q1->count;
}

So, now we have a shared pointer q which points to the same object owned by p (new Y) and the object gets destroyed when both p and q go out of scope. And both the print statements above will print 3 as the count.
Now, I can achieve the same thing without the use of enable_shared_from_this by doing below.
class Y
{
    public:
      Y(): count(3){}
      int count;
}

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q(p);
    cout << "\n Count from P is " << p1->count;
    cout << "\n Count from q is " << q1->count;
}

Even in the above example both P and Q point to the same object and will print 3.
So, what benefit am I getting by using the enable_shared_from_this?
Comment: A crazy thought: `shared_from_this` is some kind of "adult version" of old C++ code that uses `delete this`; i.e. it appeals to the same dirty minds.
Comment: You didn't get the mention of `count` right in the sample you're pointing to. The answerer meant the internal `shared_ptr` count.
Comment: @g-makulik - I believe my question is different to the previous question already asked in SO. My question is that both examples above provide shared ownership to the object Y. In that case, why should we use enable_shared_from_this? what benefit is enable_shared_from_this providing compared to 2nd example?
Comment: @devana It's very well explained there why it's needed and useful, and I don't see your question adding any value above the other one. It's not just rewording and changing the samples slightly, that make up a new question.
Comment: @KerrekSB hat-tip https://twitter.com/sehetw/status/519773714003402752
Answer: shared_from_this is a very special animal. Usually, you should separate responsibilities: A class does one thing, and one thing only. Owning a resource is such a responsibility, so a class should either own a resource and do nothing else, or do something else but not own a resource.
The use for shared_from_this is when this principle is violated, and a class knows that it is owned by a shared pointer. In that case, you need a way to get at that ambient shared pointer that is owning you. You cannot simply say shared_ptr<T>(this), because that would create a new owner, rather than share ownership with the existing owner.
To communicate from the class to its ambient owner, you need to derive from enable_shared_from_this, and then use shared_from_this to produce a new shareholder.
(This works practically by adding a weak_ptr<T> member to the class, and upon creation of the ambient shared pointer, that weak pointer is set to observe the shared pointer. So shared_from_this is a simple lock() invocation on the weak pointer.)

Here's an example to clarify the usage:
auto x = std::make_shared<T>();
f(*x);

// ...

void f(T const & t)
{
    auto y = t.shared_from_this();
    // ...
}

Inside f, we don't see the owner of t immediately, but shared_from_this brings it out.
Comment: @devana: Of course, but in the second example you're cheating and you already have `p`. `shared_from_this` is for situations where you only have `*p` (or `p->`)! I added an example.
Comment: My understanding is that 2nd example provided the question gives the same shared ownership as provided by enable_shared_from_this in the 1st example. Am I correct in thinking in that? If both the examples provide shared ownership to the object, why should i use enable_shared_from_this ?
Comment: Thanks for that 2nd example. That makes it very clear.
Comment: Downvoter, care to explain your objection?
Answer: The benefit is a matter of structuring. In your example, the guy who owns q might not know anything about, or have access to, the guy who owns p. It's sometimes easier to get another shared_ptr to the same instance from the type (in this case Y).
That said, I personally never use enable_shared_from_this. It's in the same boat as singletons as far as I'm concerned.
Comment: `shared_from_this` is an important idiom, when creating anonymous functors bound to `this` and passing them to an asynchronous subsystem, for instance.

Why we need enabled_shared_from_this


How to set more than one potential arguments for Keyword Element Should Contain from SeleniumLibrary in Robot Framework

Question: Could anyone help me with the following situation:
I need to check the value of a status cell in a table on a web page that can potentially have one of several different values (strings), for example: imported, done, failed.
I am using the keyword Element Should Contain from the SeleniumLibrary and would like to validate as a positive result, if the value is either imported, or done.
So far I only know how to check only for one of those, for example for imported, by using as an argument for the expected result - imported, however I need that in both cases, either imported or done, to be considered as passed.
Thank you very much in advance!
Answer: Suppose you can use for your purpose something like the following:
<code>*** Settings ***
Library    SeleniumLibrary

Test Teardown  Close Browser

*** Variables ***
${BROWSER}          Chrome
${URL}              https://stackoverflow.com/questions/64679739/how-to-set-more-than-one-potential-arguments-for-keyword-element-should-contain
${ELEMENT_LOCATOR}  //*[contains(text(), 'Ask Question')]
${EXPECTED TEXT 1}  Ask Question
${EXPECTED TEXT 2}  Anything else

*** Test Cases ***
Test with two acceptable values
    Open Browser  url=${URL}
    ...           browser=${BROWSER}
    ${element}=   Get webElement  locator=${ELEMENT_LOCATOR}
    ${bool_result}=  Set variable if  '${element.text}' == '${EXPECTED TEXT 1}' or '${element.text}' == '${EXPECTED TEXT 2}'
    ...                                ${True}
    ...                                ${False}
    Should be true  ${bool_result}
    ...             msg=Expected that element with locator '${ELEMENT_LOCATOR}' contains text '${EXPECTED TEXT 1}' or '${EXPECTED TEXT 2}', but got '${element.text}'
    Close Browser
</code>
Here I've just created the boolean variable with the result of the comparison of my element's text and the acceptable two values (${EXPECTED TEXT 1} and ${EXPECTED TEXT 2}).


Add badgeview on ActionBarSherlock MenuItem

Question: I would like to add a badge over ActionBar MenuItem
But the digit icon didn't shows.
Here's what I have done so far
public class Main extends SherlockFragmentActivity
{
  private Fragment menuFrag=null;
  private MenuItem menuMsg=null;
  private BadgeView badge=null;

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    //Do my stuff...
    initUI();
  }

  private void initUI()
  {
    FragmentManager fm=getSupportFragmentManager();
    FragmentTransaction ft=fm.beginTransaction();
    menuFrag=fm.findFragmentByTag("f1");
    if(menuFrag==null)
    {
      menuFrag=new MenuFragment();
      ft.add(menuFrag, "f1");
    }
    ft.commit();

    // badge=new BadgeView(Main.this, (View)menuMsg); //Not working
    badge=new BadgeView(Main.this, menuMsg.getActionView()); //Not working as well
    badge.setBackgroundResource(R.drawable.badge_ifaux);
    badge.setTextSize(10);
    badge.setBadgeMargin(2);
    badge.setText("1");
    badge.show();
  }

  private class MenuFragment extends SherlockFragment
  {
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      setHasOptionsMenu(true);
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
      menu.add("Cloud").setIcon(R.drawable.icon_cloud).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
      menu.add("List").setIcon(R.drawable.icon_list).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
      menuMsg=menu.add("Msg");
      menuMsg.setIcon(R.drawable.icon_msg).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
      Toast.makeText(Main.this, "Got click: " + item.toString(), Toast.LENGTH_SHORT).show();
      return true;
    }
  }
}

Where do I did wrong ?
Comment: I don't see what you would expect to happen as all you did in your code was creating a `BadgeView`. If you read the docs for that library you would see that the author explicitly says you can't do that(so feel free to extend it to add the desired behavior). Also, you shouldn't do it because it's not an Android specific design pattern.
Answer: RRTW,
The library you are using doesn't support badging Actionbar menu items natively.
https://github.com/jgilfelt/android-viewbadger/commit/e08c3a78cb92c0c8587790b15e73434f972912cf
However, it doesn't mean you can't get it to work.
The setup is going to be as follows (this assumes you already have the viewbager library setup in your project)
(1) onCreateOptionsMenu --> (2) Add a R.menu.your_place_holder_item --> (3) setActionView with custom xml layout --> (4) findViewById of the MenuItem object to get your button/view to set the badge.
1) setup your onCreateOptionsMenu and create a the R.menu.actionbar_menu_messages
R.menu.actionbar_menu_messages:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
         >
    <item android:showAsAction="ifRoom" android:icon="@drawable/action_bar_pk_content_email"
        android:id="@+id/menuMessages" android:title="More"></item>

</menu>

onCreateOptionsMenu:
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getSupportMenuInflater(); //If you are using the support library otherwise use: getMenuInflater();
    inflater.inflate(R.menu.actionbar_menu_messages, menu);
    this.setupMessagesBadge(menu.findItem(R.id.menuMessages));  //This is part of step 2
    return true;
}

2) Defined the common_messages_indicator
R.layout.common_messages_indicator:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="64dp"
             android:layout_height="fill_parent"
             android:paddingTop="10dp"
             android:gravity="center">
    <ImageView
        android:id="@+id/imgMessagesIcon"
        android:layout_width="32dp"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:scaleType="fitCenter"
        android:src="@drawable/messages_button"
        android:background="@android:color/transparent"
        android:focusable="false"
        />

   </FrameLayout>

perform setActionView to add your custom xml layout to the ActionView
private void setupMessagesBadge(final MenuItem msgItem) {
    msgItem.setActionView(R.layout.common_messages_indicator);

    if(msgItem.getActionView().findViewById(R.id.imgMessagesIcon) != null)
    {
        ImageView imgMessagesIcon = ((ImageView)msgItem.getActionView().findViewById(R.id.imgMessagesIcon));

        imgMessagesIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Your click on the action bar item will be captured here
            }
        });
        int badgeCnt = 20;// Add your count here
        if(messageCenterBadge == null && badgeCnt > 0)
        {
            //imgMessagesIcon is the imageview in your custom view, apply the badge to this view.
            messageCenterBadge = new BadgeView(this, imgMessagesIcon);
            messageCenterBadge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
            messageCenterBadge.setBadgeMargin(0);
            messageCenterBadge.setTextSize(12);
            messageCenterBadge.setText(String.valueOf(badgeCnt));
            messageCenterBadge.show();
        }
        else if(messageCenterBadge != null && badgeCnt > 0 )
        {
            messageCenterBadge.setText(String.valueOf(badgeCnt));
            messageCenterBadge.show();
        }
        else if(messageCenterBadge != null && badgeCnt == 0) {
            messageCenterBadge.hide();
        }
    }
}

Comment: what are `messageCenterBadge` variable and `appState.GetIsDisplayMessageCenter()` ? How do I initialize it?
Comment: `messageCenterBadge` nvm i got that. still what is `appState` variable and `GetIsDisplayMessageCenter()` method?
Comment: I have removed that method from the example above. It was specific to a an application I was working on. It is not required to implement the badging.


Conditional CSS if div content wraps

Question: I have a navigation bar across the top of the page. It's just made up of a div wrapping stylized a links. JsFiddle

    1
    2
    3
    4

When the user shrinks the page and the links go beyond the width of the window, some of them drop below. What I'd like is for a border to go at the bottom of everything but the last child--that is, the last children that just became the last children because of window resize and not actual code placement. Is this possible?
Comment: This is the only way with CSS I can think to do it: http://jsfiddle.net/LenMU/13/
Comment: please add your actual code in rather than only provide a jsFiddle. there is a reason you were forced to put a code block into your question.
Comment: @PlantTheIdea I wasn't forced to this time but sure.
Comment: you weren't forced to "this time" because you put `div` and `a` as code blocks. its the cheaters way to get around the requirement, and highly frowned upon. greatly appreciate you making the change.
Comment: Could you set a height on your div and then put a border on that?
Comment: @Chad I could, but if the window is resized to extreme tininess, the border would only appear to be around the topmost link group.
Comment: I think I'm having trouble visualizing what you're asking for. If you put together some simple diagrams, I should be able to help you.
Comment: @Chad Hope this is explanatory enough: http://jsfiddle.net/LenMU/9/ Pretending that the navigation widths are what the user would've resized their window to. I basically just want a separator between 'rows'.
Comment: @Chad Looks simple and perfect, thank you!
Answer: Something like this should work
@media (max-width: 100px) {
    .navigation a { border-bottom: 1px solid red; }
    .navigation a:last-child { border-bottom: none; }
}
}

Comment: Nice, but is there any way to make this work for other formations (eg. one below or two below instead of just one column) without calculating the max-width of everything? The link text I am using for real aren't of all the same length, and said length will change depending on the language.
Comment: What you're trying to do is called Responsive design. You may want to look into a framework or some tutorials on responsive layouts.

http://www.getskeleton.com/
Answer: Hi if you want a separation between rows you can use this code that evaluates if some a element are separated from the top:
$('.navigation a').each (function () {
        var off=$(this).offset().top;
        if (off > 10) {
            $('.navigation a').css('border-bottom','3px solid red');
        } else {
            $('.navigation a').css('border-bottom','none');
        }
    });

Check it here working http://jsfiddle.net/LenMU/16/

Conditional CSS if div content wraps


hook_cron(): PHP output does not appear

Question: I am (finally) migrating our Drupal 7 sites to Drupal 10.
The one problem I have not been able to resolve is output from the hook_cron().
Everything appears to execute, whether running on the browser using the special link, clicking on the 'Run cron' button, or as a crontab job. (This is verified by the logger messages, or informational messages which will subsequently appear on the site.)
However, none of the PHP output (for example, echo or print_r()) which worked under Drupal 7 appear on the browser or as an external crontab task. The web page doesn't even refresh.  This is problematic because our cronjobs output a lot of debug information that allow us to verify that the tasks ran correctly, and this output is redirected into an email which can be reviewed without accessing the Drupal site.  So it is not practical to use the logger or other Drupal mechanisms.
Interestingly, there are scenarios where the output does appear, which might provide a clue as to what the problem is:

if I include a call to phpinfo()
on certain (but not all) PHP errors, which causes all preceding output to appear

Note that this issue also occurs with the example cron code (cron_example.module) if I try to add echo statements; I have found one other user (on the drupal forum) who also ran into this as part of other questions, but there was no any information on how to resolve it.
I tried flush() in case it's some sort of buffering issue, but to no avail.
function cron_daily_cron() {
  // This output is not shown.
  echo "cron_daily_cron started...";

  // The messenger message is shown.
  \Drupal::logger('cron_daily')->notice('cron_daily_cron started');
  \Drupal::messenger()->addMessage('cron_daily_cron started...', 'info');
  \Drupal::logger('cron_daily')->notice('cron_daily_cron exited');

  // The error output caused by the following line is shown.
  inexistentfunctioncall();

  // This message is not shown.
  echo "cron_daily_cron exited";
}

thank you!
Comment: Thanks, I will investigate our php configuration.It may indeed be unusual, but as I wrote, it's our way to manually verify that the cronjob is working correctly, such as sending timely email notifications.  Think of it as proactive debugging, in case an email was sent which should not have, or vice-versa, among other types of issues.  We can't just rerun the cronjob to figure out after the fact what happened since it may resend emails, or conditions have changed.
Comment: Is this because of output buffering in Drupal?  I didn't know that echoing strings in hook_cron implementations is even supposed to be supported.
Comment: I tried turning off php.ini variables that might cause the issue, specifically output_buffering and implicit_flush, but no effect.
What did work is enclosing all the cron output between ob_start() and ob_get_clean( ) and emailing the buffered output, so this workaround will do.
Comment: This seems to be specific to cron, since all the output from other custom modules,  are displayed.
Answer: The cron controller returns an empty string with a HTTP status 204 (No Content) by design. Otherwise, they could buffer the output and put it in the response.
However, you can try to run cron via drush
drush cron

This does produce PHP output on the command line when I test it.

hook_cron(): PHP output does not appear


Very slow query to find all records without a relationship

Question: I am trying to find all of the users which do not have any orders.
So far I've tried the following:
select * from `users` where not exists
(select * from `orders` where `users`.`id` = `orders`.`user_id`)

I've also tried the following:
select users.*, count(distinct orders.reference) as orders_count from `users`
left join `orders` on `users`.`id` = `orders`.`user_id`
group by `users`.`id` having orders_count = 0

However, both are very slow running queries. There are around 5000 customers and 30,000+ orders. Is there a more efficient way of doing this?
Comment: Did you tried indexing?
Answer: You need to limit your subquery to only look at user_id. Also make sure user_id is indexed.
Alter table orders add index(user_id)

Select * from users where id NOT IN(select user_id from
orders)


How can I rehearse and perform with PDF scores on screen instead of paper scores?

Question: As a chorus and opera singer, I have gotten tired of lugging thick opera scores everywhere. Most of the music I sing is public-domain, and the scores are freely available in in PDF form. I am working my way to a setup that lets me rehearse and perform by reading PDF scores from tablet readers, instead of from printed books.
The problems I have with printed scores are:

They are heavy, especially for rehearsals where we are doing numbers from multiple shows and so I need multiple scores
Photocopying pages from scores or printing from downloaded PDF files imposes a cost per page
Published scores are expensive
Some operas don't have printed scores in distribution for any reasonable price

What equipment set and score preparation process would let me leave my heavy vocal scores behind for good?
Comment: Inspired by [_What's a good PDF score reading app for iPad?_](http://music.stackexchange.com/questions/8250/whats-a-good-pdf-score-reading-app-for-ipad?noredirect=1), but worded to focus on "Practice technique" (per FAQ) and not on "shopping recommendations".
Comment: Along with PDF organizer apps in the answers, I might add that there are reliable apps e.g. https://michaelng126.github.io/ai-page-turner/ which use your face gestures (e.g. winking) to turn pages. It's worked well for me :)
Comment: @Supermartingale thank you for this comment. It sounds like it is a partial answer to the question. I encourage you to write an answer which includes ai-page-turner and the other gear which works well for you. Share your experience!
Answer: Disclaimer up front: I work for the company that makes these devices, but also use the software they run myself regularly.
Have a look at the MusicOne range. You do lose a degree of portability over a tablet in going for a larger screen size.
The problem of rendering speed is overcome by importing the PDF files or scanning the originals into a library that stores pages as high-quality images, which render much faster than PDFs.
They also give you the ability to annotate the score.
Answer: One commercial solution is musicreader.net, as well as the device "Freehand MusicPad Pro" (the producing company is no longer operational, however). ePaper is too slow, you need a TFT of 10 inch or more, especially since scanned scores do not reflow. Especially the multi-voice scores wont stay readable easily.
Exercise marks are difficult: do you expect to do that on the device itself? If not, any PDF editing program will do. Note taking is possible on many devices, you can at least put a dog ear for later reference (bookmark in the eReader sense as opposed to PDF sense).
Answer: There are several music-score-oriented PDF display apps for iPad that are highly-rated. I'm not making any endorsement and I have no direct experience with them. The advantage of these systems is that they are designed to enable you to assemble "set lists" of scores that can be placed in a specific order so you don't have to hunt around for different scores between pieces. They also provide annotation features designed for marking up sheet music.
ForScore by MGS Development
iGigBook by Black & White Software
Do a Google search for "sheet music pdf for ipad" to find more.
Answer: For what it's worth, here's what I've learned so far, in using scanned music scores in PDF form on an iPad.

Some PDF files containing high-resolution scans of the score take a long time to display. The degree of lag is a function of how the PDF file was made. In some scores it seems like the page starts off blurry and comes into focus.
It's difficult to jump to arbitrary points in the score (e.g. director says, "let's skip to page 166", those with books turn easily, I fumble fumble on the device)
It's hard to add bookmarks to PDF files to correspond to rehearsal numbers, to speed up jumping to points in the score.
There's no way I know of to make annotations on the score during a rehearsal, even an "x" to say "review this later". The built-in PDF reader does let you "bookmark" pages, but that seems to just put a red ribbon mark on the page, and it's not easy to jump to that bookmark during a performance.

In trying to read a score with a Kindle, I found:

Screen size too small. Not enough of the score is visible at a time.
The built-in PDF reader on the Kindle is really delicate. Some of my music score PDF files caused it to crash.

So far my list of capabilities to look in on-screen score systems are:

Should read ahead in the PDF file, digesting the next couple of pages of the score, so that when I turn to the next page, the page appears instantly -- for all PDF files, even those with high-resolution scanned images.
Easy ways to jump to page numbers and rehearsal numbers quickly, while rehearsing.
Ways to add bookmarks to scores for rehearsal numbers
Some way of annotating the score.
Displays each musical staff at least 7mm high, while still showing a complete line of music.
Displays the score at least 15cm x 10cm, preferably 20cm x 25cm, and a huge 50cm x 33cm would be even better. These are based on sizes of printed music scores used by commercial publishers, which presumably reflect the best practices of centuries of tradition.
Comment: It occurs to me that a system where you took one picture per measure or per pair of measures, then set a metronome like timing to scroll the stack of images may work.


Base64 chegando corrompido via post no flask

Question: Estou enviando um base64 dentro de um post para o flask, e o mesmo esta substituindo o sinal de adição "+" por espaços " ".
Exemplo de código original:
curl -X POST localhost:5000/api/send -d 'data={"num": "01", "msg": [{"text": ":)", "att":"JVBERi0xLjMNCiXi48/TDQoNCjEgMCBvYmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL091dGxpbmVzIDIgMCBSDQovUGFnZXMgMyAwIFINCj4+DQplbmRvYmoNCg0KMiAwIG9iag0KPDwNCi9UeXBlIC9PdXRsaW5lcw0KL0NvdW50IDANCj4+DQplbmRvYmoNCg0KMyAwIG9iag0KPDwNCi9UeXBlIC9QYWdlcw0KL0NvdW50IDINCi9LaWRzIFsgNCAwIFIgNiAwIFIgXSANCj4+DQplbmRvYmoNCg0KNCAwIG9iag0KPDwNCi9UeXBlIC9QYWdlDQovUGFyZW50IDMgMCBSDQovUmVzb3VyY2VzIDw8DQovRm9udCA8PA0KL0YxIDkgMCBSIA0KPj4NCi9Qcm9jU2V0IDggMCBSDQo+Pg0KL01lZGlhQm94IFswIDAgNjEyLjAwMDAgNzkyLjAwMDBdDQovQ29udGVudHMgNSAwIFINCj4+DQplbmRvYmoNCg0KNSAwIG9iag0KPDwgL0xlbmd0aCAxMDc0ID4+DQpzdHJlYW0NCjIgSg0KQlQNCjAgMCAwIHJnDQovRjEgMDAyNyBUZg0KNTcuMzc1MCA3MjIuMjgwMCBUZA0KKCBBIFNpbXBsZSBQREYgRmlsZSApIFRqDQpFVA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NTIyIDAwMDAwIG4NCjAwMDAwMDE2OTAgMDAwMDAgbg0KMDAwMDAwMjQyMyAwMDAwMCBuDQowMDAwMDAyNDU2IDAwMDAwIG4NCjAwMDAwMDI1NzQgMDAwMDAgbg0KDQp0cmFpbGVyDQo8PA0KL1NpemUgMTENCi9Sb290IDEgMCBSDQovSW5mbyAxMCAwIFINCj4+DQoNCnN0YXJ0eHJlZg0KMjcxNA0KJSVFT0YNCg==", "mime":"application/pdf"}]}'

Isso é o que estou printando do outro lado (demorei para perceber que o problema não era o decode do base64):
{"num": "01", "msg": [{"text": ":)", "att":"JVBERi0xLjMNCiXi48/TDQoNCjEgMCBvYmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL091dGxpbmVzIDIgMCBSDQovUGFnZXMgMyAwIFINCj4 DQplbmRvYmoNCg0KMiAwIG9iag0KPDwNCi9UeXBlIC9PdXRsaW5lcw0KL0NvdW50IDANCj4 DQplbmRvYmoNCg0KMyAwIG9iag0KPDwNCi9UeXBlIC9QYWdlcw0KL0NvdW50IDINCi9LaWRzIFsgNCAwIFIgNiAwIFIgXSANCj4 DQplbmRvYmoNCg0KNCAwIG9iag0KPDwNCi9UeXBlIC9QYWdlDQovUGFyZW50IDMgMCBSDQovUmVzb3VyY2VzIDw8DQovRm9udCA8PA0KL0YxIDkgMCBSIA0KPj4NCi9Qcm9jU2V0IDggMCBSDQo Pg0KL01lZGlhQm94IFswIDAgNjEyLjAwMDAgNzkyLjAwMDBdDQovQ29udGVudHMgNSAwIFINCj4 DQplbmRvYmoNCg0KNSAwIG9iag0KPDwgL0xlbmd0aCAxMDc0ID4 DQpzdHJlYW0NCjIgSg0KQlQNCjAgMCAwIHJnDQovRjEgMDAyNyBUZg0KNTcuMzc1MCA3MjIuMjgwMCBUZA0KKCBBIFNpbXBsZSBQREYgRmlsZSApIFRqDQpFVA0KQlQNCi9GMSAwMDEwIFRmDQo2OS4yNTAwIDY4OC42MDgwIFRkDQooIFRoaXMgaXMgYSBzbWFs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AwMDAyNDU2IDAwMDAwIG4NCjAwMDAwMDI1NzQgMDAwMDAgbg0KDQp0cmFpbGVyDQo8PA0KL1NpemUgMTENCi9Sb290IDEgMCBSDQovSW5mbyAxMCAwIFINCj4 DQoNCnN0YXJ0eHJlZg0KMjcxNA0KJSVFT0YNCg==", "mime":"application/pdf"}]}

Answer: O problema é que o CURL por padrão manda dados emulando formulários enviados por um browser, com o Content-Type como "application/x-www-form-urlencoded" - o que o Flask faz quando vê esse cabeçalho é traduzir alguns caracteres de forma que a mensagem fique intelígivel como partes de um formulário - e isso inclui traduzir o "+" para " ".
Para evitar isso é só mudar o cabeçalho de content-type. Usando o CURL, isso significa passar a opção "-H" com o cabeçalho exato desejado:
curl http://127.0.0.1:7500 -H "Content-Type: application/json" --data '{"teste": "blip+blop"}'

Alternativamente você pode usar o "httpie" - um projeto semelhante ao CURL, para disparar requisições HTTP a partir da linha de comando, mas que é mais amigável para o uso de APIs. O httpie é em Python, então pode ser instalado no próprio ambiente do seu projeto com  pip install httpie - isso disponibiliza o comando http (para ser usado no lugar do Curl) - que pode simplificar bastante  a vida.
Comment: Era isso mesmo. Passei dias revisando o código, printando e debugando... Muito obrigado.


Windows Run can't find batch file

Question: I created a very simple batch file that works when I double click the file, but if I try to launch it by typing in the name of the batch file into Windows Run, Windows is unable to find it. If I type in the name of the folder containing the batch file, the folder opens up.
Fairly new to coding. I'm going through "Automate the Boring Stuff" book
Comment: WIN+R starts in your `%userprofile% directory. Where is your script, and where is the folder located?
Comment: In Run their is a _Browse_ button. Browse to your file and it will fill in the right path to type. Then it will be in the history in Run.
Answer: Run searches the folders in your global %PATH% variable for your file. It's unlikely that your script is in one of the directories mentioned in %PATH%.
To see the contents of PATH, type ECHO %PATH% into a command prompt. You can then move your script to one of the directories.
Alternatively, to temporarily (for the current CMD session) add a directory to PATH, run SET PATH=%PATH%;C:\path in your command prompt. A permanent change in PATH requires use of the registry.
I recommend you reconsider this approach however, as launching CMD then navigating to the script's location (CD C:\path) to then run the script is generally preferable to changing global variables.
Comment: Hey, just trying to figure things. Windows Run is able to find the folder containing my batch file, but it can't find the batch file itself. Shouldn't it be able to run the file in the folder if it can open the folder?
Comment: What do you mean by "find the folder containing the batch file"? If you're typing the path to the folder into Run, it'll open the path using Explorer. Likewise, if you're typing the full path of your batch file into Run, it'll open the batch file directly. If you only type in a filename, it'll search for that filename as I described in my answer.

Windows Run can't find batch file


How to obtain variance of proportion given its point estimate and 95% CI

Question: Suppose I have a proportion estimate and 95% CI: 0.39 (0.28, 0.58), how would I obtain the variance?
Typically 95% CIs are defined as $0.39 \pm 1.96\cdot SE = (0.28, 0.58)$. And suppose I know that the sample size $n = 100$. Since $SE = \frac{\sigma}{\sqrt{n}}$, I can easily solve for $\sigma^2$ with algebraic manipulation. However, I have two questions:

How to deal with the asymmetric nature of this confidence interval?  That is, the 2 estimates of $\sigma$ below are not consistent:

Lower bound: 0.$39-1.96\cdot \frac{\sigma}{10} = 0.28 \Rightarrow \sigma = 0.56$
Upper bound: $0.39 + 1.96\cdot \frac{\sigma}{10} = 0.58 \Rightarrow \sigma = 0.96$

How to make sure that the proportion is $\in [0, 1]$?
Suppose I take the larger value of $\sigma = 0.96$ just so the CI will be more conservative (wider), so my new lower bound is $0.39-1.96\cdot \frac {0.96}{10} = 0.21$ which is fine for this example, but there might be cases where taking the more conservative $\sigma$ will lead to a CI that is outside the bounds of $[0, 1]$
Comment: The CI has not been obtained using the approach you suggest, since that gives a symmetric interval. There are many [CIs for binomial proportions](https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval); however you can estimate a standard error for the proportion from the proportion and $n$
Comment: If your proportions are close to zero or unity (for some meaning of close) you may want to transform them first anyway, work on the transformed scale, and then back-transform.
Answer: There are many ways to obtain confidence intervals. Generally, there are different corrections for different measures that all correct for some properties of the data, where the standard method may be inaccurate (e.g. Wherry's $R^2$ to correct for the amount of $IV$ in OLS regression). Similarly, in some cases there are methods to generate better CIs than the standard method.
Because the distribution of the correlation is not normal (not even symmetric) you have to use some trick. To give an extreme example consider a population correlation of $\rho=0.99$. Clearly, the distribution of all sample correlations $r$ around this $\rho$ will be (heavily) left-skewed.
Fishers Z transformation is good tool to use with correlations. You transform your correlation to follow an approximately normal distribution, calculate the CI, and transform the CI back for interpretation.
Let's start: You are given $r$ and $n$ the sample correlation and sample size.
First, you transform your $r$ to $r_z$ the Fisher transformed $r$.
$$r_z=\frac{1}{2} ln\left(\frac{1+r}{1-r}\right)$$
Now $r_z$ is approximately normal, $r_z\sim N\left(\rho_z, 1/\sqrt{n-3}\right)$. Therefore, we can easily apply the standard method to $r_z$.
The confidence interval will be
$$r_z \pm z* \frac{1}{\sqrt{n-3}}$$
Now you inverse the transformation:
$$r=\frac{e^{2 r_z}-1}{e^{2r_z}+1}$$
Apply this formula to the lower and upper bounds of $r_z$ and you will receive the CI for $r$.
Beyond your question: you can also apply standard null hypothesis significance testing to $r_z$. Though, if you are testing against $\rho=0.5$, you do not have to apply the transformation, because in this rare case $\rho$ already is normally distributed.


`dict.popitem` with filtered data and a conditional flag

Question: I am implementing a something that uses a dictionary to store data. Additionally to the normal data, it also stores some internal data, all prefixed with _. However, I want to isolate the user of the library from this data since he is normally not concerned with it. Additionally, I need to set a modified flag in my class to track if the data was modified.
For all interface functions this worked nicely, here are two examples, one with and one without modification. Note that in this case, I do not hide internal data, because it is intentionally demanded as a key:
def __getitem__(self, key):
    return self._data[key]

def __setitem__(self, key, value):
    self.modified = True
    self._data[key] = value

On some functions, e.g. __iter__, I filter out everything that starts with _ before I yield the data.
But a single function makes real problems here: popitem. In its normal behaviour it would just withdraw an arbitrary item and return it while deleting it from the dict. However, here comes the problem: Without deep internal knowledge, I don't know which item will be returned beforehand. But I know that popitem follows the same rules as items and keys. So I did come up with an implementation:
keys = self._data.keys()
for k in keys:
    if k.startswith("_"):
        continue
    v = self._data.pop(k)
    self.modified = True
    return k, v
else:
    raise KeyError('popitem(): dictionary is empty')

This implementation works. But it feels to unpythonic and not at all dynamic or clean. It did also struggle with the idea to raise the exception like this: {}.popitem() which looks totally insane but would give me at least a dynamic way (e.g. if the exception message or type ever changes, I don't have to adjust).
What I am now after is a cleaner and less crazy way to solve this problem. There would be a way of removing the internal data from the dict, but I'd only take this road as a last resort. So do you have any recipes or ideas for this?
Answer: Give your objects two dict attributes: self._data and self._internal_data.  Then forward all the dict methods to self._data, and you won't have to filter out anything.
edit: Okay, I missed the "last resort" bit at the end.  But I suspect that managing two dicts will be far easier than "fixing" every single dict method and operator.  :)
Comment: @kindall or possibly look at `ChainMap`
Comment: If you want to do this, then subclass `dict` and implement `__missing__()` so that it looks up items in the second dict when it fails to find them in the first.
Comment: @kindall doesn't that defeat the point?  i'm not actually sure why this data is all stored in the same dict in the first place when the OP is going to such lengths to hide it all.
Comment: @Eevee The OP states he wants the data to be available if the exact name is requested but not when iterating, popping, etc.
Comment: @kindall whoops, missed that paragraph entirely.  checking both in `__getitem__` is simplest by far then.
Comment: `__missing__` is even simpler, since you don't need an `if`.
Comment: That is **awesome**. Through a combination of using two distinct dicts and persisting them as a tuple and applying `__missing__` and `UserDict` with some additional tweaks required for this case, I got a way simpler solution working.
Answer:
Subclass dict rather than wrapping a dictionary. You'll need to implement a lot less stuff.
Store your "internal data" as attributes on the object, not in the dictionary. This way they are easy to get to if you need them, but won't appear in ordinary iteration. If at some point you need to combine them, do that with x = dict(self); x.update(self.__dict__) to create a new dictionary having both sets of values.

If you do want to store your internal data as a dictionary, embed that one. Implement __missing__ on your main object so you can grab items from the internal dictionary if they're not found in the main one.
Answer: Well, the logic's correct, you could reduce it to something like:
self._data.pop(next((key for key in self._data if not key.startswith('_')), 'popitem(): dictionary is empty'))

So, find the next key in self._data that doesn't start with _, otherwise default it to a key that isn't going to match any of the other keys in the dictionary so that when the pop fails, you automatically get the KeyError thrown (with your "error message")


Movendo peça, acrescenta novo tabuleiro de jogo

Question: Bom dia, Estou com um pequeno problema na elaboração de um jogo de tabuleiro.
Quando tento mover uma peça, devolvendo um novo quadro(array de arrays), esta é adicionado à página em vez se substituir. Fico assim com dois e três quadros de acordo com as jogadas que fizer.
O meu código é o seguinte:

"use strict"
function main() {

 var sGame = startGame(8, 4, 3)

 createGrid(sGame)
 //document.getElementById("game").innerHTML = tableOfGame; //passar para o html

 var UP1 = document.getElementById("UP1");
 UP1.onclick = function () {
  sGame = moveUp(sGame, 'P1');
  createGrid(sGame)

 }

 var Down1 = document.getElementById("Down1");
 Down1.onclick = function () {
  sGame = moveDown(sGame, 'P1');
  createGrid(sGame)
 }

 var Left1 = document.getElementById("Left1");
 Left1.onclick = function () {
  sGame = moveLeft(sGame, 'P1');
  createGrid(sGame)
 }

 var Right1 = document.getElementById("Right1");
 Right1.onclick = function () {
  sGame = moveRight(sGame, 'P1');
  createGrid(sGame)
 }
}

function createTurtleBoard(boardSize) {
 let tabuleiro = [boardSize];
 for (let row = 0; row < boardSize; row++) {
  tabuleiro[row] = [boardSize];
  for (let column = 0; column < boardSize; column++) {
   tabuleiro[row][column] = 0;
   //playerPosition.addEventListener('click', movePlayer, false)
  }
 }
 return tabuleiro;
}

function jewelsInsert(tableOfGame) {
 let rowA = (tableOfGame.length) / 2;
 let rowB = (tableOfGame.length) / 2 - 1;
 let columnA = (tableOfGame.length) / 2;
 let columnB = (tableOfGame.length) / 2 - 1;
 tableOfGame[rowA][columnA] = 'J';
 tableOfGame[rowB][columnB] = 'J';
 tableOfGame[rowA][columnB] = 'J';
 tableOfGame[rowB][columnA] = 'J';
 return tableOfGame
}

/*
*
*
*
*/
function addPlayers(tableOfGame, numPlayers) {
 let position = tableOfGame.length - 1;
 switch (numPlayers) {
  case 1:
   tableOfGame[0][0] = 'P1';
   break;
  case 2:
   tableOfGame[0][0] = 'P1';
   tableOfGame[position][0] = 'P2';
   break;
  case 3:
   tableOfGame[0][0] = 'P1';
   tableOfGame[position][0] = 'P2';
   tableOfGame[position][position] = 'P3';
   break;
  default:
   tableOfGame[2][2] = 'P1';
   tableOfGame[position][0] = 'P2';
   tableOfGame[position][position] = 'P3';
   tableOfGame[0][position] = 'P4';
   break;
 }
 return tableOfGame
}

function wallInsert(tableOfGame, numWall) {
 let size = tableOfGame.length - 1;
 let count = 0;
 while (count < numWall) {
  let column = Math.floor((Math.random() * size))
  let row = Math.floor((Math.random() * size))
  if (tableOfGame[row][column] === 0) {
   tableOfGame[row][column] = 'W'
   count++
  }
 }
 return tableOfGame
}

function startGame(boardSize, numPlayers, numWall) {
 let board = createTurtleBoard(boardSize);
 board = jewelsInsert(board);
 board = addPlayers(board, numPlayers);
 board = wallInsert(board, numWall);

 return board;

}

function playerFinder(tableOfGame, player) {
 let len = tableOfGame.length;
 for (let row = 0; row <= len; row++) {
  for (let column = 0; column <= len; column++) {
   if (tableOfGame[row][column] == player) {
    return [row, column];
   }
  }
 }
}

function isItAllowed(tableOfGame, player, tag) {
 let pl = playerFinder(tableOfGame, player)
 let row = pl[0];
 let column = pl[1];

 if (tag = "mUp") {
  if (row == 0 || tableOfGame[row - 1][column] == "p1" || tableOfGame[row - 1][column] == "p2" || tableOfGame[row - 1][column] == "p3" || tableOfGame[row - 1][column] == "p4" || tableOfGame[row - 1][column] == "w") {
   return false;
  }
  else { return true }
 }

 else if (tag = "mDw") {
  if (row == tableOfGame.length - 1 || tableOfGame[row + 1][column] == "p1" || tableOfGame[row + 1][column] == "p2" || tableOfGame[row + 1][column] == "p3" || tableOfGame[row + 1][column] == "p4" || tableOfGame[row + 1][column] == "w") {
   return false;
  }
  else { return true }
 }

 else if (tag = "mLf") {
  if (column == 0 || tableOfGame[row][column - 1] == "p1" || tableOfGame[row][column - 1] == "p2" || tableOfGame[row][column - 1] == "p3" || tableOfGame[row][column - 1] == "p4" || tableOfGame[row][column - 1] == "w") {
   return false;
  }
  else { return true }
 }

 else if (tag = "mRt") {
  if (column == tableOfGame.length - 1 || tableOfGame[row][column + 1] == "p1" || tableOfGame[row][column + 1] == "p2" || tableOfGame[row][column + 1] == "p3" || tableOfGame[row][column + 1] == "p4" || tableOfGame[row][column + 1] == "w") {
   return false;
  }
  else { return true }
 }
}

function moveUp(tableOfGame, player) {
 var table = tableOfGame;
 let pl = playerFinder(table, player)
 let row = pl[0];
 let column = pl[1];
 console.log("pos" + table[row][column])
 let control = isItAllowed(table, player, "mUp")
 console.log("control" + control)
 if (control == true) {
  var n = table.length
  table[row][column] = 0;
  table[row - 1][column] = player;

 }
 return table
}

function moveDown(tableOfGame, player) {
 var table = tableOfGame;
 let pl = playerFinder(table, player)
 let row = pl[0];
 let column = pl[1];
 console.log("pos" + table[row][column])
 let control = isItAllowed(table, player, "mDw")
 console.log("control" + control)
 if (control == true) {
  var n = table.length
  table[row][column] = 0;
  table[row + 1][column] = player;

 }
 return table
}

function moveLeft(tableOfGame, player) {
 var table = tableOfGame;
 let pl = playerFinder(table, player)
 let row = pl[0];
 let column = pl[1];
 console.log("pos" + table[row][column])
 let control = isItAllowed(table, player, "mLf")
 console.log("control" + control)
 if (control == true) {
  var n = table.length
  table[row][column] = 0;
  table[row][column - 1] = player;

 }
 return table
}

function moveRight(tableOfGame, player) {
 var table = tableOfGame;
 let pl = playerFinder(table, player)
 let row = pl[0];
 let column = pl[1];
 console.log("pos" + table[row][column])
 let control = isItAllowed(table, player, "mRt")
 console.log("control" + control)
 if (control == true) {
  var n = table.length
  table[row][column] = 0;
  table[row][column + 1] = player;

 }
 return table
}

function createGrid(tableOfGame) {
 var y = document.getElementById("gridOfGame");
 var n = tableOfGame.length;
 for (let i = 0; i < n; i++) {
  var tablerow = document.createElement("tr");
  var tableData;
  for (let j = 0; j < n; j++) {
   tableData = document.createElement("td");
   tableData.innerHTML = (tableOfGame[i][j]);
   tablerow.appendChild(tableData);
  }
  y.appendChild(tablerow);
 }
}

function delRow() {
 let x = tableOfGame.length;
 for (let i = 0; i < x; i++) {
  function moveUp() {
   document.getElementById("myTable").deleteRow(i);
  }
 }
}

document.addEventListener("DOMContentLoaded", function (event) { main() });
<!DOCTYPE html>

  <meta charset="utf-8">

  <link href="style.css" rel="stylesheet">
  <link href="position.css" rel="stylesheet">
  <title>Play</title>

  <audio autoplay>

    <source src="music.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
  </audio>

Login

Como Jogar

Classificação

História

Registar

Game

    <button id='UP1'>UP</button>
 <button id = 'Left1'>Left</button><button id = 'Right1'>Right</button>
 <button id = "Down1">Down</button>

Início

Carregando numa direção qualquer o 'P1' vai mudar de posição, mas vai duplicar o quadro.
Como faço para não o fazer e me devolver o quadro alterado só?
Obrigado pela ajuda.
Comment: Acredito que está duplicando pois a cada interação você faz a chamada novamente do método de criação. Logo acredito que uma alternativa é "limpar" a #gridOfGame antes de recriar a tabela, pesquise sobre remover elementos com javascript. Ou seja, em sua função de createGrid(tableOfGame) faça alguma maneira para limpar . Se você utilizar o inspecionador de elementos do seu navegador para entender melhor o fluxo. Espero ter ajudado.
Answer: Esvazie a div que recebe a tabela antes de fazer o appendChild colocando:
y.innerHTML = '';

Após:
var y = document.getElementById("gridOfGame");

Na função createGrid.


Do I need to put dynamic range compression on my cover songs recording?

Question: For example  I record a guitar cover and I want to know do I need to put  dynamic range compression on it because it lasts for 3-4 minutes? Or should I put  dynamic range compression on vocals? I ask because it is a long take and it's not a song but a video cover of a song.
Or do people in blogs put dynamic range compression on vocals because they talk for 10 minutes straight?
Comment: Do you mean compression from the audio engineering or the software engineering definition? Because the two concepts are not really related.
Comment: Hi! You seem to be confusing two meanings of "compression." When people talk about "applying compression to" a recorded source, they usually mean [dynamic range compression](https://en.wikipedia.org/wiki/Dynamic_range_compression), which makes soft parts louder and loud parts softer. It doesn't affect the size of digital files. Meanwhile, [data compression](https://en.wikipedia.org/wiki/Data_compression) *does* find ways to make digital files smaller. There are many approaches; whether you need it or not would have a lot to do with how and where you're sharing it.
Comment: Don't think 'compression' is the right term here.
Answer: In music-making, "compression" means narrowing the dynamic range of audio signal content. Usually it is used to make instruments and mixes sound louder. https://en.wikipedia.org/wiki/Dynamic_range_compression
When talking about data compression, it means making the amount of stored and transferred data smaller. Sound files can be data-compressed, and then we talk about methods and file formats like MP3 and FLAC compression. It's supposed to sound the same, but take up less data storage spage and be faster to transfer over networks. For images, you've probably seen things like JPEG and PNG. For general data files, you may have seen the name ZIP. These formats are about data compression as well. https://en.wikipedia.org/wiki/Data_compression
When you upload music to internet services, you'll most likely want to use audio data compression of some sort, often MP3, instead of sending raw uncompressed files over the internet. MP3 and other audio data compression methods can reduce the amount of transferred and stored data a lot. A data reduction of 90% is common. Uncompressed, a minute of  "CD quality" stereo music takes around 10 megabytes, but with MP3 or other audio data compression methods it can be on the order of 1 megabyte, depending on the exact method and quality settings.


Ability to use Bootstrap 3 grid system to specify width of select element

Question: I have the following <select> element as follows:
<select id="statusSelect" style="width:175px" class="form-control" name="statusCode">

However, someone has just told me that this can cause dynamic exceptions on hidden elements. My question is this: How can I use Bootstrap 3's Grid system to specify the width of the <select> element. I have tried the following:
<select id="statusSelect" class="form-control col-md-2" name="statusCode">

But, unfortunately, using col-md-2 or even col-md-4 does not change the width of the <select> element. So, can anyone help me to see how I can use Bootstrap 3's grid classes to specify the width of the <select> drop-down box.
Any help would be much appreciated.
Comment: what you have tried to change in bootstrap ? does it show any error if you tried ?
Answer: You have to add the classes to an wrapping div.

  <select id="statusSelect" class="form-control" name="statusCode">

Answer: col-md-2 does not change the width because form-control overwrite the width property because it has width: 100%
you can add class col-md-2 without form-control
<select id="statusSelect" class="form-control col-md-2" name="statusCode">

or add the col-md-2 to the parent like @trieber answer


Background image in stylesheet won't appear

Question: Hi I'm a new developer and I'm trying to build a portfolio site for myself. Anyway, I can't seem to get the background image I put together to show. The image is located in the images folder of my CSS folder. I notice if I try to put a background color in it works just fine. However, I don't want a background color just an image.

The file pathway in my project is as follows:
ProjectName > SiteRoot > CSS > images > hmebckgnd.jpg
This is my code for styles.css
body{
                background-image: url('/images/hmebckgnd.jpg');
                background-repeat: no-repeat;
                margin: 0;

            }

Answer: The first / in the path attempts to find the images folder from the root directory, removing it will load it relative to the directory the stylesheet is in (which should be the CSS folder):
body{
    background-image: url('images/hmebckgnd.jpg');
    background-repeat: no-repeat;
    margin: 0;
}

Comment: @user3473475 is this all of the relevant CSS? Are you sure the filenames are correct?
Comment: I'll check again but I'm pretty sure
Comment: I use the exact same pathway as I used for my logo and buttons and they work just fine.
Comment: @user3473475 There seems to be something else at play here. Could you post a screenshot of your directory tree with all the relevant folders expanded? Also if you have any other CSS that would be valuable as well.
Comment: I changed the name of the image to something simpler. It's now 'hb,jpg'
Comment: @user3473475 in your screenshot you have the url as `css/images/`, it should just be `images/`.
Comment: I tried it that way and that didn't work either. So I copy and pasted the pathway for my logo image which works and swapped out the logo image for my background image. That's why that's why I put it in like that like that.
Comment: @user3473475 I'm at a loss. The path is relative to the stylesheet directory, so `images/` is the correct way to target it. Your browser log shows that `css/images/` attempts to navigate to `css/css/images/` because of this. Are you sure it's a `jpg` and not a `png` or something?
Comment: Yes I'm sure. I've been using Netbeans IDE but I think I'll start the project in Dreamweaver. Maybe I'll have better luck. Thank you for all your help.
Comment: I found out what my issue was sort of. I think my image was too big. When  I used a standard image it worked. Thanks!
Answer: If your image has path like this:
ProjectName > SiteRoot > CSS > images > hmebckgnd.jpg
why don't you include css directory in css file?
body{
                background-image: url('../images/hmebckgnd.jpg');
                background-repeat: no-repeat;
                margin: 0;

            }

It is good practice to use relative path in css file and load whole css file with forward slash in your HTML file.
Comment: Sorry your css file is porbably in css directory, but images are in images directory. So you have to move back to /siteRoot and then go to images its done by ../images


Hide a field from "Manage display"

Question: If a field is set a hidden on Manage display, unless it's displayed  in a view, it cannot be seen anywhere on the site.
Specify how fields are displayed says:

Format
The format column contains the options to show the field value in different formats. Hidden is the global value which is present in all the format option list. If you choose hidden, it will hide the whole field from showing on the content page.

I understand it hides a field from the view mode, but you can also hide it if you don't try to do by using those modules, which are designed to output fields, like the Views module.
Is there still any possibility that users can see the hidden field even if those modules are not used?
Answer: If you use, on Manage display the hidden format (not label: hidden), the field won't show for the display mode for that content type. The field could still be shown in another display mode, for example the one for teasers. You need to set the field to hidden for all the display modes.
It is still possible to make a view with the Views module that displays the field. It depends on how you set up the view. If you set up a view of teasers, the standard teaser display is used (and the field is hidden according to the display settings). If you make a view of fields, you just have to avoid picking the "secret field."
If this is an existing Drupal site where this content type and field is a part of many different views and/or other modules, you will need to test this out. Also if the field is searchable or hard-coded in some template.

Hide a field from "Manage display"


AFNetworking - occasionally get "unacceptable content type: application/json" on http response

Question: I can't figure out why this message is being thrown by AFNetworking 2.0.  My understanding is that application/json is the default serialization scheme, so if the server returns JSON with content-type:application/json, why would AFNetworking throw this error?
Failure with messages Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: application/json" UserInfo=0x17e2ed60 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x17e84100> { URL: http://XXX/XXX/XXX } { status code: 200, headers {
        Connection = "keep-alive";
        "Content-Type" = "application/json;charset=UTF-8";
        Date = "Fri, 14 Aug 2015 16:16:52 GMT";
        Server = "Apache-Coyote/1.1";
        "Transfer-Encoding" = Identity;
        "X-Application-Context" = application;
    } }, NSErrorFailingURLKey=http://XXX/XXX/XXX, NSLocalizedDescription=Request failed: unacceptable content-type: application/json, com.alamofire.serialization.response.error.data=<7b227374 61747573 223a3230 302c2263 6f646522 3a225636 594d227d>}

Commented out URL's with X's in the code block.  This only happens sometimes, and it causes the request to fail.  If I issue another request, it succeeds.
I'm using an AFHTTPSessionManager singleton to issue all requests.
Answer: Try this:
sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];

Comment: That definitely helped.  I also discovered since asking that I was trying to set and re-set the serialization for different types of responses on the same session.  The issues generally stopped when I created two session managers, each with their own serialization scheme
Comment: Thanks for the response!  I'll give it a try and see if the errors continue to show up..


Multiple placeholder SQLite Python not working

Question: I am trying to UPDATE UnitPrice of a TrackId from Track TABLE. The UnitPrice and the TrackId are given arguments by user input. I am currently  receiving an error on number of arguments:
    Traceback (most recent call last):
    File "HW4.py", line 48, in <module>
    conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?", (n_price,t_id))
    sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

Here is my code:
track_id = raw_input('Enter Track ID\n')
t_id = (track_id,)
cur = conn.execute("SELECT T.UnitPrice FROM Track T WHERE T.TrackId = ?", t_id)
for row in cur:
    print "Unit Price: ", row[0]

new_price = raw_input('Enter New Price\n')
n_price = (new_price,)
conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?", n_price, t_id)
conn.commit
print "Total number of rows updated: ", conn.total_changes

cur = conn.execute("SELECT T.UnitPrice FROM Track T WHERE T.TrackId = ?", t_id)
for row in cur:
    print "Unice Price: ", row[0]

I'm guessing it is a syntax error on how I am putting n_price and t_id into the ? placeholders.
Comment: Your traceback message doesn't match your posted code.
Answer: You need to pass in your parameters as a single iterable, like a list or a tuple, but you are wrapping your n_price parameter in another, nested tuple:
n_price = (new_price,)  # this is a tuple
conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?",
             (n_price, t_id))  # wrapping in another tuple

So now you are passing in ((new_price,), t_id), but that first tuple is not a supported type.
Pass in your arguments together in one tuple:
params = (new_price, t_id)
conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?", params)

or use
conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?", (new_price, t_id))

Comment: Quick Response. Fixed Problem. Great Explanation. Superb.


How does mathematics handle its huge size?

Question: Since after Hilbert it isn't possible anymore to have knowledge in everything going on in mathematics. For most if not all mathematicians today there are many topics in mathematics completely unknown to them. Even if one only focuses on one specific topic, one needs to do many years of study to start working on own contributions.
What can be done against this? Since mathematics is further growing, will it take more and more time for students to study before doing own research?
Comment: I figure the same can be said for any science.
Comment: Maybe in other sciences more things tend to become obsolete.
Comment: While it's true that mathematics is growing rapidly, it's also true that the resources to learn mathematics (including state-of-the-art, research-level math) are growing just as fast. Case in point: this website.
Answer: In some ways that is true. But in a longer perspective remarkable things happen. The Greeks and Romans had number systems in which modern arithmetic taught to children was next to impossible - the fact that the Greeks were able to do so much mathematics without is really astonishing. I am not sure I understand how the Romans did arithmetic at all.
Slightly older students are taught about cartesian co-ordinates in the plane which are so powerful that Euclidean Plane Geometry is pretty much a mathematical speciality rather than a practical tool.
Vectors and vector analysis transform things like Maxwell's equations into an essential and more accessible core.
I think the greater challenge is the level of abstraction now involved, which requires the formation of mathematical imagination [though this is hugely evident in Euclid, for example]. The abstractions are different in different disciplines. Each of the examples I have given involves the creation of a new and unifying language in which concepts can be expressed and understood.
And of course there is also the question of the number of mathematicians, and the effect of the need for each to make a mark - there is lots of mathematics being done, and that affects how much any individual can know.


Submit um form usando request no php

Question: Bom dia gente,
Estou fazendo um formulário (trabalho do curso) e preciso dar echo em todas as informações digitadas no formulário usando REQUEST (pode ser POST também) quando eu clicar no botão "submit".
Procurei muito na internet, vi vários vídeos, mas só acho como fazer isso dado a dado, tipo, fazendo uma linha de código para cada dado... mas são muuuuuito dados no formulário e lembro que meu professor fez uma linha só que imprimia todas as informações digitadas, mas não lembro como ele fez isso.
Comment: Dá pra usar `var_dump($_POST)` ou `var_export($_POST)` ou `print_r($_POST)`...
Comment: `echo var_export($_REQUEST, true);` ou usa um `foreach` e itera sobre todos os campos recebidos
Comment: Eu precisava usar echo e request pq foi o q ele pediu, mas se eu não conseguir vou tentar o que vc falou. É só colocar um dos 03 q vc listou entre a tag de php? preciso referenciar ao arquivo? nunca usei nenhum dos 03.
Comment: Obrigada, vou testar assim que chegar em casa.
Answer: Além das opções sugeridas pelo Fernando...
Se você precisa dar echo em todas as informações digitadas no formulário eu faria assim:
echo implode(" ", array_slice($_REQUEST,0,count($_REQUEST) - 1));

O array_slice vai pegar tudo o que foi digitado menos o submit. Enquanto o implode vai juntar todos os valores dos elementos do array colocando um espaçamento entre eles.
Comment: Muito obrigada!!
Comment: @RWProgramer isso funciona caso o submit estiver no final do formulário

Submit um form usando request no php


Pra que serve a tag ?

Question: Estava lendo este tópico na página da Mozilla, e uma parte me chamou a atenção:

Retorna o elemento  ou o <frameset> do documento atual, ou null se nenhum destes elementos existir.

O link para <frameset> estava ausente, então procurei um pouco, mas os sites que eu encontrei me confundiram mais que explicaram.
Este, por exemplo, em um determinado trecho, diz:

Isso quer dizer que não iremos mais utilizar a tag body, [...]

Por que document.body pode retornar <frameset>? E por que o <frameset> substituiria o ? O que ele é, na prática?
Comment: Essa tag foi depreciada com o html5, ela era utilizada para renderizar um html dentro de outro, a página do Mozilla sem tradução parece estar melhor: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frameset
Comment: @DanielMendes ["depreciada"](https://pt.stackoverflow.com/questions/178138/o-que-%c3%a9-um-c%c3%b3digo-depreciado#comment368172_178138)
Answer: O elemento <frameset> é valido no DTD HTML Frameset como já expliquei em:

https://pt.stackoverflow.com/a/209599/3635

Exemplo de uso:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
   "http://www.w3.org/TR/html4/frameset.dtd">

Vale notar que as tags e esta maneira de criar páginas está obsoleto:

https://html.spec.whatwg.org/multipage/obsolete.html
https://dev.w3.org/html5/pf-summary/obsolete.html

Deve ser evitado e uma boa sugestão nesta resposta:

https://pt.stackoverflow.com/a/15174/3635

O "DTD HTML Frameset"
O DTD ajuda o navegador a determinar o comportamento, é claro que o navegador "tenta" determinar sem o DTD (DOCTYPE Document), então provavelmente em um documento com frameset outras tags seriam ignoradas, a não ser que o navegador seja muito antigo e não suporte frames (mas é falar muito do passado), então se fizer isto por exemplo:

<title>exemplo de iframe</title>

<frameset cols="20%, 80%">
  <frameset rows="100, 200">
      <frame src="contents_of_frame1.html">
      <frame src="contents_of_frame2.gif">
  </frameset>
  <frame src="contents_of_frame3.html">
  <noframes>
      seu navegador não suporta frames
  </noframes>
</frameset>

Se testar vai notar que a tag

<frameset cols="20%, 80%">
  <frameset rows="100, 200">
      <frame src="contents_of_frame1.html">
      <frame src="contents_of_frame2.gif">
  </frameset>
  <frame src="contents_of_frame3.html">
  <noframes>
      seu navegador não suporta frames
  </noframes>
</frameset>

Então o elemento principal neste tipo de documento é mesmo o frameset, sendo o principal significa que não podem haver elementos no mesmo nível (exceto o ) pois este é o objetivo do frameset, ser a subdivisão de uma janela (window subdivision), como descrito em:
<![ %HTML.Frameset; [
<!ELEMENT FRAMESET - - ((FRAMESET|FRAME)+ & NOFRAMES?) -- window subdivision-->
<!ATTLIST FRAMESET
  %coreattrs;                          -- id, class, style, title --
  rows        %MultiLengths; #IMPLIED  -- list of lengths,
                                          default: 100% (1 row) --
  cols        %MultiLengths; #IMPLIED  -- list of lengths,
                                          default: 100% (1 col) --
  onload      %Script;       #IMPLIED  -- all the frames have been loaded  --
  onunload    %Script;       #IMPLIED  -- all the frames have been removed --
  >
]]>

Por isto não existe BODY nele, e o uso de document.body para obter o frameset é mera convenção.
Note que no doctype do HTML4 é indicado isto:

<!ENTITY % HTML.Frameset "IGNORE">

Que afirma que o documento (a página) deve mudar para o formato de framesets e somente a tag frameset é indicada e quando não for o caso ele usa esta estrutura indicada:

<!ENTITY % html.content "HEAD, BODY">

O conteudo de HTML "poderá" conter o HEAD e o BODY (não sendo obrigado, claro que os browsers também tentam compensar e nem sempre o motor vai seguir "a risca")

Pra que serve a tag ?


Calculate Expected value using conditioning

Question: How to calculate E[X] using conditioning. Let a random variable Y = X^2, While X is a random variable that can take the following values {-2,-1,0,1,2}. Each value can occur with equal probability i.e., 1/5.
Comment: What's the question?  If the goal is to compute $E[X]$, where does $Y$ come in?
Comment: @lulu I think Y will be used as following formula could be used to find E[X]........"E[X]=E[E[X|Y]]"  But I'm not so much sure about that.
Comment: But $E[X]=0$, obviously.  What's the problem?
Answer: We have
\begin{align}
\mathbb E[X] &= \sum_{n=0}^2 \mathbb E[X\mid Y=n]\mathbb P(Y=n)\\
&=\mathbb E[X\mid Y=0]\cdot\frac15 + \mathbb E[X\mid Y=1]\cdot\frac25 + \mathbb E[X\mid Y=4]\cdot\frac25\\
&=0+0+0=0.
\end{align}
Comment: How could we have $Y = 2$ since $Y = X^2$?
Comment: Good point, I have changed it to $Y=4$.
Comment: @Math1000 isn't the probability for Y=4 is 2/5 ? Well the ans will still be zero but just for the correction.
Answer: $$ E(X) = \left( \frac{1}{5} \right)(-2) + \left( \frac{1}{5} \right)(-1) + \left( \frac{1}{5} \right)(0) + \left( \frac{1}{5} \right)(1) + \left( \frac{1}{5} \right)(2) $$
$$ E(X) = \frac{ -2 -1 + 1 + 2} {5} $$
$$ E(X) = 0 $$
Now for the $E(Y)$.
$$ E(Y) = \left( \frac{1}{5} \right)((-2)^2) + \left( \frac{1}{5} \right)((-1)^2) + \left( \frac{1}{5} \right)(0^2) + \left( \frac{1}{5} \right)(1^2) + \left( \frac{1}{5} \right)(2^2) $$
$$ E(Y) = \frac{ 4 + 1 + 0 + 1 + 4}{5} $$
$$ E(Y) = \frac{10}{5} = 2 $$
Comment: This is just a simple method but I'm supposed to find E[X] by conditioning method.
Comment: @Xzcess I have not heard of the conditioning method. Are you sure you have that term right?


SQL: Having multiple conditional Averages between two tables

Question: I have two tables
Sample from e.g. T1
----------------------
ID  || Operation Name |
----------------------|
101 || QA             |
----------------------

Sample from T 2
----------------------------------------
ID  || Employee  ID || Employee || Audit |
----------------------------------------
101 || 505788       || Marley   || 50    |
230 || 5487525      || Smith    || 100   |
-----------------------------------------

I should return each operation name with it's own Audit average  in conditions (if it's >= 90 as "Good" - if it's <90 and >= 40 as "Medium" - if it's < 40 as "Bad") and prevent any audit with average (0)
the table should be like this
---------------------------------------------------
Operation Name || Operation ID || Audit Evaluation |
----------------------------------------------------
Maintenance    ||   190        ||       Medium     |
---------------------------------------------------

Comment: What did you try?
Comment: Where does OperationID = 190 come from? How are the two tables linked to each other?
Comment: Operation ID is the ID in the first table
Answer: demo:db<>fiddle
SELECT
    t1.name AS operation_name,
    t1.id AS operation_id,
    CASE
        WHEN AVG(t2.audit) >= 90 THEN 'Good'
        WHEN AVG(t2.audit) >= 40 THEN 'Medium'
        ELSE 'Bad'
    END AS audit_evaluation
FROM
    t1
JOIN
    t2 ON t1.id = t2.id
GROUP BY t1.id, t1.name
HAVING AVG(t2.audit) > 0

Joining both tables on id
Grouping by their ids
HAVING filters out the AVG = 0 groups
Calculating AVG
Using CASE clause to build the sections
Comment: Thanks a lot. BUT I want Medium to  <90 and > 40 in the same time, too. Any help.
Comment: a) What is with values that equal 90? b) It works as expected: If it is >90 then it would be taken the first one, if not, the next comparison takes part. So if it is <=90 and >40, this works.
Comment: Ok, added the >= comparators. Now it works: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=61f71bb05eacd867592d6836b5d04db6
Comment: And for Medium, I don't have to say >= 40 ((And <90))? -- Just  >=40, Right?


"Redirect Loop" when creating a multisite

Question: I know there are a few questions related to this one, yet I haven't been able to answer mine.
I want to develop 2 websites pointing to the same Drupal core files,
so :
drupal1.example.com should point /www/dev/sites/drupal1.example.com drupal2.example.com should point to /www/dev/sites/drupal2.example.com

I've created both subdomains to point to /www/dev/ folder.
I've put settings.php in drupal1.example.com and default.settings.php in drupal2.example.com
When I load drupal2.example.com, I get a "Redirect Loop" error.

Do you know what I'm doing wrong ?
Thanks!
ANSWER :
When there was no settings.php file in my sites/drupal2.example.com folder, it showed the drupal1.example.com website.
When there was a settings.php file in my sites/drupal2.example.com folder, it got me an infinite loop.
So I modified the settings.php in sites/drupal2.example.com folder to connect to a different empty databse, but then I got an error "Base table or view not found: 1146" then another error upon refresh "error: Class 'SelectQueryExtender' not found".
It seemed as though the installer had a hard time loading the 2nd instance of Drupal since there were no tables in the DB.
So I imported DB #1 into DB #2 and it worked.  I could change the theme in drupal2.example.com and I still had the old theme in drupal1.example.com.
The only downside is that I have to delete the content types, nodes, menus, etc ... in my drupal2 but I least it's working!
Comment: If you want to keep the name of your site private, I suggest that you check your post again :)
Comment: Pointing `/www/dev/sites/drupal1.example.com` to `/www/dev/` sounds dodgy.
Comment: @coleopterist - have you ever been on example.com ? :o)
Comment: @coleopterist I want both subdomains to point to Drupal's root installation folder (/www/dev/) so that Drupal spits out the right sites (in the sites/ folder) for the right subdomain.
Comment: My bad - I thought you were symbolic linking them; and I was talking about itx-****.com. You missed a spot.
Comment: if that's the answer...could you please put it as an answer and check it as solved...it will help others to identify quickly the solution :)
Answer: Assuming you have ServerName and ServerAlias properly defined in Apache, I suspect you have the default canonical URL redirects enabled in your .htaccess.  Make sure this stuff is all commented out:
  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

Also make sure you don't have any other Apache rules that are doing something similar, and that you don't have any modules (eg, Domain Access or Mobile Tools) or custom code that would do a redirect.
Comment: Thanks!  I've disabled the clean URLs in the default installation and have uncommented the lines :
`#   RewriteCond %{REQUEST_FILENAME} !-f
#   RewriteCond %{REQUEST_FILENAME} !-d
#   RewriteCond %{REQUEST_URI} !=/favicon.ico
#   RewriteRule ^ index.php [L]`
But now I'm getting a 403 Forbidden error to access "/install.php" .. any thoughts ?
Answer: If you are on a shared host and have installed Drupal through a Script check if install.php is in the document root.
If not, download Drupal, extract install.php and put it in the document root. Now go to the site and the installer should work.