C# - Get group info from Azure AD

Question: I'm using Azure AD login for an app to login with Microsoft credentials and get the groups (and their info) that the user is a part of.
With this line I'm able to get the logged in user:
var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
With this line I'm able to get the groups that the user is a part of:
var groups = userClaims?.Claims.Where(claim => claim.Type == "groups").Select(c => c.Value);
Now I'm trying to integrate Microsoft.Graph so I can get the group's info (I only need the group's display name).
I'm using this code:
GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer");
return Task.FromResult(0);}));

var group = graphClient.Groups[g].Request().GetAsync();

This doesn't work or I can't seem to figure out how to read properties of the group var.
Any simple way I can get the group's info?
Answer: As per the offical ms graph you can fetch the group display name by below
GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var groups = await graphClient.Groups
    .Request()
    .GetAsync();

Another work around is below:
var graphClient = GraphUtility.CreateGraphClient(accessToken);
var targetGroupCollection = await graphClient.Groups.Request()
                                    .Filter($"startsWith(displayName,'{groupName}')")
                                    .GetAsync();

Comment: The thing with the first bit of code is the authProvider. I can't figure out how to create it properly.
Also with the second one, where does the accessToken come from?
Comment: You need to be Authenticate first to get the access token.
Comment: I'm sorry but that was not helpful, if I knew how to do that I wouldn't be asking
Comment: [Web App calling Graph api](https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2).This reference helps you to connect the graph API.Once you are successfully connected to graph API, you can use the above query for group display name

C# - Get group info from Azure AD


Clustered Stacked bar plot over time

Question: I have a data frame as below:
   time       type      category   count
2021/01/01   regular       A         2
2021/01/02   new           B         3
2021/01/02   regular       A         5
2021/01/03   new           A         1
... and so on

What I want is a clustered stacked bar plot such that the time is on the x-axis and is in order, the count on the y-axis, and the plot should be able to tell the information like on a particular day how many regular types of category A visited (count) out of how many total regulars that day and same for the new type.
I am assuming for this we first need to convert the data in a way so that we have all the combinations with zero counts as well so like the first entry in the above table will be converted into four entries like:
   time       type      category   count
2021/01/01   regular       A         2
2021/01/01   regular       B         0
2021/01/01   new           A         0
2021/01/01   new           B         0
... and so on

Kindly guide me on how I can achieve what I want. I am new to this visualization stuff
Edit
I am able to fill in missing values using:
pd.DataFrame({'count' :df.groupby(['time','type','category']).size().unstack(fill_value=0).stack()}).reset_index()

Still not sure regarding how to plot this in a stacked multi bar plot. If there is a better option than this plot, Kindly suggest.
Answer: What you expect is not fully clear (please provide an example, even just a schematic), but here are some examples.
First, you need to rework a bit you dataframe using pivot:
df_pivot = df.pivot(index='time', columns=['type', 'category']).fillna(0)['count']
df_pivot

output:
type       regular  new
category         A    B    A
time
2021/01/01     2.0  0.0  0.0
2021/01/02     5.0  3.0  0.0
2021/01/03     0.0  0.0  1.0

Then you can plot with:
df_pivot.plot.bar(stacked=True)

If you want to make sure that you have all categories, you need to reindex:
import itertools
idx = itertools.product(df['type'].unique(), df['category'].unique())
df_pivot = df_pivot.reindex(idx, axis=1).fillna(0)
df_pivot.plot.bar(stacked=True)

Clustered Stacked bar plot over time


Acceptance-Rejection Technique Theorem Proof

Question: I am assigned to discuss the acceptance-rejection technique in our class. I have trouble understanding the last part of proving its theorem.
The theorem goes like this:

The acceptance-rejection algorithm generates a random variable X such
that $\mathbb P\{X=j\}=p_j$, $j=0,1...$
In addition, the number of iterations of the algorithm needed to
obtain $X$ is a geometric random variable with mean $c$.

The proof goes like this:

