DKIM: Can I simply change the RSA key used in DKIM without changing the DKIM selector?

Question: Can I simply change the RSA key used in DKIM (DNS TXT Record) without changing the DKIM selector or will this result in any issues?
If not, what's them the purpose of the DKIM selector?
BTW: 20120113 is the selector I'm talking about in 20120113._domainkey.gmail.com
Answer: As you can read here "....A selector is added to the domain name, used to find DKIM public key information...".
Also, in Wikipedia terms: "...The receiving SMTP server uses the domain name and the selector to perform a DNS lookup [...] the selector is a straightforward method to allow signers to add and remove keys whenever they wish..."
In other words, if you are sending a DKIM-signed e-mail, you have to tell external mail-servers HOW they can retrieve your RSA key to check the validity of your email. The RSA-key is published into your DNS, ok, but WHERE? Which DNS-query will retrieve it? How will they know which DNS query/record resolve? This is where the selector plays its role: if you are sending mail from the example.com domain and, in your mail, you declare whatever as selector then:

in the outgoing mail-header you need to reference your domain and related selector, like in:

DKIM-Signature [...] d=example.com; [...] s=whatever

in your DNS you have to provide a TXT record for whatever._domainkey.example.com publishing your RSA key, like in:

whatever._domainkey.example.com IN TXT "k=rsa\; t=s\; p=MIGfMA[...]AQAB"

As you can see, the DNS-query is in the form <selector>._domainkey.<your_domain>
Based on this, we can say that:

the RSA-key can be replaced/updated without any impact on the selector. Obviously it's critical that, when you update one side of the key (the public one, published on the DNS), you change also the other side (the one used to "sign" your outgoing mail);
if you leave the selector unchanged while updating the RSA-key, than a side effect is that.... remote clients (not servers; I'm talking about MUAs) that for whatever reasons want to check the DKIM-signature included in their old/archived e-mails, will fail the verification process (as the archived e-mail has been signed with a private-key whose public-one, the one published on the DNS, has been updated and now is different!).

I want to add that, in my experience, I'm used to think that DKIM-signing/verification is a process targeting the transport of the e-mail, and not the verification client-side. So I would bet that it's quite safe to update the KEYs leaving the selector untouched.
By I also think that.... if you're going to update the KEYs, than you've to change both your signing-code (that need to point to new private-key) and the DNS (to publish the new public-key in the TXT record). So, why not to change also the selector (again, at both side?). You will end up having TWO selectors published on the DNS, one pointing to the old-key and another one pointing to the new one. In this way, everything will be fine during SMTP-transport and, also, MUAs will be able to validate old/archived e-mails as the old-key, associated to old selector, is still available.
Comment: `I want to add that, in my experience, I'm used to think that DKIM-signing/verification is a process targeting the transport of the e-mail, and not the verification client-side. So I would bet that it's quite safe to update the KEYs leaving the selector untouched.`

Be careful with this assumption. DKIM has nothing to do with transport; the signature is a header like any other that is irrelevant to transport or routing. DKIM is used by the receiver specifically to verify whether the message truly originates from the sender indicated and was not modified in transit.
Comment: @cmeid: I agree that such a statement sounds a bit strong. What I mean is that it's common to have DKIM-checking activities **inside** the final SMTP-server (there are plenty of content-filters for Postfix or other SMTP-servers, as well as other plenty of email filters --antivirus, antispam, etc.-- out there). But once the message has been delivered, by the final SMTP server, to the user mailbox, than it's only a matter of the MUA... and I'm not aware of any MUA doing DKIM-verification of e-mails, nor during POP3/IMAP fetch, nor later on. What's your opinion on this? I'm really interested BTW!
Comment: I see what you mean now. DKIM should be verified sometime before final delivery, by an MTA before the MDA. After delivery, the MUA *may* do something based on the `Authentication-Results:` header, but it should not re-validate the actual signature. (Not least for the reasons above, that keys may have been rotated or de-published in the interim.)
Answer: Can I simply change the RSA key used in DKIM (DNS TXT Record) without changing the DKIM selector or will this result in any issues?
Yes, you can, but without a good reason I would strongly advise not to do so.
Here are some reason why reusing the selector would not be a good idea:

DNS changes can take some time to propagate. If a selector is reused after a key change, this can result in the verification failing for e-mails send shortly after the key change.
You do not know how much time will elapse between sending and verification. This could result in older messages failing the verification after the key change. Some possible reason for the delay:
Message getting stuck during transit.
Although I think very uncommon, verification can also happen inside the MUA ([there exists an add-on for Thunderbird which does this][1])
From the RFC: "Reusing a selector with a new key
(for example, changing the key associated with a user's name)
makes it impossible to tell the difference between a message that
didn't verify because the key is no longer valid and a message
that is actually forged. For this reason, Signers are ill-advised
to reuse selectors for new keys. A better strategy is to assign
new keys to new selectors."

What's the purpose of the DKIM selector?
"To support multiple concurrent public keys per signing domain". Here are some use-cases for concurrent keys:

"Beyond administrative convenience, selectors make it possible to
seamlessly replace public keys on a routine basis."
Allow different entities to sign your e-mails (with a different key and selector) without the need to share a private key. This is useful for:
delegating signing to an external organization
administratively distributed organizations
Make it possible to explicitly revoke a key (by leaving the public-key data (the "p=" tag) empty).

All quotes are from the [RFC 6376][2].
[1]: https://addons.mozilla.org/en-US/thunderbird/addon/dkim-verifier/
[2]: https://www.rfc-editor.org/rfc/rfc6376#section-3.1
Answer: You can do this. It's not necessarily BCP though.
The reason to have multiple selectors is specifically so that a key can remain valid for a period of time after being rotated.
For example, if you change the RSA key used in selector 20120113, then any message that was still in a queue somewhere and is later delivered will fail DKIM because the key has changed.
Ideally, you would publish a new key, 20160106 if you did it today, and add that as an additional selector. That way, messages using both keys can be validated. After a reasonable period of time, say two weeks, you can depublish the old key.
(I am assuming you don't really mean the key 20120113._domainkey.gmail.com literally? If you really are talking about a Gmail key, stop and talk to John RG internally before changing anything.)


Unable to play youtube videos in android devices

Question: Meta data
<meta http-equiv="Content-Security-Policy" content="default-src * data: filesystem: android-webview-video-poster:; style-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.youtube.com;  script-src 'self' 'unsafe-inline' 'unsafe-eval'; font-src *;">

Error Message
VM772:712 Refused to load the script 'https://www.youtube.com/iframe_api' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval'"

Answer: Replace script-src to below snippet
script-src *
<meta http-equiv="Content-Security-Policy" content="default-src * data: filesystem: android-webview-video-poster:; style-src 'self' 'unsafe-inline';  script-src * 'unsafe-inline' 'unsafe-eval'; font-src *;">


Order total discount in ubercart?

Question: I want to total order discount in ubercart on drupal 7. I want to 10% discount on total order.Is there any way to do that?
Comment: Welcome to Drupal Answers! What did you try to do so far? Where are you stuck exactly?
Answer: Commerce Discount Extra

Provides a number of common discount condition and offer types:
Order discounts
Condition types

Order-owner role
Total items in order

Offer types

Fixed amount per-quantity discount (Buy X product get Y (or X)    product at discount up to some number of (or unlimited) times)
Percent per-quantity discount

Ubercart Discount Coupons

A checkout pane, a cart pane and a block are available for customers
  to enter coupon codes, each of which can be enabled or disabled
  separately. Discounts can be shown as an item in the cart or applied
  on the checkout page.

Order total discount in ubercart?


Styles of items in Task list in Sharepoint 2013

Question: I have problem with client side in Task list in Sharepoint 2013. I need to distinguish maintask (set the background color for example). I tried to change styles ".ms-listviewtable .ms-itmhover" and ".ms-alternating" in core15v.css, but did not get the expected result. How i can solve this problem?
Answer: It's best to leave core15 as is OOTB and add a new stylesheet with your overwrites. Make sure this new stylesheet is called after core15 in the masterpage and use the inspector in your browser to make sure you're getting the entire selector. If you write new properties for .ms-listviewtable but core15 uses #s4-workspace .ms-listviewtable, the one defined in core15 will take precedence as a more specific selector.


How do I output the geojon points on google maps using javascript?

Question: I am trying to get an understanding javascript and json objects on a whole. Forgive my beginner lingo but I have these five json objects(which are the result of a database query) I am trying to display these five coordinates onto the map.  I spent the last three hours searching the internet to find some relevant info on googlemaps. That was a failure, now i am here on SO.  I would like to know how do i go about outputting the coordinates onto a google map. Below is my code but for some reason my map doesn't load.

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

UPDATE:
So scaisEdge  greatly helped me get my map to display. so the map is generated, but i am unable to load the markers from the json object onto the map. I get  uncaught Eb ... You have included the Google Maps API multiple times on this page Can someone help me to show the markers from the json object onto google maps?
ALSO here is a link to the code
Answer: If you want a marker for each lat,lng  you should place the marker creation inside the loop   and this inside tye function initilize()
  var json = {
        "type": "Point",
        "coordinates": [
            [40.7666969299316, -73.9906158447266],
            [40.6885147094727, -73.9647598266602],
            [40.7145042419434, -74.0056304931641],
            [40.704719543457, -74.0092620849609],
            [40.7271041870117, -74.0029678344727]
        ]
    }

    var map;

    function initialize() {
        var mapOptions = {
            zoom: 12,
            center: new google.maps.LatLng(40.730610, -73.935242),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);

      var cods = json.coordinates;
      for (i=0; i<cods.length; i++){

        latlng =  new google.maps.LatLng( cods[i][1], cods[i][0]);
        var marker = new google.maps.Marker({
           position: latlng,
           map: map,
          title: 'test'
        });

     }

Comment: There is at least one typo in your code (from the original post). JavaScript is case sensitive, `latlng` is different from `latLng`. `data.title` is not defined.
Comment: Hey @scaisEdge Thanks for the response. The map is generated but the markers don't populate. Any idea why?
Comment: I have update the answer  wrong $json  and  entry[1] + entry[0] instead of json and  entry[1], entry[0]
Comment: The error message is Uncaught ReferenceError: data is not defined(…)
Comment: I still get Uncaught ReferenceError: data is not defined(…).
Comment: answer  updated  you have a data.title in title attribute of marker ... changed  in a static text ..
Comment: Awh man, this is annoying, Now i get *uncaught Eb ... You have included the Google Maps API multiple times on this page*
Comment: I see only one script for google maps  .. check for your code .. in the code you provided  this error is not evaluable  . so...
Comment: Here is the link to my code. http://www.w3schools.com/code/tryit.asp?filename=FA4XD8LD7ND9
Comment: looking to you code .. should work but  you get an error that i don't understand  .. so i can help  in this case ..
Comment: Okay i shall update my question and give you the necessary credit.
Comment: @MichealC.   many thanks .. i suggest you of post a new question strictly  related  to your last probleme  .. with a specific title  .. and the correct code  .. so all the SO comunity can help for your actual problem ..


problemas com Float Action Buttom (speedDial) - Android

Question: Olá! Encontrei uma lib de um float action com speed dial e estou tentando implementa-la no meu projeto Android, mas não estou conseguindo interagir com o Float Button...
segue o código do fragmento que contém o float:
public class NovaPesquisaFragment extends Fragment {

private AlertDialog.Builder dialogBuilder;
AlertDialog dialog;
private ArrayList<PerguntasModel> perguntas;
private CardView cardDinamicoPergunta;
private RecyclerView recyclerView;
private FirebaseAuth mAuth;
private FirebaseUser user;
private DatabaseReference fbDatabaseRef, fbUserDatabaseRef;
private FirebaseFirestore fbCloudStore;
private Listener listener;
private int i;
private View rootView;
private AdapterPerguntas adapterPerguntas;
private FabSpeedDial floatSpeelDial;

public NovaPesquisaFragment() {
}

public interface Listener{
    public DatabaseReference getdatabaseRef();
    public FirebaseDatabase getfbDatabase();
    public FirebaseAuth getmAuth();
    public FirebaseAuth.AuthStateListener getmAuthListener();
    public FirebaseUser getUser();
    public FirebaseFirestore getFbCloudStore();
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null){
        i = savedInstanceState.getInt("i");
    }else{
        i = 0;
    }
}

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_nova_pesquisa, container, false);
    variaveisDoXML();
    return rootView;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("i", i);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    pegarFirebaseListener();

    recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
    final AdapterPerguntas adapterPerguntas = new AdapterPerguntas();
    recyclerView.setAdapter(adapterPerguntas);

    dialogBuilder = new AlertDialog.Builder(getContext());
    perguntas = new ArrayList<>();

    floatSpeelDial.setMenuListener(new SimpleMenuListenerAdapter(){
        @Override
        public boolean onPrepareMenu(NavigationMenu navigationMenu){
            return true;
        }
        public boolean onMenuItemSelected(MenuItem menuItem){
            switch (menuItem.getItemId()){
                case R.id.menuSpeedDial_action_call:
                    Toasty.info(getContext(),"item 1", Toast.LENGTH_LONG).show();
                    break;
            }
            return true;
        }
    });
}

private void variaveisDoXML() {

    floatSpeelDial = (FabSpeedDial) rootView.findViewById(R.id.floatSpeelDial);
    cardDinamicoPergunta = (CardView) rootView.findViewById(R.id.cardView_dinamico_pergunta);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView_perguntas);

}

private void criarDialogo(View view, Boolean canceleable, Boolean canceleableTouch){
    dialogBuilder.setView(view);
    dialog = dialogBuilder.create();
    dialog.setCancelable(canceleable);
    dialog.setCanceledOnTouchOutside(canceleableTouch);
    dialog.show();
}

private void pegarFirebaseListener(){
    listener = (Listener) getActivity();
    mAuth = listener.getmAuth();
    fbDatabaseRef = listener.getdatabaseRef();
    user = listener.getUser();
    fbCloudStore = listener.getFbCloudStore();
    fbUserDatabaseRef = fbDatabaseRef.child(user.getUid());
}

@Override
public void onPause() {
    super.onPause();

}

@Override
public void onResume(){
    super.onResume();
}
}

