Piano fingering for basic triads in B flat major

Question: I'm trying to re-train my hand to use better fingerings. Recently I looked at my fingering for something very basic: primary triads.
I want to adapt the fingering for all 24 keys and both hands.
I think my fingering for C major is straight forward. That same fingering seems to work in B flat major too, but I also tried an alternate fingering. C major and alternate B flat fingerings are...

...a few details about how I am approaching things:

C major, bar 4, I keep my finger 5 on the G for the first note and sort of contract my thumb (1) in for the C. Is that kind of shift in position OK or standard? It seems better to hold 5 on G from bars 3 to 4, get the rest of my finger on the C chord, and then switch to 4 on the G. Better to contract my hand than to reach finger 4.
Bb major, bar 1 to 2, thumb on a black key is sometimes avoided, but in this case 1 and 3 are both on black keys in bar 1 so the hand is sort of pulled up onto the black keys together, then in bar 2 fingers 3 and 5 drop down to white keys pulling away from the black keys, I then switch to finger 2 for the Bb, because it naturally reaches the black key easier that the thumb.
Bb major, bar 4, last note, I push my hand in a bit to get 1 onto the Bb, it a little awkward, but it gets my hand back into position for the repeat and the Eb chord. Keeping finger 2 on the Bb and then trying to reach 5 up to the G of the Eb chord seem an even more awkward option to avoid.

I'm trying to find economical fingerings that fit the hand well.
Some aspects of these fingers feel a little unnatural. If I'm not concentrating, I might use other fingers. But, I can't really tell if that is simply old habits taking over versus bad fingerings.
I'm willing to put in the time to re-train, but don't want to devote that time to bad fingerings.
Am I headed down the path of bad fingering?
Comment: Your question mentions both B major and B flat major but only has sheet music for B major.
Comment: Ugh! I will fix the notation as soon as I can get to my computer. It's supposed to be B flat. But the fingering numbers are correct.
Comment: Key signature correct. Sorry about that!
Comment: I find that fingerings are very personal, as everyone's hand anatomy and physiology are different. It's the length and relative length of digits as well as the mobility of each, and the action between them. I could explain what *I* would do, but that's not a lot of use to many apart from me: my fingers, being mine, are going to work for me in my ways - and sometimes that's problematic! However, just because another does it well their way certainly doesn't mean it'll work as such for me. Part of the fun (?) of practising is to try all options and choose the best in each situation.
Comment: Sure, each hand is different. But, I'm sure most people have a thumb much shorter in reach than the other fingers. My fingering questions revolve mostly around that issue and the general avoidance of the thumb on a black key.
Answer: Whenever you are trying to find the best fingerings, I recommend you try to play the line/phrase with moving your hand as LITTLE as possible. For the first four bars, I think in the 2nd chord in the 2nd measure, you should play the fingering (top to bottom) 5-3-2. This will give you the least move into the next chord.
For the last four bars, they are almost perfect. This is optional but I like to use this fingering to keep my and from moving too much. So, in the first chord of the second measure of the last four bars, I recommend using the fingering 5-3-1 and the next chord 5-3-2.
I hope that helps!
Answer: Am I headed down the path of bad fingering?
No. The fingerings presented are fine, and appropriate considerations have been made in constructing them.
Here are some additional ideas toward this or some future exercise.

The "canonical" fingerings for close-position triads in all keys are: 1) root position = RH: 1-3-5; LH: 5-3-1; first inversion = RH: 1-2-5; LH: 5-3-1; second inversion = RH: 1-3-5; LH: 1-2-5. These are the hand positions that are traditionally drilled into piano students as they learn the basic triads.
In the OP key of C, measure 4, I would prefer 5-1-3-1 over 5-1-2-1 in the first half of the measure. That allows me play it as well as the previous and subsequent chords shifting only my thumb. 5, 3, and 2 remain "dedicated" to G, E, and D, respectively, which I find more economical.
In the second Bb measure, I prefer 1-2-4 to 2-3-5. It fits my hand better, but it's easy to see why a different hand shape/size would find 2-3-5 best.
Using 1 on the very final note, for the reasons given in the OP, I agree with entirely. It is slightly awkward, but it's the best option given the return to G.


Calcular idade em anos usando javascript

Question: Como calcular a idade à partir de um input type="text" usando javascript?
Tenho o input:
<input style="width: 100%" type="text" readonly id="data_nascimento"/>

Como realizar esse cálculo? O formato da data é "01/01/2015".
Preciso converter em Object Date?
Como Realizar esse procedimento à partir do conteúdo do input?
Answer: Usando apenas Javascript, você pode usar essa função:
function calcularIdade(aniversario) {
    var nascimento = aniversario.split("/");
    var dataNascimento = new Date(parseInt(nascimento[2], 10),
    parseInt(nascimento[1], 10) - 1,
    parseInt(nascimento[0], 10));

    var diferenca = Date.now() -  dataNascimento.getTime();
    var idade = new Date(diferenca);

    return Math.abs(idade.getUTCFullYear() - 1970);
}

Fiddle: https://jsfiddle.net/kodrw5sj/
Comment: Obrigado pelo fiddle e pela atenção ao formato. Resposta Correta.
Answer: Se você puder usar o momentjs, será mais simples fazer este cálculo.
Veja neste link:

var birthDay = "1984-10-22";
var age = Math.floor(moment(new Date()).diff(moment(birthDay),'years',true));
console.log(age);

Answer: Verifica esta função. Acho que faz o que pretendes. Não tenho é a certeza em relação ao formato da data.

function getAge(dateString) {
  var today = new Date();
  var birthDate = new Date(dateString);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}
<input style="width: 100%" type="text" readonly id="data_nascimento" onBlur="getAge(this.value)" />
Comment: procure escreve o conteúdo dos links na sua resposta. Links podem ficar ficar off line e a sua resposta fica sem referência. Transcreva o conteúdo do link na sua resposta.
Answer:

