Does $\mathbb{R}^\mathbb{R}$ have a basis?

Question: I'm studying linear algebra on my own and saw basis for $\mathbb{R}, \mathbb{R}[X], ...$ but there is no example of $\mathbb{R}^\mathbb{R}$ (even though it is used for many examples). What is a basis for it? Thank you
Comment: Cue the AC guys...
Comment: Conveniently, there is nothing much useful that we could do if we got a basis for $\mathbb{R}^\mathbb{R}$ as a Christmas present.
Comment: @Jos: He is referring to the fact that the answer to your question depends very strongly on the axiom of choice (AC).
Comment: @MarianoSuárez-Alvarez, what do you mean?
Answer: If $V$ is vector space over a field $F$ then a subset $B$ is called Hamel basis (or simply a basis) for $V$ if $B$

is linearly independent, which means that for any finite subset $\{b_1,\dots,b_k\}\subseteq B$ the implication
$$c_1b_1+\dots+c_kb_k=0 \Longrightarrow c_1=\dots=c_k=0$$
holds for any $c_1,\dots,c_k\in F$.
generates $V$, which means that any $v\in V$ can be expressed in the form
$$v=c_1b_1+\dots+c_kb_k$$
for some $b_1,\dots,b_k\in B$, i.e. as a finite linear combination.

In the case of finitely-dimensional spaces this is precisely the same thing as the usual notion of basis, which is usually introduced in the first course in linear algebra.

Many properties valid for the finitely-dimensional case are true for Hamel basis as well, e.g.:

