Ext js 4.0.2a: Change tab color

Question: I need to change the color of a single tab on an action.
so I do this
activeTab.tab.el.dom.className = 'tv-x-tab';

And add CSS styles.
 /* line 58, ../../extjs/themes/stylesheets/ext4/default/mixins/_frame.scss */
 .tv-x-tab .x-tab-default-top {
 -moz-border-radius-topleft: 4px;
 -webkit-border-top-left-radius: 4px;
 -o-border-top-left-radius: 4px;
 -ms-border-top-left-radius: 4px;
 -khtml-border-top-left-radius: 4px;
 border-top-left-radius: 4px;
 -moz-border-radius-topright: 4px;
 -webkit-border-top-right-radius: 4px;
 -o-border-top-right-radius: 4px;
 -ms-border-top-right-radius: 4px;
 -khtml-border-top-right-radius: 4px;
 border-top-right-radius: 4px;
-moz-border-radius-bottomright: 0;
-webkit-border-bottom-right-radius: 0;
-o-border-bottom-right-radius: 0;
-ms-border-bottom-right-radius: 0;
-khtml-border-bottom-right-radius: 0;
border-bottom-right-radius: 0;
-moz-border-radius-bottomleft: 0;
-webkit-border-bottom-left-radius: 0;
-o-border-bottom-left-radius: 0;
-ms-border-bottom-left-radius: 0;
-khtml-border-bottom-left-radius: 0;
border-bottom-left-radius: 0;
padding: 3px 3px 0 3px;
border-width: 1px 1px 0 1px;
border-style: solid;
background-image: none;
background-color: white;

}

/* line 91, ../../extjs/themes/stylesheets/ext4/default/mixins/_frame.scss */
  .tv-x-tab .x-nlg .x-tab-default-top-mc {
  background-image: url('/themes/images/default/tab/tab-pnl-top-bg.gif');
  background-color: white;
 }

 /* line 104, ../../extjs/themes/stylesheets/ext4/default/mixins/_frame.scss */
 .tv-x-tab .x-nbr .x-tab-default-top {
  padding: 0 !important;
  border-width: 0 !important;
 -moz-border-radius: 0px;
 -webkit-border-radius: 0px;
 -o-border-radius: 0px;
 -ms-border-radius: 0px;
 -khtml-border-radius: 0px;
 border-radius: 0px;
 background-color: transparent;
 background-position: 1100404px 1000000px;
}

 /* line 147, ../../extjs/themes/stylesheets/ext4/default/mixins/_frame.scss */
 .tv-x-tab .x-nbr .x-tab-default-top-tl,
 .tv-x-tab .x-nbr .x-tab-default-top-bl,
.tv-x-tab .x-nbr .x-tab-default-top-tr,
.tv-x-tab .x-nbr .x-tab-default-top-br,
.tv-x-tab .x-nbr .x-tab-default-top-tc,
.tv-x-tab .x-nbr .x-tab-default-top-bc,
.tv-x-tab .x-nbr .x-tab-default-top-ml,
 .tv-x-tab .x-nbr .x-tab-default-top-mr {
  zoom: 1;
  background-image: url('/themes/images/default/tab/tab-pnl-top-corners.gif');
}
/* line 168, ../../extjs/themes/stylesheets/ext4/default/mixins/_frame.scss */
.tv-x-tab .x-nbr .x-tab-default-top-ml,
.tv-x-tab .x-nbr .x-tab-default-top-mr {
 zoom: 1;
 background-image: url(/themes/images/default/tab/tab-pnl-top-sides.gif');
  background-position: 0 0;
}

 /* line 200, ../../extjs/themes/stylesheets/ext4/default/mixins/_frame.scss */
 .tv-x-tab .x-nbr .x-tab-default-top-mc {
  padding: 0 0 0 0;
 }

But its not working.
What am I doing wrong here? Can somebody suggest how to do this.
I have to change only the color of a single tab.
Answer: You've got a couple of mistakes here.

You're wiping out all the class names and replacing them with "tv-x-tab" instead of      adding that class name, which is what you seem to want to do since your CSS still depends on  "x-tab-default-top" being there.
So assuming activeTab is a reference to your current active tab, change
activeTab.tab.el.dom.className = 'tv-x-tab';
to
activeTab.tab.el.addCls('tv-x-tab');
That will add the class name without removing the other ones.
Your CSS selector is not proper syntax. You've written it as if "x-tab-default-top" is a child of "tv-x-tab" but they are actually the same element, so you need to remove the space between selectors.
Change
.tv-x-tab .x-tab-default-top {

to
.tv-x-tab.x-tab-default-top {

That should set you up.

Ext js 4.0.2a: Change tab color


Limit of a composite function.

Question: Here:
$$\lim_{x\to n} {f(g(x))}$$
When the exact amount of $g(x)$ in $x=n$ is k and it's Constant in that area, what do we do next?
Should I approach the $f(x)$ in k or just calculate $f(k)$?
And why?
I know it's superficial but it confused me.
Thanks in Advance.
Comment: if $f, g$ are continuous at $a,$ then $\lim_\limits {x\to a} (f\circ g)(x) = (f\circ g)(a)$
Comment: You have to take the limit for $f$ also.
Answer: I assume the case you intend to describe is as follows:

$g(n) = k$ in a neighbourhood of $n$. This means there is an interval $(a,b)$ (which might be possibly quite small) with $n \in (a,b)$ and $g(x) = k$ for all $x \in (a,b)$
Besides this you need $f$ to be defined at $k$. (Below, you will see why.)

In this case you are totally right in just calculating $f(k)$ as the searched for limit. Here is why:
Let $x_i\stackrel{i\to\infty}{\longrightarrow}n$. Then, it follows that $g(x_i) = k$ for all $i\geq I$ from a certain index $I$ on. This is so because $g$ is constant on the interval $(a,b)$ which contains $n$.
So, the sequence $f(g(x_i))$ is only well defined if $f(k)$ is defined. But then $f(g(x_i)) = f(k)$ for all $i\geq I$, which means $\displaystyle\lim_{i\to \infty}f(g(x_i))=f(k)$.
Since this holds for any sequence $x_i\stackrel{i\to\infty}{\longrightarrow}n$ in the domain of $g$, you have $\displaystyle\boxed{\lim_{x\to n}f(g(x))=f(k)}$.
Comment: Thanks a lot, it seems like f(x) must be continues in x=k, am I right? Otherwise we say the limit does not exist?
Comment: @BoshraAlef In this special case the continuity of $f$ is not necessary. It only needs to be defined at $k$.
Comment: Let the g(x) be |x|+|x-2| and f(x) be [x], and the variable approaches to 1.5. So here we say that $\lim_{x\to 1.5} {f(g(x))}$ is two?
Comment: @BoshraAlef :  You are completely right. The limit is well defined. $g(x)=2$ in a neighbourhood of $1.5$ and, hence, $f(g(x))=2$ in the same neighbourhood of $1.5$. Hence, $\lim_{x\to 1.5}f(g(x))=2$.
Comment: You may also graph it:
https://www.wolframalpha.com/input/?i=plot+%7By%3D%7Cx%7C%2B%7Cx-2%7C%2Cy%3DFloor%28%7Cx%7C%2B%7Cx-2%7C%29%2Cx%3D1.5%7D%2C+x%3D0..4
Comment: Thank you so much for your help. Now I got it:)
Comment: You are welcome :-)

Limit of a composite function.


return false não funciona TypeScript

Question: Estou fazendo um código com TypeScript e eu faço a verificação se um campo tem menos de 9 dígitos, se ele tiver menos de 9, não deve prosseguir o submit, mas por algum motivo está prosseguindo.
<form method="post">
  Nome: <input type="text" id="nome"/>
  <button type="submit" id="enter">Submit</button>
</form>

Meu código em TypeScript está assim:
document.getElementById("enter").addEventListener("click", function () {
  if ((<HTMLInputElement>document.getElementById("nome")).value.length < 9) {
    (<HTMLInputElement>document.getElementById("tet")).innerHTML = "O Campo \"Nome\" deve conter 9 dígitos.";

    setTimeout(function () {
      (<HTMLInputElement>document.getElementById("tet")).innerHTML = "";
    }, 5000);

    return false;
  }
});

e está dentro de um
window.onload = function () {}

e logo após ele, ainda dentro do onload tem um
(<HTMLInputElement>document.getElementById("form")).addEventListener("submit", function () {
});

ainda dentro do window.onload.
Oque estou fazendo de errado?
Comment: Só pra descargo de consciência: você tem um elemento com o id `tet` na tela, né?
Comment: tenho sim kkk @LINQ
Answer: O que acontece aí  é que a submissão do formulário está sendo disparada no momento que você clica no botão.
Para que isso não aconteça é possível usar o método preventDefault() e depois disparar o submit manualmente.
Note que se existirem outros formulários na página será necessário especificar qual form deve ser submetido.
Veja um exemplo:

document.getElementById("enter").addEventListener("click", function (e) {
    e.preventDefault(); // Previne que o submit seja disparado

    const nomeEl = document.getElementById("nome");

    if (nomeEl.value.length >= 9) {
        document.querySelector('form').submit(); // Faz o submit
    }
    else {
        console.log("O Campo \"Nome\" deve conter 9 dígitos.");
    }
});
<form method="post">
  Nome: <input type="text" id="nome"/>
  <button type="submit" id="enter">Submit</button>
</form>
Comment: Acho que seria bom notar também que está sendo feito um cast em `tet` para `HTMLInputElement`, e logo depois o `innerHTML` desse input é alterado. Mas inputs não possuem HTML interno, é bem possível que o @Samuel esteja fazendo cast de todos os elementos para `HTMLInputElement`, o que não apenas é desnecessário, mas também torna o código sujeito a erros.
Comment: Então cara, esse código me ajuda um pouco. O que acontece é que eu nao faço apenas o submit, no `(document.getElementById("form")).addEventListener("submit", function () {
});` eu executo outras ações.
Comment: E o que tem? Só de adicionar o preventDefault já evita o submit automático.
Comment: Certo, consegui dar um jeito através do  seu exemplo. Obrigado @LINQ

return false não funciona TypeScript


Why is Algorithm 8 of Neal (2000) a valid sampler?

Question: I have been having difficulty understanding why Algorithm 8 of Neal (2000) is a valid sampler.
I am looking for lecture notes that include a nice explanation of the proof. Does anyone know of any such reference?
Comment: Please provide the background so that a reader does not need reading Neal (200) first.
Comment: Thank you for the edit, I will be sure to do this in the future.
Comment: @Xi'an It's a good reading though :D
Answer: For brevity, I'm omitting the normalizing constants.  Under the standard (Polya urn) Gibbs Sampler for a vanilla DP, the model would be:
$$
P(c_i = c\mid \ldots) \propto \begin{cases}
n_{\neg i, c}f(Y_i\mid\theta_c) &\text{ for }1 \leq c \leq k^{\neg i}\\
\alpha\int_{\theta} f(y_i\mid\theta)dG_0(\theta) &\text{ for }c = k^{\neg i} + 1
\end{cases}
$$
Doing that integral analytically is difficult, if $G_0$ is not conjugate to $F$.
Some of Neal's algorithms offer various perturbations of this model trying to bypass the need for conjugacy, by doing that integral implicitly.  By sampling $\theta$ from $G_0$, then weighting by $f(y_i\mid\theta)$, you effectively get samples from $f(y_i\mid\theta)dG_0(\theta)$.  In fact, I think algorithm 7 does just this (with a single sample per iteration).  Algorithm 8 recognizes that a single sample doesn't represent that integral very well, so we generate $m$ samples from $G_0$, and weight them accordingly.


Drug dictionary android

Question: I want to make this type of app

list item
filter search
list activity

I have problem at list activity. I don't know how to start a new activity when a list item is clicked. I can do the same activity for all list items, but I cannot choose a particular activity for each item.
For example, I have list items with drug names, such as  "Paracetamol", "Digoxin", "Adrenaline", and so on.
When I click on "Paracetamol", I want to start a new activity for parcetamol, and when I click on "Digoxin", I want to start a new activity for this drug. I want to make this type of app.
Comment: You really don't need an `activity for each item`.
Comment: please phrase your question properly and people will help you.
Comment: public void onItemClick(AdapterView parent, View view, int position, long id) {

// make Toast when click

Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show();

Intent intent = new Intent(MainActivity.this, DictionaryActivity.class);

intent.putExtra("DICTIONARY_ID", position);

startActivity(intent);
Answer: When launching the detail activity you can receive information with the intent so that you are able to display the item accordingly.
from the list activity :
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("OBJ_ID", drugObj.id);
startActivity(intent);

from the detail activity in the onCreate method :
int drugID = getIntent().getIntExtra("OBJ_ID", 0);

Please note the above is an example based on a drug object that has its unique id an integer
After you get the ID from the intent you are good to go..loop through your drug objects and display data accordingly.
Hope it helps
Comment: public void onItemClick(AdapterView parent, View view, int position, long id) { // make Toast when click Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show(); Intent intent = new Intent(MainActivity.this, DictionaryActivity.class); intent.putExtra("DICTIONARY_ID", position); startActivity(intent);

Drug dictionary android


Stack overflow (0xC00000fd) when populating an array argument but not when populating a static array

Question: Disclaimer: I am a C newbie.
I wrote a program to generate a bunch of random numbers in a normal distribution with mean mean and standard deviation stddev. The numbers are put into an array r. The number of random numbers to generate is specified by the constant NUMRANDOMS.
I wrote a function getRandom that is passed mean and stddev. It creates the random numbers and puts them into r.
I wrote two versions of getRandom. The first version creates r as a static array and returns a pointer to r:
double * getRandom(double mean, double stddev) {
    static double r[NUMRANDOMS];

    for (int i = 0; i < NUMRANDOMS; i++) {
        r[i] = normal(mean, stddev);
    }
    return r;
}

That version works perfect no matter how big I set NUMRANDOMS. I have gone up to 100 million and it works perfect.
For the second version of getRandom, I pass it the array r and the length of the array (i.e., NUMRANDOMS):
void getRandom(double r[], int len, double mean, double stddev)

    for (int i = 0; i < len; i++) {
        r[i] = normal(mean, stddev);
    }
    return;
}

That version works fine for NUMRANDOMS with values of 1,000 or 10,000 or 100,000 but when I set it to one million I get the runtime error 0xC00000fd. From other posts, I learned that that error message means "stack overflow".
Why does the second version work fine until getting to one million? Why does the first version work fine even with 100 million?
Comment: How is the array allocated in the second version?
Answer: Most likely, you are allocating r in the stack in the caller like:
double r[NUMRANDOMS];
getRandom(r, NUMRANDOMS, ...);

While in the first version you have it as a static:
static double r[NUMRANDOMS];

In this latter version, the memory is reserved by the operating system when loading the program.
The stack in typical operating systems, by default, is quite small (for example, 1 MB). On contrast, the BSS/data sections usually have a limit orders of magnitude higher.
Comment: Yes, on both accounts. Fantastic! Thank you @Acorn


Changing an if condition in javascript

Question: Please give me your lights. I am using some javascript for the behavior of one form. As you can see on the code that i provide below, if the form is submited successfully, a message is displayed. What i need is instead of this message, a URL to open. I guess the change has to be made in the if (resp.result=="success") . Note also that the else condition have to be the same
function mce_success_cb(resp){
    $('#mce-success-response').hide();
    $('#mce-error-response').hide();
    if (resp.result=="success"){
        $('#mce-'+resp.result+'-response').show();
        $('#mce-'+resp.result+'-response').html(resp.msg);
        $('#mc-embedded-subscribe-form').each(function(){
            this.reset();
        });
    } else {
        var index = -1;
        var msg;
        try {
            var parts = resp.msg.split(' - ',2);
            if (parts[1]==undefined){
                msg = resp.msg;
            } else {
                i = parseInt(parts[0]);
                if (i.toString() == parts[0]){
                    index = parts[0];
                    msg = parts[1];
                } else {
                    index = -1;
                    msg = resp.msg;
                }
            }
        } catch(e){
            index = -1;
            msg = resp.msg;
        }
        try{
            if (index== -1){
                $('#mce-'+resp.result+'-response').show();
                $('#mce-'+resp.result+'-response').html(msg);
            } else {
                err_id = 'mce_tmp_error_msg';
                html = '
 '+msg+'
';

                var input_id = '#mc_embed_signup';
                var f = $(input_id);
                if (ftypes[index]=='address'){
                    input_id = '#mce-'+fnames[index]+'-addr1';
                    f = $(input_id).parent().parent().get(0);
                } else if (ftypes[index]=='date'){
                    input_id = '#mce-'+fnames[index]+'-month';
                    f = $(input_id).parent().parent().get(0);
                } else {
                    input_id = '#mce-'+fnames[index];
                    f = $().parent(input_id).get(0);
                }
                if (f){
                    $(f).append(html);
                    $(input_id).focus();
                } else {
                    $('#mce-'+resp.result+'-response').show();
                    $('#mce-'+resp.result+'-response').html(msg);
                }
            }
        } catch(e){
            $('#mce-'+resp.result+'-response').show();
            $('#mce-'+resp.result+'-response').html(msg);
        }
    }
}

Answer: How about this?
window.location = "http://www.example.com";

Answer:
What i need is instead of this message, a URL to open.

OK, so replace the part of the code you don't need with this:
window.location = "yourURLhere";

More information from MDN.
If your intention was to open a page in a new window then try this:
window.open("yourURLhere", "AWindowName", strWindowFeatures);

Where strWindowFeatures is an optional parameter that lets you set the size, position, etc. for the new window. See MDN for complete doco on window.open().
Comment: Sure that works! the window.location command is only opening in new window? are any options for parent?
Answer: Unless I misunderstand your question you just need a:
window.location = 'http://www.domain.com';

line inside your if (resp.result=="success"){ block.

Changing an if condition in javascript


Showing that $\lfloor\frac{x-1}3\rfloor=\lfloor\frac{x}3+\frac23\rfloor-1$ and $\lfloor\frac{x+1}3\rfloor=\lfloor\frac{x}3+\frac13\rfloor$.

Question: I have 2 questions about the floor functions:
1) $\left\lfloor \frac{x-1}{3}\right\rfloor =\left\lfloor \frac{x}{3}+\frac{2}{3}\right\rfloor -1$
2) $\left\lfloor \frac{x+1}{3}\right\rfloor =\left\lfloor \frac{x}{3}+\frac{1}{3}\right\rfloor$
As we know that the definitions and properties of floor functions are:
1) $\lfloor x\rfloor =m$ if $m\leq x<m+1$ and
2) $\lfloor m+x\rfloor =\lfloor x\rfloor +m$ if $m$ is an integer.
Questions:
1) Why the first floor function above has to +1 inside the floor brackets and -1 outside the floor brackets:
  $\left\lfloor \frac{x-1}{3}\right\rfloor$