function idade(d1, d2) {
  d2 = d2 || new Date();
  var diff = d2.getTime() - d1.getTime();
  return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
console.log(idade(new Date(1998, 09, 3)));

JsFiddle
Answer: function nasc (timestamp){
    const today = new Date()
    const nascDate = new Date(timestamp)

    let nasc = today.getFullYear() - nascDate.getFullYear()
    const month = today.getMonth() - nascDate.getMonth ()

    if (month < 0 || month == 0 && today.getDate() < nascDate.getDate()){
        nasc = nasc -1
    }

    return nasc
}

Comment: Por favor, descreva melhor sua resposta
Answer: function idade (timestamp){
    const hoje = new Date() //estou pegando a data do dia
    const diaDoNiver = new Date(timestamp) // aqui se refere ao dia do aniversário

    // a linha abaixo nos dá um retorno de idade, baseando-se apenas no ano, //subitraindo do ano atual o ano de nascimento ex: 2021-1990 = 31.
    let idade = today.getFullYear() - diaDoNiver.getFullYear() //é necessário usar //o let pq vai ser alterado
    // na linha abaixo vamos verificar está no mês do aniversário
    const mes = today.getMonth() - diaDoNiver.getMonth ()

    //a linha abaixo valida o mês e a data exata do aniversário

    if (mes < 0 || mes == 0 && hoje.getDate() < diaDoNiver.getDate()){
        idade = idade -1 /// se não for o mês e a data exata diminue 1
    }

    return idade
}


What does a random variable 1 with subscript [0,1/2] mean?

Question: I came across the following notation that I cannot follow:
$1_{[0,1/2]}$ It is supposed to be some kind of random variable (or just an event? not sure)
It is hard to google this, too. What does such a random variable mean? If it helps, it was defined given a probability space $([0,1],B(0,1),L)$ where $B(0,1)$ contains Borel sets intersecting $[0,1]$ and $L$ is the Lebesgue measure.
Is there a general way to google specific notations that I might miss? I have skimmed through the wiki articles of Borel sets and the Lebesgue measure without success.
Comment: If I had to guess, I would say "uniform distribution on $[0, 1/2]$", but I dunno.
Comment: $\mathbf{1}_\mathbf{A}$ for a set $A$ often designates the characteristic function of $\mathbf{A}$, here $\mathbf{A}=[0,\frac{1}{2}]$. When $\mathbf{A}$ is Borel (which is obviously the case here), $\mathbf{1}_\mathbf{A}$ is thus a random variable (of total measure $\mu(\mathbf{A})$).
Comment: @YannHamdaoui: Please make that an answer.
Answer: For a set $\mathbf{A}$, $\mathbf{1}_\mathbf{A}$ often designates the characteristic function of $\mathbf{A}$, that is, the function defined by $\mathbf{1}_\mathbf{A}(x) = 1 \text { if } x \in \mathbf{A}$ and $\mathbf{1}_\mathbf{A}(x) = 0$ otherwise.
When $\mathbf{A}$ is measurable, so is $\mathbf{1}_\mathbf{A}$ and $\int \mathbf{1}_\mathbf{A}d\mu = \mu(\mathbf{A})$
In your case, $\mathbf{A} = [0, \frac{1}{2}]$ and $\mu$ is the Lebesgue measure, so $\mathbf{1}_{[0,\frac{1}{2}]}$ is a random variable of expectation $\frac{1}{2}$.
Comment: You're welcome. $[0,\frac{1}{2}]$ is the closed interval containing all $x$ between $0$ and $\frac{1}{2}$ included, id est the set $\{ x \in \mathbb{R} \mid 0 \leq x \leq \frac{1}{2} \}$. Open intervals (containing all $x$ bewteen two reals but excluding these reals) are written with parenthesis like $(0,\frac{1}{2})$ for example, or with reverse brackets as $]0,\frac{1}{2}[$.
Comment: Thank you very much! So, is $[0,\frac{1}{2}]$ an open interval in our case? If yes, what exactly is the meaning of this interval? If it reflects the values of the cumulative distribution function, this would make sense (and then, is there a linear slope for values in between or is it just not defined?) If this can be answered by just studying Borel sets and Lebesgue's measure more thoroughly, let me know
Comment: thank you! Still I do not understand exactly what the meaning of the interval in this context is. I see we can integrate it to get the mean... Not sure if there is more to it, I just don't see the value of writing it this way. Is this another notation to write that the values of this variable are in the range $[0, \frac{1}{2}]$ and uniformly distributed?
Comment: I guess this is indeed just a convenient notation but also widely used (not just in probability, but in set theory, real analysis, topology, etc.). As far as I can tell, I don't know another notation and this one would be the first one and the most natural to come to my mind if I had to refer to this function, no matter the context.
Comment: $\chi $ (to remind us of the word "characteristic) is sometimes used. $I$ (to remind us of the word indicator) is also sometimes used. The actual syntax is pretty universal though. Anyway no, it has nothing to do with the values: the values are 0 or 1, depending on whether the sampling variable $\omega $ is in $[0,1/2] $ or not.


I'm allergic to my violin chin rest

Question: I have a metal allergy. Unfortunately, the chinrest on my violin has two metal bars on it that contact my skin when I'm playing, and cause me an allergic reaction. (My chinrest is similar to that shown in this picture).
I've tried covering the metal bars by putting a sock over the entire chinrest (looks weird and feels awkward) and by covering just the metal bars in painters tape (it eventually wore away and left weird residue).
Aside from buying a new chinrest, what can I do to prevent myself from reacting to my violin?
Comment: A one minute search on google revealed chinrests with no metal parts for way less than £20. Maybe doesn't answer your question, but answers your problem!
Comment: Violin hickeys can be caused by various things, are you sure you're allergic? If so, titanium chinrest screws should help, though a hypoallergenic chinrest would probably be cheaper.
Comment: Indeed. How severe is the allergic reaction? How long do you spend practicing every day?
Comment: @GeneralNuisance It's simply a rash - not severe, but quite annoying. I average 1-1.5 hours of practice a day, 6 days a week.
Comment: You can't prevent an allergy. You can, however prevent contact with the offending material.  This is an important medical difference which is why I'm pointing out the difference.
Comment: Take up baroque violin and learn to play without a chin rest.
Answer: Maybe try using a non-toxic metal coating like a paint or primer or something?
Comment: Some brass players with a nickel allergy will paint their mouthpiece with clear nail varnish. It's a thinner coating than paint or primer and transparent. You can hardly tell it's there at all.
Comment: That's a good idea!
Comment: It is very common to spray metallic objects (esp. brass fittings on the exterior of a building) with a clear spray lacquer. Nail polish is, basically, the same thing and works pretty well.
Answer: hey i don't know if you've solved your problem - i play the violin too and had an allergy to the chin rest metal - it's easily solvable problem, lots of music stores sell a titanium part, basically you can use the same chinrest you just replace the metal with titanium and basically people in general aren't allergic to titanium (or just generally less than the amount of people allergic to nickel) and for me that just got rid of the problem entirely:) hope it helps
Answer: Look up "violin chin rest cover" on the Internet music warehouse of your choice.  I find a large number of offerings.  It may also help to buy some cheap enough chin rest with non-allergic material and then steal its joining elements (basically hollow tubes with different threadings on the inside): I think that the threadings will be more or less standard.
Answer: Well, the function of the chin rest is to provide a place for your chin to rest. Some people with short necks just lose the chin rest and/or the shoulder-rest.
Alternatively, INSTEAD OF A LARGE CLOTH to block the metal portion, use a smaller piece of fabric securely and semi-permanently fastened to the back of the violin, just to cover the metal. You could shove it in to the gap between the metal pieces and the wood of the violin. This would eliminate some of the awkwardness.
Anyway, you have options. Given the fact that most of them are in fact very DIYish, I would personally just buy a cheap new chin rest. They really only have a very simple function, so it's hard to go wrong with cheap (A more expensive option makes sense if you play for long periods of time, but for the casual session, cheap is good.)
Comment: Plenty of violinists/violists use a cloth laid over both chin rest and shoulder rest.
Answer: "moleskin" tape or sheet that is used for sports or in shoes to prevent rubbing can be easily applied over the metal parts.  It usually is available in various thicknesses and the glue does not creep.
Do not let the tape contact the violin finish though, wrap it only on the metal and chinrest wood, as the glue could damage your violin lacquer.
https://en.wikipedia.org/wiki/Moleskin
Answer: You could also consider foregoing the chin rest completely. If I remember correctly both Izthak Perlman  and Hillary Hahn do that.
Comment: Playing without a chin rest depends very much how long your neck is. If you can't hold the violin firmly under your chin without using your hands, and without contorting your neck, that idea won't work. FWIW the picture on Hahn's official website http://hilaryhahn.com/ *does* have a chin rest.

I'm allergic to my violin chin rest


SQL Server supports a maximum sector size of 4096 bytes

Question: I am trying to install SQL Server 2012. It fails with message

Cannot use file 'D:\SQL\tempdb.mdf', because it is on a volume with
  sector size 8192. SQL Server supports a maximum sector size of 4096
  bytes. Move the file to a volume with a compatible sector size.

But fsutil fsinfo ntfsinfo d: shows:
NTFS Volume Serial Number:       0x281643d216439fa4
NTFS Version:                    3.1
LFS Version:                     2.0
Number Sectors:                  0x00000000e8d29fff
Total Clusters:                  0x000000003a34a7ff
Free Clusters:                   0x000000002a37c684
Total Reserved:                  0x0000000000000000
Bytes Per Sector:                1024
Bytes Per Physical Sector:       4096
Bytes Per Cluster:               4096
Bytes Per FileRecord Segment:    1024
Clusters Per FileRecord Segment: 0
Mft Valid Data Length:           0x000000000a540000
Mft Start Lcn:                   0x00000000000c0000
Mft2 Start Lcn:                  0x0000000000000002
Mft Zone Start:                  0x00000000000ca540
Mft Zone End:                    0x00000000000cc820
RM Identifier:                   F3BAAB08-F2E7-11E2-804B-3C4A9279C348

D: drive is RAID 0 drive with total capacity of 4 TB made from two 2 TB disks. RAID controller is AMD RAID and its utility shows that disk's sector size is 1 KB:

Why SQL Server setup program thinks that disk sector size is 8K and what needs to be done to install SQL Server on this disk?
Answer: That AMD RAID is almost definitely software RAID and is probably reporting weird things to the OS.
Use striping at the OS level and see if that fixes your problem.
Just be aware that if one drive fails you'll lose all data on your 4TB volume.
I really really hope you're ONLY using this for development.
Comment: Looks like you are right and problem was causing by AMD RAID driver. I've tried to replace default Windows Server 2012 driver with latest driver from AMD (3.8.1540.30). That didn't help. Then I've tried older driver (3.2.1540.75), just in case. I was using it for Windows Server 2008 R2 before upgrading to 2012. With this driver the problem disappeared.
Comment: And yes, I am using this RAID array as a storage for nonsensitive data, so data loss won't be a big problem. Thanks!
Answer: I suspect what it's really complaining about is the NTFS Cluster Size, which was set at format-time. The default size for a 4TB volume is a 4KB cluster, so I'm not sure how it would get set to 8KB unless it was set by hand. chkdsk will show your cluster size.
Comment: Yes I thought about that, but I remember I left cluster size option in default state (which was 4K) at format time. `chkdsk` also reported that cluster size is 4K. Looks like it is a bug in latest version of AMD RAID driver.


Unbiased estimation of the mean of a normal distribution when the parameter space is restricted

Question: Let $X_1, . . . , X_n$ be an iid sample from $\text{N}(\theta,\sigma^2)$, in which $\sigma^2$ is known and $\theta$ can have the values $0,±1,±2, . . .$,  and let $\bar{X}_n^*=\max\{k\in\mathbb{Z}:k\leq \bar{X}_n\}$ be the largest integer smaller or equal than $\bar{X}_n$.

Show that $\bar{X}_n^*$ is an unbiased estimator for the restricted parameter $\theta$. That is, prove that $\text{E}_\theta\left[\bar{X}_n^*\right]=\theta$, for every integer $\theta$.
There exist positive constants $a$ and $b$ such that, for all sufficiently large $n$, $\text{Var}_\theta\left[\bar{X}_n^*\right] \leq a\cdot e^{−b\,n}$, for every integer $θ$.
Comment: -1 because you don't state what you have tried to answer the question, nor given any indication of where you're having trouble.
Answer: The first assertion does not seem right, but maybe I am wrong (in which case I hope somebody wiser jumps in and proves it).
The estimator $\bar{X}_n^*$ is the floor function of $\bar X_n$, $\bar{X}_n^*=\lfloor \bar X_n \rfloor$ and we have that
$$\lfloor \bar X_n \rfloor = \bar X_n - \{\bar X_n\}$$
Where $\{\bar X_n\}$ is the fractional part, $0\le\{\bar X_n\} <1$.
Then
$$E (\bar{X}_n^*) = E(\lfloor \bar X_n \rfloor) = E(\bar X_n - \{\bar X_n\}) = \theta - E(\{\bar X_n\}) $$
But since $0\le\{\bar X_n\} <1$, It does not seem possible to have $E(\{\bar X_n\}) =0$ so as to establish unbiasedness, since $n$ remains finite... It looks like the floor function could only be asymptotically unbiased... Any comments?


Erro na biblioteca facebook. "Malformed access token"

Question: Estou tentando obter as informações de contato do usuário do facebook. Para isso estou utilizando o Facebook PHP SDK.
Consigo gerar a url de login corretamente. Porém, quando vou tentar obter as informações me é gerado o erro "Malformed access token".
O código que estou tentando atualmente é:
$code = Input::get('code'); // Código que vem na queryString

Session::put('facebook', Input::all());

$facebook = $this->facebook_api_instance();

// Aqui é onde eu passo o código OAuth2 e é gerado um erro
$request = $facebook->request('GET', '/me/friends', [], $code);

$response = $facebook->getClient()->sendRequest($request);

Comment: Você tem que gerar um Token e colocar na URL no código. Tipo assim:  `&access_token=$authToken`. Essa variável `$authToken` é de algo parecido que fiz aqui que contém um Token que gerei no Facebook Developer.
Comment: Ah entendi. Achei que fosse algo a ver com o Token do Facebook. Beleza!
Answer: Descobri o que era.
É que o Facebook usa a sessão nativa do PHP internalmente para salvar dois dados vindos da url, que é o state e o code. Mas o Laravel, que é o framework que uso, não usa a sessão nativa do PHP.
Me recusei a dar um session_start só por conta dessa biblioteca.
Criei uma adaptação para a biblioteca, para usar a sessão do laravel.
http://github.com/wallacemaxters/facebook
Agora está funcionando, como esperado!
Exemplo:
$api_data = Config::get('facebook_api');

$facebook = new Facebook([
    'app_id'                  => $api_data['app_id'],
    'app_secret'              => $api_data['app_secret'],
    'persistent_data_handler' => new Laravel3SessionPersistentData,
]);


Invoking an exported function from module in TypeScript

Question: The question is a simple one.
Here is how the module exports the function.
exports = module.exports = debug.debug = debug;

Here is how the ES5 module consumes it.
var debug = require('debug')('http')

Now in Typescript it's a bit different.
import * as debug from 'debug';

This returns a strange object that I have never seen before, a nested object without a key value pair.
{ [Function: debug]
  coerce: [Function: coerce],
  disable: [Function: disable],
  // More properties go here
}

How do I invoke the function debug
Comment: That first item you're seeing is indicating that the object returned is a callable. You can invoke it, e.g. `import * as debug from 'debug'; debug('http');`.
Comment: Nope that did not work.
Comment: ?? In your answer you are invoking `debug` exactly the same way I mentioned in my comment.
Comment: Yep exactly the same.
Answer: I found it digging through the documentation
const log = debug('http');
log.log = console.log.bind(console); // binding to console


Page template for custom form

Question: I'm trying to create a new page template for a custom form I'm building in my module. My goal is to use create something like a new page.tpl.php for this specific form and it looks like this method is creating the equivalent of a custom node.tpl.php within the content area of my site instead of generating a separate page template.
For example
/*
 * Implements hook_menu
 */
function mymodule_menu() {
  $items = array();
  $items['foo/my_custom_form'] = array(
    'title' => 'My custom form',
    'page callback' => 'mymodule_custom_page',
    'access callback' => TRUE, // Everyone has access.
  );
  return $items;
}

function mymodule_custom_page(){
  return theme('mymodule_template');
  return drupal_get_form('mymodule_form');
}

/*
 * Implements Hook_theme
 */
function mymodule_theme() {
  return array(
    'mymodule_template' => array(
      'template' => 'custompage', // template file called custompage.tpl.php
      'arguments' => array(),
    ),
  );
}

function mymodule_form($node, &$form_state){
//my form in here
}

I'm having an issue with the form not appearing.
Maybe I'm going down the wrong path and should be trying to create function in my theme's template.php, and then use a hook_preprocess_page to set some variables to create a page--custom.tpl.php for my form?
I can achieve what I'm trying to do by making some configuration changes to some blocks and redrawing the content area with CSS, but not sure if that's the best practice.
Comment: [`return`](http://php.net/manual/en/function.return.php) does exactly what it says on the tin. It _returns_ from the function, and any code after it is ignored. So `return drupal_get_form('mymodule_form');` can never be executed. Your question about theming is quite a broad one, I'd recommend starting at the [Theming Guide Docs](http://drupal.org/documentation/theme). Also check out the [Simple PHP tutorial](http://php.net/manual/en/tutorial.php) to make sure you're happy with usage of the language
Answer: Here is your issue, your can't return twice in a function.
function mymodule_custom_page(){
  return theme('mymodule_template');
  return drupal_get_form('mymodule_form');
}

What you need to do is just the first line,  return theme('mymodule_template'); You also need to change your form function parameters to &$form, &$form_state.
Then, in your custompage.tpl.php, you do the drupal_get_form('mymodule_form');
Result:
/*
* Implements hook_menu
*/

function mymodule_menu() {
  $items = array();
  $items['foo/my_custom_form'] = array(
    'title' => 'My custom form',
    'page callback' => 'mymodule_custom_page',
    'access callback' => TRUE, // Everyone has access.
  );
  return $items;
}

function mymodule_custom_page(){
  return theme('mymodule_template');
}

/*
* Implements Hook_theme
*/

function mymodule_theme() {
  return array(
    'mymodule_template' => array(
      'template' => 'custompage', // template file called custompage.tpl.php
      'arguments' => array(),
    ),
  );
}

function mymodule_form(&$form, &$form_state){
  //my form in here
}

And in custompage.tpl.php:
print drupal_get_form('mymodule_form');

Answer: IF the page you want to theme differently is going to be on the path foo/mycustomform, you can use Drupal's built in template suggestions and "just" create a page--foo--mycustomform.tpl.php (D7) or page-foo-mycustomform.tpl.php (D6) file and put it along with any other templates in your theme's directory.
Clear your caches and you should be on your way.
More information about template suggestions are available for D7 here: http://drupal.org/node/1089656 and D6 here: http://drupal.org/node/1089642 but basically Drupal will recognize page-PATH template suggestions.

Page template for custom form


Enviar elementos formatados para modal

Question: Boa noite!
Tenho uma lista de números onde o usuário seleciona quais números quer reservar e depois informa seu nome e telefone em um modal, e eu salvo estes dados no banco.
Quando o usuário seleciona mais de um número, eles ficam 'juntos'(ver imagem 1'). Existe uma forma de no script js eu formatar e colocar um estilo(css) nos números e para enviar ao modal já formatado(ver imagem 2)? Ou alguma outra forma?
Imagem 1:

Imagem 2:

$('#teste').on('shown.bs.modal', function () {
    $('#myInput').trigger('focus')
  })

  $(document).ready(function(){
      $("#mybtn1").click(function() {
          var p=$("#teste #result");
          $.each($("input[name='disponivel']:checked"), function() {
              $(p).html($(p).html() + '  ' + $(this).val());
          });
      });
  });
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Reservados

              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
              </button>

              <form>

              </form>

              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

<form id="form">

<input type="checkbox" value="1" name="disponivel">1

<input type="checkbox" value="2" name="disponivel">2

<input type="checkbox" value="3" name="disponivel">3

<input type="checkbox" value="4" name="disponivel">4

<input type="checkbox" value="5" name="disponivel">5

</form>

      <button  id = "mybtn1" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#teste" >Reservar números</button>

Answer: Faz um .append() com os números dentro de um span, e esse span você formata no CSS. É preciso também esvaziar a div antes senão irá acumular com o que já tem lá. Para isso você usa .empty().
O CSS do span:
#result span{
   display: inline-block;
   width: 50px;
   height: 50px;
   line-height: 50px;
   background-color: red;
   color: #fff;
   text-align: center;
   border-radius: 50%;
   margin: 5px;
}

Código:

$('#teste').on('shown.bs.modal', function () {
   $('#myInput').trigger('focus')
});

$(document).ready(function(){
   $("#mybtn1").click(function() {
      var p=$("#teste #result");
      p.empty();
      $.each($("input[name='disponivel']:checked"), function() {
         $(p).append(''+ $(this).val() +'');
      });
   });
});
#result span{
   display: inline-block;
   width: 50px;
   height: 50px;
   line-height: 50px;
   background-color: red;
   color: #fff;
   text-align: center;
   border-radius: 50%;
   margin: 5px;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

Reservados

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <form>

        </form>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

<form id="form">

<input type="checkbox" value="1" name="disponivel">1

<input type="checkbox" value="2" name="disponivel">2

<input type="checkbox" value="3" name="disponivel">3

<input type="checkbox" value="4" name="disponivel">4

<input type="checkbox" value="5" name="disponivel">5

</form>

<button  id = "mybtn1" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#teste" >Reservar números</button>

Ajuste as bolinhas vermelhas como quiser alterando o width, height, line-height (deve ser igual ao height para centralizar verticalmente).
Comment: É exatamente o que preciso! Muito obrigado pela ajuda Sam!

Enviar elementos formatados para modal


Dressing a mannequin with different items in android

Question: I am trying to implement similar screen. Unable to add different items at proper place. I want to add shoes at the proper place.
Layout
<?xml version="1.0" encoding="utf-8"?><RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:padding="0dp">

<ImageView
    android:id="@+id/imgBody"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:scaleType="fitXY"
    android:src="@drawable/dress" />

<ImageView
    android:id="@+id/imgFeet"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/imgBody"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="0dp"
    android:src="@drawable/ic_shoe1"
    android:visibility="gone" />

<ImageView
    android:id="@+id/imgFace"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="55dp"
    android:layout_marginTop="0dp"
    android:src="@drawable/ic_head"
    android:visibility="gone" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white"/>

Answer:
Try to user Table layout for split a screen in two part. like below :
  Here i have use android:layout_weight="0.5" for screen size.

   <TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#EBEBEB"
    android:stretchColumns="2"
    android:weightSum="2">

    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="0.5"
            android:background="#FFFFFF"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="0.5"
            android:background="#FFFFFF">

        </RelativeLayout>
    </TableRow>
</TableLayout>

Answer: Use Constraint Layout it will be easy for you to Design your Requirement
Add this dependency in your Project
 compile 'com.android.support.constraint:constraint-layout:1.0.2'

Here I have added a code for your design
 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/guideline4"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:srcCompat="@drawable/splash" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:minHeight="55dip"
        app:layout_constraintLeft_toLeftOf="@+id/guideline4"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Left" />

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Center" />

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Right" />
    </android.support.design.widget.TabLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Review"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="@+id/guideline4"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_editor_absoluteX="265dp"
        tools:layout_editor_absoluteY="463dp" />

    <android.support.v7.widget.RecyclerView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="0dp"
        app:layout_constraintBottom_toTopOf="@+id/button"

        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="@+id/guideline4"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tabLayout"
        app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>

Answer: I think instead of layout you should try to use canvas in left preview screen. On selecting any item should update left canvas by adding item in canvas and rendering elements.
Please have a look over canvas and drawing images over canvas.


Stuck at 'Uploading Application' using vmc push/update

Question: I'm trying to upload a lift webapp to CF but keep getting stuck at 'Uploading Application'. I've tried from two different machines, on two different networks, on two different operating systems. The application creates in a STOPPED state but the war file never gets uploaded.
I've also tried deleting the application and re-pushing, to no avail. Here's a sample trace output. Nothing else is printed after 'Uploading Application:'
<code>          "detection": [
        {
          "*.war": true
        }
      ]
    }
  }
}
<<<
>>>
REQUEST: get http://api.cloudfoundry.com/apps/cps-test-harness
RESPONSE_HEADERS:
    server : nginx
    date : Fri, 01 Jun 2012 09:44:34 GMT
    content_type : application/json; charset=utf-8
    transfer_encoding : chunked
    connection : keep-alive
    keep_alive : timeout=20
    etag : "01c08aca6ec2d2e0ca88b2bb0ed69d97"
    cache_control : max-age=0, private, must-revalidate
    x_ua_compatible : IE=Edge,chrome=1
    x_vcap_backend : 172.30.49.4:9022
    x_vcap_router : 172.30.49.23