$B$ is a basis if and only if every vector $v\in V$ can be uniquely expressed as $v=c_1b_1+\dots+c_kb_k$, i.e. as the linear combination of the basic vectors.
For any linearly independent set $A$, there exists a basis $B\supseteq A$. (The proof of this fact uses Zorn's lemma which is equivalent to axiom of choice.) This result implies that every vector space has a Hamel basis.
If you prescribe the values of a map $f: V\to W$ for elements of $B$ (where $W$ is a vector space), this determines uniquely a linear map $f:V\to W$. (More formally: For any $g:B\to W$ there is there exists exactly one linear map $f:V\to W$ such that $f|_B=g$.)
If $B_1$, $B_2$ are Hamel bases of a vector space $V$, then $|B_1|=|B_2|$, i.e. any two bases of the same space have the same cardinality. Hence it is possible to define Hamel dimension of a vector space.

As I have mentioned above, the proof that every vector space $V$ has a basis uses Axiom of Choice. In fact, this claim is equivalent to Axiom of Choice. This means that we are not able (at least not for all spaces) to write down explicitly a basis. In some cases it might be possible.
EXAMPLE: Let $c_{00}$ be the space of all real sequences which have only finitely many non-zero terms. Then $\{e^{(i)}; i\in\mathbb N\}$, where the sequence $e^{(i)}$ is given by $e^{(i)}_n=\delta_{in}$, is a Hamel basis of this space. (Note that $c_{00}\subseteq\mathbb R^{\mathbb N}$. Thus we have just found infinite linearly independent subset of $\mathbb R^{\mathbb N}$, namely the set $\{e^{(i)}; i\in\mathbb N\}$. This implies $\mathbb R^{\mathbb N}$ cannot have finite basis. The argument that $\mathbb R^{\mathbb R}$ cannot have a finite Hamel basis is very similar.)

In fact, we can see quite easily that Hamel dimension of $\mathbb R^{\mathbb R}$ (as a vector space over $\mathbb R$ ) is $2^{\mathfrak c}$. Since the functions $\delta_x$ given by $\delta_x(x)=1$ and $\delta_x(y)=0$ for $y\ne x$ form a linearly independent set, we get that $|B|\ge|\mathbb R|$.
Every element of $V=\mathbb R^{\mathbb R}$ is determined by a finite sequence of pairs $(c,b)\in\mathbb R\times B$. The cardinality of all such finite sequences is $|\bigcup_{n\in\mathbb N} (B\times \mathbb R)^n| = \aleph_0 \cdot |B\times \mathbb R| = |B|$. Hence we get $|B|=|V|=|\mathbb R^{\mathbb R}|=2^{\mathfrak c}$.

You might notice that I stressed the word finite several times. In fact, if we only work with the structure of vector space, we are only able to do finite linear combinations. But if there is an additional structure on the space $v$, which enables us to define convergence (e.g. if we have topology, norm, metric) then we can also consider something like "infinite linear combinations" and ask whether there is a set $B$ such that every element $v\in V$ is expressible precisely in one way as $\sum_{b\in B} c_b\cdot b$. Such bases are indeed studied, example of this type of base is Schauder basis.
Let me mention a few references where you can learn more:

Christopher Heil. A Basis Theory Primer, New York, 2011.
Draft version of that book is available at author's website.
Marek Kuczma. An introduction to the theory of functional equations and inequalities, Birkhäuser, Basel, 2009.
Or you can simply try to google for Hamel basis.

Typically, Hamel basis is often mentioned in books about set theory (since it is connected to axiom of choice), about functional analysis (but here other types of bases, like Schauder basis, are more interesting) or about functional equations (since it is related to Cauchy equation).
See also this question: basis of a vector space
Comment: Isn't it time you hit that 10,000 mark? Congratulations! :-)
Answer: Even though $\mathbb{R}^\mathbb{R}$ has a basis, it is not finite, because $\mathbb{R}^\mathbb{R}$ is not finitely spanned (there exists no finite set of vectors $\{v_1, ...,v_n\}$ so that $S[v_1,...,v_n] = \mathbb{R}^\mathbb{R}$).
A basis for $\mathbb{R}^\mathbb{R}$ has not been found yet, I believe, so unfortunately, we won't be able to give you one.
Comment: @Joel: $|2^\mathbb R|=|\mathbb R^\mathbb R|$. Therefore the cardinality is much bigger than $\mathbb R$. If $I$ was a spanning set of cardinality continuum, then $\mathbb R$ would have the same cardinality as $\mathbb R^\mathbb R$. - All that, and perhaps more, without even using the axiom of choice; let alone CH, GCH and so on. I did, however, assume that there is a basis to $\mathbb R^\mathbb R$.
Comment: Can you give some references for the last sentence you wrote?
Comment: @Damian, I recall it from my linear algebra course (2 years ago). I have no formal reference to this. I should perhaps change the sentence to something lighter.
Comment: @DamianSobota : Here's a thought : If $(e_i)_{i \in I}$ is a basis of $\mathbb{R}^{\mathbb{R}}$ then $I$ is strictly bigger than $\mathbb{R}$ (otherwise $\text{span}(e_i)$ is in bijection with finite subsets of $\mathbb{R}^2$, which is in bijection with $\mathbb{R}$). So (assuming the continuum hypothesis) $I$ is in bijection with $\mathbb{R}^{\mathbb{R}}$. That means a basis of $\mathbb{R}^{\mathbb{R}}$ is simply huge. So in my opinion it seems very unlikely we can find an explicit example (or at least very difficult).
Comment: @Joel: What does the Continuum Hypothesis have to do with that?
Comment: @AsafKaragila : I'm using the fact that a subset of $\mathbb{R}^{\mathbb{R}}$ that is strictly bigger than $\mathbb{R}$ is in bijection with $\mathbb{R}^{\mathbb{R}}$ (which follows from the generalized continuum hypothesis). There might very well be simpler way to show $I$ is in bijection with $\mathbb{R}^{\mathbb{R}}$ without assuming CH, but I stated only what I knew.
Comment: @Joel: I'm not sure that I follow your logic. The fact that is a subset of $\mathbb R^\mathbb R$ whose cardinality is greater than the continuum is true without assuming CH, GCH or even AC. It's a simple corollary of the fact that $\mathbb R^\mathbb R$ is Dedekind-infinite, and Cantor's theorem. GCH has really nothing to do with that.
Comment: @AsafKaragila : My proof (although I admit it's surely not the simplest) was the following : We have $I \subset \mathbb{R}^{\mathbb{R}}$, but $I$ is strictly bigger than $\mathbb{R}$, so $I$ must be in bijection with $\mathbb{R}^{\mathbb{R}}$. How would you use Cantor's theorem for that ?
Answer: The dimension of $\mathbb R^\mathbb R$ over $\mathbb R$ is $2^{\frak c}$. It is not even the size of the continuum. As Jeroen says, this space is not finitely generated. Not even as an algebra.
Even as an algebra it is not finitely generated. What does that mean? Algebra is a vector space which has a multiplication operator. In $\mathbb R[x]$, the vector space of polynomials, we can write any polynomial as a finite sum of scalars and $x^n$'s. This is an example for a vector space which is not finitely generated, but as an algebra it is finitely generated.
In introductory courses it is customary to deal with well understood spaces. In the early beginning it is even better to use only finitely generated spaces, which are even better understood.
The axiom of choice is an axiom which allows us to "control" infinitary processes. Assuming this axiom we can prove that every vector space has a basis, but we cannot necessarily construct such space.
Answer: For this space (or simpler the vector space of infinite sequences of reals) one cannot actually write down a basis, even though one can prove using the axiom of choice that every vector space has a basis. Proofs of existence that essentially need the axiom of choice provide no means to actually construct the objects whose existence they establish.


vuex sub modules - pros vs cons

Question: My company have a really big application, with a lot (!) of data.
We have an argument using 3 modules for the main areas, and the main as flat module in store,
or using sub-modules as much as needed. (for each main sub-module about 6-8 sub-modules)
I wanted to get opinion only from people with experience in complex application using vuex.
Is it better to keep the module flat? or to use sub-modules?
Pros vs Cons
Answer: If you go by separation of concerns, It really makes sense to have submodules for different part of your system. It makes the feature enhancement easy and adding in one submodule does not alter anything in other modules, which makes collaboration also easy with different people working on different modules of your application.
Vuex submodules also helps keeping states of different submodules isolated from each other, otherwise it is too easy to have all the state variables mingled among each other. it implicitly emphases this discipline.
But in case your application is very simplistic and it is too much trouble to separate those in different submodules, than it will be definitely a overkill to use submodules.
Comment: lets say we have 3 main areas in the application. 3 modules will be enough? We need to learn from experience....
Comment: If the 3 are fairly independent from each other and each one is big enough to be a module in itself, you can go ahead with it.

vuex sub modules - pros vs cons


Number of balanced partitions of a set

Question: Question:
A balanced bipartition of set $X$ splits $X$ into two parts $A$ and $B$ so that the sizes
of $A$ and $B$ differ by at most $1$. In particular, when $X$ is even, $|A| = |B| = \frac{|X|}{2}$;
when $|X|$ is odd, $|A| = |B|—1 = \lfloor |X|/2\rfloor$. We refer to the bipartition as $A \cup B$. For
example, $\{b, e\} \cup \{a, c,d\}$ and $\{a,c\} \cup \{b, d, e\}$ are two different balanced bipartitions
of {a,b,c,d,e}. On the other hand, we treat $\{a,b\} \cup \{c,d\}$ and $\{c,d\} \cup \{a,b\}$ as
the same bipartition of $\{a, b, c,d\}$.
Solution:

For $|X| = 2$ we have $\{1\}\cup\{2\}$

For $|X| = 3$ we have $\{1,2\}\cup\{3\}$, $\{1,3\}\cup\{2\}$, $\{2,3\}\cup\{1\}$

For $|X| = 4$ we have $\{1,2\}\cup\{3,4\}$, $\{1,4\}\cup\{2,3\}$, $\{1,3\}\cup\{2,4\}$

My thinking is the number of ways are:

If $X$ is even then $\frac{\binom{X}{\frac{X}{2}}}{2}$
If $X$ is odd then $\binom{X}{\lfloor \frac{X}{2} \rfloor}$

But I am unsure if this is correct or how to prove it.
Answer: Yes, your answers are correct.
Suppose $|X|$ is even. To obtain a balanced partition of $X$, we can choose a subset $A$ of $X$ of size $\frac{|X|}{2}$, at which point $A$ and its complement $X -A$ form a balanced partition of $X$. Furthermore, note that all balanced partitions of $X$ are of the form $A$, $X-A$ with $|A| = |X-A| = \frac{|X|}{2},$ so this obtains all balanced partitions.
There are $\binom{|X|}{\frac{|X|}{2}}$ ways of choosing such an $A$. But note that choosing $A$ first and choosing $X-A$ first give the same pair $A, X-A$, so we have double counted. Therefore, the number of balanced partitions is $$\frac{\binom{|X|}{\frac{|X|}{2}}}{2},$$ which is what you got.
Now, suppose $|X|$ is odd. Any balanced partition of $X$ is of the form $A, X-A$, where $|A| +1 = |X-A|$, and thus $|A| = \left\lfloor\frac{|X|}{2}\right\rfloor$. So, to obtain all balanced partitions of $X$, we simply need to calculate the number of ways of choosing a subset $A$ of $X$ with size $\left\lfloor\frac{|X|}{2}\right\rfloor$, which is $$\binom{|X|}{\left\lfloor\frac{|X|}{2}\right\rfloor},$$ which is what you got.
Note that the reason we don't double count in the $|X|$ odd case is because there is an asymmetry: one of the sets in the balanced partition has size one smaller than the other, so we can't reverse their roles and obtain the same partition as we can in the even case.
Comment: Thank you. Small typo, I think instead of "first" you meant "second"

Number of balanced partitions of a set


How can Toolbar with overflow menu be created with Jetpack Compose?

Question: How can menu icons of Toolbar can be turned into overflow in Compose?
Scaffold(
    topBar = {
        TopAppBar(
            title = {
                Text(text = "LayoutsCodelab")
            },
            actions = {
                IconButton(onClick = { /* doSomething() */ }) {
                    Icon(Icons.Filled.Favorite)
                }

                IconButton(onClick = { /* doSomething() */ }) {
                    Icon(Icons.Filled.Refresh)
                }

                IconButton(
                    onClick = { /* doSomething() */ }) {
                    Icon(Icons.Filled.Call)
                }

            }
        )
    },
    bottomBar = {
        BottomNavigationLayout()
    }
) { innerPadding ->
    PhotoCard(Modifier.padding(innerPadding))
}

I want only one of the icons in Toolbar menu to be visible while others to be added to overflow menu like done with xml using app:showAsAction="never"
<item
    android:id="@+id/action_sign_out"
    android:title="@string/toolbar_sign_out"
    app:showAsAction="never"/>

Answer: You have to provide the OverFlowMenu yourself, e.g.:
@Preview
@Composable
fun PreviewOverflowMenu() {
    OverflowMenuTest()
}

@Composable
fun OverflowMenuTest() {
    var showMenu by remember { mutableStateOf(false) }

    TopAppBar(
        title = { Text("Title") },
        actions = {
            IconButton(onClick = { /*TODO*/ }) {
                Icon(Icons.Default.Favorite)
            }
            IconButton(onClick = { showMenu = !showMenu }) {
                Icon(Icons.Default.MoreVert)
            }
            DropdownMenu(
                expanded = showMenu,
                onDismissRequest = { showMenu = false }
            ) {
                DropdownMenuItem(onClick = { /*TODO*/ }) {
                    Icon(Icons.Filled.Refresh)
                }
                DropdownMenuItem(onClick = { /*TODO*/ }) {
                    Icon(Icons.Filled.Call)
                }
            }
        }
    )
}

Edit: Updated for Compose 1.0.0-beta08
Comment: With the latest version of compose.material3-android (1.2.1) this way of creating the DropdownMenuItem is deprecated. Text and Icon composable should be passed as a parameter.  Use `leadingIcon` and `trailingIcon`

`DropdownMenuItem(
 trailingIcon= {  Icon(Icons.Filled.Refresh, contentDescription = "refresh") }, onClick = { /*TODO*/ })`
Answer: I modified a bit @jns's answer to make it more modular and reusable.
This is the reusable OverflowMenu:
@Composable
fun OverflowMenu(content: @Composable () -> Unit) {
    var showMenu by remember { mutableStateOf(false) }

    IconButton(onClick = {
        showMenu = !showMenu
    }) {
        Icon(
            imageVector = Icons.Outlined.MoreVert,
            contentDescription = stringResource(R.string.more),
        )
    }
    DropdownMenu(
        expanded = showMenu,
        onDismissRequest = { showMenu = false }
    ) {
        content()
    }
}

And this is how it is used inside the TopAppBar:
TopAppBar(
        title = {
            Text(text = stringResource(R.string.my_title))
        },
        actions = {
            OverflowMenu {
                DropdownMenuItem(onClick = { /*TODO*/ }) {
                    Text("Settings")
                }
                DropdownMenuItem(onClick = { /*TODO*/ }) {
                    Text("Bookmarks")
                }
            }
        }
    )

We can possibly add icons to DropDownMenuItems if desired. And these items can be extracted as reusable composables as well. If there are other action buttons that you want to show as iconified buttons on the menu(i.e. show as action), you should put them before the OverflowMenu.
TopAppBar(
        title = {
            Text(text = stringResource(R.string.bookmark))
        },
        actions = {
            //This icon will be shown on the top bar, on the left of the overflow menu
            IconButton(onClick = { /*TODO*/ }) {
                Icon(Icons.Filled.FavoriteBorder, stringResource(R.string.cd_favorite_item))
            }
            OverflowMenu {
                SettingsDropDownItem(onClick = { /*TODO*/ })
                BookmarksDropDownItem(onClick = { /*TODO*/ })
            }
        }
    )

.
@Composable
   fun SettingsDropDownItem(onClick : () -> Unit) {
      //Drop down menu item with an icon on its left
      DropdownMenuItem(onClick = onClick) {
         Icon(Icons.Filled.Settings,
            contentDescription = stringResource(R.string.settings),
            modifier = Modifier.size(24.dp))
         Spacer(modifier = Modifier.width(8.dp))
         Text(stringResource(R.string.settings))
     }
  }

  @Composable
  fun BookmarksDropDownItem(onClick : () -> Unit) {
     //Drop down menu item with an icon on its left
     DropdownMenuItem(onClick = onClick) {
        Icon(painter = painterResource(R.drawable.ic_bookmark_filled),
            contentDescription = stringResource(R.string.bookmark),
            modifier = Modifier.size(24.dp))
        Spacer(modifier = Modifier.width(8.dp))
        Text(stringResource(R.string.bookmark))
    }
}

Comment: `showMenu` could also be done as:
`val showMenu = remember { mutableStateOf(false) }`
`showMenu.value = !showMenu.value`, using `showMenu.value` everywhere else `showMenu` is currently used
Answer: Inspired by @jns's answer,  I made an ActionMenu composable which takes a list of ActionItemSpec objects. and displays them with an overflow menu if necessary. I modelled the ActionItemSpec a bit like the old XML menu item entries, but added an onClick lambda.
It's used like this
@Preview
@Composable
fun PreviewActionMenu() {
    val items = listOf(
        ActionItemSpec("Call", Icons.Default.Call, ActionItemMode.ALWAYS_SHOW) {},
        ActionItemSpec("Send", Icons.Default.Send, ActionItemMode.IF_ROOM) {},
        ActionItemSpec("Email", Icons.Default.Email, ActionItemMode.IF_ROOM) {},
        ActionItemSpec("Delete", Icons.Default.Delete, ActionItemMode.IF_ROOM) {},
    )
    TopAppBar(
        title = { Text("App bar") },
        navigationIcon = {
            IconButton(onClick = {}) {
                Icon(Icons.Default.Menu, "Menu")
            }
        },
        actions = {
            // show 3 icons including overflow
            ActionMenu(items, defaultIconSpace = 3)
        }
    )
}

and the preview looks like this

Full pastebin is here: https://gist.github.com/MachFour/369ebb56a66e2f583ebfb988dda2decf
Comment: Well done machfour. A slight tweak might be to use DSL style definition of the contents of the ActionMenu: "ActionMenu(...) {  ActionItemSpec(...) ActionItemSpec(...) ... }".
Comment: Great suggestion @Duane. This would definitely look nicer and is more idiomatic Compose code. It's quite a refactor since the Compose code is currently all in ActionMenu, and ActionItemSpec is essentially just a data class, but I will consider it
Comment: @Duane actually, it's not really possible to do this while also keeping the ability to dynamically adjust the number of items displayed as icons. The ActionMenu has to know how to lay out each ActionItem either as an icon or entry in the overflow menu.


Data Structure for Two Variables (Doubles) in Objective-C

Question: I am looking for the best data structure (container) which will store only two variables in Objective-C (Mac OS X or iOS app):
<code>-(X) minAndMaxFinder: (NSMutableArray *)dataX {
double maxX = [[dataX valueForKeyPath:@"@max.intValue"] doubleValue];
double minX = [[dataX valueForKeyPath:@"@min.intValue"] doubleValue];
//adding these two variables (minX and maxX) to the structure X, later these data will be used in different methods
return X;
}
</code>
Should it be NSArray or something else? NSDictionary is not the obligatory solution because these two variables are not necessary connected like key-value. For example, NSMutableArray will let easily to change stored variables, but it will let as well to add more additional variables. Probably it is better to keep restriction not to let add additional variables like NSArray. As far as I know there are no vectors in Objective C unless integrating C++.
Which solution is the most recommended in this case?
Comment: Any objection against creating an `@interface { @public id a, b; }` ?
Comment: Please pick one pair of types that you want to store (even if it's "two of anything at all"), or this quickly becomes too broad.
Comment: Have you looked around for [other people's ideas about tuples](http://stackoverflow.com/search?q=%5Bobjc%5D+tuple)?
Comment: @DariusMiliauskas Oops, missed that "I would like to calculate..." part. What do you mean by "calculate them in a method"? Hmm, I'm almost sure you didn't get -[valueForKeyPath:@"max.intValue"] right. What are values in your example's dataX array? NSNumbers? That then should raise exception or return two nils (casted to 0.0) at least. There is no way to "just get int" from *generic* method like valueForKeyPath: in Objective-C anyway. When we say "generic container", we're stuck with objects and boxed values everywhere, especially under ARC.
Comment: Silly question but why don't you simply pass two discrete parameters to the method (or methods)? Why the desire to complicate the issue by wrapping the two values in some strange container? Such an approach prevents good compiler checking and it adds more complicated code to encode and decode the two values.
Comment: It would help if you showed a more concrete example of what you are trying to do.
Comment: I added a concrete example.
Comment: @user3125367 I didn't think about that possibility. A good suggestion but what if I would like to calculate them in a method?
Comment: In MRC epoch, we would just pass `id vs[2]` or `struct { id a, b; } vs`. Unfortunatelly, ARC didn't include support arrays and/or structs.
Comment: @ user3125367, there are integer or double numbers in the dataX array. Calculations are that find the minimum and the maximum values. Basically, my point in the above example is to get these two edge values from dataX array.
Comment: @rmaddy, I considered your point, but sometimes you need just two values to go to the next methods as the parameters. Instead of writing a long methods, I just encapsulate the calculations in different methods. Moreover, sometimes it would be more better performance to access the values from some container, then processing the whole methods.
Comment: I think "tuple" is not compatible in objective-c.
Answer: I ran into this myself when dealing with a strange problem where this was the best solution.  It's not a typical thing to need so consider finding another way around it, however, I have a very simple class I called a Pair.  It's immutable for me but it doesn't have to be for you.
<code>@interface DGCPair : NSObject

@property (nonatomic, readonly) id first;
@property (nonatomic, readonly) id second;

- (instancetype)initWithFirst:(id)first
                       second:(id)second;

@end
</code>
Even if your implementation file is mostly empty except for the init method this should serve your purposes.  Maybe it's a little overkill for something that could happily be done with basic data structures (or tuples if we had them) but it gets the job done.  Mine implements NSCopying for purposes of being a key in a dictionary, but, again, yours doesn't have to.
So in your case you could have:
<code>-(DGCPair *)minAndMaxFinder:(NSArray *)dataX {
    double maxX = [[dataX valueForKeyPath:@"@max.intValue"] doubleValue];
    double minX = [[dataX valueForKeyPath:@"@min.intValue"] doubleValue];

    return [[DGCPair alloc] initWithFirst:@(maxX) second:@(minX)];
}
</code>
You just have to make sure you remember or document which object was in which position (max in first, min in second).


Google Cloud Stackdriver Monitoring - Compute Engine Disk Space

Question: I am trying to add an alert and dashboard in Stackdriver Monitoring for our Google Cloud servers to monitor Disk Space (Volume).
I have managed to create the alert but am not getting any notifications even though I've set the threshold to 5%.
I can't seem to find an option at all in the Dashboard for Volume or Disk Space?
The server I am testing is running Windows 2012 R" and i have downloaded and installed the agent from - https://repo.stackdriver.com/windows/StackdriverMonitoring-GCM-46.exe
Comment: Do you have external IP with your VM instance? For instances without external IP addresses, you must enable [Private Google Access](https://cloud.google.com/vpc/docs/configure-private-google-access) to allow the Monitoring agent to send metrics. "Disk utilization" (agent.googleapis.com/disk/percent_used) metric is a readily available [agent metric](https://cloud.google.com/monitoring/api/metrics_agent#agent-disk). You can search typing "Disk utilization" at the metric field not "Volume" or "Disk Space".
Comment: The problem with "Disk utilization" is that it shows both free and used space, i have got round this by hiding half the results, but it's not ideal and no use at all for alerts.
Answer: @David At the moment this feature is not available. While  setting up monitoring of disk volume is under investigation within cloud engineering team, I created this  feature request on your behalf. You can track this thread to post any further comments or check the updates regarding this feature request.
Comment: Excellent Thank You


How to add a link href on a HTML element and open in new window in React

Question: I am having a banner on my React side.
When clicking the banner it should open in new tab target: _blank and go to href://www.example.com.
The markup would be something like:

 // Banner markup

What are best practices in React to do this and what should be the HTML attribute to click on?
Answer: you can do like this:

 window.open('www.example.com.', '_blank')}>
 // Banner markup


Single value "db_query": How to SELECT value that related to the node

Question: From this page, if what we need is SELECT single value, we can use fetchField method like below:
$nbr_records = db_query("SELECT count(nid) FROM {joke}")->fetchField();

I've created single value Integer field type with machine name field_subscription_period attached to node type yearly_rent.
I'm using this in Rules Action.
I've tested many db_query example with no luck.
Below is what I'm using, which it will get value of entity_id 2:
$result = db_query("SELECT field_subscription_period_value FROM {field_data_field_subscription_period} WHERE entity_id = 2")->fetchField();

Above query will get value of entity_id 2... but I want to SELECT field_subscription_period value that related to the node. So, how to get value that related to the node?
-newly added-
I still don't understand how to use $node = node_load($nid);. Lets say I want to use the value as variable to be calculated in date field.
I've tried below with no luck:
$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');
$newdate = strtotime("+$values year","$value");
return $newdate;

..and also I got error:
Notice: Undefined variable: nid in eval() (line 1 of /var/www/testd7/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7539 of /var/www/testd7/includes/common.inc).

Answer: You should not use direct queries to the database tables used for fields, for the simple fact the fields could not use database tables to store their value; this is what happens by default, but if a different storage implementation is exposed by a module, the information will be saved in another place. That is actually what happens with the Mongodb module.
If you know the node ID, and you want to get the value of a field associated to it, you can use the following code.
$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');

$values is an array whose structure depends from the field. It contains at least an item, but the exact number depends from how many values the field can have. (It is normally set in the setting page for the field.)
To see the structure of that array, you should install the Devel module, and use test code similar to the following one.
$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');
dsm($values);

For example, the first screenshot shows the structure used for a node body, while the second one shows the structure used for an image field.

If you need to find all the nodes of a specific content type, and filter out the list basing on the value set for a field, you should use the EntityFieldQuery class, as in the following code.
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'yearly_rent')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_subscription_period', 'value', $minimum_value, '>')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

addMetaData('account', user_load(1)) is necessary because the EntityFieldQuery class respects the access permission associated with fields; if the current user doesn't have access to the field, fieldCondition() would fail.
Once you have the node object, you can use field_get_items(). If you want to obtain a value to render, you should call field_view_field().
Comment: Still not works, I dont understand how to use it. The question has been updated above
Comment: But sadly, it looks impossible to use `nid` in Rules if I choose `Set a data value` action.


which neural network to use?

Question: I have explored this site for the answer but could not find what i was looking for. My problem is i have data containing many variables (22) that are continuos and categorical and my output has two levels 1(present) or 0 (absent). My questions are:
1) What type of library, for a neural network model, would be best for this type of data (nnet or neuralnet in r)
2) I have been told that this is a regression problem not a classification, however since my output only has two levels why is this regression and not classification?
Answer: Both packages neuralnet and nnet can be used for your task.
If you receive warnings on you are running regression but not classification, try to change the type for the response variable using function factor.
library(nnet)
library(mlbench)

set.seed(0)
d=mlbench.2dnormals(500)
plot(d)
d=data.frame(x1=d$x[,1],x2=d$x[,2],y=d$classes)

# nnet function from nnet package
fit1<-nnet(y~.,data=d,size=10)
fit1

# nnet from neuralnet package
library(neuralnet)
d$y=as.numeric(d$y)
fit2<-neuralnet(y~x1+x2,data=d,hidden=10)
fit2

Comment: Thank you, however when i convert my response variable into a factor in the neuralnet package i get an error message stating that i am using the wrong model for classification ?
Comment: @Martin hard for me to see what's happening with limited information here. But I will give you 2 examples on each package by revising answer.
Comment: Thank you for the example. This works fine for me and i can do both types of models from each package with no problem. however, when i try to cross validate this, under the caret package, i get the error message, "wrong model for classification", even when i convert the response variable to a factor. This is where my confusion comes from and why i ask the question, "is this is a classification or a regression problem", as it seems running the 'neuralnet' package with a factor as the response variable does not work?
Comment: @Martin that seems to be off topic for CV.
Comment: Thanks for the heads up, this could be why i cannot find the answer to this problem anywhere.

which neural network to use?


Getting PJSIP with TLS to work with Twilio SIP Trunking on FreePBX

Question: I'm wondering if someone can help me debug this problem I'm having. I'm trying to get secure trunking setup between my FreePBX server and Twilio using the PJSIP stack.
Unencrypted trunking works fine over UDP. However, when I try to enable TLS/SRTP, I can't seem to get it to work. As soon as I update the trunk to use 5061 and the TLS transport I get the following in the Asterisk logs.
WARNING[5268] pjproject: tsx0x27c4cd8 .Failed to send Request msg OPTIONS/cseq=28056 (tdta0x26d3af0)! err=171064 (Unsuitable transport selected (PJSIP_ETPNOTSUITABLE))
ERROR[5268] res_pjsip.c: Error 171064 'Unsuitable transport selected (PJSIP_ETPNOTSUITABLE)' sending OPTIONS request to endpoint Twilio

I think the issue may be that PJSIP does not support wildcard SSL certs and Twilio uses one, but I'm not sure how I can be sure. Any ideas on how to debug this would be very helpful.
Update: I tweaked some of the URIs directly in the asterisk config files and now I've gotten past the unsuitable transport error. The new error is as I feared:
ERROR[524] pjproject: RFC 5922 (section 7.2) does not allow TLS wildcard certificates. Advise your SIP provider, please!

Any ideas on how to work around this?
Answer: After talking with Twilio support, encrypted SIP trunking is only supported on PJSIP 2.5.5 or higher. I tested it on an Alpha build of the FreePBX Distro which runs 2.5.5, and it still complained about the wildcard cert, but it allowed the call to go through.
Of course, the older chan_sip module works with encrypted trunking on any modern version of FreePBX.
Comment: What configuration in FreePBX successfully worked for you?
Comment: I wound up sticking with chan_sip and following the [configuration guide here](https://www.twilio.com/docs/api/sip-trunking/sample-configuration)


Bounded above and denumerable sets

Question:
a.Let $A$ and $B$ be subsets of $[0,\infty)$ that are bounded above.
  Define the set $AB$ to be $AB = \{ab : a \in A; b \in B\}$. Prove that
  $AB$ is bounded above, and that $\sup(AB) \leq \sup(A) \sup(B)$.
b. Let $A$ and $B$ be two denumberable sets, such that $A\cap B =
\emptyset$. Show that $A\cup B$ is denumerable by exhibiting bijection
  between $A\cup B$ and $\mathbb{N}$.

For a. to be a subset of $[0,\infty)$ then it must be contained in $[0,\infty)$, but how will $[0,\infty)$ be bounded above? I know it is bounded below since it contains $0$ but I do not know why it ois bounded above since $\infty$ is not bounded.
For b. to be dumerable then there is an injection of domain $B$ in range of $\mathbb{N}$. Thus if the intersection of $A$ and $B$ is nonempty then will that be a cut?
Answer: (a) The set $[0,\infty)$ isn't bounded above; it's the sets $A$ and $B$, which are subsets of $[0,\infty)$, that are assumed to be bounded above. In other words, you're given that there are real numbers $x_A$ and $x_B$ such that $a\le x_A$ for each $a\in A$, and $b\le x_B$ for each $b\in B$. Since we're dealing only with non-negative numbers here, we can multiply these inequalities to show that $ab\le x_Ax_B$ for each $a\in A$ and $b\in B$; this shows that $x_Ax_B$ is an upper bound for $AB$, proving that $AB$ is bounded. You still have to prove that $\sup AB\le\sup A\sup B$, however. For that it's useful to realize that if $S$ is a set bounded above by some number $x$, and $s\le x$ for all $s\in S$, then by definition $\sup S\le x$. Apply this with $S=AB$.
(b) If you've defined denumerable set to be one that admits an injection into $\Bbb N$, start with injections $f:A\to\Bbb N$ and $g:B\to\Bbb N$, and consider the function
$$h:A\cup B\to\Bbb N:x\mapsto\begin{cases}
2f(x),&\text{if }x\in A\\
2g(x)+1,&\text{if }x\in B\;.
\end{cases}$$
Comment: @Q.matin: You're welcome; my pleasure!
Comment: Thanks! And for B I should have said "If there is a one-one function with domain $B$ and range equal to all of $\mathbb{N}$, then the set $B$ is denumerable " will that be a better definition ?
Comment: @Q.matin: It depends on whether you want *denumerable* to include finite. I prefer the term *countable*, but I use both to mean *finite or countably infinite*; that's compatible with the definition that I used in my answer. If you want it to mean *countably infinite*, then yes, you want it to be a bijection. (The trick that I suggested will still work, though.)
Comment: Thanks again for the help Brian!
Answer: The set $[0, \infty)$ itself is not bounded above, the sets $A$ and $B$ which are contained in $[0, \infty)$ but different from $[0, \infty)$ are the ones that are bounded above.
By denumerable I think the question means countably infinite, so for $A$ and $B$ there are bijections $f\colon A \to \mathbb N$ and $g\colon B \to \mathbb N$.  To answer this question you should define a map $h\colon A \cup B \to \mathbb N$ which is also a bijection.
Edit: If your professor defined denumerable as having an injection $A \hookrightarrow \mathbb N$ then you will not in general be able to exhibit a bijection $A \cup B \hookrightarrow \mathbb N$.  Because the question asks for a bijection $A \cup B \rightarrow \mathbb N$ then it must be the case that "denumerable" means there is a bijection $A \to \mathbb N$.  Otherwise the question is incorrect.
Comment: A lot more clear now, thanks! For part b since A and B are denumerable then there is an injection and from that I have to follow that their union will be a bijection? Also, How hard would you rate these two question in a scale from 1 to 10. 10 being the hardest for a real analysis intro course?
Comment: I would rate them as pretty easy on a difficulty scale, but pretty abstract for someone who hasn't seen this stuff (so don't feel bad if it's confusing at first).
Answer: It should be read that $A$ and $B$ are subsets of $[0,\infty)$ and $A$ and $B$ are bounded from above (not that $[0,\infty)$ is bounded from above). This just means that there exists a $K_A>0$ and $K_B>0$ such that
$$
a\leq K_A\text{ for all } a\in A,\quad\text{and}\quad b\leq K_A\text{ for all } b\in B.
$$
In b. let $A=\{a_1,a_2,\ldots\}$ and $B=\{b_1,b_2,\ldots\}$, then
$$
A\cup B=\{a_1,b_1,a_2,b_2,\ldots\}.
$$
Comment: Again, it's tough for me to rate, because I'm not sure what _a real analysis intro course_ covers. But anyhow, a. is pretty easy and intuitively clear, whereas b. is much more abstract and needs some careful thought.
Comment: A lot more clear now, thanks! For part b since A and B are denumerable then there is an injection and from that I have to follow that their union will be a bijection? Also, How hard would you rate these two question in a scale from 1 to 10. 10 being the hardest for a real analysis intro course?
Comment: See @Brian M. Scott's answer for an explicit construction of the bijection. He's simply mapping the elements of $A$ into to the even integers, and the elements of $B$ into the odd integers. My answer was merely an attempt to make it intuitively clear that $A\cup B$ is indeed denumerable. I would rate a. as a 1, and b. is a bit harder so maybe a 3.
Comment: Thank a lot, even though I was hoping for a higher scale rate which means I have a lot more studying to do!

Bounded above and denumerable sets


kineticjs slow down when I create many objects

Question: I'm new in using javascript and kineticJs. And I have a little problem, when I have created many object the animation slow down. I thought that I had removed that objects with .destory() but I think not because the project is going slow.
Here is my code:
var framesSegundo = 1000/20; //1000 seconds 20 frames
var stage, fondo;
var personaje;
var intv;
// calculate the time between one enemy and the oher one
var SegEneCreado = 0 ;
var layer = new Kinetic.Layer();
//Group with the chrachters
var grupoPersonajes = new Kinetic.Group({});
var grupoEnemigos = new Kinetic.Group({});
// screen create
var stage = new Kinetic.Stage({
        container: 'game',
        width: 960,
        height: 640
      });

//Level Create
function creaNivel(){
    //creamos un personaje
    personaje = new Kinetic.Rect({
      width: 100,
      height: 50,
      x: 10,
      y: stage.getHeight()/2,
      fill: 'red'
    });
    grupoPersonajes.add(personaje);
    layer.add(grupoPersonajes);
    stage.add(layer);
}

//Create the enemies
function creaEnemigos(){
   // we left the time of one second to create enother enemy
   if (SegEneCreado <= 0){
      if (aleatorio(0,1000)>970){
         SegEneCreado = framesSegundo;
         //create the enemies
         var tipoEnemigo = parseInt(aleatorio(0,3));
         if (tipoEnemigo == 0){
            var enemigo = createEnemy(stage.getWidth() + 10, 0, 'green');
         }
         else if (tipoEnemigo == 1){
            var enemigo = createEnemy(stage.getWidth() + 10, 0, 'blue');
         }
         else if (tipoEnemigo == 2){
            var enemigo = createEnemy(stage.getWidth() + 10, 0, 'yellow');
         }
         else {
            var enemigo = createEnemy(stage.getWidth() + 10, 0, 'C48BD9');
         }
         enemigo.setY(aleatorio(0,stage.getHeight() - enemigo.getHeight()));
         grupoEnemigos.add(enemigo);
         layer.add(grupoEnemigos);
         stage.add(layer);
      }
   }
   else{
      SegEneCreado--;
   }
}

function MoverEnemigos(){
   for (i in grupoEnemigos.children){
      var asset = grupoEnemigos.children[i];
      asset.move(-5,0);
      if (asset.getX() + asset.getWidth()<0){
        console.log(asset.getX() + asset.getWidth()<0);
        asset.move(0,0);
        asset.remove();
      }
   }

}

//random value
function aleatorio(inferior, superior){
   var posibilidades = superior - inferior;
   var random = Math.random() * posibilidades;
   random = Math.floor(random);
   return inferior + random;
}

function createEnemy(x, y, color){
  var enemy = new Kinetic.Rect({
      width: 100,
      height: 50,
      x: x,
      y:0,
      fill: color
    });
  return enemy
}

creaNivel();
intv = setInterval(frameLoop,framesSegundo);

function frameLoop(){
   creaEnemigos();
   MoverEnemigos();
   stage.draw();
}

I'm new in forums too... I found things about going slow down but I think these is a different problem.
Thanks
Answer: asset.remove will take the enemy off the canvas, but not destroy the enemy object.
Use asset.destroy to remove the resources used by the enemy object.
It would be more efficient to "recycle" your enemies rather than recreating a new enemy:
When an enemy goes offstage, set it's X property to -100 to indicate it's inactive
function MoverEnemigos(){
   for (i in grupoEnemigos.children){
      var asset = grupoEnemigos.children[i];
      if(asset.x()==-100){
          // enemy is inactive, do nothing
      }else{
          // enemy is active
          asset.move(-5,0);
          if (asset.getX() + asset.getWidth()<0){
              // enemy is offstage so make enemy inactive
              asset.x(-100);
      }
   }
}

Then when you need a new enemy you can find an inactive enemy an reset its properties.
function createEnemy(x, y, color){

    // see if there is an inactive enemy to reuse
    for (i in grupoEnemigos.children){
      var asset = grupoEnemigos.children[i];
      if(asset.x()==-100){
          // this enemy is inactive, reuse it
          asset.x(x);
          asset.y(0);
          asset.fill(color);

          // this enemy is already in groupoEnemigos so don't add it
          // Don't add it again in creaEnemigos
          return(asset);
      }
    }

    // no available inactive enemy so create a new enemy
    var enemy = new Kinetic.Rect({
        width: 100,
        height: 50,
        x: x,
        y:0,
        fill: color
      });

    // this enemy is not in groupoEnemigos so add it
    grupoEnemigos.add(enemy);
    return enemy
}


FragmentPagerAdapter - prevent next tab from being created automatically?

Question: I'm using FragmentPagerAdapter with a tabbed interface. My interface happens to have three tabs. I can see that as soon as my app is created, the adapter requests that both tabs one and two both be created immediately (I assume this is so swiping to the next tab appears smooth to the user).
Is there a way to stop the automatic loading of the next tab? My tabs are pretty heavy, and loading two right at startup is taking a good deal of time,
Thanks
Answer:
Is there a way to stop the automatic loading of the next tab?

Sorry, no. This is driven by setOffscreenPageLimit(), and the minimum value is 1, meaning that ViewPager will always try to create and hold onto at least 1 page on each side.
It sounds like you need to move more logic into background threads.
Comment: @LạngHoàng: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v4/java/android/support/v4/view/ViewPager.java


Why is real part written first in complex numbers?

Question: While expressing complex numbers as $a + \iota b$, is there a specific reason for writing the real part before the imaginary part?
Who introduced this notation first? Is it a case where it just hung up with us due to the guy you introduced us to this?
Comment: @JyrkiLahtonen It is not about it being acceptable. Only one way seems to be prevalent. In all of academia, that usually happens if some popular book which pioneered the topic introduced the notation. I would like to know the history.
Comment: The addition in the field of complex numbers is commutative, as is multiplication. In other words $a+bi$, $bi+a$, $a+ib$ and $ib+a$ are all equal. Who says only one way of writing it is acceptable?
Comment: No specific reason.
Comment: For the same reason that we write the $x$-coordinate and then the $y$-coordinate when we write an ordered pair $(a,b)$.
Answer: It is a historical convention, and Euler himself chose it:

But there are some pretty good mathematical reasons to prefer it, which might explain why Euler chose it.
$
\def\lfrac#1#2{{\large\frac{#1}{#2}}}
\def\rr{\mathbb{R}}
$
At first, it might seem more natural to write $ai+b$, like "$ax+b$" where $x$ is the variable, but that is mostly useful only when de-emphasizing the constant terms. Here it is not the case, because $i$ is the constant. $\{1,i\}$ form the standard basis of the complex numbers over the reals, so in this setting one can think of a complex number as $a·1+b·i$, and we drop the "$1$" because it is redundant. If this was all, then there would be no reason to prefer one ordering of the basis elements over the other. However, $1$ is in fact very special, as it is the multiplicative identity.
This specialness of $1$ results in various facts that favour putting it first:

The reals embed into the complex numbers as numbers of the form $a+bi$ where $b = 0$. Thus it makes sense to put the real part first. The reals form a field, while the purely imaginary numbers do not, so we can see the complex numbers as a field extension of the reals, whereby it is natural to likewise extend the representation by appending a "${}+bi$".
$\exp(iz) = \cos(z) + i·\sin(z)$ for any complex $z$. Obtained from the Taylor series, $\cos(z)$ is the asymptotically significant term approximating $\exp(iz)$ as $z \to 0$. So it makes sense to put it first. Note also that we usually write "$i·\sin(z)$" to emphasize the viewpoint that this equation relates $\exp,\cos,\sin$, in which $i$ is merely a coefficient. Typographical issues established this form in history as $\operatorname{cis}$, but I think it is very likely that anyone who rediscovers the identity will choose the same form.
Related to the above, $r·\exp(it)$ for real $r,t$ is not only the polar form of a complex number but also can be seen as a spiral transform (scaling plus rotation) about the origin. The identity spiral transform is just $1 = \cos(0)+i·\sin(0)$, so again it makes sense to have the $\cos(0)$ first.
When defining the complex logarithm as the inverse of the complex exponential function, namely via $\ln(r·\exp(it)) := \ln(r)+it$ for real $r,t$ where $r > 0$ and $t \in (-π,π]$, it makes sense to put the scaling $r$ first before the rotation $\exp(it)$, because scalings are in some sense simpler. For example they preserve the reals, and have diagonal transformation matrices.
Comment: In what sense is $\cos z$ the first-order term? I would call it $0$th or second-order, and $i\sin z$ first-order.
Comment: @mr_e_man: I have always thought that English meaning of "first-order" in approximation is that it is the most significant. When comparing $\cos(z)$ and $i·\sin(z)$, the most significant is $\cos(z)$. But to remove ambiguity, I'll edit my answer. Thanks! =)


Migration from csv problem (Incorrect string value: '\xAB Nove...')

Question: In my drupal 8 project, I'm trying to import data of a content type from a csv file, everything is well, but when I'm trying to execute the migration command drush mim my_migration I got the following error:
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xAB Nove...' for column 'sourceid1' at row 1 in                   [error]
/Users/brahim/Sites/news8/core/lib/Drupal/Core/Database/Statement.php:59

It seems like a problem of database encoding.. but I don't know what is it really, any idea about the solution?
Comment: maybe related to the source file encoding format (try with UTF-8). Check also for string issues (special characters) on the source file.
Comment: thanks @xaa for replying, how can I change/check the file encoding format?
Comment: depends of your text editor, google it. eg https://stackoverflow.com/questions/18693139/how-to-convert-csv-files-encoding-to-utf-8
Comment: Thank you dude! that was exactly the solution, I changed the file to UTF-8 encoding format and re-execute the migration the content has been imported as it should. thank you!
Answer: maybe related to the source file encoding format (try with UTF-8). Check also for string issues (special characters) on the source file.


Probability of $3$ people choosing the same number

Question: $5$ people will choose randomly and independently an integer between $1$ and $200$.
What is the probability that there will be exactly $3$ people who choose the same number?
Here is my solution:
$$\frac{{200 \choose 2}{2\choose 1}{5 \choose 3}+{200 \choose 3}{3\choose 1}{5 \choose 3}2}{200^5}$$
is it correct? Any suggestions?
Comment: How did you come up with this answer? Would you explain?
Comment: The answer is correct.
Comment: The answer is correct.  The first term describes the number of ways in which three people match with one number and the remaining two people match while the second term describes the analogous number of ways where instead the remaining two had different numbers.
Comment: The answer can be found more directly, as shown below, but it will be the same answer otherwise just appearing in a different form.
Answer: Let's fix first the three people that will choose the same number.  The first of them has $200$ possibilities, and the two others have no possibilities, they have to choose the same. Finally, the two last people can choose among $199$ numbers, they can't choose the same numbers as the three firsts. So there are $200 \times 199 \times 199$ possibilities.
Now, you have to integrate the fact that there are ${5 \choose 3}$ ways to choose the three people concerned. So the total number of cases is equal to ${5 \choose 3} \times 200 \times 199^2$.
Finally, you get that the probability is equal to
$\frac{{5 \choose 3} \times 200 \times 199^2}{200^5} \simeq 0.02 \%$.


Why are there dimples on the surface of golf balls and how do they function?

Question: I'm not a big golfer, but many people in my family play the sport, so I'm constantly surrounded by golf equipment and lingo. I've always wondered why the golf balls being used have "dimples" on the surface. See in the picture.

I'm 90% sure they are there for aerodynamics. So if someone could clarify that I am correct, that would be excellent. But if I am correct about the aerodynamics aspect, my question is this...
In a mathematical/scientific explanation, how/why do the dimples on the surface of the ball provide better aerodynamics for the ball?
If someone could give me an explanation on how the technology actually works that would be awesome.
Answer: You are correct that this has to do with aerodynamics, more specifically drag and air friction. This article goes over all of the specifics. Ultimately, it boils down to less drag on the ball, allowing it to fly farther. The exact details and an explanation of the difference between a smooth sphere and a dimpled ball are included in the linked article.
The following image shows the difference between a smooth sphere and a dimpled ball. The smooth sphere separates the air rapidly, creating a large pressure differential between the front and rear of the ball. This creates a large wake that creates lots of drag, forcing the ball to descend more quickly. In contrast, the dimpled ball delays the separation of the air, reducing the size of the wake. This helps to also reduce the pressure differential between the front and rear of the ball, reducing the drag and subsequently allowing the dimpled ball to fly farther than the smooth sphere.
Comment: Awesome. I was looking for a non article, detailed explanation and you gave it to me. +1
Comment: This answer is incomplete.  Since the ball is spinning (with a driver between 2000-4000 rpm depending on the player), the friction of the air over the ball changes.  In the above picture, the ball is moving right to left, and the ball is spinning clockwise.

Therefore, there is less friction on the top part of the ball vs the bottom of the ball, because the top of the ball is moving more slowly through the air relative to the bottom part of the ball because of the direction of airflow.

This makes the top of the ball have a lower pressure relative to the bottom, creating lift.
Comment: @LarryBud - That would happen on a smooth ball as well, but to a lesser degree. The main cause of lift is the deflection of the airflow around the ball by its rotation; the side of the ball rotating away from the airstream separates from the airflow later, directing the airflow on that side of the ball in the direction of rotation.


How do I port this event subscriber?

Question: The following code works fine with Drupal 9.

namespace Drupal\vl_login\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
// use Symfony\Component\EventDispatcher\Event;
use Drupal\Component\EventDispatcher\Event;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {

    $allowed = [
      'user.logout',
      'user.register',
      'user.login',
      'user.reset',
      'user.reset.form',
      'user.reset.login',
      'user.login.http',
      'user.logout.http',
      'user.pass'
    ];

    //redirect anonymous user to user login page
    if ( ($this->account->isAnonymous()) && ( !in_array(\Drupal::routeMatch()->getRouteName(), $allowed)) ) {
      $response = new RedirectResponse('/user/login', 302);
      $response->send();
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkAuthStatus');
    return $events;
  }
}

The module file

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function vl_login_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
  $form['#submit'][] = 'vl_login_user_login_submit';
}

/**
 * Form submission handler for user_login_form().
 *
 * Redirects the user to the dashboard after logging in.
 */
function vl_login_user_login_submit(&$form, FormStateInterface $form_state) {

  $url = Url::fromRoute('vl_login.dashboard');

  // Check if a destination was set, probably on an exception controller.
  // @see \Drupal\user\Form\UserLoginForm::submitForm()
  $request = \Drupal::service('request_stack')->getCurrentRequest();

  if (!$request->request->has('destination')) {
    $form_state->setRedirectUrl($url);
  }
  else {
    $request->query->set('destination', $request->request->get('destination'));
  }
}

I upgraded to Drupal 10 and I am not able to log in after I changed class from Symfony\Component\EventDispatcher\Event to Drupal\Component\EventDispatcher\Event because I get this exception.

TypeError: Drupal\vl_login\EventSubscriber\RedirectAnonymousSubscriber::checkAuthStatus(): Argument #1 ($event) must be of type Drupal\vl_login\EventSubscriber\GetResponseEvent
Comment: Next time include the full type error. The full error explains much.
Answer: The correct Drupal 10 version would be using RequestEvent:
  public function checkAuthStatus(RequestEvent $event) {

    $allowed = [
      'user.logout',
      'user.register',
      'user.login',
      'user.reset',
      'user.reset.form',
      'user.reset.login',
      'user.login.http',
      'user.logout.http',
      'user.pass'
    ];

    //redirect anonymous user to user login page
    if ($this->account->isAnonymous() && !in_array(\Drupal::routeMatch()->getRouteName(), $allowed)) {
      $response = new RedirectResponse('/user/login', 302);
      $event->setResponse($response);
    }
  }

For all Drupal versions since Drupal 8, don't send a response, set it in the event.
And add the use statement at the top:
use Symfony\Component\HttpKernel\Event\RequestEvent;

How do I port this event subscriber?


Random Intercept model vs. GEE

Question: Consider a random intercept linear model. This is equivalent to GEE linear regression with an exchangeable working correlation matrix. Suppose the predictors are $x_1, x_2,$ and $x_3$ and the coefficients for these predictors are $\beta_1$, $\beta_2$, and $\beta_3$. What is the interpretation for the coefficients in the random intercept model? Is it the same as the GEE linear regression except that it is at the individual level?
Answer: GEE and Mixed Model Coefficients are not usually thought of as the same. An effective notation for this is to denote GEE coefficient vectors as $\beta^{(m)}$ (the marginal effects) and mixed model coefficient vectors as $\beta^{(c)}$ (the conditional effects). These effects are obviously going to be different for non-collapsible link functions since the GEE averages several instances of the conditional link across several iterations. The standard errors for the marginal and conditional effects are also obviously going to be different.
A third and oft overlooked problem is that of model misspecification. GEE gives you tremendous insurance against departures from model assumptions. Because of robust error estimation, GEE linear coefficients using the identity link can always be interpreted as an averaged first order trend. Mixed models give you something similar, but they will be different when the model is misspecified.
Comment: @guy there are any number of ways of analyzing such data. Certainly, if you are interested in average levels of BP and conditioning out intracluster variability, then a random intercept model is a fine choice. Sometimes, you need to handle effects of time with random slopes, AR-1, or fixed effects which adds another wrinkle. So in general, the answer depends upon the question.
Comment: +1, your point about differences, even for linear models, w/ model misspecification is a nice one. A small worked example illustrating this would be a really great addition, should you be interested in providing one.
Comment: @AdamO: Suppose you take 10 measurements of blood pressure of 100 people over time. In this case, there would be 100 random intercepts?
Answer: GEE estimates the average population effects. Random intercept models estimate the variability of these effects. If $\alpha_j=\gamma_0+\eta_j$, $\eta_j\sim\mathcal{N}(0,\sigma^2_\alpha)$, random intercept models estimate both $\gamma_0$ (which is the average population intercept and, in normal linear models, is equal to the one estimated by GEE) and $\sigma^2_\alpha$.
If the intercept is modeled by second-level predictors, e.g. $\alpha_j=\gamma_0+\gamma_1 w_j+\eta_j$, a random intercept model can estimate how the intercepts vary at the individual level, i.d. according to economic, demographic, familiar etc. factors, to the 'group' to which a specific individual belongs.
Comment: GEE is appealing because provides consistent estimates of the fixed effects _even if the variance models is misspecified_, but without the 'true' variance model you can't get consistent estimats of random effects. Furthermore, while fixed effects require second order moments, consistent estimates of random effects would require fourth order moments ([here](http://courses.washington.edu/b571/lectures/set3.pdf), page 139). Last but not least, the choice of a working matrix is tipically aimed to reduce the number of... nuisance parameters (Lang Wu, Mixed Effects Models for Complex Data, p. 340).
Comment: This seems to be missing the current point of comparing a linear mixed model with a random intercept to a GEE with exchangeable correlation. Both models will have inconsistent estimates of the variance without the true variance model. All I'm really interesting in arguing about is your claim that gee with exchangeable correlation doesn't measure the variability of the random effects.
Comment: Why are you claiming that a random effects model estimates $\sigma_{\alpha}^2$ but a GEE does not? Won't a mixed model also produce inconsistent estimates of the variability of the random effects if the variance model is misspecified?
Comment: BTW: I _never_ said that GEE does not estimate $\sigma^2_\alpha$. Are you trolling?
Comment: You claim gee estimates population effects. Then you imply that's in contrast to a random effects model which estimates both population effects and variability of random effects. Did I misinterpret what you were trying to say?
Comment: Marginal models (including GEE) are "population-average models", mixed effects models (including random intercept models) are "subject-specific models". They have "different _targets of inference_ and thereby address subtly _different scientific questions_". So they are not basically equivalent as you claim. According to Fitzmaurice, Laird & Ware (_Applied Longitudinal Analysis_, 2nd ed., pp. 341-342), not to me.
Comment: Indeed, my claim appears to have been worded too strongly.  This quote, however, does not support the wording of your answer!  The whole point seems to be that the random effects have been integrated out in the GEE, but that does not mean that a GEE is not estimating the variability of the random effects, which is precisely what you imply when you say "GEE estimates the average population effects. Random intercept models estimate the variability of these effects."!
Comment: Integrated out??? Random effects are _targets of inference_ in random coefficients models, are just nuisance parameters in GEE. This is what I've said.
I'm not interested in continuinig this sterile discussion.
Comment: This is sad.  I don't think we really disagree all that much in the end.  I just think your answer could have been clearer :(
Comment: Yes, integrated out.  A colloquial term for marginalization.  Hence the term marginal or population model, which you are clearly well aware of.
Comment: In GEE $\sigma^2_\alpha$ is just a nuisance parameter, in random intercept models $\hat{\sigma}^2_\alpha$ makes feasible subject-specific inference. See [this paper](http://www.researchgate.net/profile/Lee_Anne_Roman/publication/23476583_Fixed_effects_random_effects_and_GEE_what_are_the_differences/file/72e7e52178ec8c727a.pdf).
Comment: What do you think the off-diagonal parameter of the exchangeable correlation matrix corresponds to?  It's $\sigma_{\alpha}^2 / ( \sigma_{\alpha}^2 + \sigma_{\epsilon}^2)$ where $\sigma_{\epsilon}^2$ is the variability of the error term.  It may be a nuisance, but it is still estimated!
Comment: Could you say that GEE _consistently_ estimates $\sigma^2_\alpha$?

Random Intercept model vs. GEE


Interpreting mortality trends shown as relative hazard

Question: I am analysing trends in survival. I was recommended to use the following package and parameterization.
I have a model as follows (done with rms package):
survobj12 = with(data, Surv(time_12months,status_12months))

model2 = cph(survobj12 ~ rcs(time_to_diagnosis_in_years, 4), data=data,x=TRUE ,

y=TRUE)

Result
Cox Proportional Hazards Model

 cph(formula = survobj12 ~ rcs(time_to_diagnosis_in_years, 4), data = data,
     x = TRUE, y = TRUE)

                     Model Tests       Discrimination
                                          Indexes
 Obs     11491    LR chi2      0.56    R2       0.000
 Events   3534    d.f.            3    Dxy      0.009
 Center 0.0343    Pr(> chi2) 0.9048    g        0.013
                  Score chi2   0.56    gr       1.013
                  Pr(> chi2) 0.9053

                          Coef    S.E.   Wald Z Pr(>|Z|)
 time_to_diagnosis_in_years    0.0145 0.0330  0.44  0.6597
 time_to_diagnosis_in_years'  -0.0271 0.0946 -0.29  0.7741
 time_to_diagnosis_ine_years''  0.0741 0.2853  0.26  0.7952

This is the plotted result:
#plot
ggplot(Predict(model2), vnames = "names")+
xlab("Time from diagnosis in years")+

This seems really nice; however, how should I interpret the plot? Is relative hazard equal to hazard ratios? The interpretation of hazard ratios is quite simple: e.g. HR = 2 means that females have two times higher risk for dying than males during a certain time period. However, my plot does not have a reference category at all.
So, are these two estimates (Relative Hazard and Hazard Ratio) equal to each other and what is the reference on my plot/analysis?
Comment: Please add to your question the specific command that you used to produce the plot that you show, as there might be some built-in default settings specific to the software. It would help if you could add to your question the result of the `cph` model and of `anova()` applied to the model. Finally, what specifically do you mean by "these two estimates"?
Comment: Good points! Edited the OP.
Answer: The most important point in this example is that your model isn't different from a null model. The p-values for both the likelihood-ratio (LR) and score tests for the model are very high, over 0.9. With a 4-knot restricted cubic spline you are estimating coefficients for the equivalent of 3 predictors, with no values significantly different from zero here.
For the plot itself, it's important to learn about what your software tools are doing; see the manual page for the rms Predict and datadist functions. An example on the manual page for Predict shows that the reference value for a continuous predictor is taken from the second value in the limits vector for that predictor in the datadist summary of the data. Resetting that value allows you to choose any reference value that you want; in that manual page example:
ddist$limits$age[2] <- 30

resets the reference value for a variable age to 30. If you don't specify your own reference, the manual page for datadist shows that the median value is chosen for a continuous predictor:

Adjustment values are 0 for binary variables, the most frequent category (or optionally the first category level) for categorical (factor) variables, the middle level for ordered factor variables, and medians for continuous variables.

That adjustment/reference value is shown in this example as the time value at which the "log Relative Hazard" crosses 0. The plot then shows changes in "log Hazard" relative to that reference time value as you go to lower or higher times. If your model had more predictors, the 0 reference for the "log Relative Hazard" would also be based on the reference values for all the other predictors, so depending on the data and the model this type of plot might never cross 0.
Comment: Thank you! I use this plot for showing/illustrating non-significant temporal trend, using plotting of the Cox model's results. Adjusting is not necessary. Is this a problem that my model is not significant from a null model? IMHO it is not a problem.
Comment: @st4co4 Finding this model not to be significantly different from a null model means there is no evidence of a significant association of hazard with time, as including that predictor is no different than including no predictor at all. That seems to have been exactly what you wished to examine. The result would be more compelling if your model also incorporated other covariates associated with survival, however. Also, be careful that the way you defined `time_to_diagnosis_in_years` isn't leading to [survivorship bias](https://en.wikipedia.org/wiki/Survivorship_bias).


PHP INCLUDE function inside an HTML file

Question: I have an HTML file that has a rather long navigation menu inside of it. I want to take that menu out of the HTML and place it into an external PHP page and then call it with
<?php include 'navigation.php'; ?> in the HTML file.
I have tried just adding this into the HTML file but it doesn't display anything as well as no errors on the page.
What do I need to do (if it's even possible) to keep the files HTML and use the php require function?
Comment: Did you give the page a .php suffix?
Comment: The `navigation.php` has the .php and the `index.html` has the .html that is the way I really want to keep it.
Comment: You need a .php extension to serve a php file. You can adjust your Apache settings to do this though
Answer: Add this in in your httpd.conf and then you can process PHP code on HTML pages
AddHandler application/x-httpd-php .php .html

Comment: Is this something that GoDaddy would provide or do I just make a new file with the `httpd.conf` name and place that code inside of it?
Comment: @user2371301 you can use it in a .htaccess file as well, GoDaddy wont give you access to the conf file, I think!
Comment: Ok I added an .htaccess file to the project and copied it into but still nothing happens?
Comment: @user2371301 cant tell you the problem, try echoing something on a HTML page and see, make sure you are in the same diretory or lower with the htaccess. Im off to bed!
Answer: Q: Did you give the page a .php suffix?  That should be all you need to do.
Remember the way PHP works - you basically "embed" your PHP code in an HTML page, and the server executes the PHP before it serves (the rest of) the HTML.
But in order for PHP to "see" your code, you need to make sure your "HTML page" has a .php suffix.
As a crude workaround, you can add ".html" to the list of file suffixes that PHP will parse.
But this could cause other things to break.
If you want to embed PHP code in your "index.html", the best, cleanest approach is to simply rename it "index.php".
IMHO...