o XML desse fragmento:

<android.support.v7.widget.CardView
    android:id="@+id/cardView_dinamico_pergunta"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="8dp"
    android:elevation="5dp"
    android:focusableInTouchMode="true"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardBackgroundColor="@color/white"
    app:cardCornerRadius="5dp"
    app:cardUseCompatPadding="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <io.github.yavski.fabspeeddial.FabSpeedDial
        android:id="@+id/floatSpeelDial"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        app:fabGravity="bottom_end"
        app:fabMenu="@menu/speeldial_menu"
        app:miniFabBackgroundTint="@android:color/white"
        app:miniFabDrawableTint="?attr/colorPrimaryDark"
        app:miniFabTitleTextColor="?attr/colorPrimaryDark" />

    <android.support.v7.widget.RecyclerView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/recyclerView_perguntas"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        app:shimmer_demo_angle="10"
        app:shimmer_demo_child_count="5"
        app:shimmer_demo_grid_child_count="1"
        app:shimmer_demo_layout="@layout/layout_demo_grid"
        app:shimmer_demo_layout_manager_type="linear_horizontal">

    </android.support.v7.widget.RecyclerView>

</android.support.v7.widget.CardView>

O arquivo do menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menuSpeedDial_action_call"
        android:icon="@drawable/icon_account"
        android:title="menu call" />

</menu>

O guia da LIB:
https://github.com/yavski/fab-speed-dial
Answer: Me parece que no método onPrepareMenu você está retornando false, com isso dizendo para a library não exibir os itens.

Events
As with all menus, you have a callback just before the list of
  actionable items are presented. The callback allows you to update your
  menu items, or not show the menu altogether.

FabSpeedDial fabSpeedDial = (FabSpeedDial) findViewById(R.id.fab_speed_dial);
        fabSpeedDial.setMenuListener(new SimpleMenuListenerAdapter() {
            @Override
            public boolean onPrepareMenu(NavigationMenu navigationMenu) {
                // TODO: Do something with yout menu items, or return false if you don't want to show them
                return true;
            }
        });

Comment: Continuo tendo o mesmo problema =\


Find $\cos (x)$ and $\tan (x)$ if $\sin (x) = 3/5$ over the interval $[\pi/2,\pi]$

Question: Need help with this please. I seem to be making a mistake somewhere because my answer is different from the text book's. Mine are:
$\cos(x) = \frac{4}{5}$
$\tan(x) = \frac{3}{4}$
But in the text book it's:
$\cos(x) = \frac{-4}{5}$
$\tan(x) = \frac{-3}{4}$
I'm not sure where I went wrong.
My approach was to treat the ratio of $\sin(x)$ as the sides of a right angled triangle and solve for the final side using Pythagoras' theorem. But I don't know where the negative values are coming from. Please help if you can.
Comment: The negative values come from "over the interval $[\pi/2, \pi]$" - $\cos, \tan$ are negative there.
Comment: You build a right angled triangle with one of its angles on $[\pi/2, \pi]$ ? How exactly did you do that?
Comment: @jjagmath I didn't use the interval but the ratios.
Answer: If $\theta\in\left(\frac\pi2,\pi\right]$, both $\cos\theta$ and $\tan\theta$ are smaller than or equal to $0$. So, you cannot possibly have $\cos\theta=\frac45$ and $\tan\theta=\frac34$ there.
Comment: Thanks. Sorry for the basic question, but then why are cos θ  and tan θ smaller than or equal to 0 over this particular interval? I thought so long as the interval was positive there'd be no negative values? Edit - Actually nevermind. I see it now.
Answer: We know that
$ sin(x) ^2+cos(x)^2=1$$\Rightarrow$ $cos(x) =\sqrt{1-sin(x)^2} $or $- \sqrt{1-sin(x)^2}$
So
$cos(x) =\frac{4}{5}$ or $- \frac{4}{5}$
We know that $x\in [\pi, \frac{\pi} {2}]$ $\Rightarrow$$ cos(x) =<0 $
so $cos(x) =- \frac{4}{5}$
$Tan(x) =-\frac{3}{4}$


All norms on $\mathbb{R}$ are equivalent.

Question: Let $X$ be a vector space. Two norms $\|\cdot\|,\|\cdot\|':X\to\mathbb{R}$ are equivalent, if there are constants $\alpha,\beta >0$, such that for all $x\in X$ holds:
$\alpha\|x\|\leq \|x\|'\leq \beta\|x\|$

Show that all norms on $\mathbb{R}$ are equivalent.

A detailed hint is given:
It is enough to show, that an arbitrary norm $\|\cdot\|'$ is equivalent to the Euclidean norm $\|\cdot\|$. [Why is that the case?]
Consider the set $M:=\{x\in\mathbb{R}:\|x\|'\leq 1\}$ and show, that it exists an $r\in (0,\infty)$, such that $M=[-r,r]$. It is possible to show, that $r\|x\|'=\|x\|$ for all $x\in\mathbb{R}$.
My first question is, why it is enough to show, that an arbitrary norm is equivalent to the Euclidean norm?
Then I want to follow the hint and find $r$ with $M=[-r,r]$, but I am stuck and do not know how to start here...
I would appreciate a hint to get me started.
Thanks in advance.
Comment: As a first step, you may want to try proving that every norm on $\mathbb{R}$ has the form $\|x\| = c |x|$, where $c > 0$ is a fixed constant and $|\cdot|$ is the ordinary absolute value. As for your question "Why is it enough to show that an arbitrary norm is equivalent to the Euclidean norm?", the answer is that equivalence is transitive.
Comment: Hint: $||x|| = || (x)(1) || = |x| * ||1||$ (where $||.||$ is an arbitrary norm on $\mathbb{R}$)
Comment: This also holds for $\Bbb R^n$ for any $n\in \Bbb N.$
Answer: 1) If you are given any two norms $\Vert\cdot \Vert_1,\Vert\cdot \Vert_2$ on $\mathbb R$ which are both equivalent to the Euclidean norm, they are also equivalent to each other. Just take your conditions for equivalence: If $$\alpha_1\leq\frac{\Vert\cdot \Vert_1}{\Vert\cdot \Vert}\leq \beta_1, $$ and $$\alpha_2\leq\frac{\Vert\cdot \Vert_2}{\Vert\cdot \Vert}\leq \beta_2,$$ then $$ \frac{\Vert\cdot\Vert_1}{\Vert\cdot\Vert_2}=\frac{\Vert\cdot\Vert_1\Vert\cdot\Vert}{\Vert\cdot\Vert_2\Vert\cdot\Vert}=\frac{\frac{\Vert\cdot\Vert_1}{\Vert\cdot\Vert}}{\frac{\Vert\cdot\Vert_2}{\Vert\cdot\Vert}}$$ and here you can use the two equations above to obtain your desired estimates. I'm of course cheating a little here but that's the heuristic behind it.
2) For finding your $r$ you can argue in the same way. Normalize one norm by the other. This is then bounded by a constant that you can take as your $r$. Can you proceed from here?
Before voting down, comment and give me the chance to improve the answer ;)
Comment: Do you mean it like this? $\frac{\|x\|'}{\|x\|}=\frac{|x|\|1\|'}{|x|}=\|1\|'\leq r$
Answer: To your first question, one can see that the equivalence of norms is (as the name would imply) an equivalence relation, and thus if two norms are equivalent to the same norm, then by transitivity they are equivalent to each other.
To your other question, you can see that $M$ is symmetric by Homogeneity of a norm. You can show that the norm $\vert \cdot \vert'$ is a continuous map, and as such on a compact set, attains it's maximum which we'll denote by $r$. Again using homogeneity, you can see that the maximum is attained at $x=\pm 1$, and since the image of an interval under a continuous map is an interval, you'll get that $M=[-r,r]$ as you intended.
Answer: The reason that it is sufficient to show that an arbitrary norm is equivalent to the Euclidean norm is that equivalence of norms is an equivalence relation, meaning that if $||\cdot||'$ and$ ||\cdot||''$ are both equivalent to the Euclidean norm, then they are equivalent to each other using transitivity. If you're unsure, you should verify for yourself that norm equivalence is an equivalence relation.
To show that there exists such an $r$, as has already been suggested you might consider the fact that $||x||' = |x| \cdot ||1||'$ for all $x$.


How do I make sure that an automatically closed window closes all its spawned windows as well?

Question: I have the following scenario:

A user on one our customer's website clicks a link. It performs an automatic signon with their credentials to our site, which is launched in a new window.
User on our site logs out, and is sent to a page which does a JavaScript window.close(), which closes the window. If they were a customer that logged into our site directly then they would go back to the Login page, but being automatically signed on, they have no use for the Login page, so the page automatically closing is better.