RESPONSE: [200]
{
  "name": "cps-test-harness",
  "staging": {
    "model": "lift",
    "stack": "java"
  },
  "uris": [
    "cps-test-harness.cloudfoundry.com"
  ],
  "instances": 1,
  "runningInstances": 0,
  "resources": {
    "memory": 512,
    "disk": 2048,
    "fds": 256
  },
  "state": "STOPPED",
  "services": [
    "postgresql-64fb1"
  ],
  "version": "6b388f21b6b27a0a0d0f71defc77a6c6-0",
  "env": [

  ],
  "meta": {
    "debug": null,
    "console": null,
    "version": 2,
    "created": 1338543874
  }
}
<<<
Uploading Application:
</code>
Comment: Can you link to the source of your app so I can try and reproduce the issue?
Comment: Gareth, just checking if you resolved this?
Comment: Hi Glenn - I gave up and used Heroku; maybe I'll try again sometime.
Comment: Actually you just prompted me to have another go.. it doesn't get stuck any more so I guess it was just a temporary glitch.
Answer: To close this question out, the original poster found a resolution in the comments above:

Actually you just prompted me to have another go.. it doesn't get stuck any more so I guess it was just a temporary glitch.
Answer: I had the same issue on a CF installation. The restarting of CF services( /bin/vcap restart ) solved the deployment issue and the vmc apps indicates the application as running.