= $\left\lfloor \frac{x-1}{3}+1\right\rfloor -1$
= $\left\lfloor \frac{x}{3}+\frac{2}{3}\right\rfloor -1$
2)Why the second floor function above doesn't need to add or minus 1 inside or outside the floor brackets:
  $\left\lfloor \frac{x+1}{3}\right\rfloor$
= $\left\lfloor \frac{x}{3}+\frac{1}{3}\right\rfloor$
Does anyone here know the reason? Thank you.
Comment: This is hard to read.  [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a good tutorial on formatting for this site.
Comment: Thank you so much.
Answer: An integer number can freely cross the floor delimiters. For all real $a$ and integer $n$,
$$\lfloor a+n\rfloor=\lfloor a\rfloor+n.$$
This is enough to justify the claims.
Comment: The problems are $\frac{-1}{3}$ of $\left\lfloor \frac{x-1}{3}\right\rfloor$ is not an integer, where $\frac{x}{3}$ is real number. Also, $\frac{1}{3}$ of $\left\lfloor \frac{x+1}{3}\right\rfloor$ is not an integer, where $\frac{x}{3}$ is a real number..
Comment: @Kuan: think twice. Also note that the question 2) has absolutely nothing to do with the floor.
Comment: Is this because $\left\lfloor -\frac{1}{3}\right\rfloor =-1$ of $\left\lfloor \frac{x-1}{3}\right\rfloor$? But, can we do it likes $\left\lfloor \frac{x-1}{3}\right\rfloor =\left\lfloor \frac{x}{3}\right\rfloor +\left\lfloor -\frac{1}{3}\right\rfloor$? This is because $\left\lfloor \frac{x-1}{3}\right\rfloor \neq \left\lfloor \frac{x}{3}\right\rfloor +\left\lfloor -\frac{1}{3}\right\rfloor$. For example: let x=4, $\left\lfloor \frac{x-1}{3}\right\rfloor =1$ and $\left\lfloor \frac{x}{3}\right\rfloor +\left\lfloor -\frac{1}{3}\right\rfloor =1-1=0$.
Comment: @Kuan: use the given property !!!
Answer: If n is an integer, then $\lfloor x + n \rfloor = \lfloor x \rfloor + n$.
\begin{align}
   \left\lfloor\frac{x-1}3 \right\rfloor
      &= \left\lfloor\frac{x-1}3 \right\rfloor + 1 - 1 \\
      &= \left\lfloor\frac{x-1}3 + 1\right\rfloor - 1 \\
      &= \left\lfloor\frac x3 + \frac 23 \right\rfloor - 1
\end{align}
The second is true because $\dfrac{x+1}3 = \dfrac x3 + \dfrac 13$.
Answer: I did it finally.
Definition:
$\lfloor x\rfloor =m$ if $m\leq x<m+1$.
So,
$\left\lfloor \frac{x-1}{3}\right\rfloor =\frac{m-1}{3}$ if $\frac{m-1}{3}\leq \frac{x-1}{3}<\frac{m-1}{3}+1$.
Then, $\left\lfloor \frac{x-1}{3}\right\rfloor =\frac{m-1}{3}=\left\lfloor \frac{x-1}{3}\right\rfloor$, where $\lfloor x\rfloor =m$.
Next, $\left\lfloor \frac{x+2}{3}\right\rfloor -1=\frac{m+2}{3}-1$ if $\frac{m+2}{3}-1\leq \frac{x+2}{3}-1<\frac{m+2}{3}$.
$\frac{m+2}{3}-1=\frac{1}{3} (m+2-3)=\frac{m-1}{3}=\left\lfloor \frac{x-1}{3}\right\rfloor$.
Thus, $\left\lfloor \frac{x-1}{3}\right\rfloor =\left\lfloor \frac{x+2}{3}\right\rfloor -1$.


Como atribuir um valor a um enum com notação binária?

Question: Para trabalhar com números hexadecimais, basta adicionar 0x na frente do numero, desta forma:
var numeroHexa = 0xff1120;

O mesmo vale para numeros octais, adicionando o 0:
var numeroOct = 037;

Mas como faz para declarar numeros binários?
var numeroBin = ??00101

Vou usar isso para melhorar os cálculos com operadores bitwise, minha intensão é: evitar ficar comentando o valor binário de cada enum:
public enum Direction
{
    None = 0,   //0000
    Left = 1,   //0001
    Right = 2,  //0010
    Up = 4,     //0100
    Down = 8,   //1000
}

E sim declarar diretamente cada valor
public enum Direction
{
    None = ??0000
    Left = ??0001
    Right = ??0010
    Up = ??0100
    Down = ??1000
}

Answer: Considerando a resposta do NULL sobre a inexistência de binários literais, sugiro usar o seguinte para melhorar a legibilidade do enum:
public enum Direction
{
    None = 0,      //0000
    Left = 1,      //0001
    Right = 1<<1,  //0010
    Up = 1<<2,     //0100
    Down = 1<<3,   //1000
}