However sometimes the following happens

A user on one our customer's website clicks a link, performs an automatic signon with their credentials to our site, which launches in a new window.
While in our application they click on the "Help" link, which at this time is another popup window.
At some point they log out of our app, which closes that window.
The help window is still open.
The user clicks on a link in the help window.
The user, not being logged in anymore, now goes to a login screen in that help window.
MASS HYSTERIA!

So what I'd like to do is ensure that when that original window is closed, it also closes any popup windows it spawns. I figure this can be done in JavaScript but how?
ADDENDUM: The suggestions below are nice but the problem is the page the user is on when the browser closes is not the same page that spawns the popup, so the handles to the pages are all gone. How can I get the handle to a popup window with a specific name?
Answer:

open child window

close me

Answer: Keep track of the window names you open the popups with.
Have a page that purely does a window.close().
When you would do a normal window.close(), make sure you do a window.open("our close page", windowNameIStored) for each of the popup windows.
This is a fix I submitted downstream to a vendor of ours and works quite well.
Answer: Stop using pop-ups, this isn't 1998 :)
Seriously, though with all of the built-in browser functionality and 3rd party apps which also block them, they've become pretty much unreliable.  Are you 100% sure the pop-up opened?  You'll have to test to make sure, but then maybe a 3rd party app closed it after your test finished, who knows, so now the customer is having a bad experience.  If they're actually paying customers, your client could be losing money.  Sure, you can put a message which says "turn off your pop-up blocker", but honestly how many users actually know how to do that?
Every time I'm asked to do a pop-up, I just stare at whoever requested it like they are speaking some other language, then ask if it is 1998.  Pop-ups are the result of one or more of the following: bad User Interface design, ignorant managers, and/or sloppy/lazy development.  Though I'm sure there are other reasons.
Just my 2-cents.
Comment: In this context though, a popup makes sense - at least when the user is coming to our site through automatic logon. They don't want to be routed out of their original session, just logged onto ours as well.

Also this isn't an answer to the question and would have been better as a comment, just FYI
Comment: I agree partially...  If the end-user is in something like extranet, it may be appropriate to open a new window for something outside the extranet.  Using pop-ups for things like "help" sections, which he describes is what I was referring to as bad.
Comment: paulj - how would you show the "help" sections without using a pop-up?

The end-user may need help with something on the page they're viewing, in which case, a pop-up to show that help could be useful, as they would not lose anything they may be working on in the main page.
Comment: David -- Most simply, I'd use a DIV which could be placed over or near the element which the user is filling in.  Data can easily be loaded asynchronously.  There are other solutions.  I am not a UX designer, I just tell them they can't have pop-ups.


Convert ListMultimap to list of keys with duplicates?

Question: So I have a ListMultimap<Integer, String> that I want to convert to a List<Integer> that contains duplicates of the same Integer if there was >1 value associated with a Integer key in the ListMultimap. For instance, if:
ListMultimap<Integer, String> myMap = {2 -> "foo", 3 -> ("bar1, bar2")}
I want my resultant List<Integer> to look like: [2, 3, 3]. What is the easiest way to do this?
Thanks.
Answer: Assuming this is Guava, this is just the one line
Lists.newArrayList(multimap.keys())

or, if you have an ImmutableListMultimap,
multimap.keys().asList()

(Note here that Multimap.keys() is a Multiset<Integer>, which iterates over elements exactly in the way you want -- that is, it will have one occurrence of each key for each value associated with that key.)
Comment: @JBNizet: Yes it would.  Note that we're referring to `keys()`, which is a `Multiset`, as opposed to `keySet()`, which is a `Set`.
Comment: Yes. I just saw my mistake and deleted my comment. +1.
Comment: Great, thank you for the concise one line solution! Beats iterating through the Multiset!


Non-measurability of ultrafilter on $\omega$