JMH AnnotationProcessor NullPointerException

Question: I created maven archetype project as specified in the JMH homepage.
I am getting "Annotation generator had thrown the exception. java.lang.NullPointerException"
when I do maven build of the generated project.
My java file is
    public class MyBenchMark
     //   extends Benchmark
{
    @GenerateMicroBenchmark
    public void timeMyOperation(int reps) {
        for (int i = 0; i < reps; i++) {
          //  ConcurrentHashMapTest.populateConcurrenctHashMap();
        }
    }

    public static void main(String args[]) throws RunnerException {
        MyBenchMark myBenchMark = new MyBenchMark();
     //   myBenchMark.timeMyOperation(50);

        Options opt = new OptionsBuilder()
                .include(".*" + MyBenchMark.class.getSimpleName() + ".*")
                .forks(1)
                .build();

        new Runner(opt).run();
    }

}

`.
The exception I get is
    org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.0:compile (default-compile) on project perftest: Compilation failure
error: Annotation generator had thrown the exception. java.lang.NullPointerException

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
error: Annotation generator had thrown the exception. java.lang.NullPointerException

    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:745)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute(CompilerMojo.java:118)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 25 more

Answer: int reps is what trips JMH. As per GenerateMicroBenchmark Javadoc:
"The arguments should be zero or more State-bearing classes. See State docs for the exact contract." Drop int reps from the arguments, and it should be fine. By the way, what you do with your benchmark is questionable, please read JMH samples first.
The error message should be better, working on that.
Comment: Thanks a lot.That works.Will surely look for the correct usage of benchmarks.


What is the definition of a geometric progression?

Question: If the first term in our geometric progression (GP) is $k$, and the common ratio is 0, then our sequence is $\{k, 0, 0, 0, 0,\ldots\}$. Is there anything wrong with this statement?
So, is $\{0, 0, 0,\ldots\}$ a GP?
I have googled for a definition of GP, but wikipedia (which I am skeptical about) is the only link with a definition. (uncited)
Answer: From Wikipedia: Geometric Progression Note the very last line.

In mathematics, a geometric progression, also known as a geometric sequence, is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed, non-zero number called the common ratio. ... The sum of the terms of a geometric progression, or of an initial segment of a geometric progression, is known as a geometric series.
Thus, the general form of a geometric sequence is
$$a,\, ar,\, ar^2,\ ar^3,\ ar^4,\ \ldots$$
and that of a geometric series is
$$a + ar + ar^2 + ar^3 + ar^4 + \cdots$$
where $r \neq 0$ is the common ratio and $a$ is a scale factor, equal to the sequence's start value. [bold face mine]

Hence, to answer your question, NO, in a geometric progression, the common ratio $r$ cannot be zero.

See also: Encyclopedia of Mathematics: Geometric Progression

A sequence of numbers each one of which is equal to the preceding one multiplied by a number $q\neq 0$ ...

There's an additional qualification there that $q \;\;\text{or r} \;\;\neq 1$.


Are query parameters working at all?

Question: So I want to use query parameters in the URL of my application. The Ember guide describes the solution: http://emberjs.com/guides/routing/query-params/
Unsuccessfully I tried it out in my ember-cli project, so I've set up a small test project without cli.
Route:
App.IndexRoute = Ember.Route.extend({
 model: function() {
  return ['red', 'yellow', 'blue'];
 }
});

Template:

Controller:
App.IndexController = Ember.ArrayController.extend({
 queryParams: ['selected'],
 selected: null,

 actions: {
   pickColour: function(colour) {
     console.log("Colour " + colour + " selected");
     this.set('selected', colour);
   }
 }
});

According to the Ember guide this should bind the selected field of the controller to the url parameters. But in this case no url parameters is set when I click a specific colour.
It should be so simple yet I can't make it work. Am I gloriously overlooking something?
Edit: SOLUTION
I missed the fact that for now it's only available in the beta. If you read this in the future, be aware that it might be available in the latest full release.
Comment: and what is the version string of your ember?
Comment: you have to use a beta version, are you?
Comment: OMG, I totally missed that! Indeed it is said at the top of the guide article. Well, I only spend half a day on this issue. :p Thank you!
Answer: This is working just fine in version 1.9.0, so this question can probably be closed.
Working demo here

Are query parameters working at all?


jquery remove from dom based on variable

Question: Have a script to add / remove options from a select field -- the "value" of the option I want to remove should be equal to the "class" of the link clicked. I've tried several different versions of this script and I cannot for the life of me figure out how to properly get the variable delText into the function to remove it. help pls!
   $('a.del').click(function() {
      var delText = $(this).attr('class');
      window.parent.$("select[name='<?php echo $f; ?>']").remove($("<option></option>").text(delText));
   });

Comment: What's the `` doing inside a jQuery/JS function?
Comment: im passing variables into the script
Comment: You pasted the script from the php file, not the generated html of the page, then?
Comment: It doesn't seem like using the class on the link to identify the `option` is going to work, since you also have the `del` class on there...
Comment: Mixing PHP (or any server-side language) into JavaScript is generally a bad idea and should be avoided if possible.
Comment: It gets you into bad habits.  Keep the server-side and client-side separated and talk to them using ajax if you need to do so.  You'll be happy you did.  Altho, I once was a PHP mixer myself... a long time ago.
Comment: I've worked almost exclusively with php for a while now and I'm only recently start to work with jQuery and I know almost nothing of ajax so I guess maybe that's the next thing to learn, thanks
Answer: If the value of the element is equal to the class of the link, then do this:
$('a.del').click(function() {
  var delText = $(this).attr('class');
  $('option[value=' + delText + ']').remove();
});

I'm not sure if that actually jives with what you're trying to do? The <?php ?> bit seems really out of place, and the I'm not sure about the window.parent bit either.
Comment: 44 seconds... *next time* I'm answering before commenting... =)
Comment: @David Sorry mate, I'll try to type more slowly next time :)
Comment: Ah, no worries; I needed to brush up on my html/js-fu anyway, this is simply an incentive... =D
Comment: i have the script running in an iframe and im using php to pass some variables from the page.
Comment: this works perfect though thanks! it wont let me accept the answer yet though but i will later, promise :-D
Comment: @thomas Thanks, I'd appreciate that.
Answer: Try something like:
$("select[name='<?php echo $f; ?>'] > option[value=" + delText + "]").detach();

To select and detach the option with the specified value that is a child (">" selector) of the named select element.
Answer: Select the links via .del means that you aren't going to be able to use their class to also identify their related <option/>.  Maybe you could use rel instead (for either value).
$('a[rel=del]').click(function (event) {
    event.preventDefault();
    $('select[name=<?php echo $f; ?>] option')
        .remove('[value=' + $(this).attr('class') + ']');
});

Working example: http://jsfiddle.net/prH9M/
If you pass in a string to remove, it filters the current set (not its children).  You could also select the option (via find) and then just call remove, without filtering
$('select[name=<?php echo $f; ?>]')
    .find('option[value=' + $(this).attr('class') + ']')
    .remove();

Comment: thanks for the example, I've tried doing this but it's not working right -- i'm running this script from an iframe so im adding window.parent. onto the front of your example but I still can't get it to remove the options :-(


Complex Exponential Function Integration

Question: I am looking for a compact form solution for this integral:
$$\psi (\nu) = \int_0^{\infty}\frac{e^{i \nu x}}{(1+a\,x)^2} dx,$$
where $i=\sqrt{-1}$, and $a>0$ is a constant and $\nu$ is Real . I searched the table of integrals book but didn't find what I am looking for. Does this mean that I need to find this integration numerically?
Thanks in advance
Comment: What is $\nu$ ?
Comment: I feel like Feynman's trick might be useful here along with integration by parts.
Comment: You'll most likely want to integrate by parts
Comment: @JohnColtraneisJC The result will be a function of v.
Comment: @FrankW. What is Feynman's trick?
Comment: I tried integration by parts, but it leads to nowhere.
Comment: @BlackMath Differentiation under the integral sign. You can set $I$ equal to the integral in your question, try intregration by parts, and try to represent the remaining integral in terms of $I'$.
Answer: Integration by parts using
 $$u={{e}^{i\nu x}}and\ dv=\frac{1}{{{\left( 1+ax \right)}^{2}}}$$   yields:
$$I=\int_{0}^{\infty }{\frac{{{e}^{i\nu x}}}{{{\left( 1+ax \right)}^{2}}}dx}=\left. \frac{-{{e}^{i\nu x}}}{a\left( 1+ax \right)} \right|_{0}^{\infty }+\frac{i\nu }{a}\int_{0}^{\infty }{\frac{{{e}^{i\nu x}}}{\left( 1+ax \right)}dx}=\frac{-1}{a}+\frac{i\nu }{a}\int_{0}^{\infty }{\frac{{{e}^{i\nu x}}}{\left( 1+ax \right)}dx}$$
Now use  $${{e}^{i\nu x}}=\ \cos \left( \nu x \right)+i\sin \left( \nu x \right)$$
$$I=\frac{-1}{a}+\frac{i\nu }{a}\int_{0}^{\infty }{\frac{\cos \left( \nu x \right)}{\left( 1+ax \right)}dx}-\frac{\nu }{a}\int_{0}^{\infty }{\frac{\sin \left( \nu x \right)}{\left( 1+ax \right)}dx}\ =\frac{-1}{a}+\frac{i\nu }{a}{{I}_{1}}-\frac{1}{a}{{I}_{2}}$$
Where these two integrals can be found in terms of cosine integral and sine integral.
Comment: After using your approach, I reach to the formula $\psi(t)=1+itE_1(-it)$ for $a=1$, and where $E_1$ is the exponential integral function. However, when I tried to find the inverse Fourier transform of $\psi(t)$ numerically using Mathematica, it didn't give me what it is supposed to give me, which is $1/(1+x)^2$. Why?
Comment: $\psi \left( \nu  \right)$ is not the is not the fourier transform of $\frac{1}{{{\left( 1+ax \right)}^{2}}}$
Comment: Why not? It is the characteristic function, and the books I read state that it is the Fourier transform of the PDF, and thus the PDF can be found by the inverse Fourier Transform. Am I missing something?
Comment: I am not familiar with "characteristic functions", but you can use Mathematica to find the fourier transform of $\psi \left( \nu  \right)$ and evaluate the integral in question, you will find the  two results different.
Comment: I have searched the internet for  characteristic function and its relationship with fourier transform and it is indeed as you said, but notice that the rage of integration for both of them is from -infinity to infinity while the integral in question is from zero to infinity, i think this what you are missing.
Comment: This is only because the range of the x random variable in my case is from 0 to infinity. This doesn't mean that this is no longer a Fourier transform of the PDF. This implies that the inverse Fourier transform of the characteristic function should give the PDF, which doesn't happen for some reason I cannot pinpoint!!
Comment: Maybe you have an error in your calculations, check it again??
Comment: OK, when I did it manually, I got the PDF correctly. So, the derivation is correct. But Mathematica and MATLAB failed to evaluate it using the inverse Fourier transform, even at specific points. This is problematic, because this is the PDF of one random variable. What I wish to find is the PDF of the summation of such random variables, which requires numerical evaluation. It is not possible to do it manually.
Comment: Why did you assume that $$\nu = -\frac{1}{1+x}$$ and not $$1-\frac{1}{1+x}$$ In my analysis $1/(1+x)^2$ is the PDF and $1-1/(1+x)$ is the CDF of a random variable $X$. So, it makes more sense use $$\nu = 1-\frac{1}{1+x}$$ in which case we are encountered with the problem of evaluating complex exponential at $\infty$!! How to solve it in this case?


How do I access my fields in a .tpl file

Question: I have a file views-view--MyView--block-2.tpl.php
there is no $fields variable, it doesn't exist.
if I do a foreach($view->field as $v=>$f)  and print both $v will show me all my fields in that view and display

created
title
field_op_author_nid
field_main_image_fid
field_teaser_value
comment_count

but $f is always empty.
How do I access my fields?
[EDIT]
Ok, let me clarify. the .tpl file I have renders just fine. the markup I have in that file shows up. The issue is that I cannot access the fields I set up in the view and displaye. I tried changing the filename to include -fields- and I indeed did get the $fields variable. This looks to be exactly the same as the $view variable that I had before, which I don't know how to get data out of. I can see the fields I need in there but the var_dump($fields( or $ view)) is about 20 pages long and every example I have seen has been just using $fields["fieldname"], which does not work.
Am I just maybe doing this wrong entirely? What is the best way to set these up, is it to have multiple tpl files, one for each field and row?
Answer: I THINK you need to be using views-view-fields--myview--block-2.tpl.php to access $fields.
Answer: Simple concept is go to theme information and check the tpl file names in the field you want and choose the unique file name from there and create the tpl file.
Now click on the first file name which will give you the basic code, copy that in your tpl file now in comment you will see all four variable try with $row and print the whole array and find all your other fields as well.
Answer: If you are not sure about the file name for your template you can use the theme developer module. You can just point and click on in your browser to find the right theme and template functions.
Answer: By the time the processes reach the views-view.tpl.php level, the Fields have already been rendered and are not available for further manipulation.
I would need more information about what you are actually trying to do, as well as which versions of Drupal and Views you are using, in order to suggest a specific solution. For example: are you trying to manipulate the data within the fields, or just wrap the field content in different HTML?
Either way, you can do a lot of manipulation of the field data and wrapping HTML within the Views UI, using the "Rewrite Results" option within each field's settings, or you can get even more control over the wrapping HTML by utilizing the Semantic Views module.
Comment: Drupal 6, OpenPublish, Views2. OpenPublish Theme is my base theme     Here's what I am trying to accomplish:   I have a new view, lets call it MyView.   In MyView I have 2 Displays, both of type Block lets call them Block_1 and Block_2   I want to wrap the fields in the block with my own markup so that they render differently.     I currently have .tpl files for this but I cannot figure out how to access the fields I added to the View.     I want to do this right, but I'm not experienced with Drupal so I don't really know any best practices or anything (sorry I can't add line breaks?)
Comment: I would highly recommend the Semantic Views module - it lets you easily alter the HTML that wraps many different Views components from within the Views UI.
Comment: Semantic Views is EXACTLY what I need! Thank you so much!


Is there an interactive notebook tool for R as iPython Notebook?

Question: I've been using RStudio and I like it, but for the type of work I do a Notebook environment (like iPython Notebook) is more useful than an IDE. Is there an iPython Notebook equivalent for R?
Comment: I haven't encountered such a tool.  However, I thought iPython actually has some capabilities of interfacing with R.  Additionally, have you tried the nifty "Compile Notebook" button in RStudio (requires the knitr package FYI)?  I tried iPython briefly, but I just couldn't get used to the notebook style.  What work do you do that lends itself so well to that?
Comment: The packlage linked from the answer unfortunately doesn't provide an interactive notebook interface.  It's just some sort of report generator: makes R code and results embeddable in in a document.  This is a common misconception about what a notebook interface is, mostly propagated by people who have never worked with real notebooks, like the ones used by Mathematica and IPython.  Here's a real notebook interface for R: https://github.com/takluyver/IRkernel
Comment: Yes, iPython has evolved into the [Jupyter Project](http://jupyter.org/), which fully supports interactive iPython-style notebooks for Python, R and Julia. There is a test-drive server here: https://tmpnb.org
Answer: There is a R Notebook with rCharts which embed D3/JavaScript in R Notebook using rCharts and Shiny.  rCharts allows you to create charts using an iPython-like interface.  In the link you will see a video that shows how it works.


How can I tell if modelling/testing with Binomial/Beta is correct?

Question: My standard disclaimer:  I'm a programmer, not a stats guy, mostly wanting to understand statistical tests for optimizing web apps.
Let's say I want to measure monetization rate of users.  "How many users monetize?".  This is a yes/no question on each user.
After reading Wikipedia, I might say, "This yes/no question is a Bernoulli variable.  I can model groups of users as instances of the Binomial distribution, and use Binomial and Beta distributions to estimate p and compare the groups of users."
But, what if p is not the same for every user in the group?  Some users will always monetize, some users will never monetize...  Some will monetize after their next payday.
Even though the question is a yes/no question, is it sometimes wrong (or rather, how safe is it) to use Binomial/Beta distributions to model a collection this way?  These distributions assume a constant p, but when p might vary for each user am I getting incorrect results?
Answer: A heterogeneous mixture of $p$'s will make a single-$p$ binomial model have the wrong variance structure.
A beta-binomial model allows for a (beta-) distribution of $p$'s and then conditional on $p$, a binomial (specifically bernoulli) distribution of individual responses. If I was taking a Bayesian approach this would be my first thought.
If you have good predictors of the $p$'s you might consider a GLM, so that conditionally the distribution is binomial and the model for the mix of $p$'s is determined by the predictors in the model.
Outside of that, and in a more general class of models, you might consider random effects models, specifically GLMs with random effects.


Sed unknown option to `s when i try to pass 2 variables