Comment: E para quem achar que isto é ineficiente: a otimização do compilador resolve essa questão.
Comment: Era algo desse tipo que eu estava procurando. Acho muito melhor dizer que `Down` é "3 bits descocados" do que simplesmente o número mágico `8`. Obrg.
Answer: O C# 7 tem sintaxe para representação binária nativa. Você poderá usar:
int x = 0b0111_0100;

Coloquei no GitHub para referência futura.
Pode usar até separadores para facilitar a leitura. Os separadores podem ser usados nas demais representações numéricas também.
Fonte.
Documentação.
Coloquei no Github para futura referência.
Answer: Não é possível pra declarar literais binários no C#. O que você consegue fazer é um parse duma string para o formato binário usando Convert.ToInt32, como pode ser visto aqui e aqui.
int binario = Convert.ToInt32("0100", 2);

Answer: Trabalhando um pouco com os DLLImport para assemblies da Microsoft, percebi que eles usam uma notação para enuns [Flag] muito eficiente, simplesmente usando valores hexadecimais:
public enum Direction
{
    None = 0x1,   //1
    Left = 0x2,   //2
    Right = 0x4,  //4
    Up = 0x8,     //8
    Down = 0x10,   //16
}

Exemplo de uso: link
Sendo que o numero 0x10 representa 16, e assim por diante, é possível continuar a numeração:
0x20 == 32
0x40 == 64
0x80 == 128
0x100 == 256
0x200 == 512
0x400 == 1024
0x800 == 2048
0x1000 == 4096
...

Quer conferir? Basta abrir a ferramenta de desenvolvedor do navegador (geralmente F12) e colar os valores.
Comment: Só não faz a menor diferença usar hexadecimal ou decimal, isto só importa para a sintaxe. E o que você queria é binário.
Comment: Sim, exatamente, tanto que a resposta certa ainda é aquela que usa o operador `<<`. Só coloquei essa resposta pra complementar e enriquecer o post mesmo.


Reverse induction?

Question: Typically, induction is done by proving that $P(1)$ and $P(n) \implies P(n+1)$ for all $n$. Is it possible to instead prove $P(1)$ and $P(n+1) \implies P(n)$? Provided that $n$ is arbitrarily large, it seems that this should prove the statement for all $n$.
Comment: How would that work?  Note with the first (standard) case, $P(1) \,\&\,P(1)\implies P(2)$ and then $P(1)\,\&P(2)\implies P(3)$ and so on.  With the second?  How would just knowing $P(1)$, or any finite string of $P(k)$ help?
Comment: Well, backwards induction is certainly a thing.  But in those cases you don't assume $P(1)$.  Rather, you assume $P(k)$ for $k≥N$ and deduce it for $P(n-1)$.  This comes up a lot in probability and in numerical solutions of differential equations with boundary values.
Comment: It also shows up for all numbers if you have an open ended sequence it works for, I gave an example below.
Comment: When you put it that way, it does sound rather silly, but I have seen some kind of "backward induction" type proofs. Is there any way to adapt my suggestion toward one of those?
Comment: You may be getting mixed up with [Fermat's method of infinite descent](https://en.wikipedia.org/wiki/Proof_by_infinite_descent).
Comment: Note that if $P(n)$ is the statement "$n$ equals $1$", then $P(1)$ is true, and also $P(n+1)\implies P(n)$ is true for all $n\ge1$.
Answer: There is no flat out pure reverse induction, but there is a form of "forward-backward" induction where you prove it works for some sequence that goes to infinity,  then prove that if it works for $n$ it works for $n-1$.
The first place people tend to see this is in proving the generalized arithmetic/geometric mean inequality:
$$\frac {x_1 +x_2 + \dots +x_n}n\geq (x_1x_2x_3 \dots x_n)^{\frac 1 n}$$
First you prove it works for arbitrary powers of 2,  i.e for $n=2^k$.   Then you prove that if it works for any $n$,  it works for $n-1$.  This gets you all natural numbers because you can get to any natural number by first reaching a power of two above it, then going backward.
This generalizes to saying that forward/backward induction works if you can show for some sequence $a_n$ where $a_n\to \infty$ $p(a_n)$  holds and that if $n\geq (\text{starting number }+1)$  and $p(n)$ holds then $p(n-1)$ holds, then $p$ holds for all numbers from your start upward.
Comment: Yes, that's a proof I've seen some time ago! (+1)
Comment: @user I had to use the same technique in Functional Analysis, the only other place I've seen it used, but I'm sure there are more
Comment: Of course, but the spirit of the question in my opinion was different, that is show that P(n) is true for n arbitrarly large and the proceed backward in order to show it holds for any $m\le n$. The question is about the validity of this method to show that P(n) holds for all n. In any case all the given examples are interesting and useful.
Comment: @user Ehh,  the formal way to say "It is true for n arbitrarly large" is exactly to show it works for a sequence of numbers that goes to infinity, imo.
Comment: Yes of course, indeed it seems meaningless as induction, in the sense the question is asking about that. Bye
Answer: Proving $P(1)$ and $\forall n[P(n+1)\to P(n)]$ won't buy anything; indeed things break at the first step: since you don't know whether $P(n)$ holds, you can't infer $P(n-1)$.
You can do reverse induction when things are bounded above. Say you want to show that $P(n)$ holds for every $n\in \{1,\dots,N\}$, where $N$ is fixed. Then, if you can prove $P(N)$ and $P(n)\to P(n-1)$ for every $n\in \{2,\dots,N\}$, you can infer $\forall n\in \{1,\dots,N\} P(n)$.
Note that this is just regular induction with a fake mustache: let $Q(n)$ be the assertion $P(N-n)$. Then "reverse induction" is just regular induction with $Q$.
Answer: Reverse induction is meaningless or useless to "prove the statement for all $n$". The scope of induction is to "conquer" step by step all the numerable values for $\mathbb{N}$, in such way to show that $P(n)$ holds for all $n\ge n_0$. The base case is the first step and to proceed we need to go forward not backward.
Comment: @BradG. It could have some meaning if used to show a statement which is true for any $n\le n_0$.
Comment: That helps immensely. Thank you.
Comment: So there is no kind of "backward induction" that does work?
Comment: @BradG. You are welcome! Bye
Answer: In a sense this is true.  If we have $P(1)$ and also $\forall n [P(n+1) \Rightarrow P(n)]$, then we can conclude that $P(k)$ holds for all integers $\le 1$.  That is, for $k = 1,0,-1,-2,-3,\dots$.
Example.  Let $P(n)$ be: "$n-2 < 0$".  We know $1-2 < 0$ and from $n+1 < 0$ we can deduce $n = (n+1)-1 < 0-1 = -1 < 0$ so $n < 0$.  The conclusion would be $k-2 < 0$ for all integers $k \le 1$.

Reverse induction?


Remover valor de um array

Question: O meu array é montado da seguinte forma:
obstacles = [[x, y], [x, y], ...]

Estou querendo remover do array uma posição [x, y]
Porém a função obstacles.remove() está desligando o servidor quando executada, se eu comenta-la, o resto funciona normalmente.
obstacles = []

class...

        if event[0] == 'position':
            oldPosX = self.__getattribute__('positionX')
            oldPosY = self.__getattribute__('positionY')

            obstacles.remove([int(oldPosX), int(oldPosY)])

            self.from_to(int(event[1]), int(event[2]), int(oldPosX), int(oldPosY), int(event[3]), int(event[4]), obstacles) '''função para cacular o path.'''

            if [int(event[3]), int(event[4])] not in obstacles:
                obstacles.append([int(event[3]), int(event[4])]) '''adiciona posição [x, y] no array'''

Comment: Você não precisa -  e não deveria - fazer coisas como `self.__getattribute__('positionX')` - apenas `self.positionX` tem o mesmo efeito. Se por acaso, você tiver o nome `"positionX"` numa variável e queira usar a variável, use `getattr(self, )`)
Answer: Quando tiver um erro, sempre veja a mensagem de erro que aparece no terminal. Se aí não descobrir o que está acontecendo, ao fazer uma pergunta, inclua a mensagem de erro junto com o seu código.
Nesse caso, você teria visto que a mensagem é do tipo

ValueError: list.remove(x): x not in list

ou seja: seu programa parou com um erro por que o elemento que você tentou remover da lista usando remove não estava na lista.
A forma mais simples de resolver o erro (embora seu programa pudesse ter outras melhorias) é testar pela presença do elemento antes de tentar remove-lo:
oldpos = [int(oldPosX), int(oldPosY)]
if oldpos in obstacles:
    obstacles.remove([int(oldPosX), int(oldPosY)])

Isso vai eliminar este erro. Quanto ao motivo dele não estar encontrando o conjunto de coordenadas, podem ser vários: mas sugiro começar vendo no seu código se você os arredondou para inteiros ao coloca-los na lista.
Uma outra dica sobre o código: remover elementos de lista com "remove" pode ser ineficiente - por que o Python tem que percorrer a lista inteira antes de remover o elemento. Se o seu "obstacles" não precisa saber sobre a ordem das coordenadas lá dentro, use um set (conjunto) em vez de uma lista - (e use tuple e não list para os pares de coordenada lá dentro): o tempo de remover um elemento de um set é constante.
Dica para postar perguntas: sempre coloque toda a declaração de classes e funções  com o contexto necessário par podermos responer uma pergunta - então:
obstcales = []
class Nome(object):
   ...
   def minhafunc(self, arg1, arg2):

       ...
       if event == 'position':
           ...

Fica bem díficil respodner sobre "position" se não sabemos como foi declarada, e o que tem dentro dela. Se o código for pequeno, procure colocar o código todo.  Ao contrário de outras linguagens onde você precisa de muito código, sempre igual, para chegar no "núcleo" onde acontece alguma coisa, em Python o "boiler plate" é mínimo: ajuda muito ver todo o contexto.
E por fim, não custa repertir: sempre, sempre veja a mensagem de erro que o Python joga no terminal quando um programa dá erro. Ele nunca simplesmente "para o servidor". (Exceto em raros casos onde acontece uma falha de segmentação em um módulo de terceiros)

Remover valor de um array


proving that $x \rightarrow x^e \pmod m$ is not one to one

Question: Let $m=pq$ where $p,q$ are primes. Prove that if $e$ is not coprime to $\phi(m)$, then the mapping $x \rightarrow x^e \pmod m$ from $Z_m^*$ to $Z_m^*$ is not one-to-one.
My attempt: Let $s,l$ be integers s.t $e = sg$ and $\phi(m) = lg$ for $g = \gcd(\phi(m),e)$. then for any $x \in Z_m^*$ we have $({x^l})^e = x^{lsg}=({x^{\phi(m)}})^s \equiv 1^s \pmod m \equiv 1 \pmod m$
So if i can show that $x^l \not\equiv 1 \pmod m$ for some $x$, i found two distinct element in the group who are both mapped to 1
Since I know that $g > 1$ then $l < \phi(m)$, meaning I have to find an element with order $> l$, and I am stuck there, and since I haven't used $\phi(m) = (p-1)(q-1)$ I guess it has something to do with it. Any guidance?
Comment: $$x \to x^e \neq 1 \to 1$$