Question: It is well-known that any non-principal ultrafilter on $\omega$ is non-measurable regarded as a subset of $2^{\omega}$. My question is "how well-known" is this fact?
Here is the only proof I know: Let $\mathcal{U}$ be a non-principal ultrafilter on $\omega$. If $\mathcal{U}$ were measurable, then, by Kolmogorov 0-1 law, it would have either measure $0$ or $1$ since it is closed under finite changes containing the Fréchet filter. On the other hand, the bit flipping operation is measure preserving and it maps the ultrafilter to its complement, so $\mathcal{U}$ would have measure $1/2$. Contradiction.
What are some essentially different proofs of this fact? Is there a proof that avoids 0-1 laws?
Comment: It's from Sierpinski, originally, I gathered. I don't know which paper (1936 IIRC). He might have another proof.
Comment: I slightly changed the title, I hope you don't mind. :-)
Comment: @AsafKaragila: Of course I don't mind :). I hope you also have some answers as well. Google can't seem to give me any other proof than the one above.
Comment: Sorry, that's the only proof I know off hand, which is somewhat annoying since I'm taking the 0-1 law as a blackbox here. I am trying to think about another proof (and I feel that I might have seen one before).
Comment: See also:
[Relationships between AC, Ultrafilter Lemma/BPIT, Non-measurable sets](https://math.stackexchange.com/q/259247),
[Lebesgue measurability of a set $A = \{\sigma_i \in B\ /\ {2^i}, B \in F\}$ for a a non-principal ultrafilter $F$](https://math.stackexchange.com/q/1018302),
[Existence of maximal analytic P-ideal](https://mathoverflow.net/q/270756)
Answer: After seeing Henno's comment I tracked down the relevant paper by Sierpiński.
Wacław Sierpiński, 'Fonctions additives non complètement additives et fonctions non mesurables', Fundamenta Mathematicae $\mathbf{30}$, $96$-$99$ ($1938$), essentially proves the result. Specifically, he shows that if there is a finitely additive, $\{0,1\}$-valued function on $\wp(\Bbb Z^+)$ that is not countably additive, then there is a $\{0,1\}$-valued function on $\Bbb R$ that is not Lebesgue measurable. Note that a function $f:\wp(\Bbb Z^+)\to\{0,1\}$ that is finitely additive but not countably additive defines a free ultrafilter $\mathscr{U}_f=\{U\subseteq\Bbb Z^+:f(U)=1\}$ on $\Bbb Z^+$, and conversely, a free ultrafilter $\mathscr{U}$ on $\Bbb Z^+$ defines such a function $f_{\mathscr{U}}$ by $f_{\mathscr{U}}(U)=1$ iff $U\in\mathscr{U}$. Thus, he shows in effect that if there is a free ultrafilter on $\Bbb Z^+$, then there is a non-measurable $\{0,1\}$-valued function on $\Bbb R$, and it follows easily from the construction that $\mathscr{U}$ is not measurable in the Cantor space.
His argument, translated into English and modern notation, is as follows.

Suppose that $f:\wp(\Bbb Z^+)\to\{0,1\}$ is finitely additive but not countably additive. Suppose that $f(\{p\})=1$ for some $p\in\Bbb Z^+$. If $p\in E\subseteq\Bbb Z^+$, then
$$f(E)=f(\{p\})+f(E\setminus\{p\})=1+f(E\setminus\{p\})\;,$$
so $f(E)=1$. If $p\notin E\subseteq\Bbb Z^+$, then
$$1=f(E\cup\{p\})=f(E)+f(\{p\})=f(E)+1\;,$$
so $f(E)=0$. But then $f$ is countably additive, contrary to hypothesis, so $f(\{n\})=0$ for each $n\in\Bbb Z^+$. Similarly, we must have $f(\Bbb Z^+)=1$, as otherwise $f$ is identically $0$ and hence countably additive.
Now define $\varphi:\Bbb R\to\{0,1\}$ as follows. Each $x\in\Bbb R$ has a unique representation
$$x=\lceil x\rceil-1+\sum_{k\in\Bbb Z^+}\frac{b_k(x)}{2^k}$$
such that each $b_k(x)\in\{0,1\}$, and $B_x=\{k\in\Bbb Z^+:b_k(x)=1\}$ is infinite, and we set $\varphi(x)=f(B_x)$. Suppose that $\varphi$ is measurable. For $i\in\{0,1\}$ let $E_i=\{x\in\Bbb R:\varphi(x)=i\}$; each $E_i$ is measurable, and $\Bbb R=E_0\cup E_1$, so at least one of $E_0$ and $E_1$ must have positive Lebesgue measure (possibly infinite).
Let $x\in\Bbb R$, and let
$$y=-(\lceil x\rceil-1)+\sum_{k\in\Bbb Z^+\setminus B_x}\frac1{2^k}=1-x\;;$$
clearly $y=1-x$. If $\Bbb Z^+\setminus B_x$ is infinite, then $\varphi(y)=f(\Bbb Z^+\setminus B_x)=1-f(B_x)=1-\varphi(x)$. Thus, $\varphi(1-x)=1-\varphi(x)$ for each $x\in\Bbb R$ such that $1-x$ is not a dyadic rational. Thus, $E_1$ differs from $1-E_0$ by a countable set, so $E_0$ and $E_1$ must both have positive Lebesgue measure.
Now let $x\in\Bbb R$ be arbitrary, and let $r$ be a dyadic rational. Then the symmetric difference $B_x\mathrel{\triangle}B_{x+r}$ is finite, and since $f$ vanishes on singletons, $f(B_{x+r})=f(B_x)$, and therefore $\varphi(x)=\varphi(x+r)$. Thus, the sets $E_0$ and $E_1$ are invariant under translation by a dyadic rational. Since they also have positive measure, it follows that $E_0\cap[0,1]$ and $E_1\cap[0,1]$ both have measure $1$, which is impossible, since they are complementary. Thus, $\varphi$ cannot be Lebesgue measurable.

As you can see, it's basically the same proof, but without explicit appeal to the zero-one law.
Comment: This answer does capture the essentials of Sierpinski's article, but as far as I can tell, not only is there no explicit appeal to the zero-one law, but the point of the argument where the zero-one law would be invoked seems not to have been addressed at all here: Sierpinski in his article simply mutters something about known properties of measurable sets, without elaboration. That point being: "it follows that $E_0 \cap [0, 1]$ and $E_1 \cap [0, 1]$ both have measure 1" in the penultimate sentence. Happily, another Math.SE answer addresses this point: https://math.stackexchange.com/a/2204277


Calculating precision and recall in R

Question: Suppose I'm building a logistic regression classifier that predicts whether someone is married or single. (1 = married, 0 = single) I want to choose a point on the precision-recall curve that gives me at least 75% precision, so I want to choose thresholds $t_1$ and $t_2$, so that:

If the output of my classifier is greater than $t_1$, I output "married".
If the output is below $t_2$, I output "single".
If the output is in between, I output "I don't know".

A couple questions:

I think under the standard definition of precision, precision will be measuring the precision of the married class alone (i.e., precision = # times I correctly predict married / total # times I predict married). However, what I really want to do is measure the overall precision (i.e., the total # times I correctly predict married or single / total # times I predict married or single). Is this an okay thing to do? If not, what should I be doing?
Is there a way to calculate this "overall" precision/recall curve in R (e.g., using the ROCR package or some other library)? I'm currently using the ROCR package, but it seems to only give me the single-class-at-a-time precision/recall.
Answer: I wrote a function for this purpose, based on the exercise in the book Data Mining with R:
<code># Function: evaluation metrics
    ## True positives (TP) - Correctly idd as success
    ## True negatives (TN) - Correctly idd as failure
    ## False positives (FP) - success incorrectly idd as failure
    ## False negatives (FN) - failure incorrectly idd as success
    ## Precision - P = TP/(TP+FP) how many idd actually success/failure
    ## Recall - R = TP/(TP+FN) how many of the successes correctly idd
    ## F-score - F = (2 * P * R)/(P + R) harm mean of precision and recall
prf <- function(predAct){
    ## predAct is two col dataframe of pred,act
    preds = predAct[,1]
    trues = predAct[,2]
    xTab <- table(preds, trues)
    clss <- as.character(sort(unique(preds)))
    r <- matrix(NA, ncol = 7, nrow = 1,
        dimnames = list(c(),c('Acc',
        paste("P",clss[1],sep='_'),
        paste("R",clss[1],sep='_'),
        paste("F",clss[1],sep='_'),
        paste("P",clss[2],sep='_'),
        paste("R",clss[2],sep='_'),
        paste("F",clss[2],sep='_'))))
    r[1,1] <- sum(xTab[1,1],xTab[2,2])/sum(xTab) # Accuracy
    r[1,2] <- xTab[1,1]/sum(xTab[,1]) # Miss Precision
    r[1,3] <- xTab[1,1]/sum(xTab[1,]) # Miss Recall
    r[1,4] <- (2*r[1,2]*r[1,3])/sum(r[1,2],r[1,3]) # Miss F
    r[1,5] <- xTab[2,2]/sum(xTab[,2]) # Hit Precision
    r[1,6] <- xTab[2,2]/sum(xTab[2,]) # Hit Recall
    r[1,7] <- (2*r[1,5]*r[1,6])/sum(r[1,5],r[1,6]) # Hit F
    r}
</code>
Where for any binary classification task, this returns the precision, recall, and F-stat for each classification and the overall accuracy like so:
<code>> pred <- rbinom(100,1,.7)
> act <- rbinom(100,1,.7)
> predAct <- data.frame(pred,act)
> prf(predAct)
      Acc     P_0       R_0       F_0       P_1       R_1       F_1
[1,] 0.63 0.34375 0.4074074 0.3728814 0.7647059 0.7123288 0.7375887
</code>
Calculating the P, R, and F for each class like this lets you see whether one or the other is giving you more difficulty, and it's easy to then calculate
the overall P, R, F stats. I haven't used the ROCR package, but you could easily derive the same ROC curves by training the classifier over the range of some parameter and calling the function for classifiers at points along the range.
Comment: I think you got precision and recall code swapped. It should be r[1,5] <- xTab[2,2]/sum(xTab[2, ])
Answer: As Robert put it correctly, Accuracy is the way to go. I just want to add that it is possible to do calculate it with ROCR. Take a look at help(performance) to select different measures.
For example, in ROCR only one decision threshold is used which is called cutoff. The following code plots accuracy vs cutoff and extracts the cutoff for maximum accuracy.
<code>require(ROCR)

# Prepare data for plotting
data(ROCR.simple)
pred <- with(ROCR.simple, prediction(predictions, labels))
perf <- performance(pred, measure="acc", x.measure="cutoff")

# Get the cutoff for the best accuracy
bestAccInd <- which.max(perf@"y.values"[[1]])
bestMsg <- paste("best accuracy=", perf@"y.values"[[1]][bestAccInd],
              " at cutoff=", round(perf@"x.values"[[1]][bestAccInd], 4))

plot(perf, sub=bestMsg)
</code>
which results in

To operate with two thresholds in order to create a middle region of uncertainty (which is a valid way to go if the circumstances / target application allows it) one can create two performance objects with ROCR

cutoff vs True Positive Rate (tpr) aka precision for the positive class
cutoff vs True Negative Rate (tnr) aka precision for the negative class

Select a suitable cutoff from the performance vectors (using the R method which) and combine them to achieve the desired balance. This should be straightforward, hence I leave it as an exercise to the reader.
One last note: What is the difference between Accuracy and calculating precision for both classes separately and e.g. combine them in a (weighted) average?
Accuracy calculates a weighted average, where the weight for class c is equivalent to number of instances with class c. This means that if you suffer a heavy class skew (98% negatives for example) on can simply "optimize" the accuracy by setting predict the label negative for all instances. In such a case a non-weighted plain average of both class precisions prevents the gaming of the metric. In the case of a balanced classes both calculation methods lead of course to the same result.

Calculating precision and recall in R


Why are residuals Normally distributed?

Question: When they assume the $\varepsilon_i$ have a normal distribution, with mean $0$ and variance $\sigma^2,$ then the estimated errors $\hat\varepsilon$ have a normal distribution with mean $0$ and variance $\operatorname{Var}(\hat\varepsilon).$
But what is the connection? Why, when errors are normally distributed, the estimated residuals also are normally distributed?
Comment: Because this is a statistics site and we have been around a fairly long time, you can find a great deal written about this [with a site search](https://stats.stackexchange.com/search?q=idempotent+hat+matrix).  The key phrase "hat matrix" is especially helpful.
Answer: The connection is made through a specific procedure: namely, ordinary least squares.  When you suppose a response $Y$ is a random variable related to other variables $X$ in the form
$$Y = X\beta + \varepsilon$$
where $\varepsilon$ is assumed to have a joint Normal distribution (plus some other assumptions that don't matter here), then the least squares solution is
$$\hat\beta = (X^\prime X)^{-}X^\prime Y = (X^\prime X)^{-}X^\prime (X\beta + \epsilon) = \beta + J\varepsilon$$
for a matrix $J = (X^\prime X)^{-}X^\prime $ that is computed only from $X.$  The residuals, or estimated errors, are the differences
$$\hat\varepsilon = Y - \hat Y = (X\beta + \varepsilon) - X\hat\beta = \varepsilon - XJ\varepsilon = (\mathbb I - H)\varepsilon$$
where $H = XJ = X(X^\prime X)^{-}X^\prime$ is the "hat matrix."  This exhibits the residuals as linear combinations of $\varepsilon$ (with coefficients given by $\mathbb I - H$).  Linear combinations of jointly Normal variables are Normal, QED.

Why are residuals Normally distributed?


Check if function is injective

Question: $$f: N \times N → N$$
$$f(m,n)=m+n+2$$
Function should be injective if $f(a,b)=f(c,d)$
Should I put a,b = c,d or a,b = b,a?
$$a+b+2=c+d+2$$
$$a+b=c+d$$
If a+b = c+d, doesn't that mean it's injective? Thats how I got told, how the answer says it's not injective, what I am not understanding here?
Comment: $4 + 5 = 6+3$.  DOes that mean $4 = 6$ and $5 = 3$?
Comment: "Function should be injective if f(a,b)=f(c,d) "  No.   Function is injective if the *only* times you have $f(a,b)=f(c,d)$ is when $a=c$ and $b=d$.  It is not injective if $f(a,b) = f(c,d)$ is possible *without* $a$ having to equal to $c$ and $b$ having to equal $d$.
Answer: Being injective means that when $f(a,b)=f(c,d)$, then $(a,b)=(c,d)$. But $f(1,2)=f(2,1)$, in spite of the fact that $(1,2)\ne(2,1)$. So, $f$ is not injective.
Comment: Why do we have $(1,2)\ne(2,1)$? Because, for instance, the first component of $(1,2)$ is $1$ whereas the first component of $(2,1)$ is $2$. Yes, $f(1,2)=f(2,1)=5$. And it is *precisely* because $(1,2)\ne(2,1)$ and $f(1,2)=f(2,1)$ that $f$ is *not* injective.
Comment: Why does $(1,2)≠(2,1)$ if the result will be the same? It will be 5 = 5
Comment: Perhaps a simpler counter example is $f(3,7) = 3 + 7 + 2 = 12$.  And $f(4,6) = 4 + 6 + 2 =12$.  So $f(3,7) = f(4,6)$.  But the pair $(3,7)$  is not the same pair as $(4,6)$. The are completely different pairs.  Likewise the pair $(1,2)$ is not the same pair as $(2,1)$ because they are in different order so they are *different* pairs. You seem to be confusing what is required.  It's not when the *results* are the same.  It's when the *only* way the result can be the same is when the input are the same.  That is *not* the case here.
Answer: Injective means:

Whenever $f(a,b) = f(c,d)$ that is ONLY possible if $a=c$ and $b=d$.  If it is ever possible the that $f(a,b) = f(c,d)$ but we don't need to have both $a=c$ and $b=d$ then it is not injective.

So if $f(a,b) = f(c,d)$ does that mean we have to have $a=c$ and $b=d$?
If $f(a,b) = f(c,d)$ then
$a + b + 2 = c + d + 2$ and so
$a+b = c+d$.
But that's as far as we can go.  We could have $a =c$ and $b=d$ but we don't have to.    We could have $a=d$ and $b =c$.  Or we could have $a= c+3$ and $b=d-3$.  Or we could have $a = c+d$ and $b = 0$.  Or we could have any number of different ways of doing this.
Perhaps easy to note just do  counter example.  $f(1,2)= 1+2 + 2= 5$ and $f(2,1) = 2+1 + 2 = 5$ so $f(1,2) = f(2,1)$.  But we do not have $1=2$ and we do not have $2=1$ so it is not injective.
Of $f(3,4) = 3+4+ 2 = 9$ but $f(5,2)=5+2 + 2=9$.  So $f(3,4)=f(5,2)$.  But $3\ne 5$ and $4 \ne 2$.  So it is not injective.
...
Perhaps an example of a function that is injective might be in order.
Consider $g(n,m) = 2^n \times 3^m$.
So if $g(a,b) = g(c,d)$ does this force $a=c$ and $b = d$?  (The answer will be, surprisingly maybe, "yes").
If $g(a,b) = g(c,d)$ then we have $2^a3^b = 2^c3^d$.
Case 1:  Suppose $a < c$.  Then $2^a3^b = 2^c3^d$ so
$3^b = \frac {2^c3^d}{2^a} = 2^{c-a}3^d$.
BUt $c -a > 0$ so $2^{c-a}3^d$ is even but $3^b$ is odd.  SO that is impossible.
Case 2:  Suppose $a > c$.
Then $2^a3^b = 2^c3^d$ so
$\frac {2^a3^b}{2^c} = 3^d$ and $2^{a-c}3^b = 3^d$.
BUt $a -b > 0$ so $2^{a-c}3^b$ is even but $3^d$ is odd.  SO that is impossible.
So $a< c$ is impossible.  And $a > c$ is impossible.
So we MUST have $a = c$.  If $g(a,b) = g(c,d)$ then we are forced to have $a=c$.
So final case:  If $a = c$ (last remaining option)
then
Then $2^a 3^b = 2^c3^d = 2^a 3^d$ so
$\frac {2^a3^b}{2^a}=\frac {2^a3^d}{2^a}$ so
$3^b = 3^d$ so
$\log_3 3^b = \log_3 3^d$ so
$b = d$.  So $a=c$ and $b =d$.
So we were forced to have both $a = c$ and $b=d$.  If $g(a,b) = g(c,d)$ that is only possible when $a=c$ and $b = d$.
So in that case $g$ IS injective.
But $f(n,m) = n+ m + 2$ is NOT.

Check if function is injective


An Example of a composite function that does not exist

Question: Let's say $f(x)$, and $g(x)$ are two completely defined functions.
My understanding of composition's existence is that the domain of $g(x)$ must be a subset of the domain of $f(g(x))$, is that correct?
If yes, what two functions I can think of that will result in a composition that does not exist?
Thank you.
Comment: you need that the image of $g$ is contained in the domain of $f$ otherwise $f\circ g$ will not be defined on all of $dom(g)$ but on the subset $f^{-1}(img(g))$
Comment: Consider $g,f:\mathbb{R}^{+}\to\mathbb{R}$ defined by $g(x)=-1$ and $f(x)=\sqrt{x}$. The domain of $g(x)$ equals the domain of $f(x)$ but $f(g(x))=f(-1)$ DNE since $-1$ isn't in the positive reals.
Comment: Got it!! Thank you.
Answer: The complete description of a function $f$ contains its domain $A = \operatorname{dom} f$ and its codomain $B = \operatorname{codom} f$ which are two sets. Therefore we should always write $f : A \to B$ instead of $f(x)$. The latter is inadequate because it does not make precise for which $x$ the function is defined and in which set its values $f(x)$ are supposed to lie.
In some cases it may be acceptable to write simply $f(x)$, for example if we exclusively deal with functions having $\mathbb R$ as domain and codomain. In such cases it is automatically clear what $\operatorname{dom} f$ and $\operatorname{codom} f$ are.
Note that we must not confuse $\operatorname{codom} f$ with its image $\operatorname{im} f = f(A) = \{ f(a) \mid a \in A \} \subset B$; we may have $\operatorname{im} f \subsetneqq B$.
The codomain of a function is frequently also called its range.
The standard definition of the composition of functions $f : A \to B$ and $g: B '\to C$ requires $B = B'$. Then we get
$$g \circ f : A \to C, (g \circ f)(x) = g(f(x)) . \tag{1}$$
We can obviously extend this definition to the case that $B \subset B'$ or, even more generally, to the case that
$$\operatorname{im} f \subset B' \tag{2} .$$

My understanding of composition's existence is that the domain of $g(x)$ must be a subset of the domain of $f(g(x))$, is that correct?

No. First of all we do not know the domain of $g(f(x))$ before we have a definition of the composite function. However, it is clear that the domain of $g(f(x))$, whatever its definition may be, must be subset of the domain of $f$; otherwise $f(x)$ would not be defined. But even if we would know the domain $A' \subset A$ of $g(f(x))$, this set has nothing to do with the domain $B'$ of $g$. Look at $(1)$ and $(2)$.
We can also define the composite function for any two functions $f : A \to B$ and $g: B '\to C$ via
$$g \circ f : f^{-1}(B \cap B') \to C, (g \circ f)(x) = g(f(x)) . \tag{3}$$
This works because for $x \in f^{-1}(B \cap B')$ we have $f(x) \in B \cap B' \subset B'$ so that we can use $f(x)$ as input for $g$.
This definition may lead to $\operatorname{dom} (g \circ f) = \emptyset$ which is completely uninteresting.


What is the definition of dataset (for Bonferroni purposes)?

Question: I'm having difficulties finding a clear rule for when a series of test should be considered a multiple comparison and when we should apply p-value corrections (like Bonferroni).
I understand corrections must be applied every time multiple hypothesis are tested using the same dataset. A classical example is a Post-hoc Tukey test on data from an ANOVA.
However, what is the proper definition of a "dataset"? Whenever two tests share a sample, are they the same dataset? Do they need to share all samples? The tests must share the same hypothesis?
I found many questions related to mine in this forum and online, but all of them seem to handle examples. If their particular case is or is not a multiple comparison and whether it needs correction, but none seem to come with a objective definition of "dataset".
Comment: For perspectives questioning the utility of such adjustments, see Rothman, K. J. (1990). No Adjustments Are Needed for Multiple Comparisons. Epidemiology, 1(1), 43–46. https://doi.org/10.1097/00001648-199001000-00010 and Saville, D. J. (1990). Multiple Comparison Procedures: The Practical Solution. The American Statistician, 44(2), 174–180. Retrieved from http://www.jstor.org/stable/2684163
Answer: The justification for control of multiple tests has to do with the family of tests. The family of tests can be mutually independent, which is often the case when they are drawn from different datasets; if so, Bonferroni is a good way to control for FWER. But in general, the concept of a dataset doesn't even enter the picture when discussing multiplicity.
It's assumed (incorrectly) that data in different datasets must, by design, be independent whereas two tests calculated with the same dataset must be dependent (also not necessarily correct). To justify and discuss the type of testing correction to use, one should consider the "family of tests". If the tests are dependent or correlated (that is to say that the $p$-value of one test actually depends on the $p$-value from another test), Bonferroni will be conservative. (NB: some rather dicey statistical practices can make Bonferroni anti-conservative, but that really boils down to non-transparency. For instance: test main hypothesis A. If main hypothesis non-significant, test hypotheses A and B and control with Bonferroni. here you allowed yourself to test B only because A was negative, this makes tests A and B negatively correlated even if the data contributing to these tests are independent.)
When the tests are independent, Bonferroni as you know is non-conservative in controlling the FWER. There is some grey area with respect to what constitutes a family of tests. This can be illustrated by considering subgroup analyses, here a global test may or may not have been significant, then the sample population is divvied up into K distinct groups. These groups are likely independent because they are arbitrary combinations of independent data from the parent dataset. You can view them as K distinct datasets, or 1 divided dataset, it doesn't matter. The point is that you conduct K tests. If you report the global hypothesis: at least one group showed heterogeneity of effect from the other groups, then you don't have to control for multiple comparisons. If, on the other hand, you report specific subgroup findings, you have to control for the K number of tests it took you to sniff that finding out. This is the XKCD Jelly Bean comic in a nutshell.
Answer: This is a much harder question than one would think and I doubt there are clear answers. The answer is relatively clear when we talk about clinical trials for regulatory purposes (whatever the regulatory authority says). I have the impression that this is an area of pragmatic traditions that have evolved in a kind of ad-hoc and not necessarily philosophically consistent manner within each field of science. There are simply some standard conventions that are typically (but not always) followed in certain fields. However, even with a field where type I error rate control per study has a lot of tradition such as medicine, there is still a debate on this topic.


Como se cria textura de neve e particulas no Unreal engine 4

Question: Estou tentando criar um mapa onde é cheio de neve, porém, eu não consegui achar nenhum tutorial em português, ou até mesmo um tutorial em inglês, que seja bem explicativo.
Pretendo colocar partículas de neve simulando uma tempestade. Também quero conseguir colisões com a neve que cai no chão.
Se alguém tiver alguma dica ou tutorial, eu agradeço.
Comment: Na própria documentação do Unreal Engine tem instruções de como criar neve e efeitos relacionados: https://docs.unrealengine.com/latest/INT/Resources/Showcases/Effects/SnowExamples/index.html
Answer: Neve no Unreal Engine 4
Para criar o efeito que quer, é usado o Cascade e o Particle Systems.
O efeito nevasca (Blizzard) é um GPU Sprite Particle System composto de um aumento significativo de pequenas partículas usando um Lit Translucent Material.

Leia mais (documentação em inglês), clique


ANT: ways to include libraries and license issues

Question: I have been trying to use Ant to compile and ready a project for distribution. I have encountered several problems along the way that I have been finally able to solve but the solution leaves me very unsatisfied. First, let me explain the set-up of the project and its dependencies.
I have a project, lets call it Primary which depends on a couple of libraries such as the fantastic Guava. It also depends on another project of mine, lets call it Secondary. The Secondary project also features some dependencies, for example, JDOM2. I have referenced the Jar I build with Ant in Primary.
Let me give you the interesting bits of the build.xml so you can get a picture of what I am doing:
<project name="Primary" default="all" basedir=".">
    <property name='build' location='dist' />
    <property name='application.version' value='1.0'/>
    <property name='application.name' value='Primary'/>
    <property name='distribution' value='${application.name}-${application.version}'/>

    <path id='compile.classpath'>
        <fileset dir='libs'>
            <include name='*.jar'/>
        </fileset>
    </path>

    <target name='compile' description='Compile source files.'>
        <javac includeantruntime="false" srcdir="src" destdir="bin">
            <classpath refid='compile.classpath'/>
        </javac>
    <target>

    <target name='jar' description='Create a jar file for distribution.' depends="compile">
        <jar destfile='${build}/${distribution}.jar'>
            <fileset dir="bin"/>
            <zipgroupfileset dir="libs" includes="*.jar"/>
        </jar>
    </target>

The Secodnary project's build.xml is nearly identical except that it features a manifest as it needs to run:
<target name='jar' description='Create a jar file for distribution.' depends="compile">
    <jar destfile='${dist}/${distribution}.jar' basedir="${build}" >
        <fileset dir="${build}"/>
        <zipgroupfileset dir="libs" includes="*.jar"/>
        <manifest>
            <attribute name="Main-Class" value="lu.tudor.ssi.kiss.climate.ClimateChange"/>
        </manifest>
    </jar>
</target>

After I got it working, trying for many hours to not include that dependencies as class files but as Jars, I don't have the time or insight to go back and try to figure out what I did wrong. Furthermore, I believe that including these libraries as class files is bad practice as it could give rise to licensing issues while not packaging them and merely including them in a directory along the build Jar would most probably not (And if it would you could choose not to distribute them yourself).
I think my inability to correctly assemble the class path, I always received NoClassDefFoundError for classes or libraries in the Primary project when launching Second's Jar, is that I am not very experienced with Ant. Would I require to specify a class path for both projects? Specifying the class path as . should have allowed me to simply add all dependencies to the same folder as Secondary's Jar, should it not?
Answer: You may use the MANIFEST.MF "Class-Path: " to cross-reference your jars.
If they are all in the same directory this will probably work as follows (using it in both projects!):
<target name='jar' description='Create a jar file for distribution.' depends="compile">
    <pathconvert property="manifest.classpath" pathsep=" ">
         <path refid="compile.classpath" />
         <flattenmapper />
    </pathconvert>
    <jar destfile='${build}/${distribution}.jar'>
        <fileset dir="bin"/>
        <manifest>
            <attribute name="Class-Path" value="${manifest.classpath}"/>
        </manifest>
    </jar>
</target>

This way you can tell the java runtime environment that your jar needs others to work, expecting them to be in the same directory as the jar you are trying to run.
As a result your primary.jar should have secondary.jar in it's classpath and secondary.jar should have guava.jar in it's classpath.
Another way to create the string may be ants manifestclasspath task (https://ant.apache.org/manual/Tasks/manifestclasspath.html) that can handle subdirectories.
If you are goin to use more and more libraries, you may want to have a closer look at ivy or even maven.


Finding What Percentage a Plane is Covered By Pennies Touching Tangentially

Question: The question is the following:

Imagine covering an unlimited plane surface with a single layer of pennies, arranged so that each penny touches six others tangentially. What percentage of the plane is covered?

I can't seem to visually understand how a penny would touch six other pennies tangentially and I am, therefore, unable to understand how the plane is being covered in that pattern. Any help will be greatly appreciated.
Comment: See this [picture](https://www.google.de/imgres?imgurl=https%3A%2F%2Fmia-static-files-prod-2017.s3.eu-central-1.amazonaws.com%2Fstatic%2Fexample_tasks%2FEisstockkuesse_4.png&imgrefurl=https%3A%2F%2Fwww.mathe-im-advent.de%2Fkalender%2Fbeispielaufgaben%2FEisstockkuesse%2F&docid=DxgZIarLzvpzCM&tbnid=b__ABLihVAVCXM%3A&vet=10ahUKEwj-hLjoprraAhWnxKYKHUiJC6kQMwg-KAAwAA..i&w=600&h=547&client=firefox-b-ab&bih=858&biw=1760&q=6%20kreise%20um%20einen%20kreis&ved=0ahUKEwj-hLjoprraAhWnxKYKHUiJC6kQMwg-KAAwAA&iact=mrc&uact=8) Why you haven´t tried it with seven pennies?
Answer: Consider this image:

The outer six pennies are touching the center penny tangentially. If you filled a plane with pennies like this, the shaded rectangular area would repeat.
If you calculate the area of the shaded rectangle, $A_{shaded}$, and the area covered by the pennies within the shaded rectangle, $A_{covered}$, the percentage of a plane covered by pennies touching tangentially is
$$100\% \cdot \frac{A_{covered}}{A_{shaded}}$$
Because the scale does not matter, you can assume the radius of the pennies to be $1$. (The scale does not matter, because you can use "the radius of a penny" as your measurement unit. Then, the area units are "the radius of a penny, squared". Because the area units cancel out, you are free to choose your length (and therefore area) units.)
To find out the height of the rectangle, consider the angle the centers of two outer pennies make with respect to the center of the center penny.
Answer: Draw a regular hexagon and put a penny in the middle and on each of the vertices. That gives you the covering you want.


PHP Ejabberd Handshaking

Question: I am creating a social networking site where I want users to chat and receive live notifications like Facebook, I tried searching for possible solutions and found ejabberd's pubsub module (I am using ejabberd for chatting), so my option is to create some sort of pubsub service for that or second solution I have in mind is that upon entering a feed into mysql db, I send some sort of special message to user using ejabberd, for that I want to use jaxl php library, I tried it and it works just fine if you send message from javascript->php->ejabberd, but dosen't work if I try to send messages using only php.
Please tell me if my approaches are right or there is a better solution for that.
Comment: if you want to create a facebook copy and you don't know where to start you are completly mad
Comment: No, I do know where to start, but I need some help with this issue.
Comment: I don't need school, please don't comment if you can't help, if you are experienced then please help, else I assume we both have to go to school *KID*
Answer: I have used JsJAC will great success.  Skip PHP all together and make this a client-side operation.
http://blog.jwchat.org/jsjac/
Comment: I am using jsjac for client side, but I have a cron job running in the back which will push notifications to user via ejabberd.

PHP Ejabberd Handshaking


Calculate simple bound on coupon collector

Question: I came across this paper which gives bounds on weighted coupon collector problem. This paper, in short, tries to prove various lower and upper bounds for the expected number of draws till we see all coupons. U1 is one of the upper bounds for the expectations. Page 451 contains a table where reference to U1 is given as 'folklore'. I presume this is trivial to follow from the definition but I can't see the logic behind this. Does anyone have hints for me? I tried to get this bound by taking the limit of probability that some coupon is not found after n tries but that needs n to be infinity.
Comment: Would be nice to describe in brief what the paper says.
Comment: @Shailesh This is the weighted coupon collector problem. The paper tries to prove various lower and upper bounds for the expected number of draws till we see all coupons. U1 is one of the upper bounds for the expectation.
Comment: I'm adding that to the question.
Answer: $\frac{\log n}{p_1}$ is not an upper bound for the expected number of coupons drawn, since it's zero for $n=1$.
However, replacing $\log n$ by $H_n$ yields $\frac{H_n}{p_1}$, which is an upper bound since it's the expected number of coupons drawn if we reduce the drawing probability of all coupons to $p_1$.


Reparameterizing non-linear functions

Question: Consider the Ricker function:
$$
 y = axe^{-bx}
$$
Where the maximum fitted value of $y$ can be obtained as follows:
$$
y_{max} = \dfrac{a}{b}e^{-1}
$$
and the value of $x$ at $y_{max}$ can be obtained as follows:
$$
 x_{max} = \dfrac{1}{b}
$$
I wish to reparameterize the Ricker function so that $y_{max}$ and $x_{max}$ are included in non-linear least-squares optimization. Basically, $y_{max}$ and $x_{max}$ are of importance to my research question, and I would like to optimize the model fit for these parameters.
I am not a mathematician and am unaware of if this is challenging or simple task.
You help is much appreciated!
Comment: What do you mean by "add these terms to the Ricker function"? Are you talking about reparameterizing the function from being in terms of $(a,b)$ to expressing it in terms of $(y_\text{max},x_\text{max})$?
Comment: Plug in the algebraic identities $a=ey_\text{max}/x_\text{max}$ and $b=1/x_\text{max}$.
Comment: Hi whuber, excellent thank you! Quite straight forward. I should have known to do this.
Comment: @Patrick perhaps you could put that in as an answer (I doubt whuber will do it for this question)
Comment: Hi Glen_b, yes that is correct. Reparameterizing is the objective.
Answer: whuber has answered this question with:

Plug in the algebraic identities $a=ey_{max}/x_{max}$ and
  $b=1/x_{max}$

This results in
$$y = {y_{max}}/{x_{max}} \,\cdot\, e^{-{x}/{x_{max}}+1}$$

Reparameterizing non-linear functions


How to create loop for array which stores objects?

Question: So, I have an array with multiple objects.
var profile = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
    ];

There is a MODE  property, and a week days properties.
What I want, is to store all MONDAY values in array called MONDAY,all TUESDAY values in array called TUESDAY, and etc. Key of that value must be value of MODE(comfort, eco, etc).
So that is the goal:
var MONDAY =  ["Comfort":"09:00:00","ECO":"22:00:00", ...]
var TUESDAY = ["Comfort":"09:00:00","ECO":"22:00:00",...]

I've tried to filter initial array
var comfort = profile.filter(p => p.MODE == "Comfort");
var eco = profile.filter(p => p.MODE == "Eco");
var standby = profile.filter(p => p.MODE == "Standby");

var comfortMode = comfort[0];
var ecoMode = eco[0];
var standbyMode0 = standby[0];
var standbyMode1 = standby[1];

console.log(ecoMode["MONDAY"]);
console.log(standbyMode0["MONDAY"]);

But I've got stuck at that point.Seems that I need to hard code values,  and write by hand
    var MONDAY = [ecoMode["MONDAY"],comfortMode["MONDAY"],standbyMode0["MONDAY"],standbyMode1["MONDAY"]];
var TUESDAY  = [...,...,...,...]

Is there any way to create loop for comfortMode,ecoMode, and other arrays  that every value with key MONDAY were stored in an array called MONDAY?
Comment: I see no loops in your code, only variables and console outputs. Why don't you try creating a loop yourself first?
Answer: Here's a solution you can use. It's not the prettiest but it works and can get you started

var profile = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
    ];

    let monday = []
    let tuesday = []
    let wednesday = []
    let thursday = []
    let friday = []
    let saturday = []
    let sunday = []
    profile.forEach(e => {
        let mode = e.MODE
        let mondayVal = e.MONDAY
        let tuesdayVal = e.TUESDAY
        let wednesdayVal = e.WEDNESDAY
        let thursdayVal = e.THURSDAY
        let fridayVal = e.FRIDAY
        let saturdayVal = e.SATURDAY
        let sundayVal = e.SUNDAY
        monday.push({[mode]: mondayVal})
        tuesday.push({[mode]: tuesdayVal})
        wednesday.push({[mode]: wednesdayVal})
        thursday.push({[mode]: thursdayVal})
        friday.push({[mode]: fridayVal})
        saturday.push({[mode]: saturdayVal})
        sunday.push({[mode]: sundayVal})
    })

console.log("Monday: ", monday)
console.log("Tuesday: ", tuesday)
console.log("Wednesday: ", wednesday)
console.log("Thursday: ", thursday)
console.log("Friday: ", friday)
console.log("Saturday: ", saturday)
console.log("Sunday: ", sunday)

Let me know if you have any questions.
Answer: You can use Array.prototype.reduce to group the items from the input array and aggregate the desired output:

var profile=[{MODE:"Comfort",MONDAY:"09:00:00",TUESDAY:"09:00:00",WEDNESDAY:"09:00:00",THURSDAY:"09:00:00",FRIDAY:"09:00:00",SATURDAY:null,SUNDAY:null},{MODE:"Eco",MONDAY:"22:00:00",TUESDAY:"22:00:00",WEDNESDAY:"22:00:00",THURSDAY:"22:00:00",FRIDAY:"22:00:00",SATURDAY:null,SUNDAY:null},{MODE:"Standby",MONDAY:"07:30:00",TUESDAY:"07:30:00",WEDNESDAY:"07:30:00",THURSDAY:"07:30:00",FRIDAY:"07:30:00",SATURDAY:null,SUNDAY:null},{MODE:"Standby",MONDAY:"21:00:00",TUESDAY:"21:00:00",WEDNESDAY:"21:00:00",THURSDAY:"21:00:00",FRIDAY:"21:00:00",SATURDAY:null,SUNDAY:null}];

var result = profile.reduce((all, el) => {

    Object.keys(el).filter(k => k !== 'MODE').forEach(k => all[k].push({[el.MODE]: el[k]}));

    return all;

}, { MONDAY:[], TUESDAY:[], WEDNESDAY: [], THURSDAY:[], FRIDAY:[], SATURDAY:[], SUNDAY:[] });

console.log(result);
Answer: you can do this to get one array of hours for each day

let profile = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
];

// declare the object with the resulting arrays
let days = {}

profile.forEach(prof => {
  // we remember the mode for later
  let mode = prof.MODE;

  // for .. in loop each attribute of an object
  for (let i in prof) {
    // not needed to save modes
    if (i !== "MODE") {
      // create the array for the day if it doesn't exists
      if (typeof days[i] === "undefined") {days[i] = [];}
      // add the current value
      days[i].push(prof[i]);
    }
  }

})

// show the final object
console.log(days)

or this to still have the mode

let profile = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
];
// declare the object with the resulting arrays
let days = {}

profile.forEach(prof => {

  // we remember the mode for later
  let mode = prof.MODE;

  // for .. in loop each attribute of an object
  for (let i in prof) {
    // not needed to save modes
    if (i !== "MODE") {
      // create the object for the day if it doesn't exists
      if (typeof days[i] === "undefined") {days[i] = {};}
      // create the array for the mode if it doesn't exists
      if (typeof days[i][mode] === "undefined") {days[i][mode] = []}

      // add the current value
      days[i][mode].push(prof[i]);
    }
  }

})

// show the final object
console.log(days)

these two method allow you to grow your initial array without problem
Answer: Here is a solution to your problem. The only difference is that in the final output you will not be:

var MONDAY =  ["Comfort":"09:00:00","ECO":"22:00:00", ...]
var TUESDAY = ["Comfort":"09:00:00","ECO":"22:00:00",...]

It will be an object with weekdays as keys.

{
  "MONDAY": [
    {
      "Comfort": "09:00:00"
    },
    {
      "Eco": "22:00:00"
    },
    {
      "Standby": "07:30:00"
    },
    {
      "Standby": "21:00:00"
    }
  ],
  "TUESDAY": [
    {
      "Comfort": "09:00:00"
    },
    {
      "Eco": "22:00:00"
    },
    {
      "Standby": "07:30:00"
    },
    {
      "Standby": "21:00:00"
    }
  ],
  "WEDNESDAY": [
    {
      "Comfort": "09:00:00"
    },
    {
      "Eco": "22:00:00"
    },
    {
      "Standby": "07:30:00"
    },
    {
      "Standby": "21:00:00"
    }
  ],
  "THURSDAY": [
    {
      "Comfort": "09:00:00"
    },
    {
      "Eco": "22:00:00"
    },
    {
      "Standby": "07:30:00"
    },
    {
      "Standby": "21:00:00"
    }
  ],
  "FRIDAY": [
    {
      "Comfort": "09:00:00"
    },
    {
      "Eco": "22:00:00"
    },
    {
      "Standby": "07:30:00"
    },
    {
      "Standby": "21:00:00"
    }
  ],
  "SATURDAY": [
    {
      "Comfort": null
    },
    {
      "Eco": null
    },
    {
      "Standby": null
    },
    {
      "Standby": null
    }
  ],
  "SUNDAY": [
    {
      "Comfort": null
    },
    {
      "Eco": null
    },
    {
      "Standby": null
    },
    {
      "Standby": null
    }
  ]
}

var profile = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
    ];

var weekdays = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"];

var finalResult = weekdays.reduce((acc, currentDay) => {
    var dayValues = profile.reduce((acc1, currentProfile) => {
        return [...acc1, {
            [currentProfile.MODE]: currentProfile[currentDay]
        }]
    }, []);

    return {
        ...acc,
        [currentDay]: dayValues,
    };
}, {});

console.log(finalResult);


Randomizing 3 arrays in JavaScript/jQuery

Question: I would like to randomize three arrays for fonts, font size, font weight.
I then need to display the results of the three arrays in a div, with a class name of randomFont.
So each time I use the class randomFont, it will return a random font/size/weight.
Any ideas on how I would go about doing this?
Let's say I have 3 variables in each array.

array 1 (fonts) > font 1, font 2, font 3
array 2 (font weight) > bold, light, 100
array 3 (font-size) > 12px, 24px, 100px

Then I want an an array to randomly choose one from each and display the output in a div>class called randomFont.
How would I do this?
Answer: Don't really need jQuery but this should do it, since you didn't supply any example code I've had to make it up but this should get you on your way.
var item = items[Math.floor(Math.random() * items.length)];
do this for each array.
Comment: I think you get a random element, but not a randomized array?
Comment: lets say i have 3 variables in each array.

array 1 (fonts) > font 1, font 2, font 2
array 2 (font weight) > bold, light, 100
array 3 (font-size)> 12px, 24px, 100px

then i want an an array to randomly choose one from each and display the output in a div>class called randomFont.
Answer: You can see one approach at http://jsfiddle.net/CrossEye/bwsvy/
var fonts = ['Arial', 'Helvetica', 'Georgia', 'Tahoma', 'Verdana'];
var weights = ['normal', 'bold', 'lighter'];
var sizes = ['16px', '20px', '24px', '36px', '40px'];

var choose = function(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
};

// ...
var text = choose(sizes) + ' ' + choose(weights) + ' '  +  choose(fonts);
output.innerHTML = '
' + text + '
';
// e.g. '24px bold Tahoma'

Comment: question: is it possible to have the  three variable pointing to classes?
e.g var fonts = ['.font1', '.font2', '.font3', '.font4', '.font5'];
  also is it possible to have this function auto run on page load, and just look for a div tag called "output"? as opposed to creating one? really hope you can help.
Comment: Yes, it would be quite possible.  Have you tried either of them?  Have you searched the web for the page load question?
Comment: i tried the var classes like above but tart isnt working, searching for it, im finding nothing :(
Answer: It's not clear what you mean by randomizing the arrays.  If you have a fixed list of values and you want to rearrange them in place, then you want a shuffle functions, something like this:
var shuffle = function(arr) {
    for (var i = arr.length; i--;) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    return arr;
}

That might be a partial answer to what you're looking for, but it's really not clear to me what you're after overall.


non unique imaginary units

Question: A professor told me that another way to define complex numbers is through the real matrices of the form  $\begin{bmatrix}a & b\\-b &a\end{bmatrix}$. With this definition, the imaginary unit becomes the matrix $I=\begin{bmatrix}0 &1\\-1&0\end{bmatrix}$. By definition $i^2=-1$ and It's pretty easy to check that the square of the matrix $I$ is the negative of the identity matrix.
So apparently, any matrix with square equal to the negative of the identity can be taken as $I$. Why is that? When you think about the $2D$ plane, this corresponds to choosing a vector different from (1,0) as $\bar i$, the unit vector in the x-direction.
Then he says that by some general theorem all complex structures in dimension 2 are isomorphic to each other and that one can allow the imaginary unit to change from point to point.
Does anyone understand what this means and why we can do this?
Answer: In a similar way, we can represent the real number $-1$ by the matrix: $\begin{bmatrix}-1 &0\\0&-1\end{bmatrix}$ which can also be thought of as rotation by $180^\circ$.  Is it rotation clockwise or anticlockwise?  Well for $180^\circ$ it doesn't matter.
However, $i$ represents rotation by $90^\circ$ and clockwise and anticlockwise make a difference.  Which is right?  It doesn't matter, just make a choice and stick to it.
Compare driving on the road.  Should we drive on the left or the right?  Clearly both work as some countries choose one and some choose the other.  However, it is important for a country to make a choice and be consistent.  Also, when visiting a country with the opposite convention, care is required to adjust.  The UK and France have similar road rules except that left and right are flipped.  For example, when joining a roundabout in the UK you give way (yield) to traffic already on the roundabout, this traffic is approaching from your right.  In France, you also give way to traffic already on the roundabout but it is approaching from your left.
Please note that this is only a brief description of the differences between driving in the UK and France.  If you actually plan to drive in France, please research the rules more thoroughly.  Swapping left and right is just a first approximation.
Comment: Actually, the situation for French roundabouts is a bit more complicated than that: https://www.rac.co.uk/drive/travel/driving-abroad/10-lesser-known-french-road-rules-youll-need-to-follow-on-your-trip/
Comment: THe second paragraph seems to match what I say.  I think that it is good enough for the analogy.
Comment: Sure, of course! Just trying to prevent future traffic accidents in France among British readers of your answer. ;-)
Comment: I'll add a warning.
Comment: So apparently the tangent bundle of an n-dimensional affine space has a tangent n dimensional vector space  at each point and somehow that's why you can have a different imaginary unit at each point. I'm not even really sure what that means but I will consult wikipedia
Answer: $(0,1)$ and $(0,-1)$ are equally good to be taken as square root of $-1$. The isomorphism that is being talked about is the map $(x,y) \to (x, -y)$.
Incidentally, the definition of $i$ as $\sqrt {-1}$ found in some books is quite meaningless.
Comment: There are two complex numbers whiose square is $-1$. Without specifying how you are going to choose a particular one we cannot define $i$ as sqruare root of $-1$. @Jama
Comment: why is it meaningless?
Comment: ok. just making sure. thanks

non unique imaginary units


Why is the backup of the site not behaving the same as the original?

Question: I've cloned my site onto a testing server prior to making changes (database and all files), but it's not behaving like the original, and I'm unable to login.
The site was at www.original.com/drupal/ and www.original.com/node/3 works.
The test site is at www.test.com (note no /drupal) and www.test.com/node/3 gives me an Apache 404 error page.
Why are the two sites not behaving the same?
No Drupal specific content resides above www.original.com/drupal.
Comment: Did you also copy the .htaccess file? Or maybe there is some configuration in the apache virtual host... compare these on the two systems.
Comment: By default, if you install Drupal in a sub-directory (e.g. drupal), the URL for the node with ID equal to 3 would be http://example.com/drupal/node/3; if you see the content at http://example.com/node/3, then some of the files (e.g. .htaccess) have been changed.
Comment: @kiamlauno: I moved the contents of `/drupal` to `/`, hence `drupal` is missing from the URLs
Comment: @Bedir: there was a .htaccess at `/` but it did not contain any drupal specifics.
Comment: And does the .htaccess exist on the test site too? Does www.test.com/?q=node/3 work? If yes, then you are either missing the .htaccess on your test installation or it is incorrect.
Comment: Hah, you're pretty good with incorrectly writing usernames by the way. If you write it correctly, those persons are automatically notified and might otherwise not look at the question again, so make sure you write the name correctly :)
Comment: Multitasking - it's a false economy
Comment: there exists `original.com/.htaccess` and `original.com/drupal/.htaccess` but only the latter remains and it is at `test.com/.htcccess`.
`?q=node/3` works as expected on both original and test sites
Comment: The problem was caused by the .htaccess not being processed due to AllowOverride None in my httpd.conf file. Changing to AllowOverride All and restarting apache cured it.
Thanks @Berdir!
Comment: Great. Please write that down as an answer and accept it (once you can) so that this question is properly marked as fixed.
Answer: The problem was caused by .htaccess not being processed due to the "AllowOverride None" directive in my "httpd.conf" file.
Changing to "AllowOverride All" and restarting Apache cured it.


Formatar Nota para 2 casas Decimais

Question: Recebendo quatro valores de inputs type number e fazendo algumas operações estou precisando que os retornos sejam formatados para sempre 2 casas decimais. Alguém tem alguma dica de como fazer, pois não consegui e com o format_number a formatação ficou com notação de moeda.
Segue código:
<form action="" method="POST" class="form">

Calculo de Notas - Pitágoras

Parcial 01

                    <input type="number" name="input1" class="input" max="10" step=0.01 maxlength="5" onkeyup="somenteNumeros(this);">

Oficial 01

                    <input type="number" name="input2" class="input" max="10" step=0.01 maxlength="5" onkeyup="somenteNumeros(this);">

                    <?php
                        if(isset($total) && !empty($total)){
                            if($total >= 7){
                                echo "
".$total."
";
                            } else{
                                echo "
".$total."
";
                            }
                        }

                    ?>

Parcial 02

                    <input type="number" name="input3" class="input" max="10" step=0.01 maxlength="5" onkeyup="somenteNumeros(this);">

Oficial 02

                    <input type="number" name="input4" class="input" max="10" step=0.01 maxlength="5" onkeyup="somenteNumeros(this);">

                    <?php
                        if(isset($total1) && !empty($total1)){
                            if($total1 >= 7){
                                echo "
 ".$total1."
";
                            } else{
                                echo "
".$total1."
";
                            }
                        }

                    ?>
                    <input type="submit" value="enviar" id="enviar" class="botao">
                </form>

                    <?php
                        if(isset($final) && !empty($final)){
                            if($final >= 7){
                                echo "
O seu resultado final foi: ".$final."
";
                                echo "
Parabéns
";
                            }else{
                                echo "
O seu resultado final foi: ".$final."
";
                                echo "
Que Pena!
";
                            }
                        }

                    ?>

Segue PHP:
if(isset($_POST['input1']) && !empty($_POST['input1'])){
    if(isset($_POST['input2']) && !empty($_POST['input2']) ){
        $nota1 = $_POST['input1'];
        $nota2 = $_POST['input2'];
        $total = ($nota1*0.3)+($nota2*0.7);

    }
}
if(isset($_POST['input3']) && !empty($_POST['input4'])){
    if(isset($_POST['input3']) && !empty($_POST['input4']) ){
        $nota1 = $_POST['input3'];
        $nota2 = $_POST['input4'];
        $total1 = ($nota1*0.3)+($nota2*0.7);

    }
}

if(isset($total) && !empty($total)){
    if(isset($total1) && !empty($total1)){
        $final = ($total*0.4)+($total1*0.6);
    }
}

?>

Answer: Uma vez que está multiplicando você pode resolver dois problemas de uma vez só, usando o BCMath, afinal float contam "errado".
Então defina a quantidade de casas:
bcscale(2);

Depois faça:
$nota1 = $_POST['input1'];
$nota2 = $_POST['input2'];

$total = bcadd(bcmul($nota1, '0.3'), bcmul($nota2, 0.7));

Teste isto aqui.
Aplique o mesmo para os outros casos. O bcadd() irá somar os resultados do bcmul(), todos eles terão duas casas definido por bcscale().

Se quiser usar o number_format:
$nota1 = $_POST['input1'];
$nota2 = $_POST['input2'];

$total = ($nota1*0.3)+($nota2*0.7);

$total = number_format($total, 2, '.', '');

Se quiser trocar o . por , mude para number_format($total, 2, ',', '');.

Formatar Nota para 2 casas Decimais


Generalized nontransitive dice

Question: Let $X_1, \ldots, X_n$ be a collection of random variables. Consider the directed graph with vertex set $\{ 1, 2, \ldots, n \}$ where there is a directed edge $i \to j$ if $\mathbb{P}(X_i > X_j) > \frac{1}{2}$.
Question 1: What directed graphs can arise in this way? Certainly they must be simple and have no loops. Is that the only restriction? Alternatively, $\mathbb{P}(X_i > X_j) > \frac{1}{2}$ defines an irreflexive antisymmetric relation on $\{ 1, 2, ... n \}$. Which such relations arise in this way?
Question 2: Does the answer change if we require the $X_i$ to all be defined on a finite sample space?
Question 3: What if we require the $X_i$ to be independent?
It is known (see nontransitive dice) that this graph can have directed cycles even if the $X_i$ are independent; in particular, the corresponding relation need not be transitive.
Comment: I'd also be curious to know if requiring independence strongly restricts the possibilities or not. Both questions (independent or not) seem interesting.
Comment: @MichaelHardy: Oh, I totally understand the invitation ... if I knew how to do it, I wouldn't have said "hunch"  :D
Comment: Instead of nontransitive dice, how about a simpler example: $(X_1,X_2,X_3)=$ either $(0,1,2)$ or $(2,0,1)$ or $(1,2,0)$, each with equal probability.  Then $\Pr(X_1c)\ge\Pr(Y>c)$ and for at least one $c$ one has "$>$" instead of "$\ge$".  A totally concrete example is that that non-central F-distribution is stochastically larger than the (central) F-distribution.  If that were not so, then the usual way of using F-tests in ANOVA problems would be absurd.
Comment: . . . . . and so here's a question whose answer I don't know, maybe because I've never thought about it for a second: Is the notion of "stochastically larger than" a partial order?
Answer: Note: I wrote this answer before question 3 became a separate part of the question; this answer only answers questions 1 and 2. Question 3 seems harder.
Every simple directed graph arises in this way. Consider probability distributions over all $n!$ possible total orders of the values of the $X_i$, and associate a potential directed edge $i\to j$ with the distribution that has probability zero for orders with $X_i\lt X_j$ and $2/n!$ for orders with $X_i\gt X_j$. Given a directed graph, choose any network flow with positive flow along all the directed edges (you can always find one by taking any flow from the sources to the sinks and adding circular flow to the cycles if necessary), and form the normalized linear combination of the distributions associated with the edges, with coefficients given by the flow.
Now consider an edge $i\to j$. The contributions from any edges not incident at $i$ or $j$ don't affect whether $\mathbb P(X_i\gt X_j)\gt\frac12$, since they assign weight to equally many orders with $X_i\gt X_j$ as with $X_i\lt X_j$. Thus we only need to consider edges incident at $i$ or $j$. For an edge $j\to k$, consider the six possible orders of $X_i$, $X_j$ and $X_k$. Three of these are assigned weight by the edge $j\to k$, namely $X_i\gt X_j\gt X_k$, $X_j\gt X_i\gt X_k$ and $X_j\gt X_k\gt X_i$, and of these, one has $X_i\gt X_j$ and two have $X_i\lt X_j$. For an edge $k\to j$, it's the other way around.
Thus, considering the effect of all edges on $\mathbb P(X_i\gt X_j)-\frac12$, the edge $i\to j$ itself contributes $1-\frac12=\frac12$, edges not incident at $i$ or $j$ contribute $\frac12-\frac12=0$, edges "aligned with" $i\to j$, of the forms $k\to j$ and $i\to k$, contribute $\frac23-\frac12=\frac16$, and edges "opposed to" $i\to j$, of the forms $j\to k$ and $k\to i$, contribute $\frac13-\frac12=-\frac16$. Equal but opposite contributions from "aligned" and "opposed" edges cancel, so for a non-terminal edge the net result is equivalent by flow conservation to that of one incoming "opposed" edge incident at $i$ and one outgoing "opposed" edge incident at $j$ with net flows equal to that of $i\to j$. Thus the net result is that flow times $\frac12-\frac16-\frac16=\frac16\gt0$. The situation is only improved by sources and sinks.
If neither $i\to j$ nor $j\to i$ is an edge in the graph, then if $i$ and $j$ are not sources or sinks all contributions cancel and $\mathbb P(X_i\gt X_j)=\frac12\not\gt\frac12$ as desired; and again the situation is only improved by sources and sinks.
Qiaochu, I should add that I probably wouldn't have come up with this solution if I hadn't learned from you to try to reduce everything to linear algebra. :-)
Answer: joriki has already presented a solution to Questions 1 and 2; but maybe the following alternate solution has some insight to provide. I'll describe some $n$-tuples of random variables, as sets of vectors in $\mathbb R^n$, with the vectors selected uniformly from that set. For example, with $n=3$, the three random variables $X_1,X_2,X_3$ could be given by the set of vectors $\{(0,1,2), (1,2,0), (2,0,1)\}$ (as in Michael Hardy's comment). Then each $X_i$ individually would be uniformly chosen from $\{0,1,2\}$, but the $X_i$ are far from independent. Notationally, let $e_j = \{0,\dots,0 ,1,0,\dots,0\}$ denote the $j$th standard basis vector in $\mathbb R^n$. Let $f=(1,2,\dots,n)$ and $b=(n,n-1,\dots,1)$.
To begin, consider the following set $U_n = \{u_{ij}\colon 1\le i,j \le n,\, i\ne j\}$ of $n(n-1)$ vectors in $\mathbb R^n$, indexed by ordered pairs of distinct integers from $1$ to $n$, where:
$$
u_{ij} = ne_i + ne_j + \begin{cases}
f, &\text{if } i<j, \\ b, &\text{if } i>j.
\end{cases}
$$
For example, with $n=7$, $u_{52} = (0,0,0,0,7,0,0) + (0,7,0,0,0,0,0) + (7,6,5,4,3,2,1) = (7,13,5,4,10,2,1)$, while $u_{25} = (1,8,3,4,11,6,7)$. Note that for each unordered pair ${i,j}$, there are exactly 2 elements of $U_n$, namely $u_{ij}$ and $u_{ji}$, for which the $i$th and $j$th coordinates are the two largest (each one gets to be largest once). Note also that if $i<j$, then the sign of the $i$th coordinate of $u_{kl}$ minus the $j$th coordinate of $u_{kl}$ always equals the sign of $k-l$; in other words, the random variables $X_1,\dots,X_n$ defined by the set $U_n$ have the property that $\mathbb P(X_i>X_j) = \frac12$ for all $i,j$.
Now we modify the set $U_n$ to account for a given directed graph $G$. Let $V_n = \{v_{ij}\colon 1\le i,j \le n,\, i\ne j\}$, where
$$
v_{ij} = \begin{cases}
u_{ij}+ne_i, &\text{if there's a directed edge from $i$ to $j$ in $G$,} \\
u_{ij}+ne_j, &\text{if there's a directed edge from $j$ to $i$ in $G$,} \\
u_{ij}, &\text{otherwise.}
\end{cases}
$$
For example, with $n=7$, suppose that there is a directed edge from 5 to 2 in $G$. Then $v_{52} = (7,13,5,4,17,2,1)$, while $v_{25} = (1,8,3,4,18,6,7)$. With this modification, it's easy to see (after grokking the notation) that
$$
\mathbb P(X_i>X_j) = \begin{cases}
\frac12+\frac1{n(n-1)}, &\text{if there's a directed edge from $i$ to $j$ in $G$,} \\
\frac12-\frac1{n(n-1)}, &\text{if there's a directed edge from $j$ to $i$ in $G$,} \\
\frac12, &\text{otherwise.}
\end{cases}
$$
Answer: This question is answered fully by NovaDenizen in this answer to a similar question. It turns out that arbitrary graphs can be achieved with independent random variables and a finite sample space. The construction is as follows:

I'm just going to describe how you'd build it up an edge at a time.
Say your graph has $n$ nodes.  Start out with $n$ identical 2-sided dice. Each having 0 on both sides will work fine.
Pick an arbitrary edge in the graph, specifying that $D_a$ should beat $D_b$.  All the dice currently have $k$ sides, and satisfy the requirements for previously added edges, and unconnected dice are even*.  Find $m$, the maximum of all the faces on the dice.  To $D_a$, add two faces with $m+3$.  To $D_b$, add two faces of $m+2$.  To all other dice, add two faces, one of $m+1$ and one of $m+4$.  Repeat this procedure for all edges in the graph, winding up with $2e+2$-sided dice.

*I assume "even" here means that neither beats the other with probability $>1/2$.

Generalized nontransitive dice


Counting outcomes for three dice

Question: Given are three 6 sided dice, which we throw at the same time.
The outcome of the throw is given by the triple $(x,y,z)$. I want to know how many combinations have at least one of the dice with a $2$ showing up.
How can I count them without writing down every possible combination $\{(2,1,1),(2,2,1),..\}$? Any well known formula for this kind of counting problems?
Comment: Consider complementary probabilities. You are looking for the probability that at least one of the dice will show a $2$. The complementary probability is that no die shows a $2$. This probability is much easier to calculate. The probability you want is $100\%$ minus the probability that no die rolls a $2$. (This is an either or. Either no die rolls a $2$, or at least one die rolls a $2$. There are no other possible outcomes, which is why we can apply the Law of Total Probability).
Answer: There are $6 \times 6 \times 6 = 216$ possible outcomes. The number of outcomes where $2$ does not appear at all is $5 \times 5 \times 5 = 125$.
The number of outcomes where $2$ appears at least once is $216 - 125 = 91$.

Counting outcomes for three dice


Best method to regress time series on another time series?

Question: Probably a bit of a basic question but I have two time series and basically just wish to use one as an explanatory variable for the other. So my question is which methods out there are most appropriate for this? I've been reading around on ARIMAX and that sounded promising but my head is spinning somewhat.
Some info on the datasets, one is stationary and the other is not, both have equal numbers of observations and no missing values, probably going to be doing this using R, if that makes a difference.
Answer: Take a look at the autoregressive distributed lag (ADL) model.
Description:

Instead of only using the dependent variable's lags as predictors, an autoregressive distributed lag (ADL) model also uses lags of other variables for forecasting.