Question: i have a problem with my sed command in my sh script.
I already tried without -i, replacing my file with a backup using > and cp, removing the simples quotes and trying with double after s/ and /g.
echo '=> Enabling Cryptodisk in GRUB'
sed -i 's/#GRUB_ENABLE_CRYPTODISK=y/GRUB_ENABLE_CRYPTODISK=y/g' /etc/default/grub #Enabling Cryptodisk in GRUB

echo '=> Adding Preload_modules in GRUB'
sed -i 's/GRUB_PRELOAD_MODULES="part_gpt part_msdos"/GRUB_PRELOAD_MODULES="part_gpt part_msdos luks cryptodisk"/g' /etc/default/grub #Adding Preload_modules in GRUB

echo '=> Adding Linux CMDLINE in GRUB'
GUIDMAPPER=$(blkid | grep ^/dev/mapper | awk -F "\"" '{print $2}') #Get mapper GUID
GUIDSDA3=$(blkid | grep ^/dev/sda3 | awk -F "\"" '{print $2}') #Get sda3 GUID
sed -i 's/GRUB_CMDLINE_LINUX=""/GRUB_CMDLINE_LINUX="cryptdevice=${GUIDMAPPER}=${GUIDSDA3}:cryptroot root=/dev/mapper/cryptroot crypto=whirlpool:aes-xts-plain64:512:0:"/g' /etc/default/grub #Adding Linux CMDLINE in GRUB

The error is triggered for the last sed call, everything else work fine.
sed -i 's/GRUB_CMDLINE_LINUX=""/GRUB_CMDLINE_LINUX="cryptdevice=${GUIDMAPPER}=${GUIDSDA3}:cryptroot root=/dev/mapper/cryptroot crypto=whirlpool:aes-xts-plain64:512:0:"/g' /etc/default/grub

