How do I choose a set of numbers from a PMF with a specified total?

Question: So basically I'm choosing a set of numbers from a probability mass function, (say binomial or scale-free). By which I mean I'm performing a weighted choose operation using the PMF as weights. However I would ideally like to choose them so they add up to a specified total. How could I go about doing this without skewing the PMF? For example, if I simply chose the last number so that the total is met without going over, then the choices would no longer adhere to the distribution.
So to give you my use case, I found this generative model here which is the configuration model for generating scale free networks. This involves computing a finite version of the scale-free distribution and then randomly choosing (weighted by distribution) a degree for each node. However there is no way of specifying what the total edge count should be.
Answer: As you've stated the issue currently, I don't think it is possible, since you are drawing single samples independently and identically distributed, presumably. If you add a constraint that the sum must add to $T$, then that distribution must change (certain combinations of draw becoming impossible, for example, which used to be fine).
If you are on a small enough scale, one thing you could do is compute the constrained joint distribution, i.e. you draw $n$ samples at once $x_1,\ldots,x_n\sim J$, where $J$ is the set of all possible combinations of size $n$ such that $\sum_i x_i=T$.
Basically, you currently have $p(X=v_i) = p_i$, you need to figure out a new distribution $q$ where $q(X_1=v_{\alpha_1},\ldots, X_n= v_{\alpha_n}) = q_\alpha$ is a PMF on combinations of variables that sum to $T$. (You have to do this for each $n$ too, if that is not fixed).
In other words, let the set of possible values be $v_1,\ldots, v_n$. Figure out the set $S=\{ (v_1,\ldots,v_m) \mid m\geq 1, \sum_i v_i = T \}$, i.e. all possible combinations of variables that sum to $T$. Any sample from $S$ is now a valid sample. The only issue is how to weight them. Ideally, you can do this by figuring out the probability $p(S)$, i.e. the chance that choosing any random combination of values you choose is in $S$ (presumably there is a maximum number of choices you can make, i.e. maximum length of the sequence, say $L$... hopefully all $v_i$ are positive). Then you can just take $p(v) = p(v_1,\ldots,v_m) = \prod_j p_j / p(S)$, since $p(v|v\in S) = p(v,S)/p(S)$ to write it a bit... informally.
This construction basically takes the subspace of all possible subsets of choices that are valid (add up to $T$) and then reweights them according to the probability you would have seen using the original probabilities in the initial space (correcting the probabilities to account for the new subspace we are now operating in).
Of course, this is non-trivial :). The pdf you linked doesn't load for me (probably an issue on my end mind you). However, it sounds like you are sampling an integer for each node in a graph. If the number of nodes is fixed, then the construction I noted above is a little simpler, since $n=L=|V|$ is fixed, and may be tractable if $L$ is small. It is the most principled approach I can think of, which exactly preserves the original relative weighting while guaranteeing it adds to $T$.
The idea of sampling normally until the last node, then setting it equal to the difference seems problematic because you could hit $T$ before reaching the last node, no? And you cannot give the node a negative degree.
Note there is a trivial algorithm but slow algorithm which prevents skewing: just sample all of them as you were, then at the end if you are not equal to $T$, keep choosing new nodes (uniformly at random) and sample a new value for them, until the sum total is $T$. No skewing but might take a very very long time. You could speed this up by slightly skewing the distribution: when sampling nodes to retry, if you are below $T$, favour choosing nodes with small degrees, or favour larger degrees slightly more.