LOL.
Answer: How much group theory do you know?  This is actually a consequence of a general fact about abelian groups.  I'll post the answer here, and maybe someone else (or you) can distill it down to your special case.
Let $G$ be a finite abelian group of order $n$.  Suppose $\gcd(e,n) > 1$, where we can--without loss of generality--assume $2 \leq e \leq n$ (so $e$ is "small").  Thus there must be some prime $r$ such that $r \mid e$ and $r \mid n$.  Since $r \mid n$, there exists an element $a \in G$ of order $r$ by Cauchy's (or Sylow's) Theorem.  Since $r \mid e$ we have $e=rk$ for some integer $k$.
Consider your function $f: G \to G$ via $f(x)=x^e$, which is a homomorphism as $G$ is abelian.  Now, if $1$ is the identity element of $G$ (which I'm avoiding calling $e$ for obvious reasons) we have $f(1) =1^e =1$.  On the other hand, $f(a) = a^e = a^{rk} = (a^r)^k=1^k=1$. Since $a \neq 1$, $f$ is not one-to-one.
Your result comes from this one under the dictionary:
$$
G = \mathbb{Z}_m^*
$$
$$
n = \varphi(m).
$$
Edit/Addendum:  Here's the distilled version for you.  Take $f: \mathbb{Z}_m^* \to \mathbb{Z}_m^*$ via $f(x)=x^e$ where $d=\gcd(e,\varphi(m))>1$.   We may write $e=dk$ and $\varphi(m) = dj$ for some integers $k$ and $j$.  By Euler's Theorem, $x^{\varphi(m)} = 1$ for any $x \in \mathbb{Z}_m^*$.
Now, any $j$th power of any element $x \in \mathbb{Z}_m^*$ will map to $1$ under $f$.  This is easy to see:
$$
f(x^j) = x^{je}= x^{jdk}  =(x^{jd})^k=(x^{\varphi(m)})^k = 1^k=1.
$$
Now just convince yourself that not all $j$th powers can be equal, so we have at least two different elements mapping to $1$.  That does it.  (Maybe this is equivalent to your effort posted in your question.  If so, sorry if it's not helpful.)
Comment: Thanks! Cauchy's theorem is what I was missing... Which is weird because we weren't taught that in class.
However, about the second part, all the $j$th powers can be equal in some cases ($p=5,q=3,e=6$) so I think using Cauchy's theorem is mandatory in this case
Comment: @user2263786  If your instructor gives a different solution w/o invoking Cauchy, I would be interested in hearing it.


.each breaking if only 1 result - rails

Question: For some reason, I keep getting an "undefined method 'each'" error every time I try to do the .each do when I have one result in the below.
If I use .inspect, I can see that there's a match.  Does .each work if there's not more than 1 result?  If not, what should I use instead?
<% friends = graph.get_object("/me/friends").map{ |hash| hash["id"] } %>

<% User.select([:id]).where(fbookid: friends).each do |common| %>

<% end %>

If I just run .inspect on the User.select line (no each), then I get
[#<User id: 1>]

Any help would be appreciated!
Thank you!
UPDATE
Adding additional parameters seemed to allow me to use each...I have no clue why.  It's the same exact result (only 1).
User.select([:id, :email, :first_name]).where(fbookid: friends).each do |friend|

Comment: I've literally cut all of the other code out.  For these three lines, if I use .each I get the error, and if I use .inspect I get the above.
Answer: You get simple object not array so that it's not working. .each  method working when if you get array you get simple object so that you can use direct means that
for example
# if name attributes
User.select([:id]).where(fbookid: friends).name

Comment: Is there a solution where I can loop no matter what rather than distinguish between multiple results and one?
Comment: you get 1 record, then how can you use loop ?
Comment: but I might not get one record in the future...that's why I'm asking...I'll have to detect whether there's one user each time?
Comment: User.select([:id]).where(fbookid: friends).class <== print that line what should be return tell me please
Answer: You can use each on User.select([:id]).where(fbookid: friends), even if there is only 1 element. It will not raise an exception even if there are no elements.
The error is happening somewhere else. Perhaps you are getting an error on something inside the each loop.
Can you post more code?

.each breaking if only 1 result - rails


Does the convergence of algorithms in machine learning to train set make sense?

Question: Think of the hypothetical situation where we have a y reponse and a scalar input x, we want a function that maps x to y perfectly at least in the training set. This does not make sense, it is just imagining a situation where there are two instances with the same value of x but different responses, it is mathematically impossible to propose a function that correctly predicts these two instances. In view of this problem, why are convergence criteria used in some ML algorithms such as neural networks?
Comment: If you have two y's for one x, it's not a function. But you can still try to approximate this relation with a function.
Comment: Perfectly predicting the training set is often a smell for an overfitted model. Which convergence criteria are you referring to?
Comment: With convergence I meant is there a model F such that L(F,yi)=0 for all i in {1,....,N}. I know what overfitting is but i'm interested on it in this question.
Answer: Having two different $y$'s for the same value of $x$ will make the function not well defined, you can try plugging a data like this to a machine learning algorithm(say NN), if all your data is the same $x$ but all have different $y$, the algorithm will try to approximate the function but will not succeed to converge!
As for the mathematical analysis of machine learning, you can check PAC Learning
You can try with this example(or tweak it) but it will not converge with this kind of data:
<code>from tensorflow import keras
import numpy as np
x=np.array([1 for _ in range(100000)],dtype=float)
y=np.array([x for x in range(2,2+len(x))],dtype=float)
model=keras.Sequential([keras.layers.Dense(10,input_shape=[1])])
model.compile(optimizer="SGD",loss="MSE")
model.fit(x,y,batch_size=500)
</code>
I hope this answer's your question!
Answer: Neural networks learn mathematical functions by minimizing the loss function between the function and the observed data. A function in mathematics is a mapping, that maps $X$ values to $Y$, $f: X \to Y$. There are one-to-one functions, where each of the elements in $X$ maps to a distinct element in $Y$, and functions that can map multiple $X$ elements to the same $Y$ values (e.g. absolute value function). There are no functions that map the same inputs $X$ to different outputs $Y$.
In most cases, we apply neural networks to learn from real-life data that is noisy, $y = f(x) + \varepsilon$, so we assume that the observed values $y$ depend on the deterministic function $f(x)$ and random noise $\varepsilon$. In such a case, it can happen that different $X$'s are paired with the same $Y$'s because of the random noise. What neural network (or any other machine learning algorithm) would do in such cases, is it will either predict something like an average between the two possible outputs or learn to pick one of them as a prediction. Another solution might be to use a probabilistic model. It will learn how probable are the outcomes and assign the same probabilities to both outcomes. To make a point prediction, you could do something like predicting the expected value (an average) or choosing between them at random, based on the predicted probabilities.
The convergence criteria used in such a case is observing that training the model further does not lead to any improvement. Obviously, this does not give you any guarantees whatsoever that a better solution is not possible, it shows only that the model that you are using, with the random initialization and hyperparameters that you used, does not seem to improve anymore. It still may be possible that using a different model, random seed, hyperparameters, or optimizer, etc could lead to better result.
TL;DR What you are asking is impossible. You cannot have perfectly fitting one-to-many mappings, they cannot be learned. There are however solutions that would yield optimal, though not exact predictions. In such a case, you train the model until it stops improving.
Comment: Suppose i am using any machine learning algorithm to minimize a loss function, suppose that in two consecutive iterations the difference in the loss function value between these iterations is close enough to zero, it just means that my model is not more improving as iterations go by but it doesn't mean that my loss function has converged to the global minimum, is that what you mean ?, that is the word "convergence" most of the time means that my model no longer improves instead to get a convergence to a minimum in the loss function?
Comment: @DaviAmérico more or less yes. Usually, you have no guarantees that you found a global minimum.
Comment: even if L is a convex function?
Comment: @DaviAmérico you asked about case where it isn't, because of having multiple minimas.
Comment: I've asked in general case.I'm still in doubt if it can get convergency even if loss function is convex.
Comment: @DaviAmérico what you mean by "getting convergence" in here? You get to the point where further training does not improve the results.
Comment: I meant if loss function will get minimum on training step if that is convex.
Comment: @DaviAmérico Your example is not a well-defined function and has global minimum, so this is not possible. It has two local minimas, so the best it can do is find both.
Comment: Okay, I thanks for share your knowledge to help me.


How do I solve for $x$ in the equation : $\lvert \sin x \rvert = \lvert \cos 3x \rvert$?

Question: The exact question asked for the number of solutions to the equation in the interval $[-2\pi , 2\pi]$.
My understanding & approach :
$\lvert \sin x \rvert = \lvert \cos 3x \rvert$
$\Rightarrow \sin x = \cos 3x$     or      $\sin x = -\cos 3x$
$\Rightarrow 4x = ( 2m \pm 1 ) \dfrac{\pi}{2}$   or   $\Rightarrow  2x = (2n \pm 1 ) \dfrac{\pi}{2}$
But by this approach , I get only $8$ solutions after applying general rule.
The answer says : There are $24$ solutions.
Comment: What about $\sin x $ being negative?
Comment: Please read this [tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Comment: @N.F.Taussig Thank you for sharing the tutorial .
Answer: $$|a|=|b| \to \pm a=\pm b \to a^2=b^2$$hence
$$|\sin x|=|\cos 3x|\\ \sin^2x=\cos^23x $$wen know $$\sin^2a=\frac{1-\cos2a}{2},\cos^2a=\frac{1+\cos2a}{2}$$ so
$$\frac{1-\cos2x}{2}=\frac{1+\cos6x}{2}\\-\cos(2x)=\cos(6x)\\ \cos(2x+\pi)=\cos (6x)\\6x=\pm(2x+\pi)+2k\pi\\3x=\pm(x+\frac{\pi}{2})+k\pi $$
$$3x=(x+\frac{\pi}{2})+k\pi \to 2x=\frac{\pi}{2}+k\pi \\x=\frac{\pi}{4}+k\frac{\pi}{2} \to -2\pi \leq \-frac{\pi}{4}+k\frac{\pi}{2} \leq 2\pi \\-8 \leq 1+2k \leq 8 \to k=-4,-3,-2,-1,0,1,2,3$$there is 8 solution
$$3x=-x-\frac{\pi}{2}+k\pi\\x=\frac{-\pi}{8}+\frac{k\pi}{4} \\
-2\pi \leq \frac{-\pi}{8}+\frac{k\pi}{4} \leq 2\pi\\-7.5 \leq k \leq 8.5 \to k=-7,-6,...,0,1,...,7,8$$there is 16 solution
8+16 =24 solution overall
Comment: Sir , how do I conclude from this that ' 24 solutions ' will lie in the interval [ -2pi , 2pi ] without checking for each value of k .
Comment: I suggest to draw $f(x)=|sinx|-|cos(3x)|$ in the interval [-2pi,2pi] and see how many time $f(x)=0$
Comment: You meant $\cos(2x + \pi) = \cos(6x)$.  The first inequality should be $-8 \leq 1 + 2k \leq \color{red}{7}$ (which is what you actually did).  The second inequality should be $-\color{red}{7.5} \leq k \leq \color{red}{8.5}$.  Also, if you type  \sin x, \cos x in math mode, you will obtain, respectively, $\sin x$ and $\cos x$.
Comment: What is wrong with solving for (  a = +|- b ) i.e without squaring both sides . Why dont simply solve as : Case 1 : sinx = cos 3x and Case 2 : sinx = -cos 3x , and then we substitute sine on each side with sin x = cos ( pi/2 - x ) ?
Comment: Nothing is wrong with $sinx=\pm cos x$
Answer: Count the solutions carefully.
You have:
$$4x = (2m \pm 1) \frac\pi2 \qquad \text{or} \qquad  2x = (2n \pm 1) \frac\pi2.$$
You do not need the $\pm$ signs; $+$ would be sufficient,
because $2m - 1 = 2(m - 1) + 1$.
Moreover, we can divide by $4$ (or by $2$) to get just $x$ on the left, so
$$x = (2m + 1) \frac\pi8 = \frac\pi8 + m\frac\pi4
 \qquad \text{or} \qquad
 x = (2n + 1) \frac\pi4 = \frac\pi4 + n\frac\pi2.$$
That is, any odd multiple of $\frac\pi8$ is a solution, and so is any odd multiple of $\frac\pi4.$
You are supposed to find solutions in the interval $[-2\pi, 2\pi].$
The odd multiples of $\frac\pi8$ in that interval are
$-15\frac\pi8, -13\frac\pi8, \ldots, 15\frac\pi8.$
That is, you have solutions of the form $\frac\pi8 + m\frac\pi4$
for $m = -8, -7, \ldots, 7.$ There are $16$ of these.
You also have solutions of the form $\frac\pi4 + m\frac\pi2$
for $m = -4, -3, \ldots, 3.$ There are $8$ of these, and none of them
matches any of the first $16$ solutions.


Bloquear download de arquivos no IIS

Question: Estou tentando bloquear o download das músicas da minha aplicação.
Tentei bloquear colocando um arquivo web.config na pasta com as músicas com as configurações abaixo:
<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
    </system.webServer>
</configuration>

Mas, ele ainda acessa a pasta e permite o download das músicas.
Comment: primeiramente muito obrigado por me ajudarem. Eu acabei achando essa resposta: (http://pt.stackoverflow.com/questions/25820/como-evitar-que-um-utilizador-armazene-os-arquivos-mp3-evitando-assim-que-os-po) e a conclusão é de que é impossível impedir o download das músicas, o que eu posso fazer é dar uma dificultada... Valeu.
Comment: Pode descrever sua aplicação? Como ela funciona, onde ficam os arquivos de música, como esse acesso direto pode ser feito.
Comment: Entende-se que download é mais do que abrir o gerenciador de downloads, o download é até mesmo reproduzir um arquivo online em um player usando a tag ``, você quer que quando a pessoa clique na musica ele abra o player diretamente? Ou você quer proteger o acesso da musica contra copias?
Comment: Oi pessoal, eu queria bloquear o acesso contra cópias... Eu tenho o player JPlayer em um html que chama as musicas dessa forma ``, eu tentei usar a configuração de segurança do web.config só que ai nem o player toca mais as músicas.
Answer: Taís, se o seu site fornece a reprodução de músicas (audio) e você quer bloquear o download das mesmas (pelo código fonte, por exemplo), será necessário um script (no seu caso, aspx eu imagino) interceptando a requisição dos ".mp3" para checar a referência (ou quaisquer outras validações) liberando ou não a continuação do "despejo" binário do arquivo de mídia.
Ex.: seu-site-de-musica.com/player.aspx?musica=10
Onde 10 é o ID da música no banco e player.aspx verifica a referência da requisição (ex.: Se não vier do host seu-site-de-musica.com, então, bloquear o acesso).
Ou então, para fazer com que o web.config bloqueie acesso a arquivos .mp3 (ou demais extensões):
web.config:
<system.web>
    <httpHandlers>
        <add verb="*" path="*.mp3" type="System.Web.HttpForbiddenHandler" />
    </httpHandlers>
</system.web>

Mais informações:
http://www.iis.net/configreference/system.webserver/security/requestfiltering
Comment: Felipe, eu só criei uma página **.html** na pasta **player/** e usei o pluggin JPlayer para tocar as musicas que estão na pasta **player/musicas/**, não tenho banco de dados para utilizar.
Comment: @Taís, entendi. Neste caso você pode utilizar o **web.config** acima e testar o seu download? Se não funcionar, tente mudar o `path="*.mp3"` para `path="player/musicas/*.mp3"`.
Comment: Ele bloqueou o download e o acesso a pasta... só que o player não toca mais... O player toca as músicas esse código ``
Comment: @Tais, tente restringir o acesso aos arquivos .mp3 somente para o usuário da conta (Ex.: TaisUser): `

`
Comment: Não esqueça de remover as linhas que criamos antes do `web.config`. A idéia aqui é limitar o acesso ao arquivo ao DONO do arquivo (no caso `TaisUser`), ou seja, outro usuário (ex.: `IUSR`) não poderá acessar, já que não são donos (`IUSR`). Tente por favor.

Bloquear download de arquivos no IIS


How to get Azure VM uptime/runtime (time in running status) with Azure Python SDK

Question: Is it any way to get how long time a Azure VM have been in running status (uptime/runtime) with use of the Azure Python SDK?
A code example would be verry helpfull.
Or any hint om where I should look to find out how to do this.
Br. Rune
Answer: As I known, there is not an existing API to get the uptime value using Azure Python SDK for Azure VM. There is a feedback about uptime which you can follow up for this feature.
Per my experience, a workaround way is that you can install some third-party libraries like uptime in Python on Azure VM to get the system uptime value to publish it via HTTP or sending to other Azure stores on schedule, then you can call or retrieve to get it when you need.
Hope it helps.


iOS 8 Photos framework: Get a list of all albums with iOS8

Question: How do I get a list of all collections, including the camera roll (which is now called moments), in iOS8?
In iOS 7, I use ALAssetGroup enumeration block, but that doesn't include iOS moments which is seems to be equivalent to Camera Roll in iOS7.
    void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group == nil) {// We're done enumerating
            return;
        }

        [group setAssetsFilter:[ALAssetsFilter allAssets]];
        if ([[sGroupPropertyName lowercaseString] isEqualToString:@"camera roll"] && nType == ALAssetsGroupSavedPhotos) {
            [_assetGroups insertObject:group atIndex:0];
        } else {
            [_assetGroups addObject:group];
        }
    };

    // Group Enumerator Failure Block
    void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
        SMELog(@"Enumeration occured %@", [error description]);
    };

    // Enumerate Albums
    [_library enumerateGroupsWithTypes:kSupportedALAlbumsMask
                            usingBlock:assetGroupEnumerator
                          failureBlock:assetGroupEnumberatorFailure];
    }];

Answer: Using Photos Framework is a bit different, you can achieve the same result though, you just have to do it in parts.
1) Get all photos (Moments in iOS8, or Camera Roll before)
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];

Optionally if you want them ordered as by creation date, you just add PHFetchOptions like so:
PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];

Now if you want you can get assets from the PHFetchResult object:
[allPhotosResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
    NSLog(@"asset %@", asset);
}];

2) Get all user albums (with additional sort for example to only show albums with at least one photo)
PHFetchOptions *userAlbumsOptions = [PHFetchOptions new];
userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"];

PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:userAlbumsOptions];

[userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
        NSLog(@"album title %@", collection.localizedTitle);
}];

For each PHAssetCollection that is returned from PHFetchResult *userAlbums you can fetch PHAssets like so (you can even limit results to include only photo assets):
PHFetchOptions *onlyImagesOptions = [PHFetchOptions new];
onlyImagesOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage];
PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:onlyImagesOptions];

3) Get smart albums
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
        NSLog(@"album title %@", collection.localizedTitle);
}];

One thing to note with Smart Albums is that collection.estimatedAssetCount can return NSNotFound if estimatedAssetCount cannot be determined. As title suggest this is estimated. If you want to be sure of number of assets you have to perform fetch and get the count like:
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];

number of assets = assetsFetchResult.count
Apple has a sample project that does what you want:
https://developer.apple.com/library/content/samplecode/UsingPhotosFramework/ExampleappusingPhotosframework.zip (you have to be a registered developer to access this)
Comment: There is a very nice documentation by Apple on this -

https://developer.apple.com/library/prerelease/ios/documentation/Photos/Reference/PHFetchOptions_Class/index.html#//apple_ref/doc/uid/TP40014396-CH1-SW5

Take a look at sortDescriptors and you will see:

"Construct sort descriptors with the properties of the photo entities that you want to fetch, listed in Table 1. For example, the following code sorts by creation date to find the oldest asset in the photo library."

Table 1 has all properties that you can use for PHAsset, PHAssetCollection, PHCollectionList, PHCollection...
Comment: Hey @Ladislav, great answer. But how did you know to use `creationDate` for the sortDescriptor, are the photo attributes documented anywhere?
Comment: Thanks. Exactly what I was looking for!
Comment: @Ladislav Thanks for the great answer. I don't understand though why you need to fetch "All Photos". I realize it does this in the sample app, but if you fetch the smart albums and albums, won't it cover all photos?
Comment: I tried to get all photos, but it doesn't include the photos in Moments (it only include Camera Roll). Not sure it got to do with iOS 9. I also tried Apple sample code, and while they say it includes moments, it doesn't.
Comment: @samwize explain to me the difference between Moments and what you call Camera Roll?
Comment: @Ladislav I am using iOS 9, and in my Moments, it includes the photos that I synced with iTunes (Photos app). Moments includes everything, while Camera Roll includes only the photos that took and not yet imported and deleted.
Comment: @samwize try playing with number 3) Get Smart Albums by changing subtype: Check enum options for PHAssetCollectionSubtype: https://developer.apple.com/library/ios/documentation/Photos/Reference/PHAssetCollection_Class/#//apple_ref/c/tdef/PHAssetCollectionSubtype
Comment: @Ladislav I tried, and doesn't work. The following code from http://stackoverflow.com/a/25996662/242682 does work, although it is kind of brute force by iterating all the assets.
Comment: Fails if estimatedAssetCount == NSNotFound
Answer: This is simply a translation of @Ladislav's superb accepted answer into Swift:
// *** 1 ***
// Get all photos (Moments in iOS8, or Camera Roll before)
// Optionally if you want them ordered as by creation date, you just add PHFetchOptions like so:
let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

let allPhotosResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: allPhotosOptions)

// Now if you want you can get assets from the PHFetchResult object:
allPhotosResult.enumerateObjectsUsingBlock({ print("Asset \($0.0)") })

// *** 2 ***
// Get all user albums (with additional sort for example to only show albums with at least one photo)
let userAlbumsOptions = PHFetchOptions()
userAlbumsOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")

let userAlbums = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: userAlbumsOptions)

userAlbums.enumerateObjectsUsingBlock({
    if let collection = $0.0 as? PHAssetCollection {
        print("album title: \(collection.localizedTitle)")
        //For each PHAssetCollection that is returned from userAlbums: PHFetchResult you can fetch PHAssets like so (you can even limit results to include only photo assets):
        let onlyImagesOptions = PHFetchOptions()
        onlyImagesOptions.predicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.Image.rawValue)
        if let result = PHAsset.fetchKeyAssetsInAssetCollection(collection, options: onlyImagesOptions) {
            print("Images count: \(result.count)")
        }
    }
})

// *** 3 ***
// Get smart albums
let smartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .AlbumRegular, options: nil) // Here you can specify Photostream, etc. as PHAssetCollectionSubtype.xxx
smartAlbums.enumerateObjectsUsingBlock( {
    if let assetCollection = $0.0 as? PHAssetCollection {
        print("album title: \(assetCollection.localizedTitle)")
        // One thing to note with Smart Albums is that collection.estimatedAssetCount can return NSNotFound if estimatedAssetCount cannot be determined. As title suggest this is estimated. If you want to be sure of number of assets you have to perform fetch and get the count like:

        let assetsFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil)
        let numberOfAssets = assetsFetchResult.count
        let estimatedCount =  (assetCollection.estimatedAssetCount == NSNotFound) ? -1 : assetCollection.estimatedAssetCount
        print("Assets count: \(numberOfAssets), estimate: \(estimatedCount)")
    }
})

Comment: Thank you so much!
Comment: Hi @Grimxn, May i know, How to fetch the Last import photos only in the Photo library. Based on creation date sorting also we are getting all the images. But my requirement is only fetch the last imported photos. because, We used external camera and take the photos and copy to IPAD. So, How to fetch the "Last Import photos" in the app end?
Comment: I'm not working on this at the moment, but I guess that you need to enumerate the asset collections `https://developer.apple.com/documentation/photos/phassetcollection#1656287` and check their `assetCollectionType`s...
Answer: Try this Code...
self.imageArray=[[NSArray alloc] init];
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode   = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = true;
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];

NSLog(@"%d",(int)result.count);

    PHImageManager *manager = [PHImageManager defaultManager];
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:countValue];

    // assets contains PHAsset objects.

    __block UIImage *ima;
    for (PHAsset *asset in result) {
        // Do something with the asset

        [manager requestImageForAsset:asset
                           targetSize:PHImageManagerMaximumSize
                          contentMode:PHImageContentModeDefault
                              options:requestOptions
                        resultHandler:^void(UIImage *image, NSDictionary *info) {
                            ima = image;

                            [images addObject:ima];

                        }];

    self.imageArray = [images copy];


Scrapy and Splash times out for a specific site

Question: I have an issue with Scrapy, Crawlera and Splash when trying the fetch responses from this site.
I tried the following without luck:

pure Scrapy shell - times out
Scrapy + Crawlera - times out
Scrapinghub Splash instance (small) - times out

However I can scrape the site with the Firefox webdriver of Selenium. But I want to move away from that and use Splash instead.
Is there a workaround to avoid these timeouts?
NOTE:
If I use local Splash instances set up by aquarium the site loads, though it still takes 20+ seconds compared to the Firefox webdriver's 10 seconds.
Comment: @DavidKong At the end found a way to scrape it using only  requests without headless browsers.
Comment: Did anything work for you?
Answer: Try to increase the timeouts for Splash. If you run Splash using Docker, set the parameter --max-timeout to some bigger value, e.g. 3600 (for more info, look into documentation).
Next, in your Splash requests, also increate timeout. If you use scrapy-splash library, then set SplashRequest argument timeout to some higher value, e.g. 3600. Like this:
yield scrapy_splash.SplashRequest(
        url, self.parse, endpoint='execute',
        args={'lua_source': script, 'timeout': 3600})

Comment: When you try to render the page using Splash web console, you can see the timings. There are also other tricks e.g. setting [`resource_timeout`](http://splash.readthedocs.io/en/stable/api.html#render-html) to speed up rendering process.
Comment: Yeah I can do that, but it's just not the right approach I think. When a site can be loaded in 3 seconds, why should I set a timeout of 3600 seconds? Are there another option to speed up splash?
Comment: Just give it a try and see if it helps and solves the problem. If it does, you can always think about better approaches. Also, look at the documentation I linked in the answer, there's a whole section dedicated to such issues.
Comment: Well I can't seem to set max timeout for Splash instances hosted on Scrapinghub. Also I went through the docs like a thousand times, but for no good. Other than that I think that it's somehow related to some anti-scrape solution, as I just don't get it why it takes so long for Splash to render the page, maybe the site has some specific defense against it. Also I used various headers like: User-Agent, Referer to get different results but without luck.
Comment: I'm sure there's a way, just contant them on [support](https://support.scrapinghub.com/support/home).
Comment: I do use the web console, so I can see the timings, and for other sites it's just okay, but with sites like this is problematic. Also `resource_timeout` is not the way to go, I already tried it, but according to my findings it's not for speeding up, but to set a default timeout value for each request.
Answer: You could retry the request with scrapy shell and setting the user agent in the headers. For me using this method on worked in a few seconds. Using the default user agent caused the connection to be dropped by the site. Default user agent declares that you're using scrapy, so it makes sense that the site would choose to drop the connection.
Replace custom user agent to match your own browser or preferred user agent, and url. You can try using the following steps, and then view the response in your browser:
scrapy shell
url = "https://www.yoururl.com"
request = scrapy.Request(url, headers={'User-Agent': 'custom user agent'})
fetch(request)
view(response)

Comment: Thanks for your answer. I already tried to set custom User-Agent headers in Splash, without luck. But I'll recheck it to be sure!


What is the maximum value for a gid in OpenLDAP

Question: Our company has many individual sites that currently each have their own scheme for Linux authentication. We are looking at redesigning to have one unified scheme with the future plan of porting all the accounts to a single LDAP, likely OpenLDAP. As part of this first phase, we would like to redo all the gids to fit at least some sort of standard. We'd like to allocate a range of gids to each site to use as needed. We are looking to start at gid 10000 (to avoid system gids, and any other already established gids at any particular site) and allocate at least 1000 gids each of them to use. This plan puts our highest gid at just under 300000.
The question comes down to whether OpenLDAP can reference a gid that high. It's not a matter of how many gids, as the majority of those sites don't currently need Linux gids. It's simply whether OpenLDAP would have an issue accessing a value at least that high or higher. It's my understanding that what *NIX OSs consider a "gid" is just a value to OpenLDAP, so theoretically, there shouldn't be a limitation on OpenLDAP's side, but I haven't found that stated, or anyone who has successfully used a gid of more than 200000.
Does anyone actually know if using a gid in the 300000 range cause an issue with OpenLDAP?
Comment: Related is this question http://serverfault.com/questions/105260/how-big-in-bits-is-a-unix-uid
Answer: the GidNumber is unlimited.
The GID number is defined as an integer in the schema definitions
<code>attributetype ( 22.214.171.124.126.96.36.199 NAME 'gidNumber'
    DESC 'An integer uniquely identifying a group in an administrative domain'
    EQUALITY integerMatch
    SYNTAX 184.108.40.206.4.1.1418.104.22.168.27 SINGLE-VALUE )
</code>
According to RFC 4517     LDAP: Syntaxes and Matching Rules

3.3.16.  Integer
A value of the Integer syntax is a whole number of unlimited
magnitude. The LDAP-specific encoding of a value of this syntax is
the optionally signed decimal digit character string representation
of the number (for example, the number 1321 is represented by the
character string "1321").  The encoding is defined by ...

Since it is a character string and not a number you don't have the OS determined maximum size for a signed integer and the GID number in LDAP is unlimited.
On the other hand, your OS support and PAM libraries may be limited to 65534.
Comment: Excellent!  This is exactly the answer I was looking for!  Thank you!
Answer: 1/ Yes, the gid and uid limit is basically almost unlimited.
2/ I encountered a regression with old tar command (not GNU tar) that could not untar with over ~2000000 as uid/gid. There is no problem with GNU tar. I stay under the limit.
3/ I highly recommand having uid/gid of Ldap over the Unix Uid/Gid range of 65535. When you integrate Ldap with Unix (with sssd/nslcd/openldap-ssh, etc.), you risk a uid/gid collision. I encountered that, the group gets mixed, which breaks and add insecurity.
4/ As an example, FreeIpa Ldap default uid/gid range can be over millions.


Which ICMP types (v4/v6) should not be blocked?

Question: I have made a lot of research into this and have found that some references contradict each other.
IPV6
For example RFC4890 says the following types should be allowed for optimal functionality:

Type 1, 2, 3, 4, 128, 129 and for mobility assistance also 144, 145, 146
and 147.

However this source doesn't mention mobility assistance was required: (also type 1 and 4 are omitted)

Type 128, 129, 2, 3 and for NDP and SLAAC 133, 134, 135, 136 and 137

On the other hand the former reference said NDP and SLAAC don't need special attention, since they will be dropped anyway. So who is right? Is it best to allow all these mentioned by both sources to be on the safe side?
IPV4:
Surpringly the reference doesn't have any recommendation for IPv4, but the other source says that types 8, 0, 3 and 11 are needed for IPv4. Are there any official reference that recommends which IPv4 ICMPs should be allowed?
UPDATE:
While the answer is good, I find it too generic to accept it as a real solution to this.  If blocking is not the answer, then rate limit must be the right way to provide a level of protection. I believe an answer with the correct code sample would be more assuring.
Comment: Does this answer your question? [Why not block ICMP?](https://serverfault.com/questions/84963/why-not-block-icmp?rq=1)
Comment: Yes, I changed my mind. I won't block it after all.
Comment: NDP is a link-local protocol, so it will never be routed.
Comment: [RFC 5927 *ICMP Attacks against TCP*](https://www.rfc-editor.org/rfc/rfc5927.html) seems relevant. The mitigations should be implemented in the TCP stack however, not in the firewall, from what I understand.
Comment: @Houman `-m icmp` is implied if you have `-p icmp`. The `-m` option is not a "matcher" itself, but pulls in the facilities for matching ICMP payload.
Comment: To allow everything, I need only `-A INPUT -p icmp -j ACCEPT` and `-A INPUT -p ipv6-icmp -j ACCEPT`, correct?  `-m icmp` is not required?  Thanks
Comment: "If blocking is not the answer, then rate limit must be the right way to provide a level of protection." Why do you think that?
Comment: @JosephSible-ReinstateMonica See the answer.
Answer: All of ICMP should not be blocked. Not by default, this can be a deny list rather than an allow list.
Start by rate limiting, but not otherwise filtering, ICMP.
Read RFC 4890 section 3  on the security considerations expected. Notably redirect diverting packets, but the standard requires those to be local, on link. Denial of service at high volume, but often that can be mitigated with rate limits. Maybe discovery of hosts, but that doesn't reveal much. ICMP is not very dangerous.
Comment: Thanks. Would you be able to provide a rate limit example with iptables, please?  I could probably do this for all ICMP, but I have a bad feeling that I might break something: `-A INPUT -p icmp -m limit --limit 10/sec -j ACCEPT`.  My scenario is the following, the users can open our app, and tap on server status to see a list of all servers shown with their ping.  Theoretically many users could do that at the same time. What number would be the right limit?


how to unbind cursor adpter with listview in android

Question: I need to know ,how to unbind cursor adapter with listview.
Continuous updates comes to my table.As cursor Adapter already register its observers .It is  directly reflected to listview which hangs my UI why scrolling.
i need to unbind listview with that of updates coming in db.The view only should unbind but the update must still come db.
I tried to extend cursoradpter overide the registerDataObserver.but it stops update coming in to the db.
Kindly assist how to proceed..
Answer: Call adapter.changeCursor(null); to unbind


How to position a borderless window in Kivy

Question: I was making an app with Kivy in python, and to make things a tad more stylish, I thought I could remove the border on the window and create by own:
from kivy.config import Config
from kivy.core.window import Window
Window.size = (900,550)
Window.borderless = True
Config.set('graphics','resizable',0)

However the border less window will pop up in the very bottom left corner of my screen. Is there anyway I can position the window so its in the middle of my screen?
If I can't do that, then is there a way to remove the rounded corners on a window?
(I am doing this on a Mac OSX Yosemite)
Answer: Borderless:
from kivy.config import Config
Config.set('graphics','borderless',1)
Config.set('graphics','resizable',0)

at the top of your file before anything else. Just the core(Window) will remain.
Position:
Config.set('graphics','position','custom')
Config.set('graphics','left',500)
Config.set('graphics','top',10)

the same condition applies for all Config.set().
Comment: Hey, exist a mode to move the window without border?


Nonlinear parallel transport: preserving level sets of an arbitrary function

Question: Motivation: Consider a smooth vector bundle $\pi:E\to M$, a fiber metric $g$, and an affine connection $\nabla$ compatible with $g$. Then the parallel transport $\Pi_{\gamma,t_0,t}$ determined by $\nabla$ is an isometry of the fibers of $E$.
Consider the smooth function $f:E\to \mathbb{R}$ on a vector bundle defined by $f(v):= g(v,v)$. In particular, parallel transport yields a smooth family of smooth maps $\Pi_{\gamma,t_0,t}:E_{\gamma(t_0)}\to E_{\gamma(t)}$ satisfying $$f \circ \Pi_{\gamma,t_0,t} = f,$$
for any path $\gamma:[t_0,t]\to M$.
Question: Suppose that $\pi:E\to M$ is a smooth fiber bundle and $f:E\to \mathbb{R}$ is an arbitrary smooth function. When is it possible to find, for any path $\gamma:[t_0,t]\to M$ a smooth family of smooth maps $\Pi_{\gamma,t_0,t}:E_{\gamma(t_0)}\to E_{\gamma(t)}$ satisfying $$f \circ \Pi_{\gamma,t_0,t} = f?$$
I.e., are there natural conditions that may be imposed on $f$ to ensure that this is possible?
Idea: If the level sets of $f$ are all manifolds and there exists a smooth Ehresmann connection on $E$ such that the corresponding horizontal bundle $\mathcal{H}$ is contained in the distribution $\ker df$, then I think the parallel transport determined by this connection would solve the problem. But it isn't clear to me when such an Ehresmann connection exists.
Evidently such a (linear) Ehresmann connection exists for the case of $E$ a vector bundle and $f(v) = g(v,v)$ described above.
Comment: On the local level, it seems that the only obstruction is the case where $\mathrm{d}f|_{e\in E}$ vanishes identically on the vertical bundle while not identically zero on $TE$. In other words, the kernel of $\mathrm{d}f$ being transverse to the vertical bundle seems to be enough. Am I missing something?
Comment: @WillieWong Now that you mention it, I think that you're right. It seems to me that you could take the local vector fields arising from the time-derivatives of such local constructions and blend with a partition of unity, solving the problem. And this seems like this also might be a necessary condition. Do you agree?
Comment: Yes, I think so.
Comment: @WillieWong if you'd like to expand this into an answer, I'll accept it since I think it is the most general. If not, no worries --- this was very helpful for me. Thank you.
Comment: I am too busy to do it right now. If you want to write things down concretely to double check your reasoning, feel free to post that as an answer. I don't mind at all!
Comment: @WillieWong okay, no worries! I took a shot at writing a detailed answer and posted it below.
Answer: There are many examples in which such a parallel transport does not exist (for example, take a non-constant function on the base $M$ and pull it back to $E$). However, it does exist in very specific cases, such as your example of a vector bundle with fiber metric. Let us try to generalize your example.
Let $E\to M$ be a fiber bundle with fiber $F$. So $E$ can be represented by a collection of trivializations and transition maps. The transition maps are all of the form $$\varphi_{\alpha,\beta}:U_\alpha\cap U_\beta\to \mathrm{diff}(F).$$ Let $G$ be a Lie subgroup of $\mathrm{diff}(F)$. A $G$-structure on our fiber bundle is a representation in which all the transition maps admit values in $G$.
Example: A vector bundle is merely a fiber bundle with fiber $\mathbb{R}^k$, equipped with a $GL_k(\mathbb{R})$-structure. Once you give this vector bundle a fiber metric, you actually reduce the structure group to $O_k(\mathbb{R})$.
We continue with a fiber bundle $E\to M$. To begin with, every fiber $E_p$ can be identified with the fiber model $F$ in many different ways. In fact, the set of diffeomorphisms $E_p\to F$ is diffeomorphic to $\mathrm{diff}(F)$. Once you equip $E$ with a $G$-structure, you distinguish a set of "special" identifications - those that respect the $G$-structure. The set of such identifications is diffeomorphic to $G$. (For example, if $E$ is a vector bundle, then the special identifications are the linear isomorphisms $E_p\to\mathbb{R}^k$. If you have a metric, the special identifications are the isometric linear isomorphisms).
Assume now that $E\to M$ has a $G$-structure and a compatible connection $\nabla$. That is, all the parallel transport maps of $\nabla$ respect the $G$-structure. Let $h:F\to\mathbb{R}$ be a function which respects the $G$-action on $F$. In other words, $h$ is constant on every $G$-orbit in $F$. Note that in this case, there is a well defined function $\tilde{h}:E\to\mathbb{R}$, which is induced by $h$. Namely, for $q\in E_p\subset E$ we have $$\tilde{h}(q)=h\circ\psi_p(q),$$where $\psi_p:E_p\to F$ is an identification that respects the $G$-structure. (Our assumptions guarantee that this is well defined). The conncection $\nabla$ will then satisfy what you want for the function $\tilde{h}$.
I leave it you to convince yourself that your example is a particular case of the situation described above.
Edit: Under mild further assumptions,  the above story is in fact the only context in which this phenomenon occurs. Namely, let $E\to M$ be a fiber bundle equipped with a connection $\nabla$, and let $h:E\to\mathbb{R}$ be a function which is preserved by parallel transport of $\nabla$. We only add the assumption that parallel transport exists for every path (this is not always the case in general fiber bundles).
Choose a point $p\in M$, and let $G$ be the group of all diffeomorphisms $E_p\to E_p$ which respect $h|_{E_p}$. Then, construct a collection of trivializations of $E\to M$ using $E_p$ as the model fiber, where all identifications $E_{p'}\to E_p$ are obtained from parallel transport along some path. There are many different ways to do that, but all the transition maps will have values in $G$. This means that the function $h$ is of the sort described above.
Remark: Willie Wong's comment is correct and gives a very simple necessary and sufficient condition. Having said that, all the examples I have encountered of such behavior of a function and a connection originate naturally from a function on the model fiber, as described in this answer (this is definitely the case in your example). In other words, there is usually a bigger picture behind such a function.
Comment: When you say that the parallel transport respects the $G$-structure, do you mean that $\Pi_{\gamma,t_0,t}$ is $G$-equivariant for any path $\gamma$ in the base?
Comment: @MatthewKvalheim No. I mean that composition with $\Pi_{\gamma,t_0,t}$ maps a distinguished identification of $E_{\gamma_t}$ with the fiber model $F$ to a distinguished identification of $E_{\gamma_{t_0}}$ with $F$.
Comment: I could be misunderstanding you, but I don't see how that isn't equivalent to what I said. Aren't your "distinguished identifications" just those coming from $G$-equivariant local trivializations of the bundle?
Comment: @MatthewKvalheim What does this even mean...? Note that $G$ does not act on the fibers. For example, if $E$ is a vector bundle with no extra structure, there is no well-defined action of $GL_k(\mathbb{R})$ on the fibers of $E$. Hence, it does not make any sense to say that a map between two fibers is $G$-equivariant.
Comment: @MatthewKvalheim Examples: if $E$ is a vector bundle, then the distinguished identifications are the linear ones. Accordingly, a connection on a vector bundle is compatible with the linear structure if the parallel transport maps are all linear. They are not equivariant in any sense. Just linear. If $E$ has a metric on the fibers, the distinguished identifications are the linear isometries. A conncetion is compatible in this case if the parallel transport maps are isometries as well.
Comment: Oops. I was thinking about principal bundles for some reason. Thanks.
Comment: @MatthewKvalheim I see. Yes, in the principal bundle context, the answer to your question is positive. This is actually closely related to everything that was said here.
Comment: Thanks for the help. I think your answer provides a nice sufficient condition. I'll accept it if I don't hear from Willie Wong in a day or so (I *think* his comments might contain the germ of a necessary and sufficient condition to answer my question)
Comment: @MatthewKvalheim I added something to the answer, you may want to read it.
Comment: Your new edit and remark were extremely helpful for me. Thank you very much for your help.
Answer: I'll give a shot at a detailed statement/proof based on Willie Wong's comments.
Theorem: There exists a parallel transport $\Pi$ as in my question iff $\ker df$ is transverse to the tangent spaces of the fibers.
Proof: $(\implies)$ Suppose there exists $e \in E$ with $\ker df_e$ not intersecting $T_e E_{\pi(e)}$ transversely. Then there exists $v \in T_{\pi(e)}M$ with $v \not \in d\pi_e(\ker df_e)$. But then any curve $\gamma$ in $M$ with $\gamma'(0) = v$ cannot lift to a curve contained in a level set of $f$, for such a lift $\tilde{\gamma}$ would satisfy $d\pi_e \tilde\gamma'(0) = v$ and also $\tilde{\gamma}'(0)\in \ker df_e$.
$(\impliedby)$ Assume now that $\ker df$ is transverse to the tangent spaces of the fibers. Suppose that we can find an open cover $(U_a)_{a\in A}$ of $E$ and for each $a \in A$ a vector bundle map $P_a:TU_a\to T U_a$ covering the identity such that $P_a$ is a linear projection on each $T_e U_a \subset T_e E$ with $\ker P_a \subset \ker d f$ and $\text{im }P_a =T_e E_{\pi(e)}$.
Taking a partition of unity $\psi_a$ subordinate to $(U_a)_{a\in A}$, $$P:= \sum_{a\in A}\psi_a P_a$$
is well-defined. $P:T E\to TE$ is a vector bundle map covering the identity, and on each tangent space it is a vertical-valued linear projection since linear projections with common image are closed under convex combinations. We also have $\ker P \subset \ker df$, because the kernel of a convex combination of linear projections is contained in the convex hull of their kernels$^\mathbf{1}$ and $\ker df$ is convex, being a vector space. Defining a horizontal bundle $\mathcal{H}:= \ker P$ yields a smooth (because $P$ is a smooth, constant rank vector bundle map) Ehresmann connection contained in $\ker df$. Parallel transport with respect to this connection does the trick, based on my Idea in the original post.
Thus it suffices to produce $(U_a)_{a\in A}$ and $(P_a)_{a\in A}$. Let $e \in E$. Being a smooth fiber bundle, $e\in E$ is in particular a smooth foliation and thus $e$ has a neighborhood $U$ diffeomorphic to $\mathbb{R}^{n_1}\times \mathbb{R}^{n_2}$, with $n_1 = \dim{M}$ and $n_2$ the dimension of the fibers. Denote a typical element of $\mathbb{R}^{n_1}$ by $x$ and a typical element of $\mathbb{R}^{n_2}$ by $(y,z)$ with $z \in \mathbb{R}$. Since we are assuming $\ker df$ is transverse to the tangent spaces of fibers, by the implicit function theorem (re-ordering the standard coordinates on $\mathbb{R}^{n_2}$ and shrinking $U$ if needed) we obtain a smooth parametrization
$$(x,y,c)\mapsto (x,y, f^c(x,y))$$
of $U$ with each of the level sets $f^{-1}(c)$ obtained by fixing $c \in \mathbb{R}$. Define the smooth vector bundle map $Q:TU\to \ker df \subset TU$ by setting $$Q\left(\sum_i a^i \frac{\partial}{\partial x^i} + \sum_j b^j \frac{\partial}{\partial y^j} + d \frac{\partial}{\partial z}\right):= \sum_i a^i \left(\frac{\partial}{\partial x^i}+ \frac{\partial f^c}{\partial x^i}\right) + \sum_j b^j \left(\frac{\partial}{\partial y^j} + \frac{\partial f^c}{\partial y^j}\right).$$
Then $P:TU \to TU$ defined by $P:= I-Q$ is a vertical-valued projection with $\ker dP \subset \ker df$.
$\square$
Footnote $^{\mathbf{1}}:$ Given $L = c_1L_1 + c_2 L_2$, note that $\ker L_i = \text{im}(I-L_i)$ and similarly for $L$, and $(I-L) = I-c_1L_1 - c_2L_2 = c_1(I-L_1)+c_2(I-L_2)$ since $c_1 + c_2 = 1$. Now use induction.


C# - Using external CLR DLL

Question: I'm trying to use an external library with my code. I have added it as a reference from within Visual Studio and things like auto-complete works fine, I can see all the available methods while typing code. It also compiles without any warning or errors.
The DLL is within the same directory as the executable.
However, I get this error:
<code>"Unhandled Exception: System.TypeInitializationException: The type initializer fo
r '<Module>' threw an exception. ---> System.DllNotFoundException: Unable to loa
d DLL 'yeppp': The specified module could not be found. (Exception from HRESULT:
 0x8007007E)
   at Yeppp.Library.yepLibrary_Init()
   at Yeppp.Library.Init()
   at .cctor()
   --- End of inner exception stack trace ---"
</code>
What am I doing wrong?
Comment: Where did you get this library? Yiu need to ask its author, as the dll has been loaded, but it looks for something else.
Comment: From here: http://www.yeppp.info/
Comment: [Click](http://stackoverflow.com/questions/7202543/how-to-solve-system-typeinitializationexception-was-unhandled-exception-in-vb-ne)? [Click](http://stackoverflow.com/questions/13566820/unhandled-exception-system-typeinitializationexception)? You forgot to install that `yeppp`?
Answer: http://docs.yeppp.info/cs/index.html#GettingStarted
You also need to deploy yeppp.dll as the article says.
Comment: This is exactly how I have set up and deployed the library.
Comment: Then drop yeppp.dll to %windir%\system32 or %windir%\SYSWOW64
Comment: @user9993 Make sure that your Yeppp.dll matches the bitness of your program (i.e. use 32-bit DLL if your program is 32-bit and 64-bit DLL if your program is 64-bit). Alternatively, you may try CLR bundle from  https://www.nuget.org/packages/Yeppp.CLR.Bundle
Comment: @MaratDukhan Works fine following your advice about NuGet. Already seeing calculation speed ups!

C# - Using external CLR DLL


javac esta configurado e não compila .class

Question: javac esta configurado mas não compila para .class
Comment: Tem até uma flecha apontando o erro no console.
Answer: O erro é claro: Não existe tipo string no java, o correto é String, o S é maiúsculo. O correto é:
<code>public static void main(String[] args)
</code>
Comment: muito obrigado, sou iniciante e fiquei o dia todo parado neste erro, muito obrigado de certo aqui


What are some good ways to practice rim shots?

Question: First of all, this is not a duplicate of this question. That question is asking about how to reliable do rim shots, and the answer was to practice. This question is about the practicing part.
Plainly doing rim shots seem boring and ineffective. If you stop playing, do a random fill, then try to start again, you will probably not get a good rim shot because you don't know the exact position; before you just experimented, found the spot, and held it there without knowing where it is or gaining any experience.
Are there any simple techniques for getting good rim shots 80-90% of the time?
Also, my left hand seems to miss quite a lot more than my right; are there any specific left-heavy exercises?
Any help would be appreciated.
Comment: You can't play a good rim shot without a good punchline. [insert rim shot]
Comment: http://instantrimshot.com/
Comment: Oh dear, @DrMayhem, I've got a feeling I'm going to be using that a LOT...
Answer: Not so much how to practise, but how to make the difference between a regular strike & a rimshot easier to determine, plus an unexpected extra benefit.
Change your snare drum angle.
Or even all your drums' angles, if you want to be able to do this with accurate repetition round the entire kit.
I have my entire kit set in such a way that the difference in stroke needed to clean strike or rimshot requires possibly as little as a 2mm difference in how I aim for the skin. [I've never actually measured it, but it's very small]
The downside is when you're first practising, you may tend to rimshot when you didn't mean to.
A slight 'cheat' to try prevent that for the snare is to set the height so if you rimshot, your hand hits your leg too, very slightly.
YMMV on that one, I guess it would depend on how close into the body you set the snare. Too far away & your knee-height will change too much as you play hats & kick. I keep mine tight in, so there is only very small variation. I also predominantly strike the skins about ⅔ towards the far side, for extra ring; I rarely pull back & hit in the very centre, so I am probably naturally a couple of inches closer in than most drummers sit.
The upsides are two-fold.

The small angle-change required makes it eventually very easy to switch from one to the other with little more than a thought.
The perhaps unexpected second benefit is that the perfect angle to strike a skin to get the best sound from it is actually about 1mm before you hit the rim. The flatter your stick to the skin, the sweeter the strike. Also - less effort input for more potential volume output.

As to left-heavy exercises …
Play entire songs in only rimshot.
In many gigs across the years I've had occasion to do that for some songs, as that's how they were written, or that's how to generate a sound closer to the original track, etc, without swapping snare drums over.
It certainly builds reliability of successful repetition.
Comment: I've also noticed that using Hot Rods / Blasticks or whatever you call them gets you a more reliable rimshot. How can I use this to get an advantage?
Comment: They possibly do it because they bend slightly, making the angle of attack less critical. I don't really use them much [once a year or two], so I'm not really all that familiar with them
Answer: Try finding a song with a lot of activity on the snare and make all (or even some of) the accents rim-shots. I find Californication really fun to practice rim-shots and drags to because the snare part is very involved with drags, rim shots and accents immediately after rim-shots (a skill which can be harder to learn than you may expect), but really any song with decent snare parts will do!


Problema com o componente confirmDialog do primefaces

Question: Na visão da minha aplicação java tenho um commandButton que deveria abrir um dialogo de exclusão, porém, ao clicar no botão excluir o dialogo não é apresentado. O código é:
<ui:composition template="/WEB-INF/template/LayoutPadrao.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">

<ui:define name="titulo">Pesquisa de Fabricantes</ui:define>

<ui:define name="corpo">

Pesquisa de Fabricantes

    <h:form id="frmPesquisa">

                    <h:outputText value="#{fabricante.codigo}" />

                    <h:outputText value="#{fabricante.nome}" />

                        <f:param name="fabricante" value="#{fabricante.codigo}"/>

                        <f:setPropertyActionListener target="#{pesquisaFabricanteBean.fabricanteSelecionado}" value="#{fabricante}" />

    </h:form>
</ui:define>

No navegador vejo o seguinte erro na console: ReferenceError: Can't find variable: confirmacaoExclusao
Answer: A chamada ao widget deve ser feita com PF() da seguinte forma:

Comment: O Primefaces a partir da versão 4.0 (se não me engano), a chamada aos widgets passou as ser via função PF('widget').
Comment: Mas por qual motivo só funciona com PF()?


Update column of a inserted row with with its generated id in a single query

Question: Say I have a table, created as follows:
 CREATE TABLE test_table (id serial, unique_id varchar(50) primary key, name varchar(50));

 test_table
 ----------
 id | unique_id | name

In that table, I would like to update the unique_id field with the newly inserted id concatenated with the inserted name in a single go.
Usually this is accomplished by two queries. (PHP way)
 $q = "INSERT INTO table (unique_id,name) values ('uid','abc') returning id||name as unique_id;";
 $r = pg_query($dbconn,$q);
 $row = pg_fetch_array($r);

 $q1 = "UPDATE test_table set unique_id =".$row['unique_id']." where unique_id='uid'";
 $r1 = pg_query($dbconn,$q1);

Is there any way to do the above in a single query?
Comment: Why would you want to do that? You can concatenate it when retrieving. Or create a view that returns unique_id.
Comment: Yes. Edited as you have said. Would creating a view help in achieving my objective of just having a single query?
Comment: Yes and no. You would only need a single insert. But the selects, would need to select from the view rather than from the "real" table.
Answer: You can have several options here, you could create a AFTER trigger which uses the generated ID for an direct update of the same row:
CREATE TRIGGER test_table_insert ON AFTER INSERT ON test_table FOR EACH ROW EXECUTE PROCEDURE test_table_insert();

And in your function you update the value:
CREATE FUNCTION test_table_insert() RETURNS TRIGGER AS $$
BEGIN
  UPDATE test_table SET uniqid = NEW.id::text || NEW.name WHERE id = NEW.id;
END;
$$ LANGUAGE plpgsql;

You need to add the function before the trigger.
An other option would be to do it directly in the insert:
INSERT INTO table (id, unique_id, name) values (nextval('test_table_id_seq'), 'abc', currval('test_table_id_seq')::text || 'abc') returning id;

But as a_horse_with_no_name pointed out, I think you may have a problem in your database design.
Comment: Thanks a bunch.. The insert command serves my purpose for now! As for the database design, its a work in progress. Possibly in the future, I could avoid this.


Laplace Transform

Question: Let us assume that complex-valued differential equations as follows
$\dot{z}(t)=-Az(t)+Bz(t-\tau)$, $z\in \mathbb{C}$
How to find the solution of the above equation by using Laplace transform.
Answer: The LT of the solution is defined as
$$\int_0^{\infty} dt \, z(t) e^{-s t} = Z(s) $$
meaning that
$$\int_0^{\infty} dt \, z(t-\tau) e^{-s t} = e^{-s \tau} \int_{-\tau}^{\infty} dt \, z(t) \, e^{-s t}$$
If we assume as we usually do that $z(t) = 0$ when $t \lt 0$, we may then conclude that the LT of $z(t-\tau)$ is $e^{-s t} Z(s)$.  Then the ODE is in $s$ space
$$s Z(s) - z(0) = \left ( -A + B e^{-s \tau} \right ) Z(s) $$
or
$$Z(s) = \frac{z(0)}{A+s-B e^{-s \tau}} $$
This is difficult to invert analytically, but all that's required once numerical values of $A$ and $B$ are given is to find the root(s) of the denominator numerically, say at $s=s_k$.   The solution to the ODE is then
$$z(t) = z(0) \theta(t) \sum_k \frac{e^{s_k t}}{1+B \tau e^{-s_k \tau}} $$
where $\theta$ is the Heaviside step function.

Laplace Transform


XML Read throws "device not ready"

Question: I'm trying to read a xml file but everytime the code arrives at the load()-function it throws the exeption "the device is not ready". This is the code:
<code>const string filepath = @"E:\xml\somefile.xml";
XmlDocument fileDoc = new XmlDocument();
fileDoc.Load(filepath);
</code>
The drive "E:\" is a physical HDD where the webapplication is saved in a folder called "app". So the folder xml is completely independent of the web apllication and iis. I also tried to locate the xml in the application folder but the same error occured.
Has someone an idea what I am missing?
Comment: No, working correctly. The application is also saved on that hard drive and everything works fine except the xml.load()
Comment: Check the access rights for the webapp's user.
Comment: acces rights are set to 'everyone' has full access (read, wirte, open)
Answer: Check if the file "E:\xml\somefile.xml" is not locked in you process when you try to read the xml. Use the right usinging of call Dispose() on the objects which write the file.
Comment: In the computermanagement I can't see that the file is opened by someone. It is a non-changeing file. It only stores data and noone / no function ever writes into it. It gets only accessed once by code an this time the error occures... :(

XML Read throws "device not ready"


Jquery get value (not selected) from select using text

Question: How to get the value of select list (not selected) using the text. I have used filter function but same is not working
var value1 = $('#ddldept option').filter(function() {
    return $(this).text() === 'abc';
}).val();

value1 is coming undefined..
Comment: i tried with .attr('value') still it is undefined
Comment: @sergioramosiker:can you share the fiddle.
Answer: If you want the values which is not selected, then
var value1 = $('#ddldept option').not(':selected').filter(function () {
    return $(this).text() === 'abc';
}).val();

console.log(value1);

JSFiddle


Find a non injective function between a set of integers and itself

Question: Say we have a set of integers:
$ A = \left\{1,2,6,8\right\}$ is there any way to find a non-injective function that when fed any of the numbers in $A$ gives another number in $A$ (Basically a non-injective surjection between $A$ and itself)
EDIT: To clarify, set $A$ is an example. I want to know a general algorithm for determining a function to do this with any set.
Comment: Ah yes, sorry, I meant surjection. I edited.
Comment: pigeonhole principle implies this is impossible
Answer: If $A$ is finite, you cannot do this. The reason is that if $A$ is a finite set, then $f\colon A\to A$ is injective if and only if it is surjective if and only if it is bijective.
If you just look for a non-injective function without fixed points (namely, it never satisfies $f(x)=x$), you can do it granted $A$ has at least two elements.
Pick $a,b\in A$ and define $f(x)=\begin{cases} a & x\neq a\\ b & x=a\end{cases}$.
Answer: Let's forget "injective" and "surjective" for a moment. It sounds as if the thing you want might be this:
(a) for every $a \in A$, we have $f(a) \ne a$, and
(b) for every $a \in A$, there's some element $p$ with $f(p) = a$.
The second of these is called "surjectivity," but the first is not called "non injectivity" --- I'm not sure that it has a name.
In general, the answer is "yes" (except in one special case). One solution breaks into five cases:

$A$ is empty. The vacuous function satisfies both conditions.
$A$ has one element: then there's only one function from $A$ to $A$, and it satisfies condition (b), but not condition (a).
$A$ is finite, nonempty Then number the elements in increasing order, so that
$$
a_1 < a_2 < a_3 < \ldots < a_k
$$
for some $k \ge 2$. Define $f(a_1) = a_2, f(a_2) = a_3, \ldots, f(a_{k-1}) = a_k$, and $f(a_k) = a_1$.
$A$ is infinite, but bounded below (i.e., it has a least element). Again, place the elements in increasing order, and define
$$
f(a_1) = a_2, f(a_2) = a_1 \\
f(a_3) = a_4, f(a_4) = a_3 \\
...
$$
and so on.  The case where $A$ is infinite but  bounded above is similar.
$A$ is infinite, but neither bounded below nor above. Again, the elements of $A$ can be ordered by "less than"; define $f$ to send each element $a\in A$ to the next higher element of $A$ (much as in case 3, but without the "wrap around" for the "last" element)).