Tested so far... :
sed -i 's/GRUB_CMDLINE_LINUX=""/GRUB_CMDLINE_LINUX="cryptdevice='"$GUIDMAPPER"'='"$GUIDSDA3"':cryptroot root=/dev/mapper/cryptroot crypto=whirlpool:aes-xts-plain64:512:0:"/g' /etc/default/grub #Adding Linux CMDLINE in GRUB

Result
Thanks (sorry for my bad english)
Comment: Your replacement contains `/`, try other delimiters, say `,`
Answer: Edit :
It works by escaping '\' in replacement.
sed -i 's/GRUB_CMDLINE_LINUX=""/GRUB_CMDLINE_LINUX="cryptdevice='"$GUIDMAPPER"'='"$GUIDSDA3"':cryptroot root=\/dev\/mapper\/cryptroot crypto=whirlpool:aes-xts-plain64:512:0:"/g' /etc/default/grub #Adding Linux CMDLINE in GRUB

Thanks to Wiktor Stribiżew
Comment: With `sed -i 's,GRUB_CMDLINE_LINUX="",replacement,g'` you don't have to escape the slashes.


Can you block redirections?

Question: The HTML redirection will work on numerous websites, but It won't work on website like Youtube, Soundcloud.
Ex:
<code><meta http-equiv="refresh" content="1;url=https://soundcloud.com">
</code>
This does not work. Did Soundcloud block the redirections?
Comment: I don't understand what you are asking. Are you making a userscript?
Comment: works for me in Chrome. I don't believe there's any way a receiving website could detect that you arrived via such a redirect.
Comment: Define "does not work".
Comment: @Hobbit I want to do a HTML redirection from my page to soundcloud, but it does not work.
Comment: @Zoidberd Nothing happens.
Comment: Does the dev console give any errors?
Comment: Refused to display 'https://soundcloud.com/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
Comment: I'm doing a Facebook tab application, so I guess it's an iframe.
Answer: No, a site cannot prevent another site from redirecting to it.
Comment: what does this have to do with redirects?
Comment: Everything if the redirect is in an iFrame! Should of told it was in an iFrame though.
Answer: Test in another browser and check your network settings - it is not possible for a website to know how you visited it - they can only tell where you were before your landed on their site (via HTTP referrer)
Comment: And HTTP Referrer can easily be spoofed.
Comment: @Maxwell You didn't specify that this code was running from within an iframe. If it isn't, then that documentation isn't what you're looking for - but yes, sites can tell a browser not to load the page if it's in an iframe, but only if the browser understands that header. (Most modern browsers do)

Can you block redirections?


Use 's' instead of 'self' as the first parameter of python method, is this good?

Question: class actor:
    def __init__(s, own, *arg, name:str, **karg):
        s.gv=own.gv; s.own=own; s.name=name; own.sub[s.name]=s; s.sub=dict()
        s._setup_(*arg, **karg)

This is part of my code. i often use s instead of self to shrink the code.
Comment: it's not "wrong", but it goes against universal convention and is therefore more or less guaranteed to confuse those who read your code. Not to mention it's much less descriptive - 1-letter variable names are almost universally a bad idea, with the common exception of "counter" variables in loops.
Comment: I've been moving all of my code to sanskrit, so `def __init__(स्वाध्याय, ...)`. Needless to say, code reviews have  been contentious.
Comment: Not a good practice but the compiler won't throw any error
Comment: There is no prize for the shortest code :-) I suggest that you use `self` per normal convention, **and** put one statement per line instead of the semicolons. Fewer lines does not always mean quicker to read.
Comment: So what is your question?
Comment: Sometimes i'm using Chinese characters as variable name.
Answer: No, this is not good. PEP8 states that self should always be used:

Always use self for the first argument to instance methods.
Always use cls for the first argument to class methods.

Trying to neaten code by resorting to more obscure names may save you tens of keystrokes, but it will ultimately make your code harder to read.
When you follow common, standardized conventions (like using self), that's one less thing someone reading your code will need to interpret. If you're reading code and you see self, you know that it's referring to the instance object being worked on. It's implicit. You don't even need to look at the parameters to see that.
Answer: You can, but the readability of your code comes down when you tend to not follow the general convention. You wouldn't face any error though.
Answer: While this will work and shrink the code, this makes it harder to read (in my opinion), and will cause problems if you ever use "s" as a variable - which is much more common than "self".
Comment: i've marked s as a keyword in my ide, so this is not a big problem when i'm the only programmer in my organisation.
Comment: @Milowork *so what are you asking?*
Answer: Based on the official Python documentation, the use of self is only a convention, but it is highly recommended to follow the convention:

Often, the first argument of a method is called self. This is
nothing more than a convention: the name self has absolutely no
special meaning to Python. Note, however, that by not following the
convention your code may be less readable to other Python programmers,
and it is also conceivable that a class browser program might be
written that relies upon such a convention.

PEP8 also recommends naming the first argument self:

Always use self for the first argument to instance methods.


Values Repeat When Scrolling in TableView

Question: When I tap a button in a custom cell and then scroll down (or up) another cell button is also tapped. I see that it's tapped because the button outlet that I created for the button is disabled.
My cellForRowAtIndexPath has a reuseIdentifier for the cell:
var cell: FeedTableViewCell? = tableView.dequeueReusableCellWithIdentifier("MusicCell") as? FeedTableViewCell

Considering I have the degueueReusableCellWithId in the cellForRowAtIndexPath do I need a prepareForReuse? When I add the prepareForReuse in my custom cell file, the cell just goes back to the default values (obviously because I reset it to the default values). Problem is I want it to keep the value of each indexPath.row.
This is how I'm querying the values:
 override func queryForTable() -> PFQuery {
        var query:PFQuery = PFQuery(className:"Music")

        if(objects?.count == 0)
        {
            query.cachePolicy = PFCachePolicy.CacheThenNetwork
        }

        query.orderByAscending("videoId")

        return query
    }