Now, if you can relax a bit the requirement that it sums to $T$, and just be near $T$, and you want to be fast, then perhaps you could do something a little cuter. :) Basically, we keep track of the total remaining number of nodes, and slightly skew our choices so that we will end up close to $T$, by putting a prior over the current sample that changes for each sample (depending on the previous samples). You can then manually balance you much each choice is allowed to be skewed versus how much you want to guarantee being close to $T$.
Let the original distribution over $v$ (a single node's degree) have an expected value of $\mathbb{E}[v]=:\mu_v$. Suppose we have already chosen degrees for $K$ nodes, and there are $U=|V|-K$ nodes left. Let $C_V$ be the set of degree values of the already chosen vertices, with sum $S_C=\sum_{v\in C_V} v$. We thus have "space left" given by $T - S_C$.
But, the expected value of the total we will get is $ E_T = S_C + U\mu_v $. Let $\Delta = E_T - T$ be the expected difference between $T$ and $E_T$. If $\Delta$ is positive, we want to choose smaller values, and if it is negative, we want to choose larger values. (But we want to skew $p(v)$ as little as possible.) How to do this is up to you, but one way is to change $p(v)$ to $q(v)$ such that $\mathbb{E}_{v\sim q(v)}[v]U + S_C = S_C + U\sum_i v_iq_i = T$, where $v_i\in\{1,\ldots,n\}$ presumably. So, for the current node, we need $q$ such that:
$$
\sum_i v_iq_i \approx (T - S_C) / U \;\;\;\;\&\;\;\;\; q_i \approx p_i
$$
where the first constraint says that we are choosing a distribution such that if  we follow it for $U$ more steps then we expect to end up with the sum at $T$, and the second constraint says that we cannot be too far from the "true" distribution over node degrees. This can be rewritten as a soft constraint optimization objective:
$$
\mathcal{L}(q) = \left[ \frac{T - S_C}{U} - \sum_i v_iq_i \right]^2 + \gamma\sum_i (p_i - q_i)^2 + \xi \left(1 - \sum_j q_j\right)^2
$$
where we want $q^* = \arg\min_q \mathcal{L}(q)$ and $\gamma$ controls how much we care about the first versus second constraint. (The third term is to make it close to a probability distribution).
Let's check the derivative
$$ \partial_{q_k} \mathcal{L} = -2v_k\left[ \frac{T - S_C}{U} - \sum_i v_iq_i \right] - 2\gamma(p_k - q_k) - 2\xi \left(1 - \sum_j q_j\right) = [\nabla_q \mathcal{L}(q)]_k $$
(Please do this yourself as I may [almost certainly] have made mistakes). This doesn't seem analytically solvable, but we can do a very quick gradient descent : $q^{(t)} \leftarrow q^{(t-1)} - \eta\nabla_q \mathcal{L}(q^{(t-1)})$
Obviously more sophisticated algos could also be used and/or automatic differentiation.
So we can basically do the following algorithm:

Draw a value for a node from $p$
Until all the nodes have chosen values:

Choose a random node $a$
Compute $q$ via a few fast optimization steps (not many maybe needed, it's random anyway)
Normalize $q$ (or use it to parameterize a Dirichlet distribution and draw $q$ from that)
Sample a random node value (degree) from $q$ and assign it to $a$

This algorithm states that every time we choose a node, we minimally adjust the PMF $p$ over degrees such that the expected total sum over nodes will be close to $T$. Of course, it won't be exactly, but it should be close (if you run this many times, the average sum should be $T$), depending on $\gamma$, $\xi$, optimization quality, the prior distribution $p$, the problem itself, etc...
For instance, if $\mu_v$ is larger than $T$, this is already very hard :)
Once you have something near $T$, then maybe you can do some smaller, more reasonable changes to get it to $T$.
Well, I better stop rambling now, let me know if you want clarifications. Or if I totally misunderstood the question.


Proving absolute continuity of the laplace transform

Question: Suppose $f \in L^\infty(\mathbb{R})$ and define the laplace transform $F:(0,\infty)\rightarrow \mathbb{R}$ by $$F(s) = \int_0^\infty f(t)e^{-st}dt.$$
Prove that $F$ is absolutely continuous on $[a,b]$ for any $b>a>0$.
So, I'm thinking that I might be able to do this by proving that $F$ is Lipschitz. I think I got most of the way to proving that it's Lipschitz, but I'm a little stuck on some algebra getting the final Lipschitz inequality in place.
What I have so far: Let $M$ be the essential upper bound of $f$ (which exists because $f\in L^\infty(\mathbb{R})$), and let $x,y \in [a,b]$. Then
$$|F(x)-F(y)| = \left\vert \int_0^\infty f(t)e^{-xt}dt - \int_0^\infty f(t)e^{-yt}dt\right\vert \leq M \left\vert\int_0^{\infty}e^{-x}-e^{-y}\right\vert = $$ $$M\left\vert \frac{1}{x}-\frac{1}{y}\right\vert \leq M\left\vert \frac{1}{a}-\frac{1}{b}\right\vert.$$
And here's where it's not totally coming to me. I'm pretty sure I'm going to want to do something with $M\left\vert \frac{1}{a}-\frac{1}{b}\right\vert$ as my constant for the lipschitz condition. I'm just not totally sure how to incorporate it. I suppose I could just be completely wrong, and the laplace transform isn't lipschitz continuous. Given that $|F(x)-F(y)| \leq M\left\vert \frac{1}{x}-\frac{1}{y}\right\vert$ I think it could be proved directly from the definition of absolute continuity.
Any thoughts either way would be greatly appreciated.
Thanks in advance.
Answer: You were almost there. For $x, y \in [a,b]$
$$\left| \frac{1}{x} - \frac{1}{y} \right| = \frac{|x-y|}{|xy|} \le \frac{1}{a^2} |x-y|$$
So that $F$ is $(M/a^2)$-Lipschitz.
Comment: Ha. Guess I was.
I think I was anticipating some fairly obscure inequality and didn't consider the obvious "just try doing the subtraction".
Thanks for your thoughts


how to send muliple emails in drupal in same time

Question: in my site when user submit a dination i want to send email to donor,charity and delivery service at same time(three different emails) in code and i want to kown how can i achieve that,below is the my mail seding function,i already tried call email function with 3 times with different keys for $key but that time emails are sending with out body content
 function zgRequestsdonor2_mail ($key, &$message, $params) {
  switch ($key) {
  case 'aftersubmit_donor':
    // Set headers etc

    $message['subject'] = t('email to donor');
    //$message['body'][] = t('Hello @username,', array('@username' => $params['username']));
    $message['body'][] = 'tyrtyrtyrtyty';
    break;
  }
}

calling it at
function zgRequestsdonor2_form_submit($form, &$form_state) {
  drupal_mail('zgRequestsdonor2','aftersubmit_donor',$donoremail, $language, $params = array(), $from = NULL, $send = TRUE);
}

Answer: If you want to send same mail to donor, charity and delivery service, then you can use CC feature of the mail.
$message['headers']['CC'] = "firstname.lastname@example.com";

Comment: no i want to send three diffrent emails to them..,i tried call the mail function three times but then emails are send with out body content...


For para criação de campos

Question: Estou tentando fazer com que quando o usuário inserir determinado número em um <input> seja criado a mesma quantidade de campos, tentei fazer de uma maneira que encontrei aqui, mas não consegui fazer com que criasse o número de campos que digito, só cria um label, nem o input aparece, segue abaixo o código:

<input type="number" class="form-control round-input" name="numero_parc" required="required" min="1" id="par">

$(document).ready(function() {
  var max_fields = 10;
  var wrapper = $("#vem");
  var add_button = $("#par");

  $(add_button).change(function(e) {
  e.preventDefault();
  var length = wrapper.find("input:text#textAdded").length;

  $(wrapper).append('' + (length+1) +'
<input type="date" class="form-control round-input" id="textAdded" name="num' + (length+1) + '">
');
  });
});

for:
function criaCampos(){
            var qtd = document.getElementById('par').value;
            if (qtd > 1) {
              for(var i=0; i < qtd; i++){
                document.getElementById('vem').innerHTML = '1º
<input type="date" class="form-control round-input" name="'+ qtd[i]+'">
';
              }
            }
          }

Comment: Você esqueceu de fechar a div que contém o input
Comment: Mesmo assim não funciona
Comment: Sim, tem outros problemas. Falta o loop em si
Comment: Tenta apenas add_button.change(function(){ ... });
Comment: Isso, não sei como montar esse loop, ou se tivesse como através desse código criar o número de campos que o usuário escolher.
Comment: Pro loop você pode usar o "for". Dá uma lida: https://www.w3schools.com/js/js_loop_for.asp
Comment: Eu tentei fazer um for da maneira que inseri na pergunta agora, mas não funcionou. Então achei esse segundo código, que pareceu melhor, mas ainda assim não funciona como preciso
Comment: `document.getElementById('vem').innerHTML += ...`
Comment: O que está dando errado é quando por exemplo, digito 3 para o nro de campos, mas aí o for cria dois e pára, e ainda o segundo é criado só o label, sem input
Comment: https://jsfiddle.net/ht6qgd83/
Answer: Tentei criar um exemplo para você de como pode ser feito. Utilizei jQuery, tudo bem?
No HTML deixei bem simples:
<input type="number" id="quantidade" value="0" />

E aqui o código jQuery:
$(document).ready(function(){

    $('#quantidade').on('change', function(){

      var quantidade = $('#quantidade').val(),
          campos = $('#campos');

      campos.html(''); //aqui eu fiz limpar a div
      for (x = 0; x < quantidade; x++) {
        campos.append('<input type="text" id="campo-'+x+'" />');
      }

    });

});

DEMO
Comment: Obrigada, ajustei algumas coisas de acordo com o que preciso e funcionou perfeitamente!

For para criação de campos


increase the width of Crystal Reports in c# windows applicaton

Question: I'm new to crystal report in c# windows application and i want to know how i can increase the width of the crystal report which is fixed to A4 size.
Comment: Are you using the version of CR that comes with Visual Studio 20xx?
Comment: Don't forget to update your questions by marking answers that were correct.
Comment: Beware: if you decrease the width of the paper, you run the risk of truncating fields on the right side of the report--Crystal Reports doesn't scale.
Answer: Use the following code:
myReport.PrintOptions.PaperSize = PaperSize.PaperB4;

myReport is the Crystal Report you created.
You may use any option available for papersize other than PaperB4.
Hope this helps...
Answer: Trying creating Crystal Report in landscape view.


Show that $r'(t)\times r''(t)=(\frac{ds}{dt})^3r'(s)\times r''(s)$

Question: (This is a question in my homework, and i have no idea how to solve this.)
We define the curvature of a path by $||r''(s)||$, where $r(s)$ is the arc-length parametrization of the path. Given a path $r(t)$, we let $r(s)$ be its arc-length parametrization so that $s=\int^t_0||r'(\gamma)||d\gamma$.
(a) Show that $r'(t)\times r''(t)=(\frac{ds}{dt})^3r'(s)\times r''(s)$
(b) Hence, or otherwise, show that the curvature can be expressed in terms of t.
    Give the explicit form of the curvature function.
Comment: What have you tried?
Answer: First, by chain rule we have
$$r'(t)=\frac{ds}{dt}r'(s)\tag{1}\label{r'}$$
Applying chain rule again comes
$$r''(t)=\frac{d^2s}{dt^2}r'(s)+\left(\frac{ds}{dt}\right)^2r''(s)\tag{2}\label{r''}$$
Now, we knoe that $v\times v=0$ for any vector, thus from (\ref{r'}) and (\ref{r''}), we have
$$r'(t)\times r''(t)=\left(\frac{ds}{dt}\right)^3r'(s)\times r''(s).\tag{3}\label{vec}$$
This concludes item (a).
For item (b), note that
$$\frac{ds}{dt}=\frac{d}{dt}\int_0^t\|r'(\gamma)\|\,d\gamma=\|r'(t)\|.$$
By other hand,
$$\|r'(s)\|=1\Rightarrow r'(s)\cdot r''(s)=0\Rightarrow r'(s)\perp r''(s).$$
From (\ref{vec}), we have
$$\|r'(t)\times r''(t)\|=\|r'(t)\|^3\|r''(s)\|.$$
Thus,
$$\kappa=\|r''(s)\|=\frac{\|r'(t)\times r''(t)\|}{\|r'(t)\|^3}.$$
Comment: Thanks a lot. This really helps!


In Tableau server, how can we get measures and dimensions of a data set using REST API?

Question: I looked at their REST API but I haven't found anything which gives me the measures and dimensions of the dataset/data source. I need to expose what measures and dimensions are there so that user knows what workbooks or visualizations he can create. Any ideas or help is greatly appreciated.
Answer: Fields in a datasource are not something that you can query directly via the REST API. My best suggestion, while not perfect, would be to add a tag for each field that you want to be queryable in the datasource, and then use the REST API to query your datasources show what is available to the user.
This shows you how to tag a datasource
Here is the specific REST API command that will return the tags
I want to stress that this isn't a perfect solution, but the REST API has a very WIP feel to it to begin with (REST should be able to do everything that tabcmd can do, but sadly, it can't).
There is also the undocumented REST API that has some additional functionality. That may have more of what you are looking for. I'm not 100% sure that this will solve your problem, but it does provide a lot of additional functionality to the base API.
Undocumented Tableau REST API


Problem iterating through onLayout calls for providing row heights of items to FlatList's getItemLayout

Question: I have a FlatList which fills with about 18000 text rows. Because the text in each row is of variable length, I cannot provide a static height for use in getItemLayout.
What I am attempting to do is first iterate through the entire dataset using a dummy view, from which I collect the height dimension via onLayout. My issue is that currently, the view is only re-rendering around 10 times before it just stops. As far as I can tell, onLayout simply isn't called for the last view that ends up appearing on the screen -- which is again only the 10th (or so, depending on the interval I iterate through the data at).
Below is my code which I've attempted to simplify somewhat here. Currently just trying to find a way to iterate through and precalculate view heights for the entire data set ahead of rendering in a separate component.
import React, { Component } from 'react';
import { AppRegistry, Text, View, TouchableOpacity, StyleSheet } from 'react-native';

export default class DummyMainItem extends Component {
constructor(props) {
    super(props);
    this.state = {
        codeData: [],
        currentItem: -1,
    };
}

componentWillReceiveProps(nextProps) {
    // Get data from MainFlatList
    if (nextProps.codeData != '') {
        console.log("PROPS in DummyMainItem are codeData of length: " + nextProps.codeData.length);
        this.setState({ codeData: nextProps.codeData });
    }
}

getItemDimensions(layout) {
    const { x, y, width, height } = layout;
    curItem = this.state.currentItem;
    console.log("getItemDimensions of #" + curItem + " (width, height) : (" + width + ", " + height + ")");

    if (curItem <= this.state.codeData.length) {
        this.setState({ currentItem: curItem + 1 });
    }
}

render() {
    console.log("Dummy Rendering item #" + this.state.currentItem);

    if (this.state.codeData != null && this.state.codeData.length > 0) {

        var item = this.state.codeData[this.state.currentItem];

        switch (item.type) {
            case '0':
                console.log("Dummy Case 0 FULLTEXT: " + item.fulltext);
                return (
                    <TouchableOpacity>
                        <View onLayout={(event) => { this.getItemDimensions(event.nativeEvent.layout) }}>
                            <View>
                                <Text>{item.fulltext}</Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                );

            case '1':
                console.log("Dummy Case 1 FULLTEXT: " + item.fulltext);
                return (
                    <TouchableOpacity>
                        <View onLayout={(event) => { this.getItemDimensions(event.nativeEvent.layout) }}>
                            <View>
                                <Text>{item.fulltext}</Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                );
            case '2':
                console.log("Dummy Case 2 FULLTEXT: " + item.fulltext);
                return (
                    <TouchableOpacity>
                        <View onLayout={(event) => { this.getItemDimensions(event.nativeEvent.layout) }}>
                            <View style={{ flexDirection: 'row' }}>
                                <Text>{item.section}</Text>
                                <Text>{item.fulltext}</Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                );

            default:
                return (
                    <TouchableOpacity>
                        <View>
                            <View onLayout={(event) => { this.getItemDimensions(event.nativeEvent.layout) }}>
                                <Text>{item.type} {item.fulltext} </Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                );
        }

    } else {
        console.log("Dummy Case Blank Render");
        return (
            <TouchableOpacity>
                <View onLayout={(event) => { this.getItemDimensions(event.nativeEvent.layout) }}>
                    <View>
                        <Text> </Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

}
}

AppRegistry.registerComponent('DummyMainItem', () => DummyMainItem);

I would expect from my code that each time a view was rendered, the getItemDimensions() function would be called, which itself adjusts the state of this.state.currentItem, this state change causing the render() function to be triggered again.
The actual behaviour is that it does the above, but only a limited number of times (closer to about 10 than the 18000 I need). getItemDimensions() is not called by onLayout, so dimensions are not obtained and the state of currentItem does not get advanced - therefore the rendering stops. What I do not understand is why for whatever last view appears on the screen, onLayout is not calling getItemDimensions.
Does anyone have any insight on why the iteration stops, or on a more effective way to achieve my goal? I need to provide getItemLayout to my FlatList as the app needs to be able to ScrollToIndex before a user manually scrolls through the entire FlatList.
Answer: The issue with onLayout not being called resulted from the fact that onLayout will not happen unless there is a difference between the previous layout and the one replacing it. In my case, when 2 views with identical heights followed one another, the iteration would stop due to onLayout not being called again.
The simple solution is to give each view a unique id per the response on this question: Forcing onLayout on React Native view. ie:
<View onLayout={(event) => { this.getItemDimensions(event.nativeEvent.layout) }}
    key={this.state.currentItem}>

By doing so, the view is layed out each render call, and so onLayout is called each time as well.
It's unfortunate that this seems to be about the only way to generate the needed height and offset information that getItemLayout() requires to allow ScrollTo operations on FlatLists with variable heights. This solution, while functional, is ultimately far too slow to be useful for me with 18000 list items and given my research hasn't found any alternatives to this point for React-Native, I'm now strongly considering returning my app to pure native development.
Comment: Hello  Very interesting investigation. While I think going to native will not help. For example the only way to measure bounding box (coordinates, width, height) of some text is to render it.
Comment: Have you finally solved your problem? And how?
Comment: At the time I was not able to solve performance here with RN, and did return to Android native development. While true that the bounding boxes are likely only measured via render, I think being limited to a single JavaScript thread for RN made this unusable for me at the time.

I would be curious if RN has somehow improved in this or if others have found ways of increasing the performance of FlatLists with irregularly sized items.
Comment: An interesting discussion re: threading in RN:
https://react-native.canny.io/feature-requests/p/parallel-multithreading--workers
Comment: You can try this novel multithreading library https://github.com/mrousavy/react-native-multithreading


Prototype Event.observe(window, 'change', function() - Not working in IE Browser

Question: Prototype, Event.observer 'window' 'change' is not working in IE browser /its working fine in Mozilla,chrome browser. Can you any one give the solution for this?
Code:

    <select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>

    </select>

    <input type="button" value="submit" id="chgButton"/>

Thanks in advance
ps
Answer: What do you expect to happen? If you're trying to use event bubbling then you might have better luck with document or document.body or something much more specific like the form element that contains those inputs.


If $f(a_{n_k}) \to a$ as $k \to \infty$, then there is some $x \in \mathbb{R}$ such that $f(x) = a$ and $a_{n_k} \to x$.

Question: I have two questions:

Let $(a_n)_{n \in \mathbb{N}}$ be a bounded sequence and let $f: \mathbb{R} \to \mathbb{R}$ be a continuous function.
If $a$ is an limit point for $f(a_n)_{n \in \mathbb{N}},$ there is there some $y \in \mathbb{R}$ such that $f(y) = a$ and $y$ is an accumulation point for $(a_n)$?
And also:
If $a$ is an limit point for $f(a_n)_{n \in \mathbb{N}},$ and there is some $y \in \mathbb{R}$ such that $f(y) = a$, then $y$ is an accumulation point for $(a_n)$.

I have tried writing the definition of continuity with $\varepsilon - \delta$ and with sequences, but I did not manage to solve the above problems, because that definition gives no information on $(a_n)$.
I have also tried constructing a counter example for the first question (since I believe to be false), but I was not able to.
Thank you in advance for the help!
Answer: If $a$ is a limit point of $\{f(a_n)\}$, then there exists a subsequence $a_{k_n}$, such that
$$
f(a_{k_n})\to a
$$
and since $\{a_{n_k}\}$ is bounded, then it possesses a convergent subsequence, say $a_{\ell_n}\to b$. Now we have that
$$
a_{\ell_n}\to b\qquad\text{and}\qquad f(a_{\ell_n})\to f(b)
$$
and also $f(a_{\ell_n})\to a$.
Thus $f(b)=a$.
Comment: Thank you for the answer!


Whose record did the Chicago Bulls team of 1995-96 break?

Question: The Chicago Bulls broke the NBA record for most victories in a season during the 1995-96 season. The question is, whose record did they break?
Answer: Chicago Bulls held the record for most wins in a single NBA season with 72 wins in the 1995-96 season, which has since been surpassed by the 2015-2016 Golden State Warriors (with 73 wins).
Prior to that, the record for most number of wins in a single NBA season was held by the Los Angeles Lakers team for the 1971-72 season with 69 wins. Conincidentally, the Bulls recorded 69 wins in the 1996-97 season as well.
The top 10 list for total number of wins in a season can be found here.


Linear Discriminant Analysis for $p=1$

Question: I'm studying 'Introduction to Statistical Learning' by James, Witten, Hastie, Tibshirani.
In page 139, of their book, they began by introducing Bayes' Theorem $p_k(X)=P(Y=k|X=x) = \dfrac{\pi_kf_k(x)}{\sum_{l=1}^k \pi_l f_l(x)}$. $\pi$ is not mathematical constant, but denotes the prior probability. Nothing is strange in this equation.
The book claims that it wants to obtain an estimate for $f_k(x)$ that it can plug into the equation given above. To estimate $f_k(x)$, it assumes that is normal. In the one dimensional setting, $f_k(x)=\dfrac{1}{\sqrt{2\pi}\sigma}\exp(-\dfrac{1}{2\sigma^2}(x-\mu_k)^2)$, where $\mu_k$ and $\sigma^2_k$ are the mean and variance for the $k$th class. It is assumed that $\sigma^2_1 = \sigma^2_2 = \cdots = \sigma^2_K$. (I began to get confused from the last statement.)
Plugging $f_k$ into $p_x$, you have this quite messy equation (1) :
$$p_x(k)=\dfrac{\pi_k \frac{1}{\sqrt{2\pi}\sigma}\exp(-\frac{1}{2\sigma^2}(x-\mu_k)^2)}{\sum_{l=1}^K \pi_l \frac{1}{\sqrt{2\pi}\sigma}\exp(-\frac{1}{2\sigma^2}(x-\mu_l)^2)}. $$
Again, no surprises here since it is just substitution.

The Bayes' Classifier involves assigning an observation to the class for which equation (1) is the largest. Taking the log of Equation (1) and rearranging terms, it is not hard to show that this is equivalent to assigning the observation to the class for which the following is the largest:
$$\delta_k(x)=x \cdot \dfrac{\mu_k}{\sigma^2} - \dfrac{\mu_k^2}{2\sigma^2} + \log(\pi_k) $$
Question: I do not understand where this came from, and what it means. I tried doing the log of equation and it doesn't become this. Are we taking the derivative somewhere here, since this is the largest observation?
Comment: Here is an appropriate and accurate derivation: https://arxiv.org/pdf/1906.02590.pdf
Answer: You can express equation (1) up to a proportionality constant,
$$p_x(k)\propto \pi_k \frac{1}{\sqrt{2\pi}\sigma}\exp \left(-\frac{1}{2\sigma^2}\left(x-\mu_k \right)^2 \right) $$
so if you then take logs
$$ \log p_x(k) \propto \log \pi_k - \log (\sqrt{2\pi} \sigma) -\frac{1}{2\sigma^2}\left(x-\mu_k \right)^2 $$
where $- \log (\sqrt{2\pi} \sigma)$ again goes into the proportionality constant because it doesn't depend on $k$. Then expand the squared term and you are there (note that expanding the bracket will give another term which will vanish into $\propto$).
Comment: Yea, that's all there is to it. $\delta_k (x)$ is called the linear discriminant function. It's just a different way of writing the posterior probability that an observation belongs to class $k$ given its characteristic $x$. So picking the class with the highest posterior probability from Bayes rule is the same as picking the class with the highest value for the LDA. You can set $\delta_k(x) = \delta_l(x)$ to compute the Bayesian decision boundary (which gives a threshold for when an observation should be classified as $k$ or $l$).
Comment: I laughed when I read your answer. It IS that simple?! Brilliant! May I know what the quantity $\delta_k(x)$ means (in layman's terms)? My background in stats is poor, but I am able to follow the mathematics.

Linear Discriminant Analysis for $p=1$


Kernel of polynomial of endomorphism is $\varphi$-invariant

Question:
Let $\varphi$ be an endomorphism on a $K$-vector space $V.$  Set $U=\ker f(\varphi)$, where $f$ is a polynomial with coefficients in $K$.  Show that $U$ is a $\varphi$-invariant subspace of $V.$

This question confuses me because I'm not certain that $U$ is non-empty. For example, if $K = \mathbb{Q}$ and $\varphi$ is the identity map, wouldn't $f(x) = x^2 + x + 1$ contradict this claim? In that case, $U = \emptyset.$
Comment: $f(\mathrm{id}) = \mathrm{id}+\mathrm{id}+\mathrm{id}$ is the map sending $x$ to $3x$; this map has kernel $\{0\}$, not empty. And if it *were* empty, then it *would* be invariant! After all, for all $x\in\varnothing$, we have $\varphi(x)\in\varnothing$....
Comment: Yes, but the empty set doesn't contain $0$, so I didn't think it was a subspace. However, that's not really important because I was thinking about polynomials of linear maps the wrong way.
Comment: The empty set is not a subspace, true.
Answer: Hint: Use the fact that $f(\varphi)\circ\varphi=\varphi\circ f(\varphi)$
Comment: That makes sense, thank you!


google plus api : followers' list of a page (javascript)

Question: Are there any solutions that I get a list of followers (and their IDs) of a certain page that I'm managing ? (a page created by my account, different from my account's page)
Tried gapi.client.plus.people.list method with userId replaced by the page's ID, it returns the message 'undefined'. (used 'visible' as collection parameter)
If I use same method with my account ID, it returns the list of people that I added to any of my circles.
Any solutions?
Comment: + if not possible in javascript, is there any language that is capable of solving this problem?
Answer: Not generally available. There is an API for page management which has this functionality (https://developers.google.com/+/api/pages-signup), but it is only available for larger page management systems unfortunately.


Avoid admin users editing other admin users

Question: I'm in a Drupal 7 installation, trying to find a way to avoid admin-users to edit other admin-user's account.
I've created a role for 'content administrators' and this users tasks involve user administration, but I don't want them to be able to edit other content administrators or admin accounts.
I wasn't able to find an option for this or a module providing the functionality and I'm a bit lost about how this can be achieved.
In D6 I guess could use hook_user() to catch an edit and check the target role in order to allow that edit or not, but this hook is gone on D7. The closest thing is hook_user_alter(), but this is called after the edit, so I can't use it.
Any pointers?
Answer: Just use the User Protect module.
This module provides various editing protection for users. The protections can be specific to a user, or applied to all users in a role.
Note: User Protect has a complicated configuration -- please take the time to read the very extensive module help before using it!
The following protections are supported:
<code>username
e-mail address
password
status changes
roles
deletion
OpenID identities
all edits (any accessed via user/X/edit)
</code>
When a protection is enabled for a specified user (or the protection is enabled because the user belongs to a role that has the protection), it prevents the editing operation in question that anyone might try to perform on the user--unless an administrator who is permitted to bypass the protection is editing the specified user. The module will protect fields by disabling them at user/X/edit.
User administrators may be configured to bypass specified protections, on either a global or per-administrator basis.
These protections are valid both when trying to edit the user directly from their user/X/edit page, or using the mass user editing operations.
The module also provides protection at the paths user/X/edit and user/X/delete, should anyone try to visit those paths directly.
Comment: Woah, thanks. It seems was being too picky with my search terms. This works great for me, just what I needed. Also, I like the approach (you just can't see the form if you don't have access to a field/user, it would be a nice way to implement this without a single module).


Como posicionar corretamente os labels na barplot?

Question: Não estou conseguindo posicionar corretamente os nomes numa barplot do R, porque são muito extensos. Meus dados estão desta forma:

Os nomes acabam aparecendo desta maneira:

fator_tecnologico_labels <- c(
  "Facilidade de testar\n e de ser avaliado\n por usuários\n de um modo geral",
  "Utilização de\n desenvolvimento\n e de qualidade\n bem definidos\n por parte\n do fabricante",
  "Compatibilidade\n com a\n infraestrutura\n existente,\n com os\n requisitos/\nnecessidades/\ndemandas,\n e/ou com a\n tecnologia\n em vigor",
  "Facilidade de\n entender,\n utilizar\n e/ou adaptar",
  "Vantagem(ns)\n em relação a\n custos com\n hardware,\n requisitos mínimos\n menos exigentes,\n custos com\n licença ou suporte,\n etc",
  "Maior\n eficiência\n em relação\n à solução,\n livre ou não,\n utilizada\n atualmente",
  "Maior\n confiabilidade\n em relação\n à solução,\n livre ou não,\n utilizada\n atualmente"
)

Como eu posso fazer para que os nomes que estão sobrescrevendo as barras apareçam corretamente?
Comment: O que é "corretamente" nesse caso? O terceiro grupo tem um texto considerevalmente longo, e se você simplesmente *baixar* o eixo X, o resultado pode não ser visualmente agradável. De todas as formas, talvez você consiga ajustar as margens dos rótulos do eixo X com o comando par: http://www.programmingr.com/content/controlling-margins-and-axes-oma-and-mgp/
Comment: @Soriano, você pode postar o código em que você chama a função `barplot`?
Answer: Primeiro eu inverti a orientação do gráfico, colocando as barras na horizontal:
fator_tecnologico_graph <- barplot(
  fator_tecnologico,
  beside = TRUE,
  horiz=TRUE,
  las=1,
  xlim=c(0,110),
  cex.axis = 0.7,
  cex.names = 0.6,
  legend.text = rownames(fator_tecnologico),
  args.legend = list("bottom", bty="n", cex = 0.7),
  col=rainbow(4),
  xpd=FALSE,
  cex.main = 0.9,
  main="Na sua opinião, em que grau estes fatores influenciam\n a adoção de software livre do ponto de vista tecnológico?"
)

Depois eu aumentei a margem esquerda do grafico
par(mar=c(5, 18, 4, 2))

E aí eu obtive algo satisfatório pra mim
Comment: @Soriano: que tal aceitar a solução? :)
Comment: Boa solução. :)
Answer: Uma solução com o ggplot2:
dados <- read.table(text='8 5 4 6 4 4 2
41 58 15 19 19 33 30
60 59 67 54 49 59 56
43 30 66 73 80 56 64', header=F, sep=' ')

fator_tecnologico_labels <- c(
  "Facilidade de testar e de ser avaliado\n por usuários de um modo geral",
  "Utilização de desenvolvimento e de qualidade\n bem definidos por parte do fabricante",
  "Compatibilidade com a infraestrutura existente,\n com os requisitos/necessidades/demandas, e/ou com a tecnologia\n em vigor",
  "Facilidade de entender, utilizar\n e/ou adaptar",
  "Vantagem(ns) em relação a custos com hardware,\n requisitos mínimos menos exigentes, custos com licença ou suporte, etc",
  "Maior eficiência em relação à solução,\n livre ou não, utilizada atualmente",
  "Maior confiabilidade em relação\n à solução, livre ou não, utilizada\n atualmente"
)

# Até aqui tu tem.

dados <- cbind(dados, Label=c('Nenhuma influência', 'Pouca influência', 'Influência considerável', 'Muita influência'))

dados <- reshape(dados, varying = list(c('V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7')), direction='long', idvar='Label', times=fator_tecnologico_labels) # Para usar o ggplot2 os dados precisam estar nesse formato.

require(ggplot2)

grafico <- ggplot(aes(x=time, y=V1, fill=Label), data=dados) + # Informa os dados
geom_bar(stat='identity', position='dodge') + # Informa que tu quer um gráfico de barras
coord_flip() + # Inverte os eixos X e Y
xlab('Frequencia') + # Coloca titulo no eixo X
ylab('Fatores') +  # Coloca titulo do eixo Y
ggtitle("Na sua opinião, em que grau estes fatores influenciam\n a adoção de software livre do ponto de vista tecnológico?") + # Coloca titulo no grafico
scale_fill_hue('Legenda') # Coloca titulo na legenda

grafico

EDIT:
Usando o strwrap() para quebrar o texto.
dados <- read.table(text='8 5 4 6 4 4 2
41 58 15 19 19 33 30
60 59 67 54 49 59 56
43 30 66 73 80 56 64', header=F, sep=' ')

fator_tecnologico_labels <- c(
  "Facilidade de testar e de ser avaliado por usuários de um modo geral",
  "Utilização de desenvolvimento e de qualidade bem definidos por parte do fabricante",
  "Compatibilidade com a infraestrutura existente, com os requisitos/necessidades/demandas, e/ou com a tecnologia em vigor",
  "Facilidade de entender, utilizar e/ou adaptar",
  "Vantagem(ns) em relação a custos com hardware, requisitos mínimos menos exigentes, custos com licença ou suporte, etc",
  "Maior eficiência em relação à solução, livre ou não, utilizada atualmente",
  "Maior confiabilidade em relação à solução, livre ou não, utilizada atualmente"
)

# Quebrando o texto automaticamente (Só tirei os \n do vetor de cima e acrescentei as 3 linhas abaixo)
tamanho <- 40 # O limite de caracteres (ele vai quebrar no espaço anterior a palavra que ultrapassa o limite)
(fator_tecnologico_labels <- strwrap(fator_tecnologico_labels, tamanho, simplify=F)) # Cria uma lista onde cada elemento é um vetor com até 40 caracteres.
(fator_tecnologico_labels <- mapply(paste, fator_tecnologico_labels, collapse='\n')) # Monta o vetor com as labels.

# Até aqui tu tem.

dados <- cbind(dados, Label=c('Nenhuma influência', 'Pouca influência', 'Influência considerável', 'Muita influência'))
dados <- reshape(dados, varying = list(c('V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7')), direction='long', idvar='Label', times=fator_tecnologico_labels) # Para usar o ggplot2 os dados precisam estar nesse formato.

require(ggplot2)

grafico <- ggplot(aes(x=time, y=V1, fill=Label), data=dados) + # Informa os dados
geom_bar(stat='identity', position='dodge') + # Informa que tu quer um gráfico de barras
coord_flip() + # Inverte os eixos X e Y
xlab('Frequencia') + # Coloca titulo no eixo X
ylab('Fatores') +  # Coloca titulo do eixo Y
ggtitle("Na sua opinião, em que grau estes fatores influenciam a adoção de software livre do ponto de vista tecnológico?") + # Coloca titulo no grafico
scale_fill_hue('Legenda') # Coloca titulo na legenda
grafico

Comment: Algo que pode te ajudar a quebrar o texto em tamanhos iguais/parecidos: `strwrap(string, tamanho)`.
Comment: Adicionei um novo exemplo.
Comment: Se eu usar isso dentro do array de labels ele criaria linhas a mais... Qual seria o jeito certo? Desculpa, sou meio noob mesmo no R


Can the general linear model be solved by generalized least squares?

Question: Can the general linear model be solved by generalized least squares?
The model that generalized least squares (GLS) can solve doesn't assume anything on the covariance matrix of the errors, which I think is the same as a general linear model?
Answer:
Yes. "General linear model" is a tag synonym for "multiple regression" at this site. GLS can of course solve multiple regression.
According to the first Wikipedia page, "the errors are usually assumed to follow a multivariate normal distribution. If the errors do not follow a multivariate normal distribution, generalized linear models may be used to relax assumptions about errors". So general linear model can also be solved by other typical estimation methods, like ordinary least squares and maximum likelihood.
I think there is no explicit connection between generalized least squares and general linear model. The key point is how to understand the term "general linear model". If we regard it as a synonym for "multiple regression", then we can also have assumptions about the errors. Wikipedia also addressed "the general linear model is a generalization of multiple linear regression model to the case of more than one dependent variable." In this way, it is another problem about multivariate analysis.
Comment: Thanks! Isn't ordinary least square assuming the covaraince matrix is diagonal and the diagonal entries are the same?
Comment: Yes, the errors are assumed to be homoscedastic and serially uncorrelated to make the OLS estimator **optimal** in the class of linear unbiased estimators. GLS has almost no connection with general linear model, as I edited above.


IBM Filenet IS: Retrieval Cache is full w/documents whose page = 65535

Question: I am relatively new to FileNet Image Services. I am coming into an existing development environment where FileNet Image Services 4.2x is set up for test purposes. As I understand it, we have a 'cache-only' installation. Before last weekend, the retrieval cache was running around 73% full (10GB cache).
The Retrieval cache filled up last weekend. Upon investigating, I found that there were thousands of documents (all of the same size, 80312kb) with a page = 65535. I have yet to discover the source of these documents, but the immediate issue is:
How do I remove/delete these documents from the cache and free up the space used by them?
fyi...I tried deldocs according to the user documentation, but it would not remove these documents. I was able to remove other documents successfully with deldocs.
Note: adding to the Retrieval cache is not an option because of a limitation on disk space. I have scoured the documentation but cannot find any help there...apologies if this is a rudimentary problem.
Thank you in advance for any help you can provide!
Answer: Take a look to the Filenet Image Services 4.2 System Tools Reference Manual
The deldocs command doesn't always suit you because

The deldocs tool deletes documents from the Image Services index
  database and/or the MKF permanent database. It could also delete
  selected documents from cache, given selected settings

Some documents could be in locked or ageable status.
So if you already tried with this command and haved no results you should go for the CSM_tool command.
You will find this tool on page 206, it will allow you to inspect your installation's cache.
Next issue a Listobjects command to see what's going on in there and have a representation of the single document cache status.
Then take a look to the DELETEobjects command, which allows you to delete cache entries by id.
CAUTION: this command, as stated in the documentation, can harm your system so pay attention about what you're doing. To issue this command you will be required to previously launch the ALLOWUPDATEs command, that ask you for username and password in order to modify the cache.
Remember that as reported in the docs:

When listing CSM_tool commands, some might not appear if you have
  not run the ALLOWUPDATES command. To list password-protected
  commands, you must first run ALLOWUPDATES.

You will be also asked to confirm every action and a report of the operation will be logged into specific files stored in folders dependent on your environment.


Is there a module for "mail routing" in Drupal 6?

Question: Is there a module, with D6 support, that allows one to "route" e-mails.
For example, by default, e-mails would be sent out by the regular mechanism, but for some e-mails, say based on their ID or destination domain, where tracking is interesting, they could instead be passed of to a third party service (such as MailChimp, ExactTarget, MailGun etc).
Answer: You could try: https://drupal.org/project/reroute_email
While it's mainly designed to reroute all email to predefined addresses, e.g during development, you could use it as a starting point for similar functionality.
Comment: I've actually looked at that module, as a previous answerer wrote basically the same thing, but shortly afterwards removed the answer. Unfortunately, what it is doing, hook_mail_alter, isn't sufficient, as it allows no control over the actual sending process.
Comment: @Letharion if you need to control the sending process, you can abort the mail send and queue the email your own way, by setting `$message['send'] = FALSE;`
Comment: Please correct me if I'm wrong, but I believe that is not supported in D6.
Comment: My mistake, D6 requires the patch on https://drupal.org/node/800434 to cancel mail send
Comment: Thanks, that issue might actually be worthwhile for me to try to progress. However, even with the ability to "not send e-mails", the functionality that I'm actually after is still missing. :)


Laravel guest middleware do not redirect properly

Question: I created a simple authentication with Laravel 5.6
I'm trying to redirect a logged-in user to dashboard if they go to the login page and redirect a guest to a login page if they go to the dashboard page.
I'm using laravel default middleware (RedirectIfAuthenticated) :
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/dashboard');
        }

        return $next($request);
    }
}

Here is my route :
Route::group([ 'middleware' => ['guest','auth:lecturer'] ], function(){
    Route::get('/', "ViewCont\Auth\LoginController@login")->name("login");
    Route::post('/login', "FuncCont\Auth\LoginController@login")->name("login_f");
    Route::get('/register', "ViewCont\Auth\LoginController@register")->name("register");
    Route::post('/register', "FuncCont\Auth\LoginController@register")->name("register_f");
});

Route::group([ 'middleware' => ['check.user.session','auth:lecturer'], 'prefix' => 'dashboard'  ], function(){
    Route::get('/', "ViewCont\Admin\DashboardController@index")->name("dashboard");
});

Everything works fine when a logged-in user try to access login page, they redirected to dashboard page. But, when a guest try to access login page, the page is error : The page isn't redirecting properly
What did I do wrong ?
Comment: you are using a middleware that redirects someone away if they are authenticated, and a middleware that redirects someone away if they are not authenticated ... and you have different guards in play
Comment: I thought return $next($request) will continue the process
Comment: why would you ever apply the `auth` middleware to a login route? you are saying you have to be authenticated to login, but to be authenticated you have to login ...
Answer: There should be 2 different middlewares. RedirectIfAuthenticated redirects user authenticated user from login page and Authenticate that redirects not authenticated user to login page.
So it seems like you need to remove 'auth:lecturer' middleware from login page cause it should be accessible for guest.
Comment: I need to specify custom guard to the middleware.. That's why I using "auth:lecturer" (To determine guard that the middleware use)
Comment: yeah, but it looks like you will redirect guest to some home page from login page and then will redirect to login page cause the user isn't authenticated. I mean login page should be accessible for guests, try to find another way to pass guard. Or I'm completely don't understand what you try to achieve
Comment: Ahh yes... I finally fixed it.. Thanks
Comment: can you please guide me how to fix this. Because i have a default login and student login. If student access without login then need to go to student login


Backbone.Marionette and Event Aggregator

Question: Referring URL : http://davidsulc.com/blog/2012/04/22/a-simple-backbone-marionette-tutorial-part-2/
I am naive into backbone and event Aggregator. Can you please let me know the reason to use the following line of code.
this.model.addVote();
MyApp.vent.trigger("rank:down", this.model);
it seems some other possibility could be
this.model.addVote();
this.model(rankDown);
or the other way
MyApp.vent.trigger("addVote", this.model
Kindly explain thanks.
Running Sample: http://jsfiddle.net/Irfanmunir/966pG/29/
Answer: Events in general are useful for decoupling objects from each other, while still allowing them to communicate. The event aggregator pattern (or pub/sub pattern) at an application level allows further decoupling by having a 3rd party in the mix: publisher, aggregator, subscriber. This way, neither the publisher nor subscriber have to know about each other. They each know about the event aggregator only.
I wrote up a small article on this a while back:
http://lostechies.com/derickbailey/2012/04/03/revisiting-the-backbone-event-aggregator-lessons-learned/
In this case, the events are used because the model needs to be manipulated in the context of the collection that it belongs to. Rather than going through the model to get to the collection (which it might not be directly assigned to... models are not required to be part of a collection), it's easier and more flexible to raise this event and have it handled somewhere more appropriate.
Comment: the first link is same as second.. maybe just delete reference to old post?
Comment: The link would not open for me, so I have created a gist from the google cache: https://gist.github.com/andreif/6018972


How to find a field name/column name of a field in database where I have only the label of that field?

Question: I am working on an integration part with drupal framework. Here it's hard to  find the table names of the field which is present in the view as I know only the field label name.
Is there any way to sort this out?
Answer: You can derive the database table name by the host entity and the field name. The name schema is ENTITYTYPE__FIELDNAME
Views don't directly show the field name, but you can look at the entity's "Manage field" page to get the field name by label. (e.g. for nodes /admin/structure/types/manage/BUNDLENAME/fields)
Examples:
node__body
node__field_image
users__field_whatsapp
taxonomy_term__field_text

Exception:
Some special fields (like title or created) are stored as a column on the base table of an entity. Base tables follow the schema ENTITYTYPE_field_data, e.g.
node_field_data
users_field_data
taxonomy_term_field_data

Comment: Thanks. Now I am having a field label called summary in the products details page. How to find that field name and it's stored table in database?
Comment: Summary is not a real field, it is the short version of the body field (like an URL field has a title and URL column). Look in the node__body table
Comment: Can you tell me where does the manufacturers list stored in database?


Trigger context by filter value?

Question: I need to essentially trigger a context when a certain filter value is selected.  Basically, in a view, when a filter is selected, based on the value selected I need to display a certain block.
Does anything like this exist?  Or am I going to have to build my own extension to Context?
Answer: With Drupal there are so many way to do things - here is one way to achieve what you need:

Go to admin/blocks and add your block to the region you want it to show up in, then set it to display on only the page for that view
In your theme css hide that block (display:none)
Add some javascript to display the block and bind it to the onchange event for the value you want, either add the js in your module or your theme.

I have not gone into specifics as each step can have variations on how you would like to implement them, but the above is one potential solution to the problem
Using context could work if you submit the view filter to a different path and then set a context to show the block on that path, but if you wnat to do it via an onChange its easier using Js & Css.
Modules that may also help:

http://drupal.org/project/views_hacks
http://drupal.org/project/views_dependent_filters
Answer: There is a patch for the context module to achieve exactly what your are looking for.
I've just installed it and tested it out and it works perfectly.
There is a thread on drupal.org about it here: http://drupal.org/node/904416
Scroll down to post 28 and download the patch.
To run the patch put it in the context module folder, and then run this command:
<code>patch -p1 < 904416.28-context-query-string.patch
</code>
This is assuming you are using a linux terminal. If you want to do this in Windows or Mac then see this post: http://drupal.org/patch/apply
Once you have applied the patch then run update.php (just go to www.your_domain.com/update.php) and then flush the cache (always a good idea).
Now when you edit your context there is a new condition called Query String.
When I tested it out I had a field called category and I wanted my block to appear when it had the value of Javascript so I put "field_category_value=Javascript" as the value of the query string on the edit context page.
One thing to note here is that the block will only appear after the user has clicked Apply on the filter. If you want it to appear and disappear as soon as the value of the select box is changed then you will need to use Andre's solution.
Comment: I think it's easier to apply with `git apply 904416.28-context-query-string.patch`, but YMMV
Answer: I found this module http://drupal.org/project/block_query and it does exactly what I need it to.
It lets you display a block based on query parameters.
Answer: https://www.drupal.org/project/context_query_param
This module introduces a context condition depending on query strings. Views exposed filters also work with query strings. So you can determine context conditions with the filter parameters.

Trigger context by filter value?


Show that there are constants $K$ and $\alpha$ such that $|(e^{At})_{ij}|\leq e^{-\alpha t}K$.

Question: I want to prove that if all eigenvalues of $\textbf{A}$ in the sytem $\dot{\textbf{x}}=\textbf{Ax}$ have negative real parts then there exist constants $K$ and $\alpha$ such that $$|(e^{\textbf{A}t})_{ij}|\leq e^{-\alpha t}K$$ for $1\leq i,j\leq n.$ This has been my proof so far:
\begin{align*}
e^{\textbf{A}t}&=\textbf{X(t)X(0)}^{-1}\text{ where $\textbf{X}$ is the fundamental matrix of solutions,}\\
&=\begin{pmatrix}
e^{\lambda_1t}x_{11}(t)&\cdots&e^{\lambda_nt}x_{1n}(t)\\
\vdots&\ddots&\vdots\\
e^{\lambda_1t}x_{n1}(t)&\cdots&e^{\lambda_nt}x_{nn}(t)
\end{pmatrix}\begin{pmatrix}
a_{11}&\cdots&a_{1n}\\
\vdots&\ddots&\vdots\\
a_{n1}&\cdots&a_{nn}
\end{pmatrix}.
\end{align*} Thus, every component of $e^{\textbf{A}t}$ is of the form
\begin{align*}
(e^{\textbf{A}t})_{ij}=a_{1j}e^{\lambda_1t}x_{i1}(t)+\cdots+a_{nj}e^{\lambda_nt}x_{in}(t).
\end{align*}
So, \begin{align*}|(e^{\textbf{A}t})_{ij}|&=|a_{1j}e^{\lambda_1t}x_{i1}(t)+\cdots+a_{nj}e^{\lambda_nt}x_{in}(t)|\\
&=|a_{1j}e^{(-p_1+iq_1)t}x_{i1}(t)+\cdots+a_{nj}e^{(-p_n+iq_n)t}x_{in}(t)|\\
&=|a_{1j}e^{-p_1t}e^{iq_1t}x_{i1}(t)+\cdots+a_{nj}e^{-p_nt}e^{iq_nt}x_{in}(t)|\\
&\leq e^{-\alpha t}|a_{1j}e^{iq_1t}x_{i1}(t)+\cdots+a_{nj}e^{iq_nt}x_{in}(t)|
\end{align*} where $-\alpha=\min\{-p_1,\ldots,-p_n\}$. From this point, I am stuck at finding $K$. I'd appreciate if someone could help me figure this out and improve my proof.
Answer: Here a somewhat different approach. It gives a bound on the norm $\parallel
\exp [\mathbf{A}t]\parallel $ of $\exp [\mathbf{A}t]$ and hence $\parallel
\mathbf{x}(t)\parallel $ rather than on individual matrix-elements.
I gather from the context that $\mathbf{A}$ is an $n\times n$-matrix and $%
\mathbf{x}\in \mathbb{C}^{n}$. Then we can equip $\mathbb{C}^{n}$ with the
standard inner product  $<\mathbf{x,y}>=\sum_{j=1}^{n}\overline{x_{j}}y_{j}$
and norm squared $\parallel \mathbf{x}\parallel ^{2}=\sum_{j=1}^{n}\overline{
x_{j}}x_{j}$. Next we write
\begin{equation*}
\mathbf{A}=\sum_{j=1}^{n}\lambda _{j}|\mathbf{u}_{j}><\mathbf{v}_{j}|,
\end{equation*}
where $\{|\mathbf{u}_{j}><\mathbf{v}_{j}|\}$ is a bi-orthogonal basis $\ $($<
\mathbf{v}_{j}|\mathbf{u}_{h}>=\delta _{jh}$). Now we expand and estimate
\begin{eqnarray*}
\exp [\mathbf{A}t] &=&\sum_{j=1}^{n}\exp [\lambda _{j}t]|\mathbf{u}_{j}><
\mathbf{v}_{j}| \\
&\parallel &\exp [\mathbf{A}t]\parallel \leqslant \sum_{j=1}^{n}|\exp
[\lambda _{j}t]|\parallel |\mathbf{u}_{j}><\mathbf{v}_{j}|\parallel
\leqslant \sum_{j=1}^{n}\exp [{Re}\lambda _{j}t]\leqslant n\exp [-{
Re}|\lambda _{0}|t]
\end{eqnarray*}
where $\lambda _{0}$ is the eigenvalue with real part closest to $0$. Then
\begin{eqnarray*}
\mathbf{x}(t) &=&\exp [\mathbf{A}t]\cdot \mathbf{x}(0) \\
&\parallel &\mathbf{x}(t)\parallel =\parallel \exp [\mathbf{A}t]\cdot
\mathbf{x}(0)\parallel \leqslant n\exp [-{Re}|\lambda _{0}|t]\parallel
\mathbf{x}(0)\parallel
\end{eqnarray*}
Here $\parallel \mathbf{F}\parallel $ is the sup-norm of the operator $
\mathbf{F}$ (in this case an $n\times n$-matrix)
\begin{equation*}
\parallel \mathbf{F}\parallel =\sup_{\parallel \mathbf{x}\parallel
=1}\parallel \mathbf{F\cdot x}\parallel
\end{equation*}
Answer: If I apply the triangle inequality and use the fact that $\left|e^{iqt}\right|=1$, then the right side of the equation becomes $$e^{-\alpha t}\underline{(\left|a_{1j}x_{i1}(t)\right|+\cdots+\left|a_{nj}x_{in}(t)\right|)}$$. However, I am not certain if the underlined part is the constant $K$ that I am looking for.
Comment: The underlined part doesn't have to be a constant. It's enough if it's bounded by a constant. I suggest trying to see whether the functions $x_{ij}(t)$ are bounded.
Comment: The hint from the book says that the functions $x_{ij}(t)$ are polynomials in $t$ of degree $\leq(n-1)$.
Comment: If $P(t)$ is a polynomial, then $|P(t)|\leq Ce^{\alpha t/2}$ for some $C$ large enough. Proving or remembering this will help you forward.


Rally find query & ordering fields

Question: Two questions somewhat related to each other:
In a "find" / "findAll" query, is it possible to order by multiple fields, e.g.
rallyDataSource.find( ... , 'order': 'ScheduleState, Rank', ...)
such that it will order primarily by ScheduleState, but then by Rank?  (I tried it, but couldn't get it to work - it seemed to only use the first field).
Also, with the example of doing a find query ordered by ScheduleState, it looks like the results are ordered according to the index / progress of the state (i.e. "Defined, then "In-Progress", and so on, and not alphabetically).  Is this observation / assumption correct?  (I'm working on a display that will be made simpler by utilizing this assumption)
Thanks!
Answer: You should be able to sort by multiple fields...
<code>order: 'Name DESC,Rank DESC'
</code>
And yes- ordering by a dropdown field should return the results in the order in which the dropdown items are defined.

Rally find query & ordering fields


PHP não imprime resultado quando igual a 0

Question: Todos os resultados são impressos na tela exceto quando é 0 e eu preciso que o número 0 seja impresso. Se é NULL ele satisfaz a condição abaixo e imprime corretamente o hífen.
if($dados['dado_1']===null){
  echo "

-
	";
}else{
  echo "

".$dados['dado_1']."
	";
}

Comment: essa verificação `===` é somente para dadoos `BOOLEAN`, com `null` não funcionará.
Comment: Opa, valeu, bom saber. Mas mesmo trocando para == não resolve o problema.
Comment: Os dados são do tipo inteiro?
Comment: Não, são do tipo FLOAT
Answer: O mais correto nesse caso é você usar o is_null, porque quando o valor da variável for 0 retornará falso, portanto não cairá no primeiro IF. Minha sugestão de código:
if(is_null($dados['dado_1'])){
  echo "

-
	";
}else{
  echo "

".(string)$dados['dado_1']."
	";
}

Comment: Beleza! Vou trocar para is_null, mas de qualquer modo, mesmo trocando para is_null continua sem exibir o resultando quando é '0'
Comment: Você tem então que indicar que é uma string. Estou alterando a resposta para você ver como faz.
Comment: ainda assim não exibe quando o valor é igual a 0
Answer: Ele deve tá vindo vazio, coloca assim:
echo "

". $dados['dado_1'] ? $dados['dado_1'] : '0' ."
	";

Comment: Essa sintaxe é um "if inline", basicamente eu estou checando se o $dados['dados_1'] tem valor verdadeiro, se sim ele coloca o próprio valor, se não coloca '0'. você já tentou dar um `var_dump` em `$dados['dado_1']` quando ele vem 0?
Comment: Opa meu caro, tendei do jeito que você falou mas continuou sem funcionar. Não houve alteração no resultado. Mas de qualquer modo, poderia me explicar essa sintaxe?
Comment: no var_dump todos os resultados são exibidos inclusive os que tem o valor igual a 0


Meteor: accessing user details on client

Question: I'm trying to access (another) user's details on the client side in meteor. I have a server side method called 'userDetails' that I'm calling from a template helper called 'acc'.
Server method:
'userDetails': function(userId) {
      check(userId, String);
      return Meteor.users.findOne({_id: userId},
                                  {fields: {
                                    "services.facebook.first_name": 1,
                                    "profile.birthday": 1,
                                    "services.facebook.gender": 1,
                                    "profile.location.name": 1
                                  }});
    }

Template helper:
acc: function(_id) {
    Meteor.call('userDetails', _id, function(err, res) {
      if(err) throw error;
      return res;
    });
  }

When I try to access acc.profile.birthday in the template I don't get anything. What could cause this?
Comment: Oh, I'm sorry, I misunderstood. Yes, you can do that. You could try consoling `res` object before returning it just to be sure of what structure the object has.
Comment: You cannot access a Template helper like that. You have to use `acc` in the Template itself to see the output.
Comment: Hi @BlazeSahlzen, are you saying I can't use {{acc.profile.birthday}} in the template? Because that's what I'm doing...
Answer: You have to wrap the return in a else statement.
if(error) {

}
else {
   return res;
}

The call to you method in asynchronous. This means that the callback function will be executed when your server method completes.
If you want to display the result on a template, you have two possibilities:
1/ Use a session.
acc: function(_id) {
  Meteor.call('userDetails', _id, function(err, res) {
    if(err){
    }else{
      Session.set('data', res)
    }

  });
  return Session.get('data')
}

2/ Use Template subscriptions (better solution):
On the server, you publish the data:
Meteor.publish("data", function(){
     return Meteor.users.findOne(...)
});

On the client, you subscribe:
Template.mytemplate.onCreated(function () {
    Template.instance().subscribe("data");
});

Then directly on the client you will be able to create a helper and call the findOne.
In the html:
  {{#if Template.subscriptionsReady}}
    {{#each myHelper}}
       {{acc.profile.birthday}}
    {{/each}}
  {{else}}

Loading...

  {{/if}}

Important Notice about users:
Users profile are editable by default. Please read this: https://dweldon.silvrback.com/common-mistakes
Comment: Thanks @hlx, it's a nice and comprehensive answer, however I'm not sure that I would have a second helper to return the session.
Comment: @L4zl0w I updated the answer so you won't need a second helper. Please mark the answer so the question does not appear a unanswered anymore
Answer: Meteor calls are asynchronous calls, that is why your helper is not returning any data.
Best option here is to either use Session or ReactiveVar or ReactiveDict
I'll use Session option here
acc: function(_id) {
  Meteor.call('userDetails', _id, function(err, res) {
    if(err){

    }else{
      Session.set('userDetails', res)
    }

  });
  return Session.get('userDetails')
}

In your html you can use this helper like this
{{#if acc}}
  {{name}}
  ...
{{else}}

Information not found

{{/if}}

Comment: Shouldn't the `return` statement be outside the Method call?
Comment: Thanks, I managed to make it work with this approach.


Docker: connection reset by peer

Question: I have a physical CentOS 7 host (A) on my LAN (192.168.0.0/16). SElinux is disabled, and firewalld is disabled. It is the only changes I made from install defaults.
I have an other host (B) on that LAN; (B) has services like www, ssh, icmp.
At this step, I can play with (B) from (A):
$ ping *(B)*
 ... success ...
$ curl google.com
 ... success ...
$ curl *(B)*
 ... success ...
$ mysql *(B)*
 ... success ...

Everything is running fine.
Now, I install Docker Community on (A):
$ yum check-update
$ curl -fsSL https://get.docker.com/ | sh
$ systemctl start docker

And now the results of such commands again on (A):
$ ping *(B)*
 ... success ...
$ curl google.com
 ... success ...
$ curl *(B)*
 ... Recv failure: Connection reset by peer ...
$ mysql *(B)*
 ... Connection reset by peer ...

So basically, once Docker is setup and active, all TCPs connections from (A) (the host OR a docker container) to my LAN failed. Such error are likely to be a firewall issue, because TCPs connections from (B) to (A) are still available.
However I check iptables on (A) for REJECT rules or policies mistakes and there is absolutely nothing. I even clean iptables entirely on (A), and the problem still occur.
If all firewalls/security systems are disabled or empty of restrictives rules, and with permissives policies, I don't understand where is the problem and where I have to check on my CentOS system to solve the issue.
Could you please help ?
Answer: This sounds like the docker bridge IP may be colliding with IP's on your network. If this is a completely clean installation and there wasn't a /var/lib/docker from before, then look into adjusting the bip setting in the docker daemon. You'll know this is an issue if docker network inspect bridge shows an IP range you need, and netstat -nr (or ip r) shows the IP range used by docker0 also being used by other interfaces or as a gateway. To update the bip setting, see https://docs.docker.com/engine/userguide/networking/default_network/custom-docker0/
Comment: I have both adjusting the docker bip and modify IP/Mask on all my interfaces from all my hosts to avoid collisions, and it works. Thanks !

Docker: connection reset by peer


Problem with time 1 minute and request.security

Question: I wanted to know why when I want to see the crossover and crossunder that occurred in the 4-hour timeframe in the 1-minute timeframe, it is not displayed in the table for the symbol related to the 4-hour timeframe, but conversely, I can see the crossover in the 1-minute timeframe in the 4-hour timeframe.
Please, if you have any information, I would appreciate your help. Thank you.
See a picture of my problem
<code>input_daily = input.timeframe("1", "Daily Time Frame")
input_mine = input.timeframe("240", "Daily Time Frame")
//
isBullish(timeframe) =>
    s1 = ta.crossover(periodLine103, periodLine216)
    s2 = ta.crossunder(periodLine103, periodLine216)
    crossoverResult = request.security(syminfo.tickerid, timeframe, s1)
                       and not request.security(syminfo.tickerid, timeframe, s2)
    crossoverResult

//
isBearish(timeframe) =>
    s1 = ta.crossover(demo1, demo2)
    s2 = ta.crossunder(demo1, demo2)
    crossunderResult = request.security(syminfo.tickerid, timeframe, s2)
                         and not request.security(syminfo.tickerid, timeframe , s1)
    crossunderResult

tsmeee = isBullish(input_daily)
tsmeee1 = isBearish(input_daily)
TM240 = isBullish(input_mine)
TM1240 = isBearish(input_mine)

var table myTable = table.new(position = position.top_right, columns = 30, rows = 3, bgcolor = #e1e1e1, frame_color = #191919, frame_width = 1, border_width = 1, border_color = #232323)
table.cell(myTable, column = 1, row = 0, text = "1")
table.cell(myTable, column = 2, row = 0, text = "240")

table.cell(myTable, column = 0, row = 0, text = "time", bgcolor = #f0f0f0)
table.cell(myTable, column = 0, row = 1, text = "cross", bgcolor = #f0f0f0)

if tsmeee
    table.cell(myTable, column=1, row=1, text="▲", text_color=color.rgb(26, 178, 59))
else if tsmeee1
    table.cell(myTable, column=1, row=1, text="▼", text_color=color.rgb(151, 17, 17))

if TM240
    table.cell(myTable, column=2, row=1, text="▲", text_color=color.rgb(26, 178, 59))
else if TM1240
    table.cell(myTable, column=2, row=1, text="▼", text_color=color.rgb(151, 17, 17))

</code>
Answer: There is no magic, the 1 minute timeframe has simply more granularity.
Crossover checks a previous value-pair and a current value-pair, and that's it. If the values in those value-pairs have swapped place (like: prev. low is now higher than prev high), that's a crossover.
If you look at a single candle, you can see when the Open and Close price happened however you cannot see how the price moved intrabar. Maybe it's the High that was reached first, then Low, or the opposite.
Based on this, your conditions might trigger with a different result or in a different order in a lower timeframe. Just imagine you have a Stop Loss and a Take Profit set up, then the next candle goes over both. Depending on which was reached first, you either win or lose the trade.


What does a Java array of any type actually look like in file?

Question: I'm learning about Java arrays and I read something along the lines of that Java arrays are actually objects. Does that mean that when I make an array, say int[] array = new int[10], the underlying mechanism is really just a class file that gets created with 10 instance variables of type int that I can access with array[(0-9)]? If so, how does it do that and how does it work? And what is the conceptual reason (if any) for the syntax to declare arrays the way it is (so I can remember the syntax rules easier)?
This is what I read in the textbook I am learning from:

Creating and Accessing Arrays
In Java, an array is a special kind of object, but it is often more
useful to think of an array as a collection of variables of the same
type. For example, an array consisting of a collection of seven
variables of type double can be created as follows:
double[] temperature = new double[7];

This is like declaring the following seven strangely named variables
to have the type double:
temperature[0], temperature[1], temperature[2], temperature[3],
temperature[4], temperature[5], temperature[6]

Comment: Arrays are implemented directly in the JVM, not inside Java. They are not implemented as "object" under the hood.
Comment: There is no class _file_, but a `java.lang.Class` _object_ is created in memory for each array type; these are seen if you attempt to print or use `.toString()` on an array, which has no override and thus inherits `java.lang.Object` which prints the name of the 'class' and hashcode of the object, and the name looks like e.g. `[L`. There are actually _two_ syntaxes in Java: the purer algol-based syntax like `int[] foo` and the C-style syntax like `int foo[]`; see the Java Language Specification (JLS) available at https://docs.oracle.com/javase/specs/index.html section 10.2.
Comment: The "conceptual reason" is so declaring arrays is easy. No class *file* is created when you declare objects, array or not.
Answer: in the code where you allocate an array:
int myInts = new int[20];

The JVM will allocate a block the size of 20 times the size of an integer (4 bytes) in the heap. The array is accessed / indexed using the index offset times the primative object size (again in this case, 4 bytes)
Also, I believe that array indexing is built directly into Java byte codes.
--- Edit ---
On array indexing being built in: If you look here, you can confirm the aaload JBC command / retrieve from an array: https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings
Comment: The block of memory is actually the Object Header + 4 bytes for the Array Length + array data (e.g. the 4 * 20 = 80 bytes).
Comment: @Andreas ... If you want to get all technical up on me - sheesh! But yes, true.
Answer: Arrays in Java are objects, but they are not instances of any class. There are no array classes -see
On the object types - section 4.3.1:

An object is a class instance or an array.

Array objects are similar to classes with a number of variables, but an array of 10 doubles is not a class. It's more like, "array of doubles" is one single type, and the number of instance variables is stored within the object itself, in the array's length field.
On arrays - section 10:

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2).
An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use non-negative integer index values. These variables are called the components of the array.

How arrays are implemented in a JVM is another matter. In OpenJDK, the memory layout for array objects includes a pointer to an "ArrayKlass" which is an internal representation for the array type. The size of the array is included within the array object, and the array objects themselves can have an arbitrary size. This is different from objects that are class instances: class instances are always the same size.
Comment: *"There are no array classes"*. Sure there are, e.g. `int[].class` is an array class. --- Javadoc of [`isArray()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isArray--) says: *"Determines if this `Class` object represents an **array class**."*
Comment: @Andreas incorrect - see [JLS 10.8](https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.8) "Every array has an associated Class object ... **Although an array type is not a class** ..."


How to count rows in a logical vector

Question: I have a data frame called source that looks something like this
185  2002-07-04      NA      NA 20
186  2002-07-05      NA      NA 20
187  2002-07-06      NA      NA 20
188  2002-07-07  14.400   0.243 20
189  2002-07-08      NA      NA 20
190  2002-07-09      NA      NA 20
191  2002-07-10      NA      NA 20
192  2002-07-11      NA      NA 20
193  2002-07-12      NA      NA 20
194  2002-07-13   4.550   0.296 20
195  2002-07-14      NA      NA 20
196  2002-07-15      NA      NA 20
197  2002-07-16      NA      NA 20
198  2002-07-17      NA      NA 20
199  2002-07-18      NA      NA 20
200  2002-07-19      NA   0.237 20

and when I try
> nrow(complete.cases(source))

I only get NULL
can someone explain why this is the case and how can I count how many rows there are without NA or NaN values?
Comment: You could also use `nrow(na.exclude(source))` (IMHO you should not name your data source as it's a common used base R function)
Answer: Instead use sum. Though the safest option would be NROW (because it can handle both data.frams and vectors)
sum(complete.cases(source))
#[1] 2

Or alternatively if you insist on using nrow
nrow(source[complete.cases(source), ])
#[1] 2

Explanation: complete.cases returns a logical vector indicating which cases (in your case rows) are complete.

Sample data
source <- read.table(text =
    "185  2002-07-04      NA      NA 20
186  2002-07-05      NA      NA 20
187  2002-07-06      NA      NA 20
188  2002-07-07  14.400   0.243 20
189  2002-07-08      NA      NA 20
190  2002-07-09      NA      NA 20
191  2002-07-10      NA      NA 20
192  2002-07-11      NA      NA 20
193  2002-07-12      NA      NA 20
194  2002-07-13   4.550   0.296 20
195  2002-07-14      NA      NA 20
196  2002-07-15      NA      NA 20
197  2002-07-16      NA      NA 20
198  2002-07-17      NA      NA 20
199  2002-07-18      NA      NA 20
200  2002-07-19      NA   0.237 20")

Answer: complete.cases returns a logical vector that indicates the rows which are complete. As a vector doesn't have a row attribute, you cannot use nrow here, but as suggested by others sum. With sum the TRUE and FALSE are transformed to 1 and 0 internally, so using sum counts the TRUE values of your vector.
sum(complete.cases(source))
# [1] 2

If you however are more interested in the data.frame, which is left after you exclude all non-complete rows, you can use na.exclude. This returns a data.frame and you can use nrow.
nrow(na.exclude(source))
# [1] 2

na.exclude(source)
#             V2    V3    V4 V5
# 188 2002-07-07 14.40 0.243 20
# 194 2002-07-13  4.55 0.296 20

Answer: You can even try:
source[rowSums(is.na(source))==0,]
#     V1         V2    V3    V4 V5
# 4  188 2002-07-07 14.40 0.243 20
# 10 194 2002-07-13  4.55 0.296 20

nrow(source[rowSums(is.na(source))==0,])
#[1] 2

How to count rows in a logical vector


Change of variable with non bijective function

Question: I have a logistic regression model: $softmax(WX)$ where $W$ is my parameter matrix and $X$ is my input. I want a density function over the outputs of that model.
Say I know that my $X$ are distributed according to some density $p$. From the change of variables I know that the density of the outputs will be something like $p'(x) = p(x) det|J^{-1}|$ where $J = \frac{\partial{softmax(WX)}}{\partial{X}}$.
However, this holds only for a bijective function $softmax(WX)$.
What can I do if this is not the case - especially if $W$ is not square?
Comment: divide the domain of your non-bijective function into parts where the function is bijective and then apply change of variables. This might work.
Answer: The generalization of the change of variable formula to the non-bijective case is generally hard to write out explicitly, check http://en.wikipedia.org/wiki/Probability_density_function#Multiple_variables
which essentially formalizes mpiktas's suggestion
Answer: I found this article
https://en.wikibooks.org/wiki/Probability/Transformation_of_Probability_Densities
excellent!
Comment: +1 I have been looking for the $\mathbb{R}^n \mapsto \mathbb{R}^m$ case.


How to install zend framwork on Xampp version 1.7.1 in windows7 eternity

Question: I have downloaded ZendFramework-1.11.11 and it has been extracted and then there is zend folder inside library folder of ZendFramework-1.11.11.And then it is copied and paste in the htdocs of xampp. My Xampp version Xampp win32 1.7.1 or Xampp win32 1.7.7
And Then what to do.To check in browser how to check,like localhost/myzendproject/test1.php
I need step by step guide.And also in test.php what to write for checking and in browser what will be URL.
I need your hand. Pls, guied me step by step
Thank you
Answer: The Zend Framework Quickstart walks you through downloading Zend Framework, setting up the include_path in PHP, creating a ZF project, and creating a virtual host in Apache to map to your newly created Zend Framework project.
I'd start there and if you get stuck in a particular spot, we're happy to help.
Answer: Installing Zend framework does not depend on the system where it will run. Follow the following article for the correct walk-through. It denotes every actions needed to get started.
Installing Zend Framework On Windows


Comando SQL para exibir registros específicos do campo "id"

Question: Qual comando SQL exibiria os registros onde o campo id fosse 22, 23, 25 e 27?
Answer: Seria algo como:
SELECT * FROM tabela WHERE id IN (22,23,25,27);

O Operador IN:
O operador IN permite que você especifique vários valores em uma cláusula WHERE.
Sintaxe:
SELECT column_name(s)
 FROM table_name
 WHERE column_name IN (value1,value2,...);

Também funciona com strings:
SELECT * FROM Customers
 WHERE City IN ('Paris','London');

Fonte: w3schools
Comment: O IN é mais "limpo" ...
Answer: Basicamente o mesmo da sua pergunta anterior. Só que agora usa o OR para selecionar mais do que um, ou seja 22 OU 23 OU 25 OU 27, qualquer um deles será selecionado.
SELECT * FROM tabela WHERE id = 22 OR id = 23 OR id = 25 OR id = 27;

Coloquei no GitHub para referência futura.
Comment: Também funciona, eu preferi usar esta forma que é mais básica porque entendi que você está iniciando e precisa entender a diferença entre `AND` e `OR`. No caso do `IN` você está dizendo "quero que seja qualquer linha que esteja DENTRO desta faixa de valores. Na prática dá o mesmo resultado". Quando você ficar mais experiente vai sempre preferir usar o `IN` **neste** caso de ser uma lista de dados. Em outros casos, só o `OR` vai resolver.
Comment: Por que não usar AND?
Comment: `AND` significa `E`, certo? Então quando você usa o AND, você quer que ambas as condições sejam verdadeiras. Se trocasse o `OR` por `AND` neste ´SELECT`, não retornaria nada. Porque qual linha teria o is 22 E 23 E 35 E 27. Nenhum! Para isto cada linha teria que ter mais de um `id` e pelo modelo mostrado isto é impossível. Podemos interpretar o `AND` como excludente, enquanto que o `OR` é inclusivo, é somador, ele adiciona tudo o que se encaixa nas condições.
Comment: Pq com and o id teria de ser igual a 22 e 23 e ... , impossível.
Comment: E quanto a usar IN(22,23,25,27);?
Comment: Será que m algo errado aqui para ter negativo?
Comment: `IN(1,2,3,n...)` é esteticamente mais bonito e mais simples de digitar, mas dá no mesmo de id = 1 or id=2 or id=3...
Comment: Você também pode fazer isso: `...where id IN(1,2,3) or id IN (4,5,6)` e também pode negar: `...where id NOT IN(1,2,3)`
Comment: E se quiser ordenar por unidade, faça algo assim: `... order by FIELD(id, 22,23,25,27)`
Answer: melhor forma! vai selecionar os campos como quer
SELECT * FROM tabela WHERE id = 22 and id REGEXP '(23|25|27)';


log out page with codeigniter

Question: I'm learning codeigniter. After a user logs in when he clicks on the log out button he goes back to the login page, but if he clicks on the browser back button he goes back to the connection page again. So the session is kept in the browser. How to redirect to the login page instead.
code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
public function __construct()
{
    parent::__construct();

    $this->load->model('user_model');

}
 public function index()
{

    if($this->session->userdata('logged_in'))
    {
        $session_data = $this->session->userdata('logged_in');
        $data['nom'] = $session_data['nom'];
       redirect('user/connection_Ok');
    }
    else
    {
        //If no session, redirect to login page
        $this->login;

    }

}
public function logout()
{
    $this->session->unset_userdata('logged_in');
   // session_destroy();
    $this->session->sess_destroy();
 redirect('login');

}

Comment: thanks for your reply  i would to return to the login page again if user clicks on the browser back button just after log out. It
Comment: Please note that I turned my previous comments into an answer.
Answer:
when he clicks on the log out button he goes back to the login page, but if he clicks on the browser back button he goes back to the connection page again. So the session is kept in the browser.

I think there's some confusion here... if he clicks "logout", your logout controller destroys the session, period.  Using the browser's "back" button cannot reverse this action or restore his session.
In other words, just because the cached page "looks like" he's still logged in, does not mean he is still logged in.  As soon as he tries to access restricted content, he will not be authorized since his previous session was already destroyed.

How to redirect to the login page instead.

You can't stop users from clicking the browser's "back" button, nor can you easily control what happens when they do.  The browser simply loads the cached version of the previous page without reloading it... it's just how browsers work.
JavaScript will give you access to things like browser history, but there is no perfectly reliable method for intercepting the "back" button.  No matter how comprehensive or complex the solution, the user can simply disable JavaScript and defeat it.
However, if you program a robust authorization system, the user will automatically be taken to a login page anytime they try to access restricted content without being logged in.

FYI - for CodeIgniter, I recommend you use a proven authorization system so you don't have to reinvent the wheel or worry about security.  I like Ben Edmund's Ion Auth, but there are a few other solutions out there for CodeIgniter... just do your research.
Comment: it's not that i want to prevent user to click on browser back button but when he does he should redirect to the page he's just because he's just logged out
Comment: @baptpro, as I also stated, *"nor can you easily control what happens when they do"* - that is because the back button loads a cached version of the page and does not reload anything.
Comment: ok, as a learner of ci, i'm gonna learn more. An exemple of my case is facebook. After i log out on facebook, and i click on browser back button i'm redirected to the login page again, So my connection page can be reached only after i log in. I hope you see what i mean !
Comment: @baptpro, I did not say it was impossible... but have you looked at the source code of a Facebook page?  There is a TON of JavaScript written by a large team of engineers for an audience of nearly a billion users.  Not a good comparison.  Although I linked to a JavaScript solution in my answer that will detect the back button, but to prevent people from bypassing it, you'll probably have to then design a website that will not operate when JavaScript is disabled.
Answer:
To disable the browser's cache: add HTTP headers to the protected pages
Always enable the secure http protocol (https) for the pages to protect; otherwise, cache may not be disabled on some browsers (Safari).

Headers are:
Cache-Control: no-cache, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0
PS: no any <meta cache-control> tags are needed in the HTML page; http headers take precedence.

log out page with codeigniter


Bound for independet set of a graph

Question: Show that for all graphs, $\alpha(G)\geq\sum_{v\in V(g)}(d(v)+1)^{-1}$, where $d(v)$ is the degree of the vertex, $V(G)$ is the vertex set of $G$, and $\alpha(G)$ is the cardinality of the biggest $k-clique$ in the complement of $G$.
I tried to use induction on $|V(G)|$, on $\alpha(G)$, on $\delta(G)$ and tried to use bounds like $\alpha(G)\geq \lceil\frac{n}{\chi(G)}\rceil$, but without results. Maybe working on Random Graphs could work, but I don't know what random variable should I use (I prefer solutions without using probability, for now).
Answer: We need to show an existence. With your distaste for probabilistic methods, that means we should try to construct a large enough anti-clique. How? One element at a time.
Start with a vertex $v_1$ of minimal degree $d$ in $G$. Now, nothing else in our anti-clique can have an edge to $v_1$, so we'll cut $G$ down to a new graph $G_1$ by removing $v_1$ and all of the vertices that are linked to it. What does this do to the sum $S(G)=\sum_{v\in V(G)}(d(v)+1)^{-1}$? Each $w$ removed had at least $d$ edges, so we subtract at most $\frac1{d+1}$ for each of the $d+1$ vertices removed. The remaining vertices may have had some of their edges removed, which then increases the sum. So, then, $S(G_1) \ge S(G)-1$.
That's basically what we need; we can keep going until we run out of vertices and $S$ hits zero (at least $S(g)$ steps), or we can use induction, applying the result on the graph $G_1$ with fewer vertices.
The key to making this work was that one innocuous line - choose a vertex of minimal degree. It's common sense to avoid vertices with too many edges, and it turns out going to the extreme is exactly what we need.
Comment: Just to make sure I understand: Induction + $\alpha(G)-1 \geq \alpha(G_{1}) \geq S(G_{1}) \geq S(G)-1$ finishes the proof, right?
Comment: Yes, that's right.

Bound for independet set of a graph


How to get a Standard Error for a Poisson Variable with Exposure?

Question: I'm looking over some work performed by a consultancy and I'm unsure whether the standard error formula they have used is correct, and the subsequent conclusions they have drawn are erroneous.
They have provided a Standard Error between the difference in observed claim frequencies and modelled claim frequencies, and then checked whether the modelled frequency lies between the observed 95% Confidence Interval.
The Standard Error Formula they have used is:
$\sqrt{\frac{Observerd Frequency * (1 - Modelled Frequency)}{Exposure}}$.
However I would have thought a more appropriate Standard Error would be along the lines of the usual Standard Error for a Proportion: $\sqrt{\frac{Observerd Frequency * (1 - Observed Frequency)}{Exposure}}$.
My problem is I don't know how appropriate is it to use the Modelled Frequency in the Standard Error Calculation?
The data looks like this:

Sum Insured Band: \$0 - \$5,000
Exposure (Years): 27,233
Observed Claims: 1271
Modelled Claims:  1433
Observed Frequency: 4.7
Modelled Frequency: 5.3

I've had a look around at disease incidence and claims frequency standard error literature on google, but haven't really found anything concrete.
Thanks for any help.
Answer: You state the data are Poisson.
Why do you try to use a standard error for a binomial proportion?
Where do the modelled numbers come from? If they're based on a model applied to data they have their own standard error which you can't just ignore. If it's from the same data, the two estimates will also be dependent in some way.
When you say "observed claims" you mean "observed claim numbers" or "observed claim count", right?
Let's take the Poisson model as a given. So the observed number of claims in exposure period $i$ will be $Y_i \sim \text{Pois}(\mu_i)$, where $\mu_i = \lambda m_i$.
Hence $\text{Var}(Y_i) = \mu_i = \lambda m_i$.
Therefore, $\text{Var}(Y_i/m_i) = 1/m_i^2  \text{Var}(Y_i) = \lambda / m_i$.
(The usual estimate of that variance is just the sample frequency itself.)
Our only issue now is to figure out what the variance of the modelled value is, and its covariance with the observed, and then we can compute a standard error. You haven't given enough information to work that out.
Comment: Since the business thinks along "frequency" ie Claim Count / Exposure, to keep the output here in a similar manner. You are correct "Observed Claims", is the count of Claims occuring in that exposure period.
Comment: That explains why you'd *scale* the Poisson by exposure to compute *frequency*, equivalenty, *rate*. It doesn't explain why you treat it as binomial. The exposure isn't a count.


Get the value of other attribute in functional react component?

Question: I want to retrieve the attribute of the functional react component.
<DynamicComponentWithNoSSR mode="html" onChange={onHtmlChange} htmlCode={`<h1>dasdasd</h1>`}/>

get the value of htmlCode in onHtmlChange function.
const onHtmlChange = (e) =>{
            console.log(e);
    }

Answer: I think htmlCode is already a part of your props.
const DynamicComponentWithNoSSR = ({ onChange, htmlCode }) => {

   const onHtmlChange = () => {
      onChange(htmlCode) //return HTML back to your upper component
   }

   //whenever HTML code get updated, we call `onHtmlChange` to update `htmlCode`
   useEffect(() => {
     onHtmlChange()
   }, [htmlCode])

   return
Whatever you want here

}

Your upper component can be like this
const UpperComponent = () => {

   const onHtmlChange = (htmlCode) => {
     console.log(htmlCode);
   }

   return <DynamicComponentWithNoSSR mode="html" onChange={onHtmlChange} htmlCode={`<h1>dasdasd</h1>`}/>
}

BUT I'm wondering one case, if htmlCode is already dynamic (not static value) in UpperComponent, you can access htmlCode value directly instead of via props of DynamicComponentWithNoSSR


Parameter passing multiple values using void pointer

Question: I want to pass multiple arguments to a function using a void pointer.
void* function(void *params)
{
//casting pointers
//doing something
}
int main()
{
  int a = 0
  int b = 10;
  char x = 'S';
  void function(???);
  return 0;
}

I know that I have to cast them to a certain variable in my function but I do not know how I can pass my 3 arguments as one void pointer to my function.
I have searched for this problem know quite some time but I could not find anything that would help me.
Comment: Create a struct with whatever members you need and pass a pointer to that.
Comment: @Mat: ... emphasising ***struct***.
Comment: Good idea I am currently using two structs. One like this struct {void *value1; void * value2}params. And one struct that has two integers how can I pass my second struct in my first void *value struct?
Comment: @Mat - Why answer in the comments?
Comment: @StoryTeller: because the question isn't clear enough to answer. Why a `void*`? Are the arguments fixed or is the OP looking for `varargs`? Or some something else entirely (e.g. try to inspect the caller's stack or something weird like that)?
Comment: @Mat - Then ask for clarifications. Honestly, that reads like an excuse.
Comment: @Mark: Please add clarifications to the question itself as an update. There is an "edit"-button below the question.
Answer: You could do it like this:
struct my_struct
{
   int a;
   int b;
   char x;
}

void * function(void * pv)
{
  struct my_strcut * ps = pv; /* Implicitly converting the void-pointer
                              /* passed in to a pointer to a struct. */

  /* Use ps->a, ps->b and ps->x here. */

  return ...; /* NULL or any pointer value valid outside this function */
}

Use it like this
int main(void)
{
  struct my_struct s = {42, -1, 'A'};

  void * pv = function(&s);
}

Following up on the OP's update:
struct my_struct_foo
{
   void * pv1;
   void * pv2;
}

struct my_struct_bar
{
   int a;
   int b;
}

void * function(void * pv)
{
  struct my_strcut_foo * ps_foo = pv;
  struct my_struct_bar * ps_bar = ps_foo->pv1;

  /* Use ps_foo->..., ps_bar->... here. */

  return ...; /* NULL or any pointer value valid outside this function */
}

Use it like this
int main(void)
{
  struct my_struct_bar s_bar = {42, -1};
  struct my_struct_foo s_foo = {&s_bar, NULL};

  void * pv = function(&s_foo);
}

Comment: Thank you very much alk that was exactly what I was looking for. Now I understand what I have to do.
Answer: The void* is used as a pointer to a "generic" type. Hence, you need to create a wrapping type, cast convert to void* to invoke the function, and cast convert back to your type in the function's body.
#include <stdio.h>

struct args { int a, b; char X; };
void function(void *params)
{
  struct args *arg = params;
  printf("%d\n", arg->b);
}
int main()
{
  struct args prm;
  prm.a = 0;
  prm.b = 10;
  prm.X = 'S';
  function(&prm);
  return 0;
}

Comment: Nitpicking: Your code does not cast at all. What happens is called "implicit conversion".
Comment: I thought type conversion were more like integer promotion or boolean conversions.. (?)
Comment: In C there are two kinds of converting types: "Implicit Conversion" (promotion is one of this) and "Explicit Conversion", which is applied using a casting operation. Here `int i = 42; double d = ((double) i) / 7;` `i` is converted explicitly (to `double`) and `7` implicitly (to `double`) via promotion.