(I'm not really good at this so I just attached a picture)
I don't quite understand how it turned $1/c$ and then $p_j$ in the last two parts of the proof.
Answer: The probability a proposal is accepted is the sum over $j$'s that the value $j$ is (1) generated and then (2) accepted:
\begin{align}\mathbb P(\text{proposal accepted})&=\sum_{j=1}^\infty \mathbb P(\text{proposal accepted and }Y=j)\\
&=\sum_{j=1}^\infty \mathbb P(\text{proposal accepted }|Y=j)\mathbb P(Y=j)\\
&=\sum_{j=1}^\infty \frac{p_j}{c}=\frac{1}{c}\sum_{j=1}^\infty {p_j}=\frac{1}{c}
\end{align}
(The argument is much more straightforward when considering continuous densities as it corresponds to a ratio of areas, $1$ under the target versus $c$ under the proposal. The picture below is taken from our Monte Carlo book.)
$\qquad\qquad\qquad$
The probability that an accepted value is equal to $j$ is the probability that a value $j$ is proposed and accepted divided by the probability a value is accepted:
\begin{align}\mathbb P(X=j)&=\mathbb P(Y=j|Y\text{ is accepted})\\
&=\dfrac{\mathbb P(Y=j\text{ is accepted})}{\mathbb P(\text{proposal is accepted})}\\
&=\dfrac{p_j/c}{1/c}=p_j
\end{align}


Preventing "Plus" from rearranging things

Question: The following code creates a diagram of a certain calculation. My problem is that even though the terms in denominator are in a nice order, after applying Plus on it, they get rearranged arbitrarily. Any suggestions how to force the original order to be kept?

(source: yaroslavvb.com)

r[i_] := Floor[(i - 1)/n] + 1;
c[i_] := Mod[i, n, 1];
adj[a_, b_] := Abs[r[a] - r[b]] + Abs[c[a] - c[b]] == 1;
indsetQ[s_] := Not[Or @@ (adj @@@ Subsets[s, {2}])];
indsets[k_] := Select[Subsets[Range[n^2], {k}], indsetQ];
twoColorGraph[g_, seen_, lbl_] := Module[{radius = .22},
   vcoords = # -> {c[#], n - r[#]} & /@ Range[n^2];
   fv = Function[{p, v}, {EdgeForm[Thick],
      If[MemberQ[seen, v], Pink, White], Disk[p, radius]}];
   GraphPlot[g, VertexLabeling -> True, VertexRenderingFunction -> fv,
     PlotLabel -> Style[lbl, 20], LabelStyle -> Directive[Bold],
    VertexCoordinateRules -> vcoords, ImageSize -> 80]
   ];
n = 2;
g = Array[Boole[adj[#1, #2]] &, {n^2, n^2}];
weight[set_] := Times @@ (Subscript[\[Lambda], c[#], r[#]] & /@ set);
denominator =
  twoColorGraph[g, #, weight[#]] & /@
   Join @@ (indsets[#] & /@ Range[2]);
numerator = twoColorGraph[g, {1}, weight[{1}]];
Style[numerator/(Plus @@ denominator), FontSize -> 30]
Comment: This is a duplicate, in intent, if not form, of another question (http://stackoverflow.com/questions/3947071/controlling-order-of-variables-in-an-expression).  Otherwise, I'd give you a +1 for the graphics alone.  What is the calculation for?
Comment: Yes, that's similar. The suggestion there is to define own function that's not orderless like "myPlus", but how do I get it to render the same as "Plus"?
Comment: The calculation is to find per-site occupation probabilities of hard-core repulsive local gas on a finite grid (ie, grand canonical gas with hard-core self-repulsion and hard-core pair interaction)
Comment: Seconded on the nice graphics. I answered the formatting question below =)
Comment: +1, @Yaroslav Bulatov, you're right.  It's definitely related, but not the same.
Answer: The trick to formatting something like myPlus to look like Plus on output is to use Format. Here's a simple example to get you started:
Format[myPlus[expr__]] := Row[Riffle[{expr}, "+"]]

Then, what you will see visually in the notebook is:
In[7]:= x = myPlus[3, 2, 1]
Out[7]= 3+2+1

... but x will still have head myPlus.
Here is a tutorial from the documentation that goes into more details about formatting output, operator precedence, etc.
Hope that helps!
Comment: +1, I was trying to do that with `Notation` and it was failing miserably.  I forgot to look at `Format` directly.
Comment: I tried to incorporate `Interpretation` with your answer so that it can be copied and pasted properly, but ran into problems. See the SO question http://stackoverflow.com/q/4112299/421225


Required sample size for exact McNemar test and for phi coefficient (power analysis)

Question: I aim to establish the required sample size for my study. In the main analyses, which are conducted to test my hypotheses, I am investigating two 2x2 tables. Specifically, I plan to perform an exact McNemar test for the first table (with a directed p-value) and to examine the phi coefficient for the second table. For the McNemar test, my focus is on comparing values in the lower-left versus upper-right cell. How can I conduct a power analysis to determine the necessary sample size with alpha = $0.05$ and power = $0.8$? Is it feasible to perform this analysis in either R (e.g., using a simulation) or G*Power?
Comment: Hi Louis! For conducting an *a priori* power analysis (i.e. finding the required sample size), you also have to determine what minimal effect size you want to be able to detect in your population of interest.
Comment: Note that McNemar's test is equivalent to a sign test; an exact test would be be based on the binomial; it's not at all hard to do a one-tailed version. This calculation is quite simple. Conversely an exact test for phi - were you to want one - could be performed if you condition on the margins, in almost exactly the same manner as the exact version of a chi-squared test is done in R (see `?chisq.test` there), using Patefield's algorithm for sampling the 2x2 tables. There's a function `r2dtable` which implements the algorithm in question and facilitates working with any statistic you like.
Answer: I Googled "Power analysis McNemar test" and found this web page from ScaleStatistics, describing, in detail, how to do it in GPower. It allows both directional and non-directional tests.
I didn't find a GPower implementation for phi (although it may exist) but Unistat has one, see this site .
As for simulation, if you are clever enough, I think you can simulate a power analysis for almost anything. I am not a programmer, but I don't think either of these should be that difficult (but I may be wrong).


Detecting Events in a series

Question: I have a series (sensor readings) with different events and I'm trying to segment/detect those events for further analysis using change point detection in python.
In general, the series consists of a mean with a fairly small standard deviation. Occasionally, an outlier reading will occur for one, maybe two points, and then usually revert to the same mean. Another common pattern is the series shifting to a new mean, either abruptly or over the course of several readings. I'd like the method I use to capture both kinds of changes.
Additionally, I'm going to be doing this online so I'd like the results to be somewhat stable. It's fine if new data makes a mean-shift more obvious and a new change point is detected at N-3, but I don't want a method that causes a change point to be detected at N-20.
It seems like ruptures is the most common change point library in python (I also looked at changefinder), all the methods are offline but I'd be happy re-running for every new data point if it worked. However, I've had trouble getting satisfactory results.
import ruptures as rpt
import matplotlib.pyplot as plt

signal = [9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 28.0, 13.0, 9.0, 10.0, 10.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 10.0, 10.0, 10.0, 9.0, 9.0, 9.0, 9.0, 9.0, 10.0, 31.0, 31.0, 35.0, 35.0, 37.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]

def detect_events(signal):
    signal = np.array(signal)
    algo = rpt.Pelt(model="rbf", min_size=1, jump=1).fit(signal)
    result = algo.predict(pen=1)

    algo = rpt.Window(model='l2', width=2, min_size=1).fit(signal)
    result = algo.predict(pen=5)

    # algo = rpt.Binseg(model="l2", jump=10).fit(signal)
    # result = algo.predict(pen=20)

    change_points = [i for i in result if i < len(signal)]
    return change_points

change_points = detect_events(signal)

optimal_change_points = [7,9, 38, 43]

print(change_points)
for cp in change_points:
    print(signal[cp-2:cp+2])
f, ax = plt.subplots(1,1)
plt.plot(signal, axes=ax)

for cp in change_points:
    ax.axvline(x=cp, color='r', linestyle='--')

for cp in optimal_change_points:
    ax.axvline(x=cp, color='g', linestyle=':')

Series with optimal change points vs detected changepoints
It seems whatever combination of search method I try with ruptures I'm either missing significant events, or detecting loads of spurious events, or getting a change point at weird spots, like well into the sequence of -1 instead of at the start.
I'm getting to the point where I'm probably going to make my own method (I'm primarily concerned with mean-shifts so I think it's feasible), though I can see that turning into a giant pile of edge-cases. The problem feels standard enough that I'd just be re-inventing a much more functional wheel but I don't know where that wheel is.
Answer: Hello again (I commented on your question on Maths SE). I think you can get more desirable results using a different cost function for the set of change points rather than completely starting again with your own method.
Here is my own coding of PELT in Python. To start, I can recover something like the segmentation that you're describing if I run
import PELT

x = [9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 28.0, 13.0, 9.0, 10.0, 10.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 10.0, 10.0, 10.0, 9.0, 9.0, 9.0, 9.0, 9.0, 10.0, 31.0, 31.0, 35.0, 35.0, 37.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]

PELT.PELT_cp_n(x, len(x) - 1, penalty = "BIC")[-1]

PELT_cp_n outputs the optimal set of change points that was determined at each time point, so [-1] selects the final set of change points. I get output
[0, 7, 8, 12, 29, 32, 37, 38, 40, 42, 43]

which looks like this:

I agree with you that this is too many change points, particularly the segmentation of the long sequence of 9s and 10s, and it's happening because PELT can get a perfect fit on the long sequence of 9s, and it's actually more expensive for it to include a few 10s in the segment than to start a new segment for the 10s. Because I'm using the BIC penalty, every time PELT throws down a new change point it has to pay the complexity penalty $\beta = 2\log(n)$, where $n$ is the number of data points. If you increase the penalty $\beta$ to be more strict then you can enforce a sparser model that only triggers more serious change points. For example, if you change the start of the PELT_cp_n to be
def PELT_cp_n(x, end_time, likelihood_model = "gaussian", K = 0, penalty = "BIC"):
    if penalty == "BIC":
        beta = 2.0 * np.log(end_time + 1)
    elif penalty == "AIC":
        beta = 2.0 * 2.0
    elif penalty == "aluchko":
        beta = 25

and run
PELT.PELT_cp_n(x, len(x) - 1, penalty = "aluchko")

then you get output [0, 7, 9, 38, 43], depicted below. You could experiment with different penalties until you find one that works in general for the kind of data that you have.
Comment: Thanks for the help, that definitely gets me a lot closer.

A constant penalty makes sense since it shouldn't be based on N. But another thought is I want to make it somewhat resistant to a shift in mean. For instance, a 20 surrounded by 19s
`x = [19] * 100 + [20] + [19] * 50`

That's not a significant change for the phenomena but is a huge outlier for the Gaussian.

I modified your implementation to add an offset to the standard deviation and that seems to perform better
`sigma_squared_hat = np.std(self.x[t0:t1]) + 1`

It feels very hacky but it seems to work.

Detecting Events in a series


Inherit props and functions from vue parent instance

Question: I am trying to define some default props and functions in my vue instance that i want to reuse in all of my components. How do i go about doing this? I have tried to pass the props but since they are read only it wont work.
Am i approaching this in the right way or should i look at another way?
<code>// vue.js
import { createApp } from 'vue';
import Page from './vue-instances/Page';

const Vue = createApp({
 data() {
  return {
    loading: false // default prop
  };
 },
 components: {
   Page
 }
});
Vue.mount('#vue-app');
</code>

<code>// Page.vue
export default {
 props: { loading: Boolean },
 data() {
   return {
     title: 'New Page',
   };
 },
 mounted: function () {
   setTimeout(() => {
     this.loading = true; // Reuse inherited props
   }, 1000);
 }
};
</code>
Comment: ...it seems [mixins](https://v3.vuejs.org/guide/mixins.html#mixins) is what you looking for
Answer: I think your approach is not the best.
If you are trying to reuse a data (the said prop) for a certain purpose, try creating a component that uses that data and reuse the said component, that would be a more natural and inline way of going about UI development.


node_save() null tid column

Question: I am trying to create a node programatically like so,
$newNode = (object) NULL;
$newNode->type = 'job';
$newNode->title = $data['JobTitle'];
$newNode->uid = $user->uid;
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;
$newNode->tid = 0;

$newNode->summary['und'][0]['value'] = $data['JobSummary'];
$newNode->body['und'][0]['value'] = $data['JobDescription'];
$newNode->field_employment_type['und'] = strtolower($data['JobType']);
$newNode->field_job_reference['und'][0]['value'] = $data['JobReference'];
$newNode->field_salary['und'][0]['value'] = "";
$newNode->field_salary_from['und'][0]['value'] = $data['SalaryFrom'];
$newNode->field_salary_to['und'][0]['value'] = $data['SalaryTo'];
$newNode->field_salary_override['und'][0]['value'] = $data['Salary'];
$newNode->field_application_email['und'][0]['value'] = $data['ApplicationEmail'];
$newNode->field_job_category['und'][2] = 2;
$newNode->field_job_category['und'][4] = 4;

//die(print_r($newNode));
// save node
node_save($newNode);

Here I have potentially 4 taxonomies to pick from (their id indicated in brackets) Creative (2), Technical (3), Marketing (4), Client Services (6).
On node_save I am getting the following error,

500 Internal Server Error : An error occurred (23000):
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'tid'
  cannot be null

How do I overcome this this I would have thought setting the field_job_category to the id of the taxonomy would be enough?
Comment: Try to create your node using [Entity API](https://www.drupal.org/project/entity), take a look at  the second example in this article  [Create a Node in Code](https://www.drupal.org/docs/7/howtos/create-a-node-in-code)  .  **Note From the article** `fewer lines of code, better clarity, and less trouble from language/translation issues`
Answer: If you have one tid by node use:
$tid = 0;
$newNode->taxonomy[0]->tid = $tid;

if the node can have more than one term use:
$tids = [0, 3, 4, 5];
$i = 0;
foreach ($tids as $tid) {
  $newNode->taxonomy[$i]->tid = $tid;
  $i++;
}

Comment: If my taxonomy is a custom field called job category would I do, `$newNode->field_job_category[$i] = $tid`
Comment: Yes, if you use a multilangual site use this: `$newNode->field_job_category[$newNode->language][$i]['tid'] = $tid;`

node_save() null tid column


Prove "Infinite Sets Contain Countably Infinite Subsets" without Using Axiom of Choice.

Question: I know how to prove "Infinite Sets Contain Countably Infinite Subsets". But I found that I have to use some kind of AC (at least DC or ACω). I read that in analysis the statement that can be proved by using AC can also be proved without using AC. Is there a way to prove this statement without using AC?
P.S.: Sorry, I didn't pose my complete logic so the "Dedekind" is a mis-input. "Infinite Set" here I mean is the opposite of "Finite Set", so please don't assume the infinite set is defined as Dedekind infinite. My complete logic is to use this fact as the lemma to prove that Dedekind infinite is equivalent to infinite. I appreciate for the nice answer given below, but that's not what I need. Description is edited already.
Comment: It's not the case that *every* statement in analysis that can be proved with AC can also be proved without it. By [Shoenfield's absoluteness theorem](https://en.wikipedia.org/wiki/Absoluteness#Shoenfield.27s_absoluteness_theorem), that's true for first-order statements about the reals of a particular maximum complexity, $\Sigma^1_3$ sentences specifically.
Comment: [Accordingly to Wikipedia](https://en.wikipedia.org/wiki/Dedekind-infinite_set#Dedekind-infinite_sets_in_ZF) the answer is positive.
Comment: It's unfortunate, but now it's a duplicate of a whole other question. But you got an answer by Wojowu below. You *can't* prove this equivalence without using the axiom of choice.
Answer: Let $A$ be a Dedekind infinite set. By definition, there is a function $f\colon A\to A$ which puts $A$ in bijection with a proper subset $B\subsetneq A$. Let $x\in A\setminus B$. Define $g\colon \mathbb{N}\to A$ by $g(n) = f^n(x)$.
Now it's not hard to show that $g$ is injective, so $\text{im}(g)$ is a countably infinite subset of $A$.
Note that I didn't use AC when I picked $x\in A\setminus B$. The existence of such an $x$, and hence of the function $g$, follows immediately from the fact that $B$ is a proper subset of $A$.
Comment: Thanks~! I really appreciate for your answer. But I apologize for that I didn't pose my description clear enough. It's edited.
Answer: No, this isn't possible. It is consistent with ZF that there is an infinite set of reals which doesn't contain a countable subset, as was shown by Paul Cohen. This shows that it cannot be proven in ZF, even for subsets of reals, which is precisely what we would (generally) care about in analysis.
Comment: The set of reals you refer to is infinite, but *Dedekind finite*. The question is about Dedekind infinite sets.
Comment: @AlexKruckman Ah, sorry; I have misread the question as asking about "Dedekind finite".
Comment: Oh, could you show me that example (infinite set of reals which doesn't contain a countable subset)? That's exactly what I need~!
Comment: @AlexKruckman Sorry, I didn't pose my question clear enough. It's edited. Wojuwu's interpretation is the one I need.


dynamo-client using local dynamodb client

Question: I'm trying to connect to my dynamodb local using the npm lib dynamo-client.  I have the local dynamodb client install and running as per:
http://aws.typepad.com/aws/2013/09/dynamodb-local-for-desktop-development.html
However trying to connect to my localhost using:
db = dynamo.createClient('localhost', dbConf.credentials)
db.request('ListTables','', (e,r) -> console.log(e))

gives the following error:
e: {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect"}

Answer: Needed to set the port and host in the options:
dbConf =
  region:
    region: 'localhost'
    host: 'localhost'
    port: 8000
  credentials:
    secretAccessKey: "KEY"
    accessKeyId: "ACCESSKEY"

db = dynamo.createClient(dbConf, dbConf.credentials)


Maximum number if the GCD is known

Question: if it is known that the GCD(a,2008) = 251, and a<4036 whats  the biggest number for a?
a. 3263
b. 4016
c. 2259
d. 3765
e. 3514
i know that the answer is d, after a long math. but does anybody have any other ways to do it?
Answer: Well, you know it is a multiple of $251$.
$4036 = 16*251+20$ so $a$ is at most $256*16$.
So $a = 251*b$ where $b \le 16$.
$2008 = 8*251$.  So $b$ and $8$ can not have any factors in common so $b \ne 16$.  (Note: $\gcd(2008, 251*16) = 2008$)
If $b=15$ then $b$ and $8$ don't have any factors in common.  ANd if we test it:  $\gcd(15*251, 2008)= \gcd(15*251, 8*251) = 251$.
So that's it.  $a = 15*251 = 3765$
Answer: Since $2008 = 8 \times 251$ you are looking for a multiple of $251$ which has no factor (other than $1$) in common with $8$ - so it can't be even. [$251$ has to be a factor of $2008$ for the question to make sense]
You are therefore looking for the highest odd multiple of $251$ less than $4036$.
Well $4016=251 \times 16$ (twice what you started with, so nice and easy to work with) so you are looking for $251\times 15$

Maximum number if the GCD is known


Multiple Highcharts on Primefaces single page, gives javascript error

Question: I am using Highcharts 4.2.5 to display graphs in my Primefaces 6.0 application, which runs on (JSF 2.0, Java 7, Weblogic 11g).
I have a requirement where i need to show multiple dynamic graphs on a single page. The graphs are not hardcoded on the page. Infact they need to be rendered on the fly based on users privileges. One user can see 1 graphs, whereas other can see multiple graphs on the same page.
My problem is that ,the jsonpCallback function which i want to get called for each graphs seperately, DOES NOT get called successfully, due to some parser error on the jsonp data.
Strange thing is that, sometimes it gets called for some graph, but after subsequent page refresh, it gives a parser error. Below is my JSF xhtml code / JS Code / and the browser console log. The below use case is of 2 graphs, but only one graph renders correctly, and other gives parser

XHTML CODE.
  <ui:repeat var="c" value="#{cg.charts}" varStatus="status">

            </ui:repeat>

Javascript Code
function generateMLChart(divId){
console.log('generateMLChart called... '+divId);
chartType="prepareMLChartOptions";

$.ajax({
        type: "GET",
        url:"./multilinechartservlet/"+Math.random()+"?jsonp="+chartType,
        dataType: 'jsonp',
        jsonpCallback: chartType, // the function to call
        success: function(json) {
                   console.log("divId = "+divId);

                    var len     = json.multilinedata.length;
                    //var divid   = json.divid;
                    i = 0;

                    // setting options variable
                    var options = {
                         credits: {
                             enabled: false
                         },
                         rangeSelector: {
                            allButtonsEnabled: true
                         },
                         legend:{
                            enabled: true
                         },
                         title:{
                            text : 'Key Policy Interest Rates'
                         },

                         series: []
                    }

                    // setting options.series variable with json data, it should be a loop coz, it can have multiple series.
                    for (i; i < len; i++) {
                        options.series.push(json.multilinedata[i]);
                    }

                    // finally populate the charts container
                    $('#'+divId).highcharts("StockChart",options);

                    console.log('success function - complete');
        },
        error:  function(xhr, status, error) {
                  alert(error);
                  console.log("xhr.responseText ="+xhr.responseText);
                  console.log("status="+status);
                  console.log("error="+error);
               }
        });

}

function prepareMLChartOptions(json,divId) {

    if(divId == undefined)
        return;

}

Chrome console log

status=parsererror multilinechart.js:49
error=Error: prepareMLChartOptions was not called
Comment: I think that this problem is not connected with Highcharts, but with JSON you are trying to get for your charts.
Comment: Why don't you use PrimeFaces charts?
Comment: @JokerTheFourth my organization, does not like primefaces jquery charts, as they dont look very attractive, and we dont want to spend time on styling it.
Comment: @GrzegorzBlachliński - the JSON  returned from the server is a valid one, but still i get the parser error occasionally. note that i get this error only after frequent page refreshes, So this issue comes randomly and not on every try.
Answer: I resolved, it by using tweaking my generateMLChart() function and using $.getJSON instead of $.ajax, and in $.getJSON, the call back function is a dynamic one, and not a static function.
    function generateMLChart(divId,
                    chartName,
                    chartId,
                    qNo) {
console.log('generateMLChart called... ' + divId+ ' - '+ chartName + ' - '+qNo);

$.getJSON("./chartservlet?chartId=" + divId + "&queryNumber=" + qNo, function (data, textStatus, jqxhr) {
    console.log("textStatus = " + textStatus);// Success
    console.log("jqxhr.status =" + jqxhr.status);// 200
    console.log("divId = " + divId);

    var len = data.multilinedata.length;
    i = 0;

    // setting options variable
    var options = {
        credits :  {
            enabled : false
        },
        rangeSelector :  {
            allButtonsEnabled : true
        },
        legend :  {
            enabled : true
        },
        title :  {
            text : chartName
        },
        series : []
    }

    // setting options.series variable with json data, it should be a loop coz, it can have multiple series.
    for (i;i < len;i++) {
        options.series.push(data.multilinedata[i]);
    }

    // finally populate the charts container
    $('#' + divId).highcharts("StockChart", options);

    console.log('-- success function - complete');

}).fail(function (jqxhr, settings, exception) {
    console.error("exception =" + exception);
    console.log("jqxhr =" + jqxhr);
    console.log("settings =" + settings);
    alert("Triggered ajaxError handler. Contact IT- Helpdesk");
});

    }


scikit learn Feature selection for time series forecasting

Question: heres the link to sklearns feature selection/engineering
http://scikit-learn.org/stable/modules/feature_selection.html
I was wondering if these methods are actually useful? I have around 20/30 features (all numerical) in total and was wondering how these methods are able to help?
Shall i perform analysis with and without FS/FE and compare?
Comment: Although wording can be improved, the question is just asking if feature selection is helpful in any situation, specially when there are about 20/30 features. A short answer to that question may be useful to future readers.
Answer: It really depends on your data, and the amount of data you have.
If you have enough data (intentionally not defining how much "enough" is, cause it really depends on many factors), you can rely on your model to find the best input features for you.
But if for whatever reason you think giving all the features to your model would result in overfitting the model, then you may want to pre-select the features. This may be because you don't have enough data for instance.
If that is the case, then yes, those feature selection methods may be pretty useful, but they're not the only ones you have at hand, and as you see there, they vary a lot and some of them come from training models for the purpose of selecting features, e.g. $L_1$ regularized linear regression, or a tree based feature selection.
You should use your domain knowledge to see which feature selection method would intuitively fit your data, and then use it if necessary.
Also, an easy way is to add some of them to your pipeline, and use a nested cross validation to see if they actually improve your results.


Output filter for dates

Question: How can I change the output of dates in a long text field based on the locale?
I was looking for a module that might work with WYSIWYG to denote a date within a text field.
My goal was to allow articles to be viewed in several locales that use different date formats, without having to create separate versions of the articles.  All of the article content is the same except for references to dates.
Answer: Use the Drupal date module.
Users can set their timezone and date will automatically be converted to the timezone of current user (you are presented with options about this when creating the field).

Output filter for dates


In Ravel's Introduction et allegro pour harpe, flûte, clarinette et quatuor à cordes - what are the flute and clarinet doing here?

Question: In Ravel's Introduction et allegro pour harpe, flûte, clarinette et quatuor à cordes, the flute and clarinet seem to start doing some very fluttery tremolo arpeggiations in the first theme - I THINK they are just doing a normal 2x tremolo, effectively doubling every note (but I might be wrong?  what is mostly throwing me off is the two dots and the bow above the note heads.)
So, I was wondering about this notation, I have never seen this before - now I assume the one strike through the note is just a single tremolo line, but as I said before it's mostly the dots and the bow above the note head
If anyone could explain what is happening here I'd be very grateful!
Comment: Does this answer your question? [Four dots over tremolo minim (half note with slash)](https://music.stackexchange.com/questions/7527/four-dots-over-tremolo-minim-half-note-with-slash)
Comment: This is an abbreviation for 32n notes. You can have the same with all other note lengths.. But honestly I've never encountered this kind of staccato notation. One staccato accent on each 16th value would be clear.
Answer: They are playing 32nd notes, i.e. each note twice. The slash through the stems indicates that the note values are halved. The notation with the staccato dots and ties indicates the notes are to be lightly separated (this is sometimes called "portato" or "mezzo-staccato"). At this tempo the woodwinds will  use a technique known as double-tonguing.
Comment: @MichaelCurtis Portato would normally be played tongued, but could theoretically be done just with the breath. For this example there is no alternative to double-tonguing.
Comment: @chasly-reinstateMonica on flute (nothing in the mouth but tongue), the whisper is "tih kih" for double tonguing.
Comment: Ahhh so my ears were not fooling me in this case - makes sense that they are doubled portato notes! Thank you
Comment: For the non-wind plays can you explain a bit _how_ the articulation is done? The link for portato talks about string bowing. Is it tonguing?
Comment: You should add the explanation that the slash thru the notes indicates doubling from 16 to 32.     Also,  FWIW  woodwinds *can* do tremolo by way of bizarre breath pulsing.  I've done it and don't recommend it!   I once asked a band director about interpreting tremolos in transcriptions, and he said in some cases a fast, light trill works.
Comment: @Michael Curtis - I don't know if it's the official way but with tin-whistle I've used a form of double-tonguing that works rather like whispering "diddle, diddle, diddle, diddle". The airway alternates between across the tongue ("di") and around the tongue ("dle").
Comment: @Pam - Thanks. That makes a much cleaner sound than I was using!
Answer: This is an ugly abbreviation. The partial beam indicates, that you are supposed to split each 16th note given into two 32nds (as you correctly assume), and now each is supposed to receive a dot. (See this question for a similar example.)
I am a bit lost, how to combine the staccato-dot with the arc above, which I assume to be a tie, so it may be a sort of portato.


Display one view in portrait while another is in landscape?

Question: I have an activity that per our requirements has to be locked into landscape orientation. However when the user holds the device in portrait we display a view on top of it. Up until now it has just been an image so I have rotated the image and I display it. Really the image is also being displayed in landscape but since I have rotated it, it appears like it is in portrait.
Now I need to complicate this by having a more complex view with layouts being displayed (layouts, textviews, buttons, etc) instead of just an image. The same "rotation" doesn't seem to work because stuff is displayed off of the screen. What is the recommended solution to show one view in portrait while the view behind it is locked in landscape?
Answer: edit:
if the idea is to literally have the view underneath to show rotated 90% while the top view is in "normal" view, you could possibly call setRotation method, available since API 11
 view.setRotation(90);

edit: below is my old answer, please see above my updated question
Do not lock the view in landscape. Instead use the layout/ and layout-land/ folders to place appropriate views. For example:
layout/main.xml
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/main_content"/>

</FrameLayout>

layout-land/main.xml
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/main_content"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="144dp"
        background="#4000">

         <include layout="@layout/top_content"/>

    </FrameLayout>
</FrameLayout>


Conditional probability question - not sure how to go about this?

Question: It may be the wording of the question, but I'm not sure how to go about doing this. This is not a homework question I just want to know if my answer is correct.
*Please note the wording is confusing, but please interpret however you understand.
90% of candidates to a job position can code both in Python and Perl. 70% of these candidates can code in Python and 50% can code in Perl. What is the probability that a candidate can code in Perl knowing that he can code in Python?'
The way I interpreted this was that the probability that a candidate can code in both is 20% (is this assumption correct?)
In the end I found that the answer is 2/7.
If someone can verify this I would be very thankful, as I'm not sure I went about it the right way!
Comment: The question appears to be inaccurately worded. "90% of candidates to a job position can code **both in** Python and Perl" should probably be written "90% of candidates to a job position can code **in either** Python and Perl".
Comment: The question is not correct.
Comment: I agree the wording is confusing. I'm not sure how to interpret it actually, I took it as can code *either Python or Perl but not sure if this is correct. Please interpret however you understand
Answer: I assume that by writing

90% of candidates to a job position can code both in Python and Perl

they actually meant "can code either in Python or Perl". This is consistent with the rest of the question, as they divide this quantity further into Perl-coders and Python-coders.
In such questions, it helps to denote the variables. Let's denote by $A$ the event that a person knows Python and by $B$ the event that a person knows Perl. Now, in the question we are given the following quantities:
$$
P\left(A \cup B\right) = 0.9 \\
P\left(A \mid A \cup B\right) = 0.7 \\
P\left(B \mid A \cup B\right) = 0.5
$$
And our final goal is to calculate $P\left(A\mid B\right)$.
Now, this question consists of multiple steps. You don't need to assume anything since you have enough data. You need to first calculate $P\left(A\right)$, $P\left(B\right)$, then calculate $P\left(A \cap B\right)$, and only then you can calculate $P\left(A \mid B\right)$. The following identifies might be helpful:
$$
P\left(A \cup B\right) = P\left(A\right) + P\left(B\right) - P\left(A \cap B\right) \\
P\left(A \mid B\right) = \frac{P\left(A \cap B\right)}{P\left( B\right)}
$$
The final result should be $P\left(A \mid B\right) = 0.4$
Comment: Thank you so much!! I am so impressed that you were able to break this down so clearly. I am hoping to be able to do this one day. How did you learn? Is there anything you recommend doing to learn to solve these comfortably?
Comment: I think it mainly comes with practice. Pick up a textbook and try to solve questions without skipping steps. I recommend "A First Course in Probability" by Sheldon Ross (it has many question on each topic). If you miss some of the theory as well, the book could be a great refreshment/study guide.


Segmentation error in simple inheritance related code

Question: Shortened code I wrote for learning purposes. Still the way it is, it doesn't work properly.
Removing last line (&&) it works OK, but with it, code doesn't reach line noted as ##, expressing
segmentation error, after the "BazOnly" text displayed.
#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

namespace nek{
    class Baz{
        int num;
        std::string  str;
        public:
        Baz(){cout<<"BazOnly"<<endl;}
        string setstr(string& val){
            //str.assign(val);
            num= 7;
        }
    };
}

namespace drg{
    class Deriv: nek::Baz{
        public:
        Deriv(char ch){cout<<"DerivChar"<<endl;}
    };
};

int main(){
    nek::Baz b;
    string priv{"zik"};
    b.setstr(priv);
    cout<<"Passed here"<<endl; //##
    drg::Deriv dc{'A'};  // &&
}

Compiled with g++ (option std=gnu++11), Ubuntu 16 on Virtual Box.
Question is what could be the reason for such behavior ?
Answer:     string setstr(string& val){
        //str.assign(val);
        num= 7;
    }

This method is declared as returning a std::string, but nothing actually gets returned from it. This is undefined behavior.
Most modern C++ compilers will warn you about this. If yours' did, this is an example of why you cannot ignore warning messages from your compiler, even if it did successfully compile your code.
Comment: Huh- must confess it's big mistake. No excuse for me, but just to mention, there were no warnings (VS Code Ubuntu 16.04).
Comment: @Djole • did you have warnings enabled?  Some compilers will only emit required warnings unless additional warnings are requested to be enabled.  For clang++, I use these `-Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -pedantic`.
Comment: It came upon my mind while taping last message. Probably I didn't. I'll double check it.


Change entity.field.FieldFormatter for a custom view

Question: For an Product entity I'm added custom field "images" // it contains all product images.
To display these images, CustomFieldFormatter is used, it is specified/set on the entity type "manage display" settings page.
So each time the entity is rendered, it uses that CustomFieldFormatter, which display grid of images, with on hover and other effects.
But now I want to create a view to display grid of products (catalog page)
and display only one (first) image of each product entity.
Please, help me find a way to change FieldFormatter for my field when it is shown inside "catalog" view. Or maybe there is some better architecture/solution?
Comment: Just add a setting to your formatter, implement that in viewElements() and then configure the display of your products to use that setting? for anything more, you'll need to share your code.
Comment: I thought about that, but CustomFieldFormatter is used to display an array of Images field as galley [it has 1 main function, call it ZoomableGalleryFieldFormatter], so adding here setting to [stop acting as galley, act as single image] does not looks correctly
Answer: The correct way to implement this, is to use "Display modes":
add custom "Display mode" for entity, and set the another formatter for images field. In the View settings set it to use that "Display mode" to display entity.


Media Library results filtered by user

Question: I am working on a project that will be using 100's users and potentially thousands of users. The users will be required to upload at the very least 5 images and possibly some PDF files.
Created a content type, and added some Media fields, which works perfect for this project.
The user files uploaded will be all public but the issue is that when the user goes to browse for their files all files from all users are listed and available. Once the site reaches a high level of users, browsing hundreds if not thousands of images and/or files is  just not ideal.
How can I filter the Media browser to only show the files that user uploaded?
Comment: I feel like I've seen this question asked recently, here or on drupal.org.
Answer: That should be quite straightforward to set up:

Add a contextual filter to the View which powers the Entity Browser
Choose "Authored by" as the field
Under When the filter value is not available, choose Provide default value
In that dropdown, select User ID from logged in user
Comment: I added the contextual filter to the views Media & Media Library and that works when viewing the media page, but not when the user browses the library, all three test images, uploaded by three different users all show up. Under >Structure>Views>Media Library I even applied it to all the widgets. Nothing changed on the file browser.
Comment: If you have the contextual filter set up on the same view then I'd suggest that's a bug
Comment: Looks like Entity Browser does some extra contextual filtering (https://www.drupal.org/project/entity_browser/issues/2865928), so that might be the cause of the problem
Comment: Well, to complicate things I decided to clear all caches and rebuild all permissions. With the contextual filter enabled as above on the view 'Media Library' on all pages of the view, no media shows up at all for all users, you can upload images but they will not show, yet they are uploaded into Media content. If I remove the contextual filter from all pages of the Media Library view, every user can see every media file. Permissions are all set for Media to have edit, create, and view "own", so everything there looks good.

Media Library results filtered by user


Imprimir Valor de um array

Question: Boa tarde,
Quero imprimir o valor do array introduzido na função getTitleIdLocation, o que estou a fazer mal?
Obrigado desde já.
<?php

class Imovel {

private $title;
private $id;
private $location;

 function __construct($title, $id, $location){
     $this->title = $title;
     $this->id = $id;
     $this->location = $location;
 }

 function getTitleIdLocation(){
     return array($title, $id, $location);
     }
}

$casa = new Imovel ("Apartamento", "3", "Porto");

echo $casa -> getTitleIdLocation();

?>

Comment: Depende o que você vai fazer com o resultado? precisa imprimir de alguma forma em especifico?
Comment: Possível duplicata de [Exibir elementos de array associativo com foreach](https://pt.stackoverflow.com/questions/187985/exibir-elementos-de-array-associativo-com-foreach)
Comment: Outras [Exibir valor de array no php](https://pt.stackoverflow.com/q/247424/5878) / [Array to string conversion in](https://pt.stackoverflow.com/q/104655/5878)
Comment: Possível duplicata de [Não consigo aceder à função](https://pt.stackoverflow.com/questions/400473/n%c3%a3o-consigo-aceder-%c3%a0-fun%c3%a7%c3%a3o)
Comment: Essa pergunta deveria ser marcada como duplicata da pergunta que ele mesmo já fez e inclusive já foi respondido?
Comment: Eu fechei como não clara por causa deste comentário: https://pt.stackoverflow.com/questions/400473/n%c3%a3o-consigo-aceder-%c3%a0-fun%c3%a7%c3%a3o/400480#comment786145_400480 . Ora, se ali diz que tentou algo e deu errado, porque essa tentativa não está na pergunta? Do jeito que está não tem uma dúvida real, poderia até ter fechado como fora de escopo porque está só pedindo para fazer o código inteiro da impressão do *array*, o que só o autor sabe como deveria ser. Se tem um dúvida específica, deve postar essa dúvida por completo, mostrar o que tentou.
Comment: As marcadas como duplicata podem ou não responder a pergunta, porque tem um contexto que indica que é outra coisa. Na verdade eu analisei as perguntas postadas e parece que não respondem (não é certeza porque a pergunta não está clara), uma delas certamente não responder porque mostra como imprimir um *array associativo* o que não é o caso. Outras duas sequer tem um laço, não sei porque foram indicadas. A que ele perguntou antes não fala nada sobre o erro que ele está tendo agora, eu mesmo indiquei abrir outra pergunta, mas a pergunta deveria constar o problema. O prob. é outro só ñ está claro
Comment: As marcadas como duplicatas, não concordo, a minha marcação de duplicata é referente a pergunta que ele mesmo já fez a aproximadamente 2 horas, essa pergunta aqui é uma duplicata da outra do mesmo autor e mesmo texto e classes ... é só observar ...
Comment: @VirgilioNovic Mas problemas diferentes...
Comment: O problema é o mesmo @AndersonCarlosWoss observe ele quer imprimir o `array` e fez duas perguntas porque não ficou satisfeito com a resposta da primeira e com certeza não entende a filosofia do site ... ele quer fazer a mesma coisa com o `array`.
Answer: Use o método implode para converter em texto.
<?php

class Imovel
{

    private $title;
    private $id;
    private $location;
    function __construct($title, $id, $location)
    {
        $this->title = $title;
        $this->id = $id;
        $this->location = $location;
    }

    function getTitleIdLocation()
    {
        return array($this->title, $this->id, $this->location);
    }
}

$casa = new Imovel ("Apartamento", "3", "Porto");
echo implode(" ",$casa->getTitleIdLocation());
// Apartamento 3 Porto
?>

Fontes:

Array to String PHP?( Em inglês)
Função implode
Comment: OBS: Eu estou editando. Não é uma resposta.
Comment: Meu ide de php tava travando. Eu tava tentado colar e não conseguia. Agora consegui.
Comment: Tem um erro no método `getTitleIdLocation` onde para acessar os membros privados deve se utilizar `$this` ou seja,  `$this->title` etc
Comment: @VirgilioNovic Obrigado.
Answer: O echo — Exibe uma ou mais strings
Você deve usar print_r — Imprime informação sobre uma variável de forma legível
$casa = new Imovel ("Apartamento", "3", "Porto");
echo $casa -> getTitleIdLocation();
//TROCA POR
print_r($casa -> getTitleIdLocation());

Imprimir Valor de um array


what are distribution by fitdistrplus R package

Question: How can I find all distribution that fitdistrplus package support. I find some examples from what I discovered what is required distr name, few example: if I am looking for log normal distribuiton distr name is "lnorm", if I am trying to fit Chi-Square Distribution then name for distr is "chi-squared", and so on. Is there some where in package manual where I can find all suported distributions.
I am interested in distributions that support positive integer values with big variance and relatively small mean (right skewed). Cullen and Frey graph suggested log normal distribution, data AIC and BIC for log normal model are the lowest but KS.test don t support this model.So I am trying to fit to other model but how to find right name for "dist".
Answer: The fitdistrplus FAQ claims to fit distributions for which d, p, q and r functions are available, whether in base R or a package or which you have written yourself (though in more obscure ones you will need to provide sensible start values).
Common distribution names such as chisq can be found in the R-intro manual


How can we compute this conditional expectation?

Question: The problem:
Suppose $(X_1,...,X_d) \in \mathbb{R}^d$ and $Y \in \mathbb{R}$ are random variable such that $(X_1,...,X_d,Y)$ is a gaussian vector.
How can we prove $\mathbb{E}[Y\mid \sigma(X)]$ is a linear combination of $(X_i)$?
I tried first proving $\operatorname{Span}_{\mathbb{R}} X_i$ is dense in $L^2(\Omega,\sigma(X))$ or equal but I cannot conclude.
Edit:
As remarked in the comments it would be more interesting if we consider $\operatorname{Span}_{\mathbb{R}} (X_i,1)$.
Comment: Finding a counter example is not hard : take $X$ and $Y$ independent with $\mathbb E[Y]\neq 0$. Then $\mathbb E[Y\mid \sigma (X)]=\mathbb E[Y]\notin Span(X).$
Comment: It's not true ! Nevertheless, there is a Borel function $f:\mathbb R^d\to \mathbb R$ s.t. $\mathbb E[Y\mid \sigma (X)]=f(X_1,...,X_d)$.
Comment: @Surb I imagine showing a counterexample can be difficult, but how can I approach this situation?
Comment: @Surb And if we esclude this case?
Comment: would $(X,Y)$ be gaussian then?
Comment: @Surb But the ipothesis is that $(X_1,...,X_d,Y)=(X,Y)$ is gaussian
Comment: @FilippoGiovagnini: Thanks you for telling me that, I didn't pay attention to this condition at all... so my previous example counter-example doesn't work. Anyway, the first one works :-)
Comment: @FilippoGiovagnini you intented to ask about $Span(X_i)$ or Affine combination of $X_i$ (that is you allow $+ constant$) ? The second would be more interesting.
Comment: @DominikKutek I agree with you, "affine combination" would be more interesting! I will modify the question.
Comment: @Surb Yes, your first suggestion works. But if we change the problem as above? Do you have any idea?
Comment: $$
\mathsf{E}[Y\mid X]=\mathsf{E}Y+\frac{\mathsf{E}(Y-\mathsf{E}Y)X^{\top}}{\operatorname{Var}(Y)}(X-\mathsf{E}X).
$$
Comment: @d.k.o. How did you get it? Could you please write it down for me?
Comment: @FilippoGiovagnini Just compute the conditional density of $Y$ given $X$ as LostStatistician18 suggested.
Comment: @d.k.o. But if we do not have density?
Answer: Suppose $f_{X,Y}$ is the joint density of the variables with $Y$ included. This is a Gaussian density function by assumption. The conditional mean is almost surely equal to the mean of the conditional density
$$
f_{Y|X}(y|x) = \frac{f_{X,Y}(x,y)}{\int_{\mathbb{R}}f_{X,Y}(x,y)dy}.
$$
Namely, you can show that
$$
E(Y|X) = \int_{\mathbb{R}} yf_{Y|X}(y|X)dy  \;\; a.s.
$$
The later term you can calculate, and it is linear in $X$, as desired.
Comment: Not necessarly it has a density. I understand that we can also assume covariance matrix is not degenerate but do you know how to approach in general case?
Answer: Let $\mu_Y:=\mathsf{E}Y$, $\mu_X:=\mathsf{E}X$, $\Sigma_X:=\operatorname{Var}(X)$ $\Sigma_Y:=\operatorname{Var}(Y)$, and $\Sigma_{X,Y}=\mathsf{E}X(Y-\mu_Y)$. Consider the following transformation (assuming that $\Sigma_X$ is invertible):
$$
Z:=Y-\Sigma_{X,Y}^{\top}\Sigma_X^{-1}X.
$$
Since
\begin{align}
\mathsf{E}X(Z-\mathsf{E}Z)^{\top}&=\mathsf{E}X(Y-\mu_Y-\Sigma_{X,Y}^{\top}\Sigma_X^{-1}(X-\mu_X))^{\top} \\
&=\Sigma_{X,Y}-\Sigma_X\Sigma_X^{-1}\Sigma_{X,Y}=0,
\end{align}
$Z$ and $X$ are independent (they're jointly Gaussian). Then
\begin{align}
\mathsf{E}[Y\mid X]&=\mathsf{E}[Z\mid X]+\mathsf{E}[\Sigma_{X,Y}^{\top}\Sigma_X^{-1}X\mid X] \\
&=\mathsf{E}Z+\Sigma_{X,Y}^{\top}\Sigma_X^{-1}X=\mu_Y+\Sigma_{X,Y}^{\top}\Sigma_X^{-1}(X-\mu_X) \quad\text{a.s.}
\end{align}

When $\Sigma_X$ is singular, some coordinates of $X$ are affine functions of a subset $X^{*}$ of dimension $\operatorname{rank}(\Sigma_X)$ (assuming that $\operatorname{rank}(\Sigma_X)\ge 1$). In that case $\mathsf{E}[Y\mid X]=\mathsf{E}[Y\mid X^*]$, and $\operatorname{Var}(X^*)$ is invertible.
Comment: It is assuming that $X$ is non-degenerate? (Covariance matrix of $X$ is invertible?)


Whether to apply the logit transformation to proportional predictor variables in a multiple linear regression? [including proportions of 0.0%]

Question: In a linear regression, I have a number of predictors variables that are expressed as proportions. The outcome variable is continuous. My residuals are not normally distributed, with a mild to moderate positive skew.
Should I use a logit transformation on the predictor variables to see how this impacts the residuals?
If yes, I am having trouble understanding with what to do with my cases that have a proportion of 0.0 on some of the predictor variable (e.g. a case with 0% on a variable). In particular, I've been considering the advice of Papke and Wooldridge (1996) and Baum (2008) on how to deal with those sorts of cases when they are measured responses as opposed to due to structural issues. They suggest various options including winsorisation and something called fractional logit responses. However, they only discuss their options in terms of proportional outcome variables, and never in terms of proportional predictor variables. Are such approaches appropriate to proportional predictor variables in a linear regression?
Answer: The Stata article you link discusses modeling an outcome as a proportion. More specifically, it discusses binomial regression, which is the same as frequency weighted logistic regression. If you don't know the denominator, nonlinear least squares or logistic regression with nonintegral outcomes and a dispersion parameter can handle the issue.
However, you mention using a proportion as a predictor. Generally, one doesn't use such transformations of a proportion. Singularities aside, it can create very high leverage values which makes regression model results a little hard to trust.
If one is interested in inference, the choice of whether or not to transform a variable depends on the question you're trying to answer. Typically, I would prefer to leave the variable untransformed so that the beta-coefficients are easier to interpret. For instance, suppose we are comparing voting preference to SES in a neighborhood based survey administered to random households in each neighborhood. If I am regressing total number of household TVs on voting preference (at the aggregate neighborhood level), I would say "Comparing neighborhoods that differ in Republican voting preference by 10%, the average number of TVs differed by X.X (95% CI X.X - X.X)".
But herein lies a caveat: what percentage are you measuring? If it is binary at the individual level, but has been aggregated up to a percentage, you would need to apply some kind of weighting to account for the difference in denominator sizes, if that is an issue. In my SES study, I may only be able to sample 3 households in one neighborhood, giving voting preference levels of only 0, 0.33, 0.66, or 1 whereas I may gather 10 households in another neighborhood. The neighborhood with more samples would use inverse frequency weighting to account for the precision.
Consider this when you consider how the "percentages" were acquired.
Comment: Thanks adam0. I am looking at participant-level data with my proportion predictors. In particular, I am looking at the proportion of words assigned to a category (e.g. nouns, verbs, etc) out of all the words that participant has written in a task. I am using a proportion because between participants use a different number of words to one another. Some participants have 0.0% of their words in some of the word categories (I.e. Predictor variables).
Comment: @SimonsSchus Consider reformatting your question according to [this](http://stats.stackexchange.com/tags/analysis/info) rubric. Give specific details so that a sensible answer can be provided. As is, your description does not have enough detail.
Comment: What about using the logit transformation of independend variables to model increasing/decreasing marginal effects? While the transformation is almost linear in the longer "middle" part, it departs from near linearity and becomes more increasing (decreasing) in the lower (upper) end. [Although for increasing/decreasing marginal effects, addition of a quadratic term can be used]
Comment: Oh, I believe I swapped the increasing/decreasing in my previous comment
Comment: @Helix123 you are probably interested in hierarchical models as a way of aggregating outcomes collected among individuals who are collectively part of units, like neighborhoods, and trying to model neighborhood level associations or outcomes. Logit transformations are of no use except modeling the unmeasured mean of a binary outcome.
Comment: See some slides here by John Fox about the logit transformation (starting at slide 70 (page 36)): http://socserv.socsci.mcmaster.ca/jfox/Courses/Brazil-2009/slides-handout.pdf - Seems to me, it could be of some use (also for independend variables).


CocoaPods not installed or not in valid state. Error launching application on iPhone 12 when flutter run on ios simulator

Question: Warning: CocoaPods not installed. Skipping pod install.
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.
CocoaPods not installed or not in valid state.
Error launching application on iPhone 12.
Comment: https://stackoverflow.com/questions/62593939/cocoapods-not-installed-or-not-in-valid-state - There are lots of solutions here
Answer: I tried running flutter doctor,everything was okay.
So I found another solution.

Close android studio
Open android studio through the terminal

open /Applications/Android\ Studio.app

Open your project again and run ,it works.

I hope someone finds another solution. because this always happens.


Updating (and configuring) chroots on general purpose CentOS webserver with yum?

Question: I'm currently providing web hosting on a shared web hosting VPS environment - that has no chroot. This is obviously a big security concern, although I've made sure that only the owners of files can edit their own stuff.
I'm getting to the point of uneasiness and necessary professionalism that I want to do this thing right. Instead of simply copying files into a chroot environment, I think I want to re-build a new VPS from scratch to get rid of old cruft, make sure I configure the chroots properly, etc...
I'm wondering if its possible to configure yum to update everything in every chroot jail on the server. Chroot jails (and configuring them) are probably one of the things I'm least knowledgeable about in terms of operating web servers.
My initial idea is to do something like this:
Have an instance of MySQL running on the root server to handle all databases. Postfix, etc... will obviously also run in the root environment. Then, don't even run apache on the root server, but have separate instances of it in each chroot jail for each user. Jails would also have separate instances of rssh (providing sftp/scp access), but nothing else.
Does this sound reasonable Do you folks have any suggestions as I move forward with this research and build?
Answer: The first step is to generate a rpmdb within the chroot by creating /var/lib/rpm within it and using rpm --root /path/to/chroot --initdb. After that you need to install the $distro-release package within it with rpm so that yum has information about the distro whose repos it needs to access. Once you've done that you can use yum --installroot=/path/to/chroot in order to have it operate within that chroot.
Comment: This is very helpful, thank you. From a security standpoint, since I'm not giving users shell access, is it legitimate to have a single instance of MySQL running? If so, I'm a little confused as to how I can connect each individual instance of Apache running in the jails to the single MySQL instance. Would the loopback address of 127.0.0.1 work? I suppose I'm also going to need to install PHP into each jail.
Comment: All the apps running in the chroots can use TCP/IP to connect to a single instance of MySQL running either outside of the chroots or within its own chroot. Each chroot will need a copy of PHP if they are to run PHP apps.
Comment: See http://prefetch.net/articles/yumchrootlinux.html


Como melhorar a qualidade da imagem salva?

Question: Utilizo a ferramenta html2canvas em um projeto para imprimimir uma determinada área do meu código e salvá-la como imagem.
Tentei salvar nos seguintes formatos, JPEG e PNG, mas ambas ficam com a mesma qualidade, gostaria de saber, de alguém que utiliza esta ferramenta também, se há alguma forma de determinar a qualidade da imagem à ser salva.
[EDIT]
Respondendo às questões solicitadas:

A tela não é retina
O Sistema Operacional é Ubuntu 15.04 x64
O navegador é Google Chrome x64

Este é o código de chamada à html2canvas, bem simples, praticamente transforma a imagem em url salva em um input hidden para salvá-la com o PHP (não sei exatamente se esse envio para salvar com o PHP tem algo a ver com este bug, caso haja, me avise, por favor):
html2canvas($("#result"), {
    onrendered: function(canvas) {
        img = canvas.toDataURL("image/jpeg");

        $("#screenshot").val(img);

        $("#form").submit();
    }
});

Neste sistema no qual trabalho, uma de suas funções é criar imagens para postagem no Facebook.
O HTML usado consiste em:

                Teste

            Teste subtítulo

A razão pela qual não utilizo uma imagem de background na
 foi uma decisão relacionada à outras funcionalidades do sistema.
O CSS consiste em:
div#template {
  width: 500px;
  height: 450px;
  position: relative;
  background: rgba(0, 0, 0, 0.1);
}
div#background {
  width: 500px;
  height: 450px;
  position: absolute;
  z-index: 1;
}
img#bg-image {
  display: none;
}
div#content {
  width: 500px;
  height: 125px;
  background: rgba(0, 0, 0, 0.3);
  position: absolute;
  top: 25%;
  color: #fff;
  display: table;
  z-index: 2;
}
div#content-bar {
  width: 500px;
  height: 40px;
  position: absolute;
  backgrund:#000;
}
h1.title {
  color: inherit;
  width: 400px;
  margin: 15px auto;
  font-size: 30px;
  font-weight: bold;
}
h2.subtitle {
  color: inherit;
  font-size: 20px;
  margin: 75px auto;
  font-weight: bold;
}

É bem básico, porque, neste caso, só faz o posicionamento absolute das divs e as posiciona uma sobre a outra, deixando a
 por trás, tendo função de plano de fundo.
Uma imagem de exemplo
Não sei se vai dar pra ver muito bem, mas estou enviando um print que tirei de uma imagem postada depois de pronta.
Se perceber, a imagem está um pouco "borrada", durante a construção da imagem isso não ocorre.

Não postei o HTML e CSS relacionados à imagem, pois não tenho eles à minha disposição no momento.
Comment: Nesse caso, para manter a qualidade, não seria melhor tentar converter o print em svg?
Comment: Também pensei nisto, mas ainda não tentei, tentarei.
Comment: Se você possuir a imagem em Canvas, você pode converte-la em SVG utilizando esse plug-in: https://github.com/gliffy/canvas2svg
Comment: @MarceloBonifazio o problema é que aí já foi gerado com baixa qualidade.
Comment: Então @bigown, estava a comentar isso, o ideal seria converter direto do HTML pro SVG, so que nunca precisei fazer algo do tipo, vou dar uma pesquisada, se achar alguma solução, posto aqui
Comment: @MarceloBonifazio Se você se refere ao `foreignObject`, acho que ele é bloqueado no Chrome por "segurança".
Comment: Poste o html e css também, se possivel poste uma imagem do problema.
Comment: @GuilhermeNascimento postado :)
Comment: @ThomersonRoncally Não entendi a parte do facebook na foto. Faz assim, sem querer pedir demais rs, posta um exemplo completo no jsfiddle por favor.
Comment: @GuilhermeNascimento Ok rsrs
Comment: @GuilhermeNascimento Editado rsrs JSFiddle + PHP + Imagem
Comment: O teste que eu fiz não houve perda de qualidade, veja o resultado: http://i.stack.imgur.com/u2EzW.jpg - pra mim parece "perfeita". Depois eu testei com cores mais avermelhadas (http://www.socwall.com/images/wallpapers/26794-1920x1200.jpg) e o resultado foi este: http://i.stack.imgur.com/5uQ5s.jpg - Com cores mais quentes é possivel observar mais detalhes, no entanto também me parece normal. Talvez o problema ocorra em outro momento, na hora que compartilha no facebook por exemplo (o facebook compacta as imagens eu acho)
Comment: @GuilhermeNascimento Hum, entendi! Pois é, em testes locais, também me parecia normal, mas houveram várias reclamações sobre isto, por isso pensei que o erro fosse com o html2canvas, mas tentarei sua solução, pra ver se altera algo e procurarei possíveis causas em outros trechos de código! Obrigado pela grande ajuda :) Caso eu solucione, compartilharei aqui, alterando a pergunta :)
Answer: Podem ser dois problemas mais conhecidos (acredito que exista um outro problema com fontes semelhante, mas parece não ser o caso):
Problema com a tela de retina
Tela de retina ou Ecrã retina (português europeu) ou Retina Display (inglês) são telas usadas LCD (da Apple) que apresentam uma densidade de pixels suficiente para o olho humano não ser capaz de perceber a pixelação a uma distância padrão, usadas em produtos Apple como iPhone e Mac.
Geralmente o conteúdo exibido na tela tem em média o "dobro" de tamanho que aparenta, ou seja e geralmente temos que usar imagens de alta qualidade para que elas não apresentem o efeito desfocado ("blurry").
No momento que você usa o html2canvas na tela de retina, o que é lhe apresentado é uma imagem que seria apenas perceptível aos pixels. Isto parece ser um problema do Canvas API que tenta ajustar a imagem na hora de exporta-la.
Bug Chrome/Safari com imagens em background no Windows 64bit

Nota: Aparentemente este bug foi corrigido nas versões mais recentes do Chromium

Não me recordo se o problema ocorre no Safari, mas no Chrome e Opera (tecnologia Chromium/Blink) isto ocorre. É um bug no Canvas API também, que ocorre geralmente quando a imagem tem o tamanho diferente do elemento (por exemplo um DIV).
Vamos supor que temos uma imagem de 100x100 chamada test.png um
 assim:

Se o seu Chrome for 32bit rodando em um sistema 64bit ocorre um efeito de desfoque, veja um exemplo (como eu mencionei aqui #206):

function putImage()
{
    //Funciona-----------------------
    var canvas=document.getElementById("myCanvas1");
    var ctx=canvas.getContext("2d");

    ctx.webkitImageSmoothingEnabled = false; //Corrige o problema

    var pat=ctx.createPattern(img, "repeat");
    ctx.rect(0,0, 64, 64);
    ctx.fillStyle=pat;
    ctx.fill();

    ctx.restore();
    //Funciona-----------------------

    //Causa o bug-----------------------
    var canvas2=document.getElementById("myCanvas2");
    var ctx2=canvas2.getContext("2d");

    var pat=ctx2.createPattern(img, "repeat");
    ctx2.rect(0,0, 64, 64);
    ctx2.fillStyle=pat;
    ctx2.fill();

    ctx2.restore();
    //Causa o bug-----------------------
}

var img = document.getElementById("lamp");

img.onload = function() {
     setTimeout(putImage, 100);
};

Imagem usada:

Funciona (com ctx.webkitImageSmoothingEnabled = false):

    <canvas id="myCanvas1" width="300" height="318"></canvas>

Falha (se não falhar é porque está usando um navegador que já teve o bug corrigido):

    <canvas id="myCanvas2" width="300" height="318"></canvas>

Possível solução 1
Está solução pode funcionar com monitores Retina, mas o foco dela é resolver o problema com o background-size. A solução parece ocasionar algum outro problema, mas não sei ao certo qual é (talvez seja com imagens redimensionadas por background-size ou width="" e height="", não tenho certeza, mas parece que o canvas perde a "precisão" das imagens redimencionadas), no entanto se a sua página é mais simples é bem possível que funcione.
No "contexto" da API do Canvas temos as propriedades:
var ctx = canvas.getContext("2d");
ctx.webkitImageSmoothingEnabled = false; //Webkit/Safari/Chrome
ctx.mozImageSmoothingEnabled = false;    //Firefox/Gecko
ctx.imageSmoothingEnabled = false;       //Outros navegadores

Estas propriedades desabilitam a suavização da imagem, porém é necessário "mexer" no código fonte do html2canvas para conseguir aplicar isto.
Possível solução 2
A segunda possível solução é voltada ao problema com as telas de retina, a ideia é que você pode criar uma imagem com o dobro do tamanho e reduzir ela posteriormente, o processo seria algo como:

Nota: Imagens canvas muito grandes não pode ser exportadas com .toDataURI, pois existe um limite de tamanho.

CSS:
.escala-x2 {
    -webkit-transform: scale(2);
       -moz-transform: scale(2);
            transform: scale(2);
}

JavaScript:
var elemento = document.getElementById("foo");

elemento.className += " escala-x2";

html2canvas(elemento).then(function(canvas) {

    elemento.className = elemento.className.replace(/\sescala\-x2/g, "");

    var new_canvas = document.createElement("canvas");

    //Copia canvas para new_canvas e redimenciona pela metade
    new_canvas.width = canvas.width / 2;
    new_canvas.height = canvas.height / 2;

    var ctx = new_canvas.getContext('2d');

    ctx.drawImage(canvas, 0, 0, new_canvas.width, new_canvas.height);
    ctx.webkitImageSmoothingEnabled = false; //Webkit/Safari/Chrome
    ctx.mozImageSmoothingEnabled = false;    //Firefox/Gecko
    ctx.imageSmoothingEnabled = false;       //Outros navegadores

    canvas = null;

    document.body.appendChild(new_canvas);//Adiciona o canvas redimensionado ao body
});

Desta maneira você pode usar o imageSmoothingEnabled tranquilamente, pois as imagens originais já foram convertidas para o canvas, então é provável que não ocorra nenhum problema.
Limite de tamanho do canvas
Cada navegador tem um limite de imagem que pode trabalhar com o Canvas, geralmente quando ultrapassar este limite é lançado um Exception, conforme a resposta do SOen (estes limites vão sendo melhorados conforme o navegador recebe atualizações):

Nota: Irei atualizar os dados conforme encontrar mais fontes

Dados de 10/13/2014:

Chrome:

Máximo de largura e altura: 32,767 pixels
Área máxima: 268,435,456 pixels (por exemplo 16,384 x 16,384)

Firefox:

Máximo de largura e altura: 32,767 pixels
Área máxima: 472,907,776 pixels (por exemplo 22,528 x 20,992)

Internet Explorer:

Máximo de largura e altura: 8,192 pixels

IE Mobile:

Máximo de largura e altura: 4,096 pixels
Comment: Respondi às questões que solicitou no post, sobre meu sistema operacional, etc... Irei tentar a segunda solução que você propôs, mas antes gostaria de saber qual o limite de tamanho para o uso do .toDataURI que você citou, pois as imagens que tento salvar são de tamanho: 500x450 ou 851x315. Agradeço
Comment: @ThomersonRoncally a limitação varia de navegador pra navegador, no entanto no InternetExplorer é de aproximadamente 8,192 pixels (largura e altura), vou atualizar a resposta, note que estes limites sempre são melhorados a cada atualização :) - Felizmente.
Comment: Acrescentei o código que chamo à html2canvas, é bem simples.
Comment: Poderia mostrar uma "foto" do problema? @ThomersonRoncally Pode ser o problema com o background (no entanto pode ser um novo problema) ou com as fontes.
Comment: posso sim, irei atualizar minha pergunta, tentando expôr um pouco mais meu problema


How to show a page create with the view module in the administrative overlay?

Question: I've created a view with the view module which is a kind of administative page and i'd like to show that page using the administrative overlay, how can i do that?
Answer: Showing a view in the overlay just requires you to implement hook_admin_paths_alter().
function mymodule_admin_paths_alter(&$paths) {
  // Treat all user pages as administrative.
  $paths['the path of your view'] = TRUE;
}

Keep in mind this:

In the path you can also use asterisks (e.g. node/*/edit), useful in the case the view is using contextual filters
If the overlay is not accessible from the user, the page will be shown using the administrative theme, which could also be the default theme used by Drupal, if the site doesn't set a the administrative theme to be another one
Comment: I found this answer very useful, and went to use. I have the menu item in main-menu `/book-view` which is a link to one of view. so  in place of `'the path of your view'` I did place `'book-view'` But there is no change.  I did place `function` in template.php and replaced `mymodule` with `bartik`. Am I doing something wrong?
Comment: I was looking for such feature for pdf file since long, suppose if I have pdf file link, so pdf file will open as overlay- same as seven theme?
Comment: It should be a path as defined in `hook_menu()` or `hook_manu_alter()` from a module. I am not sure it works for menu links like that. For file links, it doesn't work; you need a page that shows the file.


Proof of Heine-Borel theorem; Hunter

Question: I know there are a few posts about the Heine-Borel theorem on the site, however, I have not found a post asking about this specific proof, i.e. from John K. Hunter's lecture notes (Chapter 5, Theorem 5.56).

Theorem 5.56 (Heine-Borel). A subset of $\mathbb{R}$ is compact if and only if it is closed and bounded.

Here is the proof and my questions.

Proof. ... First, we prove that a closed, bounded interval $K=[a, b]$ is compact. Suppose that $\mathcal{C}=\left\{A_i: i \in I\right\}$ is an open cover of $[a, b]$, and let
$$
B=\{x \in[a, b]:[a, x] \text { has a finite subcover } \mathcal{S} \subset \mathcal{C}\}.
$$
We claim that $\sup B=b$. The idea of the proof is that any open cover of $[a, x]$ must cover a larger interval since the open set that contains $x$ extends past $x$.
Since $\mathcal{C}$ covers $[a, b]$, there exists a set $A_i \in \mathcal{C}$ with $a \in A_i$, so $[a, a]=\{a\}$ has a subcover consisting of a single set, and $a \in B$. Thus, $B$ is non-empty and bounded from above by $b$, so $c=\sup B \leq b$ exists. Assume for contradiction that $c<b$. Then $[a, c]$ has a finite subcover
$$
\left\{A_{i_1}, A_{i_2}, \ldots, A_{i_n}\right\}
$$
with $c \in A_{i_k}$ for some $1 \leq k \leq n$.

Why does $[a,c]$ have a finite subcover? Maybe equivalently, how do we know that $c\in B$?

Since $A_{i_k}$ is open and $a \leq c<b$, there exists $\delta>0$ such that $[c, c+\delta) \subset A_{i_k} \cap[a, b]$.

If $A_{i_k}$ is open, there exists $\delta>0$ such that $(c-\delta,c+\delta)\subset A_{i_k}$. Why $[c, c+\delta) \subset A_{i_k} \cap[a, b]$?

Then $\left\{A_{i_1}, A_{i_2}, \ldots, A_{i_n}\right\}$ is a finite subcover of $[a, x]$ for $c<x<c+\delta$, contradicting the definition of $c$, so sup $B=b$.

Why is $\left\{A_{i_1}, A_{i_2}, \ldots, A_{i_n}\right\}$ a finite subcover of $[a,x]$ for $c<x<c+\delta$?

Moreover, the following argument shows that, in fact, $b=\max B$.
Since $\mathcal{C}$ covers $[a, b]$, there is an open set $A_{i_0} \in \mathcal{C}$ such that $b \in A_{i_0}$. Then $(b-\delta, b+\delta) \subset A_{i_0}$ for some $\delta>0$, and since $\sup B=b$ there exists $c \in B$ such that $b-\delta<c \leq b$. Let $\left\{A_{i_1}, \ldots, A_{i_n}\right\}$ be a finite subcover of $[a, c]$. Then $\left\{A_{i_0}, A_{i_1}, \ldots, A_{i_n}\right\}$ is a finite subcover of $[a, b]$, which proves that $[a, b]$ is compact.
Now suppose that $K \subset \mathbb{R}$ is a closed, bounded set, and let $\mathcal{C}=\left\{A_i: i \in I\right\}$ be an open cover of $K$. Since $K$ is bounded, $K \subset[a, b]$ for some closed bounded interval $[a, b]$, and, since $K$ is closed, $\mathcal{C}^{\prime}=\mathcal{C} \cup\left\{K^c\right\}$ is an open cover of $[a, b]$. From what we have just proved, $[a, b]$ has a finite subcover that is included in $\mathcal{C}^{\prime}$. Omitting $K^c$ from this subcover, if necessary, we get a finite subcover of $K$ that is included in the original cover $\mathcal{C}$.
To prove the converse, suppose that $K \subset \mathbb{R}$ is compact. Let $A_i=(-i, i)$. Then
$$
\bigcup_{i=1}^{\infty} A_i=\mathbb{R} \supset K
$$
so $\left\{A_i: i \in \mathbb{N}\right\}$ is an open cover of $K$, which has a finite subcover $\left\{A_{i_1}, A_{i_2}, \ldots, A_{i_n}\right\}$. Let $N=\max \left\{i_1, i_2, \ldots, i_n\right\}$. Then
$$
K \subset \bigcup_{k=1}^n A_{i_k}=(-N, N)
$$
so $K$ is bounded.
To prove that $K$ is closed, we prove that $K^c$ is open. Suppose that $x \in K^c$. For $i \in \mathbb{N}$, let
$$
A_i=\left[x-\frac{1}{i}, x+\frac{1}{i}\right]^c=\left(-\infty, x-\frac{1}{i}\right) \cup\left(x+\frac{1}{i}, \infty\right) .
$$
Then $\left\{A_i: i \in \mathbb{N}\right\}$ is an open cover of $K$, since
$$
\bigcup_{i=1}^{\infty} A_i=(-\infty, x) \cup(x, \infty) \supset K
$$
Since $K$ is compact, there is a finite subcover $\left\{A_{i_1}, A_{i_2}, \ldots, A_{i_n}\right\}$. Let $N=$ $\max \left\{i_1, i_2, \ldots, i_n\right\}$. Then
$$
K \subset \bigcup_{k=1}^n A_{i_k}=\left(-\infty, x-\frac{1}{N}\right) \cup\left(x+\frac{1}{N}, \infty\right),
$$
which implies that $(x-1 / N, x+1 / N) \subset K^c$. This proves that $K^c$ is open and $K$ is closed.

I do not understand how $K \subset \left(-\infty, x-\frac{1}{N}\right) \cup\left(x+\frac{1}{N}, \infty\right)$ implies $(x-1 / N, x+1 / N) \subset K^c$. By $\subset$, the author does not mean proper subset, but rather $\subseteq$ (see page 3 chapter 1):

In our notation, $A \subset X$ does not imply that $A$ is a proper subset of $X$ (that is, a subset of $X$ not equal to $X$ itself), and we may have $A=X$.
Comment: @AnneBauval you may as well post this as an answer
Answer:
Use that $c$
belongs to some $A_i$
and is the limit of a sequence in $B$
which eventually belongs to $A_i,$
to construct a finite subcover of $[a,c].$
Because for $δ>0$
small enough, $c+δ≤b.$
Because it covers $[a,c]$
and $[c,c+δ).$
Because $E⊂F⟹F^∁⊂E^∁$
and $(u,v)⊂[u,v].$
Comment: Exactly! I was too lazy to write all these details...
Comment: Thank you for the answer! For 1, I argue in the following way (maybe this is what you suggested): $c$ belongs to some $A_i$. Since $A_i$ is open, $(c-\delta,c+\delta)\subseteq A_i$ for some $\delta>0$. Since $c=\mathrm{sup}(B)$, there exists an $x\in B$ such that $c-\delta<x$. So $[a,x]$ has a finite subcover, and this cover together with the cover for $\{c\}$ makes up a finite subcover of $[a,c]$. We also have that $[a,x]$ is covered for any $c<x<c+\delta$, which answers question 3. Thank you again.

Proof of Heine-Borel theorem; Hunter


Get field (list type) label in a twig template

Question: I have a content type (appel_offre) with a field_categorie_avis field, which is a list type with these values.

ouvert | Ouvert toute l'année
restreint | Restreint 24h
concurrence | Appel public à concurrence

In the node--appel-offre.html.twig template, I want to print this field but I only get the key, not the value. For example, for Appel public à concurrence, I always get concurrence.
I am using node.field_categorie_avis.value. Is there another way to get the same value?
Comment: what does it spit out if you use dump() on the field?
Comment: Hello and happy new years !
Comment: Happy New year to you too!
Answer: You can use
{{ content.field_categorie_avis[0]['#markup'] }}

to display label.
Dont miss the [0] because drupal always store items in array in case of field size limit change.
Comment: Very useful. I was struggling with this for last couple of hours.
Comment: This did not work for me in Drupal 8.9. Instead, use: `element['#object'].field_name.setting('allowed_values')[element['#object'].field_name.value]`
Answer: Came across this same issue, none of the proposed solutions worked... in a node template what worked was:
node.field_myselect_list.fieldDefinition.itemDefinition.settings.allowed_values[node.field_myselect_list.value]


Expectation of the product of two random variables

Question: Given x[n] is independently distributed with mean $\mu$ and variance $\sigma ^2$ for all n.Show that
$$
   E\{  x[n] x[m] \} = \begin{cases}
                  \mu ^2, & \text{m $\ne$ n}.\\
                  \mu ^2 + \sigma ^2, & \text{m = n}.
                 \end{cases}
$$
I can see that the m = n case can be solved by using the equality $E[x^2] = Var(x) + ( E[x] ) ^2$ but how do I prove the m $\ne$ n condition?
Comment: You've got it backwards. If $m\neq n$ then $= \mu^2$. and the other way for the other case.
Comment: Thanks, I fixed the question
Answer: Hint: If X and Y are independent, E[XY] = E[X]E[Y].
Comment: I've seen that inequality but are x[n] and x[m] independent? x[m] is essentially a shifted version of x[n] so it's value strongly depends on what the value of x[n] is right?
Comment: When you said "Independently" distributed for all n, did you mean something else? To me, x(n) is an indexed collection of random variables which are independent as per your premise. And mind you, what you are talking about is a deterministic signal i.e. $x[n-m]$ is a shifted version of x[n]. This need not be true in a stochastic process.


What kind of E is this? (What is this type of variation called?)

Question: This monday, as I started my 'song a week' routine, I came up with this lovely chord progression (listed below). It is clearly some form of E, and I could go as far as to say it's a major scale. (The chords were named with the help of an app so I committed no mistakes).
<code>Eb-F-Bb-F-G (listed as Ebadd9)
D-F-Bb-F-G (listed as Gm7/D)
C#-F-Bb-F-G (listed as Bbm6/C#)
C-Eb-G-Bb (listed as Cm7)
</code>
As it is evident, the first three chords vary only at the 'bass note' (?), with Eb, D and then C#. The fourth chord was an attempt to alleviate the tension and direct it to the root.
Is there a name for this type of variation? Has this scale a formal name?

When it ends, the last chord I play is a lone D7 (D-F#-C-D-A) to create unresolved tension. Should I play a Ddim7 instead, for theory purposes?
Comment: Never do anything for theory purposes. Alway do the thing that *sounds* right.
Comment: "The chords were named with the help of an app so I committed no mistakes" The (big) mistake you make was assuming the app understood what was going on musically. These aren't "chords that need to be named" - they are a single chord, over a moving bass line. The names don't tell you anything useful about their *function* - apparently, the app is just finding the "best" name for each combination of notes, taken out of the context of the rest of the music.
Comment: Looks more like a modulation from Eb or Bb to F, to diminished, and so on.
Comment: Is it relevant that it is the only chord progression I have during the whole song? (the song is three verses long)
Comment: That 3rd chord should have been called Bbm6/Db. Where did you source it?
Comment: No, no. You got me wrong. I used the app so I committed no mistakes at naming the notes. I understand that the names may vary depending on the context. As a proof I could tell you that the third chord is also a C#dim7 or Dbdim7 (again, it depends on context). I'm showing you the 'raw' info because I hope you can judge better than I can.
Comment: Except there is  an error! And the 3rd chord cannot be a dim anything.
Comment: @condosz I'm a little confused by your question. What do you mean by "kind of E"? Are you thinking this is an E scale, or an E key of some kind?
Comment: @Richard Well, yes, that's what I think... It isn't?

I really want to understand why what I did works so well. I don't have a really solid idea of what I just did.
Answer: Seems like a chromatic move, down to a major 7, then to dominant 7, ending with the relative minor, all with added notes. The last chord is going to be entirely up to you and your ears. Theory will try to explain what's happening, after. It usually does a good job. But ears do it better...
Answer: Not sure what you mean by 'I could go as far as to say it's a major scale'?  There's a descending chromatic scale in the bass.   That's a very strong element in the progression, so much so that it would be surprising if the scale didn't continue at least as far as Bb. The bass line is so strong that it would justify almost any harmonies that fitted it.   Even the simplistic planing chords in my second example.   Though I feel we're travelling towards a tonic at the Bb this time.   What do you think?
Beware of chord-naming 'apps'.  Chord naming is often very much affected by context.  And yours has made one glaring mistake - how can a Bbm6 chord possibly include C#?   I could be cruel and say that if you don't see why it has to be Db, you're not ready to start analyzing harmony.  But I won't  :-)
Comment: It looks like "Bbm6/C#" means a Bb minor sixth with an added C#.  So, perhaps the chord app has simply failed to analyze the enharmonic Db when the input is a C#.  On the other hand, if that is the case, "Gm7/D" would seem to be a definite mistake, since it is saying that the D is a non-chord tone.
Comment: I think you misunderstand how slash chord names work.    And you prove the point that a chord-naming app is only useful to a person who knows enough not to need one!
Comment: Ok, I looked it up and yes, I did misunderstand.  Slash chord names basically serve the same purpose as figured bass, without having to write the bass note.  Thanks for pointing that out.


Properties of P-matrices?

Question: I have two $n \times n$ matrices satisfying $0 \leq A \leq B$, where $\leq$ denotes element-by-element comparison. I'm trying to show that if $(I-B)^{-1}$ exists and all of its elements are non-negative, then $(I-A)^{-1}$ exists and all its elements are non-negative. Not sure where to start. I'm deliberately not assuming that $\sum_{j=1}^{n} B_{ij} < 1$, which would imply that $(I-B)^{-1} = \sum_{k=0}^{\infty} B^k \geq \sum_{k=0}^{\infty} A^k =  \geq 0$.
Answer: The spectral radius of $B$ is necessarily $<1$.
Let $v$ be a Perron vector of $B$. As $(I-B)^{-1}$ is nonnegative, we have $0\le (I-B)^{-1}v=(1-\rho(B))^{-1}v$. Hence $(1-\rho(B))^{-1}\ge0$ and $\rho(B)<1$.
It follows that $\rho(A)\le\rho(B)<1$ and the Neumann series $I+A+A^2+\cdots$ converges to $(I-A)^{-1}$. Hence $(I-A)^{-1}$ is nonnegative.

Properties of P-matrices?


What is the Domain of $\frac{2}{5x+8}$

Question: I had originally thought that it was $(-\infty, -8/5) \cup (-8/5,\infty)$ but LON CAPA says that is wrong. Original function is $$\frac{2(\frac{1}{x})}{8(\frac{1}{x})+5}$$
Comment: Who is LON CAPA? The original function is not defined at $x=0$.
Comment: It is the original function that determines the domain, not the simplified form.
Comment: The "original function" and title function are different, so I may agree with LON CAPA.
Comment: Please read this [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Comment: You forgot to exclude x = 0
Answer:
The question "What is the domain of [some expression]" is a poorly phrased question.  A function is defined, in part, by its domain.  If you are not told ahead of time what the domain (and codomain!) of a function is (are), then any answer is legit.  For example, the answer $\{1, 2, \pi, -10^{100}\}$ is a perfectly reasonable answer to the given question.  However, I am being cranky.  I presume that the question is meant to be read

What is the largest set of real numbers on which the expression
$$ \frac{2\cdot\frac{1}{x}}{8\cdot\frac{1}{x}+5} $$
defines a function?

After doing a bit of simplification, you seem to have noticed that
$$ \frac{2\cdot\frac{1}{x}}{8\cdot\frac{1}{x}+5} = \frac{2}{5x+8}. $$
However, this equality holds only when both the left-hand side (LHS) and the right-hand side (RHS) are defined.  The two expressions are not defined for all of the same values (and, in fact, this is sufficient to show that the largest set of numbers on which the LHS defines a function is different from the largest set of real numbers on which the RHS defines a function).  The simplification step can be useful in other circumstances, but it isn't helpful for determining the maximal domain.

Finally, to get at the largest possible domain, note that the original expression is a fraction of fractions involving a variable $x$.  It will define a function as long as the fraction takes a well-defined value.  Typically, fractions take well-defined values whenever both their numerators and denominators are real numbers, and their denominators are nonzero.  Thus we have three questions to answer:

When is the numerator a real number?
When is the denominator a real number?
When is the denominator nonzero?

The numerator is a real number as long as $\frac{1}{x}$ is defined, which implies that $x\ne 0$.  Similarly, the denominator is defined as long as $x\ne 0$.  Thus we definitely know that $0$ is not in the domain of the function defined by this expression.  Finally, note that
$$ 8\cdot\frac{1}{x} + 5 = 0
\iff \frac{1}{x} = -\frac{5}{8}
\iff x = -\frac{8}{5}.
$$
Thus the fraction is undefined when $x = -\frac{8}{5}$, which implies that this value is not in the domain of the function.
We have shown that neither $0$ nor $-\frac{8}{5}$ is in the domain of the function, but every other real number works (since all other real numbers satisfy the conditions addressed by the three questions above).  Therefore the domain of the function is the set of real numbers, minus those give above, i.e.
$$ \mathbb{R} \setminus \left\{ 0, -\frac{8}{5} \right\} = \left( -\infty, -\frac{8}{5} \right) \cup \left(-\frac{8}{5}, 0\right) \cup (0,\infty).$$
Answer: Unless otherwise specified, the domain of a rational function is the set of all real numbers except those that make the denominator equal to zero.
The function
$$f(x) = \frac{\dfrac{2}{x}}{\dfrac{8}{x} + 5}$$
is the quotient of two rational functions.
Both the numerator and denominator are undefined if $x = 0$.  You correctly determined that the denominator is equal to zero when $x = -8/5$.  Hence, the domain is
$$\text{Dom}_f = \left\{x \in \mathbb{R} \mid x \neq 0, -\frac{8}{5}\right\} = \left(-\infty, -\frac{8}{5}\right) \cup \left(-\frac{8}{5}, 0\right) \cup (0, \infty)$$
When you multiplied the numerator and denominator of
$$f(x) = \frac{\frac{2}{x}}{\frac{8}{x} + 5}$$
by $x$ to obtain
$$g(x) = \frac{2}{5x + 8}$$
you found the domain of $g$ to be
$$\text{Dom}_g = \left(-\infty, -\frac{8}{5}\right) \cup \left(-\frac{8}{5}, \infty\right)$$
While, the functions $f$ and $g$ agree on the intersections of their domains, the functions $f$ and $g$ are not equal since they do not have the same domain.
Comment: Please explain the reason for the downvote.
Answer: $\displaystyle \frac{2\cdot \frac 1 x}{8\cdot\frac 1 x + 5}$ is equal to $\displaystyle \frac 2 {8+5x}$ except when $x=0,$ in which case the former expression is undefined, and when $x=-8/5,$ when both expressions are undefined.
Answer: We are concerned about dividing by zero. What values of $x$ make the denominator be zero?
$$5x + 8 = 0$$
$$5x = -8$$
$$x = -{5\over8}$$
so, the domain is the whole real line $except$ $x = -{5\over8}$.
Comment: Be careful.  The original function is $$f(x) = \frac{\frac{2}{x}}{\frac{8}{x} + 5}$$ You have not accounted for when the original numerator and denominator are defined.
Comment: @N.F.Taussig ah, thanks. You are correct. I did not read the question too carefully - just the question posed in the title...Grrr!
Answer: $f(x)=\dfrac{2(\dfrac{1}{x})}{8(\dfrac{1}{x})+5}$
$\mathcal{D}_f = \bigg\{x\in \mathbb{R};\quad x\ne0\land \left(\dfrac{8}{x}+5\right)\ne 0\bigg\}$

What is the Domain of $\frac{2}{5x+8}$


Appending a css class to a textbox javascript

Question: Is it possible to add the css class named color to the textbox define inside the javascript below?

thanks
Answer: this should do it
newTextBoxDiv.after().html('Colors and price: #'+ counter + ' : ' + '<input name="colors[]" value="" class="color" >');

Answer: you mean, to the input?
simply
'<input name="colors[]" value="" class="color">'

Answer: Yes
newTextBoxDiv.siblings("input:text[name='colors[]']").addClass('color');

Answer: if you mean the newTextBoxDiv then use:
newTextBoxDiv.addClass('color');

If it is the input then:
'<input name="colors[]" value="" class="color">'


To eliminate constants $a$ and $b$ and find corresponding p.d.e

Question: Eliminate the parameters $a$ & $b$ from the equation $z^2(1+a^3)=8(x+ay+b)^2$ and find corresponding partial differential equation.
here $z$ is function of $x$ & $y$.
Differentiating with respect to $x$ we get
$$p = \frac{8(x+ay+b)}{z(1+a^3)}$$
& Differentiating with respect to $y$ we get
$$q =\frac{8a(x+ay+b)}{z(1+a^3)}$$
where $p=z_x$ & $q=z_y$.
Now how should I proceed to eliminate the parameters $a$ & $b$?
Comment: $q/p = a$ will get things started.
Comment: Substitute $a = q/p$ back into either expression for the partial derivatives, and calculate $b$ in terms of $p,q,z$. Then replace $a,b$ in the original equation and that's the PDE.
Comment: Sorry but I am not getting you. What is your final P.d e?
Answer: Obviously, when $p\ne0$,
$$a=\frac qp.$$
Then
$$8(x+ay+b)=z(1+a^3)p.$$
Plugging in the initial equation,
$$z^2\left(1+a^3\right)=\frac18\left(z\left(1+a^3\right)p\right)^2,$$
and after simplification
$$8=(1+a^3)p^2$$
or
$$p^3+q^3=8p.$$


Density of the function class

Question: Let $X$ be any set and let $[0,1]^X$ (the class of all functions $X\to[0,1]$) be endowed with the metric given by $\rho(f,g):=\sup_{x\in X}|f(x) - g(x)|$. Consider any class of functions $\mathscr F\subseteq [0,1]^X$. Define:
$$
  d_\mathscr F(x,y):=\sup_{f\in \mathscr F}|f(x) - f(y)|.
$$
Clearly, $d_{\mathscr F}$ is a pseudo-metric on $X$, that is it is symmetric and satisfies the triangular inequality, but $d_{\mathscr F}(x,y) = 0$ does not necessarily imply $x = y$. Define the corresponding Lipshitz functions:
$$
  \mathrm{Lip}(d_{\mathscr F}):=\left\{f\in [0,1]^X:\sup_{d_\mathscr F(x,y)\neq 0}\frac{|f(x) - f(y)|}{d_{\mathscr F}(x,y)}\leq 1\right\}.
$$
Is it always true that $\mathscr F$ is dense in $(\mathrm{Lip}(d_\mathscr F),\rho)$?
Comment: Extreme case: $X = [0,1]$, $\mathscr{F} = \{\operatorname{id}_{[0,1]}\}$. It's not dense.
Comment: Please check formulas. Do you mean $\rho(f,g)$? What is $\tilde x$?
Comment: @DanielFischer: sure, the space is very nice and of course this example can be extended to other cases as well. Thanks! You can post it as an answer.
Answer: In general, $\mathscr{F}$ is not dense in $\operatorname{Lip}(d_\mathscr{F})$. As an extreme case, consider $X = [0,1]$ and $\mathscr{F} = \{\operatorname{id}_{[0,1]}\}$. Then $d_\mathscr{F}$ is the usual distance, and $\mathscr{F}$ is closed in $\operatorname{Lip}(d_\mathscr{F})$. Since $\operatorname{Lip}(d_\mathscr{F})$ always contains the constants, no finite family can be dense.

Density of the function class