This is the numberOfRowsInSection and cellForRowAtIndexPath
 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return  objects!.count
    }

   override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {

        var cell: FeedTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? FeedTableViewCell
        if(cell == nil) {
            cell = NSBundle.mainBundle().loadNibNamed("FeedTableViewCell", owner: self, options: nil)[0] as? FeedTableViewCell
        }
        if let pfObject = object {
               //I took out the irrelevant methods. I can add them if that makes a difference...
                var votes:Int? = pfObject["votes"] as? Int
                if votes == nil {
                    votes = 0
        }
        cell?.votesLabel?.text = "\(votes!)"

}

I'm registering this in the viewDidLoad above the super.viewDidLoad()
 tableView.registerNib(UINib(nibName: "FeedTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier)

This is my  button query in the customCell:
@IBAction func heartButton(sender: AnyObject) {
        if(parseObject != nil) {
            if var votes:Int? = parseObject!.objectForKey("votes") as? Int {
                votes!++

                parseObject!.setObject(votes!, forKey: "votes")
                parseObject!.saveInBackground()

                votesLabel?.text = "\(votes!)"
            }
        }
        heartOutlet.enabled = false
}

Any help and suggestions mean a lot.
Thank you.

REFRENCE LINKS I USED:
I referred to several links but they were in objective-c and didn't help:
UICollectionView Tap Selects More Than One Cell
How to use prepareForReuse method
I also referred to the docs, and that didn't help much.
Comment: Add the code of UITableView DataSource Methods
Comment: Where i'm querying and sending the data from the tableView? Or from the custom cell? @HarikrishnanT
Comment: Tbale view data source methods include `cellForRowAtIndexPath`, `numberOfCellsInTableView` etc. please post the code of `cellForRowAtIndexPath`(and `willDisplayCell` if you are using that too). There has to be something wrong you are doing in there that causes the issue.
Comment: Just updated the question, thank you @HarikrishnanT
Answer: From the code you have posted, it is clear that you are not setting the enabled property of the UIButton with respect to the DataSource(The array and its objects you are using to load the tableview, that is the elements in objects array). Whatever objects that array contains, add a property to determine if the condition for the button should be true or false, and then in cellForRowAtIndexPath set the enabled property of the button according to that. When the button is clicked, add a callback to the ViewController(using a delegate) and set the property there.
Sample Code
In custom cell class:
protocol CellButtonDelegate
{
    func buttonClicked(cell : PFTableViewCell)
}

public var delegate : CellButtonDelegate?

public var buttonEnabled : Bool?
{
    get
    {
        return heartOutlet.enabled
    }
    set
    {
        heartOutlet.enabled = newValue
    }
}

@IBAction func heartButton(sender: AnyObject) {
        if(parseObject != nil) {
            if var votes:Int? = parseObject!.objectForKey("votes") as? Int {
                votes!++

                parseObject!.setObject(votes!, forKey: "votes")
                parseObject!.saveInBackground()

                votesLabel?.text = "\(votes!)"
            }
        }
        delegate?.buttonClicked(self)
}

In ViewController:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {

        var cell: FeedTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? FeedTableViewCell
        if(cell == nil) {
            cell = NSBundle.mainBundle().loadNibNamed("FeedTableViewCell", owner: self, options: nil)[0] as? FeedTableViewCell
        }
        if let pfObject = object {
               //I took out the irrelevant methods. I can add them if that makes a difference...
                var votes:Int? = pfObject["votes"] as? Int
                if votes == nil {
                    votes = 0
        }
        cell?.buttonEnabled = objects[indexPath.row].isEnabled //The new property you need to add. true by default
        cell?.delegate = self //Make sure you implement the delgate
        cell?.votesLabel?.text = "\(votes!)"
        return cell?
}

func buttonClicked(cell : PFTableViewCell)
{
     //Here, get the indexPath using the cell and assign the new property in the array.
}

Please note that the above code is rough. Just get the idea from the code and implement it as per your requirement.
Comment: I'm using ParseUI to get the objects, so `objects` array is a ParseUI property that stores those objects. Can you provide some sample code? I'm having trouble understanding the logic of where this should be placed. Isn't it only relevant in the `cellForRowAtIndexPath`? Why would it be relevant in the `objects` array if I'm having a problem with the UIButton and the datasource? @HarikrishnanT
Comment: Sample code added. You will have to make some changes in the current logic after referring the code I posted.
Comment: Trying it now! Thanks a lot!
Comment: 2 problems:  I get this error: `Cannot assign value of type "FeedTableViewController" to type CellButtonDelegate?` for this link: '        cell?.delegate = self` I added the delegate in the cell like this: `var delegate : CellButtonDelegate?` right under the class definition of the cell. and for this function:  `func buttonClicked(cell : PFTableViewCell){  cell.buttonEnabled = objects![indexPath.row].isEnabled = true  }` which I put in the `cellForRowAtIndexPath` right under the other methods and i get this error: `value of type PFTableViewCell has no member buttonEnabled`. Suggestions?
Comment: I'm also getting an error when adding the delegate to the class definition*. @HarikrishnanT
Comment: Delegate shouldn't be added in class definition, put it right outside the class definition below the import statements. I thought you were aware of the basic syntax. :-)
Comment: Hey, I did add it there but I got an error so I declared in right below... EDIT: Now i fixed it and added it on the top. I got it initialized and it works now. My issue is making a an array and adding boolean condition for each button. I can't make it a dictionary, which is what I'm trying. @HarikrishnanT
Comment: The proper way of doing it adding a boolean property to the object of the array `objects` to determine if the button has to be enabled or not. :-)
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/96263/discussion-between-lukesivi-and-harikrishnan-t).
Comment: How do I add a property to the array objects to determine if the button has been enabled or not? Sorry for the newbie questions! :) @Harikrishnan


Lebesgue measure of a subspace of lower dimension is 0

Question: I'm currently reading Rudin's book Real and Complex analysis. In page 52 he says

To prove (e) let $T:R^k\to R^k$ be linear. If the range of T is a subspace Y of lower dimension then $m(Y)=0$.

I don't quite get that part. I'm guessing it could be deduced from the determinant formula given in page 54 but that seems like a circular reasoning. Is there a direct argument without using determinants and the decomposition of a linear map as a finite product of the type of linear maps given in page 54?
Comment: Is Fubini's Theorem too advanced for that point in the book?
Comment: Yep, It comes way after that.
Answer: One could decompose the subspace into countably many unit hypercubes of the same dimension as the subspace. Then note that each hypercube is contained in an open set of arbitrarily small measure and hence has measure 0. Then use countable additivity.
Comment: I kinda get where you are going, you want to regard $Y$ as $0\times...\times 0\times R^m$, that has measure 0 cause it is written as a countable union of hypercubes $[0,1]^m$ that have measure 0 (from this logic chain it is clear cause page 52 shows that $m([0,1]^m)=vol([0,1]^m)=0$ cause it has a side 0. But I think the problem is when you regard $Y$ as $0\times ...\times 0\times R^m$. They are homeomorphic, yes, but $(0,1)$ and $R$ are also isomorphic but their measure isn't the same. I'm writing a possible fix using determinants and the like tomorrow,there is no other option, thanks anyways.
Comment: What do you mean by "An hypercube of the same dimension as the subspace". I got a more or less similar idea but it seems kinda lenghty.
Comment: @xD13G0x If the subspace is of dimension $k$ then the hypercube is homeomorphic to $[0,1]^k$.
Comment: I don't get the meaning of "dimension of an hypercube". By an hypercube you mean a subset of Y?.
Comment: @xD13G0x if you think of the Y as $\mathbb{R}^m$, then translates of the subset of all points with all coordinates between 0 and 1 inclusive.
Comment: Ok, so we write Y as a countable union of some kind of subsets of Y that are translates of each others and we now have to prove that any of these subsets have measure 0. How can we build those open sets of arbitrary small measure in the simplest way?
Comment: @xD13G0x Translate $Y$ so it is the first few coordinates. I would show the unit hypercube $[0,1]^m$ has arbitrarily small measure by considering the open set $(-\epsilon,1+\epsilon)^m\times (0,\epsilon)^{n-m}$.
Answer: First prove that if $B$ is a box in $\mathbf{R}^k$, then the set $T(B)=\{Tx:x\in B\}$ is lebesgue measureable, and
$$m(T(B))=\det(T)|B|.$$
then uses the definition of outer measure, it easy to see that for any set $E$
$$m^*(T(E))\leq \det(T)m^*(E)$$
Note that if $m(E)$ is infinite, we can write $E=\cup_{n=1}^\infty E\cap B(0,n)$.
Answer: Let $k < n$, where $k,n \in \Bbb N$ and $n > 1$. Let $Q \subset \Bbb R^n$ be a $k$-dimensional subspace of $\Bbb R^n$. Let $\{\mathrm e_i| 1 \le i \le n\}$ denote the unit vectors along the axes.
Consider the k-dimensional hyperplane $K$, spanned by the unit vectors $\mathrm e_i, 1 \le i \le k$. Define $\forall m \in \Bbb Z, \; I_m := [m,m+1)$.
We have
$$K = \bigcup_{m_i \in \Bbb Z} (\Pi_{i=1}^k I_{m_i} \times \Pi_{i=k+1}^n \{0\})$$
$K$ is covered by a countable collections of hypersquares with hyperarea $1$. Suppose $S_r$ is an enumeration of these hypersquares. Consider the hypercubes $C_r :=S_r \times \Pi_{k+1}^{n-1} (-\frac{1}{2},\frac{1}{2}) \times (-\frac{\varepsilon}{2^r},\frac{\varepsilon}{2^r})$, with hypervolume $\frac{\varepsilon}{2^r}$. We have:
$$K \subset \bigcup_{r = 1}^\infty C_r \\
    \mu(K) \le \sum_{r=1}^\infty = \varepsilon $$
As $\varepsilon$  was chosen arbitrarily, $\mu(K) = 0$.
Let Q be an arbitrary k-dimensional subspace of $\Bbb R^n$ and $\mathrm e'_i, 1 \le i \le k$ be an orthonormal  basis of $Q$, obtained through Gram-Schmidt process. Extend this basis to $\{\mathrm e'_i| 1 \le i \le k\} \cup \{\mathrm w_j, k+1 \le j \le n\}$ with $\{\mathrm w_j| k+1 \le j \le n\}$ being orthogonal to $Q$. Denote the space spanned by  $\{\mathrm w_j, k+1 \le j \le n\}$, by $Q^{\bot}$. Applying Gram-Shmidt process to $\{\mathrm w_j | k+1 \le j \le n\}$, we obtain obtain the orthonormal set $\{\mathrm e'_j | k+1 \le j \le n\}$ spanning $Q^{\bot}$.
Let $x_i$ and $x'_i, 1 \le i \le n$ denote the coordinates of $\mathrm x \in \Bbb R^n$ with respect to $\{\mathrm e_i| 1 \le i \le n\}$ and $\{\mathrm e'_i| 1 \le i \le n\}$ respectively, i.e. $\mathrm x = \sum_1^n x'_i \mathrm e'_i = \sum_1^n x_i \mathrm e_i$.
For $x, y \in \Bbb R^n$, $\sum_1^n (x_i -y_i)^2 = \sum_1^n (x'_i -y'_i)^2$. Therefore we obtain the same metric space by defining distance function to be $d(x,y) = \sum_1^n (x'_i -y'_i)^2$ with the lebesgue measure defined on this metric coincinding with the original one and the same reasoning as in case of co-ordinate hyperplane K, gives $\mu(Q) = 0$.
Answer: Here's how I think Rudin wants you to think about it.
First, it suffices to show that the k-dimensional measure of a lower dimensional hypersquare is always zero, because then the lower dimensional subspace can be written as a countable union of these squares.
You then consider partitions of the whole k-dimensional space into 2^-n boxes, and keep only those finitely many boxes that intersect your hypersquare. Each time you increment n, the union of the finite collection either stays the same or shrinks. All you need to show is that it shrinks to arbitrarily small measure as n goes to infinity. This is pretty obvious. For example, take any n, and note that there will come a point when at least half of the mass in that union will be discarded.
Answer: You can prove this by first proving the lemma that if for all i belonging to some set A:

Ei belong to M (where M is a sigma algebra)
mu(Ei) > 0 (where mu is a positive sigma-finite measure on M)
Ei and Ej are disjoint if i!=j and j belongs to A

then:
A is at-most countable A.
This can be proved via Lema 6.9 (page 121 of Rudin's RCA) and then using the logic regarding at-most countability at the end of section 4.15 (page 84 of Rudin's RCA).
Once we have proved the above:
Let Y be a subspace of lower dimension in Rk (the Euclidian space of dimension k). There exists P belonging to Rk that does not belong to Y.
For all t belonging to R1 (the set of real numbers), let Qt = Y + P*t
if m(Y) > 0, then Qt satisfy the conditions of the lemma at the beginning. Therefore, m(Qt) > 0 on at-most countable t, which is a contradiction, because m(Qt) = m(Y+t) = m(Y) for all t belonging to R1 (which is uncountable).


PHP - take element from array and push it at the beginning

Question: Is there a simple way to take specific array element, and place it at the beginning of the array?
For example I have this array:
<code>$array = [

    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Joana Doe',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Some Name',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Another Name',
        'age'  => 44,
        'sex'  => 'f'
    ],

];
</code>
and I want to take array where name is Some Name, and place it at the beginning  of the array.
Answer: If you want to search by value and reindex the array, then something like that should do.
<code>function searchForId($name, $array) {
   foreach ($array as $key => $val) {
       if ($val['name'] === $name) {
           return $key;
       }
   }
   return null;
}
$id = searchForId('name', $array);
if($id !== null) {
   $tmp = $array[$id];
   unset($array[$id]);
   $array = array_values($array);
   array_unshift($array, $tmp);
}
</code>
Answer: Of course. Simple element swapping.
<code>$tmp = $array[2]; // 3rd element
$array[2] = $array[0]; // set 3rd to values with 1st
$array[0] = $tmp; // set first to values with 3rd
</code>
Comment: I'd assume they want to keep the order of the rest of the elements, so effectively "move them all up" by one index ...


Allowing a CGI-EXE app to access the registry

Question: I have an exe app that I run on IIS (from C:\inetpub\wwwwroot in DefaultAppPool) and needs to access the registry, but it doesn't work, it seems like it doesn't have permission. What's weird is I ran it on Windows 8 and it works fine, but on Windows 7 and Server 2012 hosts it doesn't run. I know registry keys have permissions and I've even tried to set Everyone to full control, but it still fails. I also tried both HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE, no luck.
I did read about trust levels but I'm unsure what those are, the only references I could find related to ASP apps. Is there something I need to add to web.config or to IIS management console to allow my CGI app to access the Registry, ideally under HKCU?
Edit: Tried to see what went on with Process Monitor but I can't see any line about it. I did however write this quick Perl script to replicate this:
use strict;
use Win32API::Registry qw (:ALL);
print "Content-type: text/plain\n\n";

RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\TestingRegistryAccess", 0, "", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, [], my $rh, []) or print regLastError();
if(defined($rh)) { RegCloseKey($rh); }

And the output is:
Access is denied.

So there has to be some way to allow a CGI script to access this, it works on my Win8 desktop.
Comment: So I managed to find a way to get it to work, but it doesn't really solves my issue completely. If I create a new user, then in IIS mgr I convert the folder into an Application, set Connect As.. to that user, then set `cgi runAsProcess` to true, then it works. But that's a ridiculous setup process, plus leaves a new user with a non-expiring password, bad security practice. I cannot believe that writing a config file in the current folder (accessible to all) is a better way to do things. **How** am I suppose to store basic settings for a CGI app (like database address, etc) ??
Comment: Why you want to read the registry, and not a config file ? You cant port your cgi to a linux os too and tbe api to read the registry overload your CGI IMO
Comment: It stores config values like database name etc. And that isn't really the point. It works on Windows 8 so I'm assuming there's some way to allow a CGI app to write to the registry as a normal app would...
Comment: For security purpose the cgi is isolated, that mean its not secure on your win8.
Comment: How is writing in the current folder more secure than writing a registry key..?
Comment: Run processmonitor and watch for acces denied.., the user is more like IUSR.. for IIS user, everyone is not enought.
Comment: Both are not secure, but its isolated in the cgi folder, you dont open other location. Its called risk management
Comment: Ok then, tell me how to give a CGI app access to write to a file? I just tried this Perl script: `print "Content-type: text/plain\n\n";
open(F, ">test.txt") or print $!;` and it failed with **Permission denied**.
Comment: Add the Internet guest account IUSR to a folder your cgi got access to
Comment: Nope, regardless of what permission I give to `C:\inetpub\wwwroot\test`, even **Full Control** to **Everyone**, I still can't write to a file. Yet if I try to write to `C:\temp` it works on the first try, without any change needed. Still, all of this doesn't solve my initial problem.
Comment: Try by setting the CGI option to impersonate user at off, will run under system account...
Comment: As CGI are executed, and can never be downloaded (unless someone hack the server, but at this point he got the full server access), I used to hard code my setting in the CGI I used to create (but it was in C). The fact you write seem a bigger problem, but I know that you can create a folder outside of inetpub, but at this point a more skilled IIS user will have to help you correctly. Like the php.ini, or such config, it's stored on the server too. The problem with the registry is that if your write there and he corrupt it, you break the windows or user profile, in folder there is quota, etc..
Answer: After hours working on this, I figured out that Registry permissions do not matter when it comes to CGI scripts, even with Everyone having Full Access IIS still blocks it. The only way a web app can access the registry is by running as a normal user, instead of as IUSR.
I wrote a batch script that assigns a username/password to virtual directories, creates a virtual directory for my web app, and allows the app to run:
@echo off
set /p id="Username: "
set /p pass="Password: "
%windir%\system32\inetsrv\appcmd set site "Default Web Site" -virtualDirectoryDefaults.userName:%id% -virtualDirectoryDefaults.password:%pass%
%windir%\system32\inetsrv\appcmd add vdir /app.name:"Default Web Site/" /path:/nodepoint /physicalPath:"%CD%"
%windir%\system32\inetsrv\appcmd set config -section:isapiCgiRestriction /+[path='%CD%\app.exe',allowed='true',description='Web App']

Hopefully this is useful to others as well.


unable to get email from facebook login in angularjs

Question: I am working on a website. I added fb login to the website but the problem is I am not getting the email id, only able to fetch name, id, profile.
Can some help me. this is my code:
<code>function _getFacebookProfileDetails() {
        var deferred = $q.defer();
        FB.api('/me','GET', { fields: 'id, first_name, last_name, email, picture' }, function (response) {
            console.log(response);
            if (!response || response.error) {
                deferred.reject('Error occured');
            } else {
                deferred.resolve(response);
            }
        });
        return deferred.promise;
    }
</code>
Answer: You need to have the email permission to get the email address. Look at
this answer
Comment: @user10428712 that is the fields you are requesting in your API call, that is _not_ where you ask for permission, that happens during login.
Comment: I already requested for this.  **FB.api('/me','GET', { fields: 'id, first_name, last_name, email, picture' },**
Comment: How to do that? plz help
Comment: follow this official  FB SDK link. https://developers.facebook.com/docs/reference/javascript/FB.login/v3.2


Erro em Insert ... Values usando oracle erro 00936

Question: estou a tentar fazer um insert numa table e está-me sempre a dar o erro 00936 que diz missing expression quando chega na linha de comando cmd.executenonquery. Alguem me sabe ajudar?
Código que tenho:
<code>using (OracleConnection conn = new OracleConnection(ConfigurationManager
                   .ConnectionStrings["CegosReportsOra"].ConnectionString))
    {
        conn.Open();

        using (OracleCommand cmd = new OracleCommand())

        {

            String lang = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString();
            lang = "";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            cmd.CommandText = "INSERT INTO ECICalendarEvent_Test(title, description, event_start, event_end, all_day) Values(@title, @description, @event_start, @event_end, @all_day)";

            cmd.Parameters.Add("@title", OracleDbType.Varchar2).Value = cevent.title;
            cmd.Parameters.Add("@description", OracleDbType.Varchar2).Value = cevent.description;
            cmd.Parameters.Add("@event_start", OracleDbType.Date).Value = cevent.start;
            cmd.Parameters.Add("@event_end", OracleDbType.Date).Value = cevent.end;
            cmd.Parameters.Add("@all_day", OracleDbType.Char).Value = cevent.allDay;
            cmd.ExecuteNonQuery();
            int key = 0;
            using (conn)
            {

                //get primary key of inserted row
                cmd.CommandText = "SELECT max(event_id) FROM ECICalendarEvent_Test where title=@title AND description=@description AND event_start=@event_start AND event_end=@event_end AND all_day=@all_day";
                cmd.Parameters.Add("@title", OracleDbType.Varchar2).Value = cevent.title;
                cmd.Parameters.Add("@description", OracleDbType.Varchar2).Value = cevent.description;
                cmd.Parameters.Add("@event_start", OracleDbType.Date).Value = cevent.start;
                cmd.Parameters.Add("@event_end", OracleDbType.Date).Value = cevent.end;
                cmd.Parameters.Add("@all_day", OracleDbType.Char).Value = cevent.allDay;

                key = (int)cmd.ExecuteScalar();
            }

            return key;
        }
</code>
O problema está na execução da linha de executenonquery. Alguem me sabe dizer que e que me estou a esquecer?
Obrigado.
Tenho uma tabela com 6 colunas em que uma delas é a chave primária (ID).
Me ajudem...
Comment: Já tentou adicionar ''entreosParametros'' no insert?
Answer: Boa Tarde, mano.
Ao que parece você está passando cinco valores por parâmetro, e existem seis campos para serem preenchidos. Passe o valor do id no INSERT ou crie uma Sequence para o mesmo. O erro diz existe um campo sendo omitido e que é obrigado a ser preenchido, que no caso é a primary key.
Comment: ola mano @Luccas Ramos. Como é que eu faço isso para criar uma sequencia para o id?
Comment: Segue o script como ficaria, mais ou menos.
Answer: Ficaria mais ou menos assim.
INSERT INTO ECICalendarEvent_Test(seu_id,title, description, event_start, event_end, all_day) Values(nome_sequence.NEXTVAL,@title, @description, @event_start, @event_end, @all_day)";

--Crie a sequence no banco ...
CREATE SEQUENCE nome_sequence
 START WITH     1 -- Valor em que a sequence vai iniciar
 INCREMENT BY   1 -- de quanto em quanto será incrementado
;


Custom JComboBox hiding JPopupMenu

Question: I'm having a little headache with a situation. Maybe some of you have been through this before and can show me another way or even my error here.
I need to add a JTree inside a JComboBox and the code below works like a charm.
public class HierarchyComboBox extends JComboBox {
    HierarchyTree ht = new HierarchyTree();
    HierarchyComboBox box;
    JPopupMenu popup;
    MouseAdapter adapter = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            if (arg0.getClickCount() == 1) {
                removeAllItems();
                addItem(ht.getSelectedLevel());
//              ((JPopupMenu) comp).setVisible(false);
            }
        }
    };

    PopupMenuListener listener = new PopupMenuListener() {
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            if (box == null) {
                box = (HierarchyComboBox) e.getSource();
                if (popup == null) {
                    final Object comp = box.getUI().getAccessibleChild(box, 0);
                    if (!(comp instanceof JPopupMenu))
                        return;
                    popup = (JPopupMenu) comp;
                }
                popup.removeAll();
                ht.getTreePane().setBorder(null);
                ht.getTreePane().setPreferredSize(new Dimension(box.getWidth(), 200));
                MyTree tree = (MyTree)ht.getTreePane().getViewport().getComponent(0);
                tree.addMouseListener(adapter);
                popup.add(ht.getTreePane());
            }
        }
        @Override
        public void popupMenuCanceled(PopupMenuEvent arg0) { }
        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) { }
    };

    public HierarchyComboBox() {
        setEditable(true);
        addPopupMenuListener(listener);
    }
}

but I added this component to 2 different dialogs.
The first one I can click and the selection is added to the JComboBox
and the second, doing EXACTLY the same instantiation, and the same tests
The component has a different behaviour:
 - The JPopupMenu disappears
 - It doesn't add the selection to the combo
Any ideas here?
Thanks in advance..
Answer: As shown in Providing a Custom Renderer, "A combo box uses a renderer to display each item in its menu." You could render the tree in a custom ListCellRenderer. Alternatively,

Render the tree in an adjacent component in response to an ActionListener.
Use a hierarchical model, shown here.
Comment: In this case, it would render the entire tree in one option. Is this what you're saying?
Comment: Yes, but I prefer your popup approach as the other component.
Comment: Exactly. I solved the problem. But thanks for the answer, @trashgod
Answer: I noticed that the JPopupMenu was loosing it's focus.
The solution was to add the component as the last component of the Panel.
Comment: Yes, I can, but not now. It tells me to wait 2 days.
You can accept your own answer in 2 days

Custom JComboBox hiding JPopupMenu