Can not aggregate a global field: Mathematical expression

Question: I installed "Physical Fields" and I created a view (block) to display the total weight of the order in the shopping cart.
In my view I added the "price" and "quantity" fields, then I add a "Global: Mathematical Expression" field with "[field_weight] * [quantity]".
I activated the aggregation on the view and I configure the parameters of the group for Global field: Mathematical expression sue "sum".
The view does not work and does not display sums.
I have seen that the field of mathematical expression can not be aggregated.
How do I get the sum of this field ?
Can I do this in the "template.php" file of my theme? If yes, how ?
Here is the export of my view :
Thank you.
<code>$view = new view();
$view->name = 'commerce_order_weight';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'commerce_order';
$view->human_name = 'Poids de la commande';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Poids panier';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  7 => '7',
  3 => '3',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relation: Commande Drupal Commerce : Referenced line items */
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['id'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['table'] = 'field_data_commerce_line_items';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['field'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['required'] = TRUE;
/* Relation: Commerce Line item : Referenced products */
$handler->display->display_options['relationships']['commerce_product_product_id']['id'] = 'commerce_product_product_id';
$handler->display->display_options['relationships']['commerce_product_product_id']['table'] = 'field_data_commerce_product';
$handler->display->display_options['relationships']['commerce_product_product_id']['field'] = 'commerce_product_product_id';
$handler->display->display_options['relationships']['commerce_product_product_id']['relationship'] = 'commerce_line_items_line_item_id';
/* Relation: Commerce Product : Referencing Nœud */
$handler->display->display_options['relationships']['field_produit']['id'] = 'field_produit';
$handler->display->display_options['relationships']['field_produit']['table'] = 'commerce_product';
$handler->display->display_options['relationships']['field_produit']['field'] = 'field_produit';
$handler->display->display_options['relationships']['field_produit']['relationship'] = 'commerce_product_product_id';
/* Champ: Commande Drupal Commerce : Identifiant (ID) de la commande */
$handler->display->display_options['fields']['order_id']['id'] = 'order_id';
$handler->display->display_options['fields']['order_id']['table'] = 'commerce_order';
$handler->display->display_options['fields']['order_id']['field'] = 'order_id';
$handler->display->display_options['fields']['order_id']['label'] = '';
$handler->display->display_options['fields']['order_id']['exclude'] = TRUE;
$handler->display->display_options['fields']['order_id']['element_label_colon'] = FALSE;
/* Champ: Commerce Product : Poids */
$handler->display->display_options['fields']['field_weight']['id'] = 'field_weight';
$handler->display->display_options['fields']['field_weight']['table'] = 'field_data_field_weight';
$handler->display->display_options['fields']['field_weight']['field'] = 'field_weight';
$handler->display->display_options['fields']['field_weight']['relationship'] = 'commerce_product_product_id';
$handler->display->display_options['fields']['field_weight']['label'] = '';
$handler->display->display_options['fields']['field_weight']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_weight']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_weight']['click_sort_column'] = 'weight';
$handler->display->display_options['fields']['field_weight']['group_column'] = 'entity_id';
/* Champ: Commerce Line Item : Quantité */
$handler->display->display_options['fields']['quantity']['id'] = 'quantity';
$handler->display->display_options['fields']['quantity']['table'] = 'commerce_line_item';
$handler->display->display_options['fields']['quantity']['field'] = 'quantity';
$handler->display->display_options['fields']['quantity']['relationship'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['fields']['quantity']['label'] = '';
$handler->display->display_options['fields']['quantity']['exclude'] = TRUE;
$handler->display->display_options['fields']['quantity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['quantity']['precision'] = '0';
$handler->display->display_options['fields']['quantity']['separator'] = '';
/* Champ: SUM(Global : Expression mathématique) */
$handler->display->display_options['fields']['expression']['id'] = 'expression';
$handler->display->display_options['fields']['expression']['table'] = 'views';
$handler->display->display_options['fields']['expression']['field'] = 'expression';
$handler->display->display_options['fields']['expression']['group_type'] = 'sum';
$handler->display->display_options['fields']['expression']['label'] = 'Poids de la commande';
$handler->display->display_options['fields']['expression']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['expression']['precision'] = '0';
$handler->display->display_options['fields']['expression']['separator'] = '';
$handler->display->display_options['fields']['expression']['expression'] = '[field_weight]*[quantity]';
/* Filtre contextuel: Commande Drupal Commerce : Identifiant (ID) de la commande */
$handler->display->display_options['arguments']['order_id']['id'] = 'order_id';
$handler->display->display_options['arguments']['order_id']['table'] = 'commerce_order';
$handler->display->display_options['arguments']['order_id']['field'] = 'order_id';
$handler->display->display_options['arguments']['order_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['order_id']['exception']['title'] = 'Tout';
$handler->display->display_options['arguments']['order_id']['default_argument_type'] = 'commerce_cart_current_cart_order_id';
$handler->display->display_options['arguments']['order_id']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['order_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['order_id']['summary_options']['items_per_page'] = '25';
/* Critère de filtrage: Commande Drupal Commerce : Type de commande */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'commerce_order';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'commerce_order' => 'commerce_order',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$translatables['commerce_order_weight'] = array(
  t('Master'),
  t('Poids panier'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('Line items referenced by commerce_line_items'),
  t('Products referenced by commerce_product'),
  t('Nœud referencing products from field_produit'),
  t('.'),
  t('Poids de la commande'),
  t('Tout'),
  t('Block'),
);
</code>
Answer: Views relies on the database to perform aggregation. Since the math field's value does not live in the database it doesn't work.
You can however use Views Aggregator plus that uses the calculated values instead.

this module:

enumerates group members
produces tallies, i.e. textual histograms
aggregates on Views PHP code-snippet evalutations
can filter out result rows on regexp patterns
gives you sorting on Views' Math expressions
can process Webform submissions
lets you add your own custom aggregation functions
Comment: Thank you for your reply, but I want to do this without add-on. How to do with a custom template ? I've created views-view-field--commerce-order-weight--block--expression.tpl.php in the templates folder of my theme. What should I write in this file ?
Comment: It is not what templates are supposed to do... A template is for wrapping HTML tags around predefined variables. You should not be processing any logic in your template files. If you must process logic, do it in a preprocess hook in `template.php` file. I have no idea what to put there, always used the power of modules.


Gostaria de saber porque este código em Javascript não está funcionando (programa simples)

Question:

var verificador = document.window.getElementById('input#verificador');
var nacionalidade = document.window.getElementById('div#nacionalidade');

function verificar() {

  if (verificador == 'brasil' || verificador == 'BRASIL' || verificador == 'Brasil') {
    nacionalidade.innerText = 'Você é brasileiro';

  } else {

    nacionalidade.innerText = 'Você é estrangeiro';

  }
}

Teste de nacionalidade

  Digite o país que você nasceu:<input type="text" name="verificador" id="verificador" />
  <input type="button" value="Clique e descubra sua nacionalidade " onclick="verificar()" />

Nacionalidade

Comment: Observação: se o id do elemento é `verificador`, você deve usar `getElementById('verificador')`. O valor `'input#verificador'` faria sentido apenas se utilizar com o `querySelector`.
Comment: Dito isso, o que deveria ser `document.window`?
Answer: Seu código está com vários erros, nessa linha está errado.
var verificador = document.window.getElementById('input#verificador');
var nacionalidade = document.window.getElementById('div#nacionalidade');

Você não pode colocar o window depois de document e o getElementById não pode selecionar seletores que nem o querySelector ele só aceita o nome do id.
var verificador = window.document.getElementById('verificador');
var nacionalidade = window.document.getElementById('nacionalidade');

E na parte do if você não está comparando o value que é o valor do input com id="verificador"
if (verificador == 'brasil' || verificador == 'BRASIL' || verificador == 'Brasil')
{
   nacionalidade.innerText = 'Você é brasileiro';

}

É só colocar o value na frente de verificador.
if (verificador.value == 'brasil' || verificador.value == 'BRASIL' || verificador.value == 'Brasil')
{
   nacionalidade.innerText = 'Você é brasileiro';

}

Pronto! era só isso, agora está funcionando perfeitamente.

<!DOCTYPE html>

    <meta charset="UTF-8">

Teste de nacionalidade

    Digite o país que você nasceu:<input type="text" name="verificador" id="verificador"/>
    <input type="button" value="Clique e descubra sua nacionalidade " onclick="verificar()"/>

Nacionalidade

Answer: Alguns erros:

o getElementById quer somente a ID, como tens input#verificador é um seletor de CSS completo e pode funcionar por exemplo com o `querySelector``
usa somente document e não `document.window``
usa .value para extrair o valor do input
coloquei os var dentro da função para evitar casos em que o JavaScript é lido antes do HTML ser interpretado. Assim fica também mais encapsulado
usei o .toLowerCase para aceitar letras grandes e pequenas

function verificar() {
  var verificador = document.getElementById('verificador').value;
  var nacionalidade = document.getElementById('nacionalidade');
  if (verificador.toLowerCase() == 'brasil') {
    nacionalidade.innerText = 'Você é brasileiro';
  } else {
    nacionalidade.innerText = 'Você é estrangeiro';
  }
}

Teste de nacionalidade

Digite o país que você nasceu:<input type="text" name="verificador" id="verificador" />
<input type="button" value="Clique e descubra sua nacionalidade " onclick="verificar()" />

Nacionalidade


variavel php dentro de linha javascript (Sweet Alert) PHP

Question: Estou criando uma mensagem utilizando o recurso Sweet Alert, e onde preciso apresentar o nome da pessoa dentro de um Alert vindo de uma variável PHP.Assim, Gostaria de saber como posso fazer corretamente.
Obs:. A conexão com o banco de dados está funcionando perfeitamente.

            echo "";
  }
      ?>

Repare que na linha eu informei o código PHP

text: 'Gostaria de cadastrar os documentos do usuário **<?php echo $usuario ['nome']?>**?',
Comment: Possível duplicata de [Posso fazer o JavaScript escrever PHP?](https://pt.stackoverflow.com/questions/90095/posso-fazer-o-javascript-escrever-php)
Answer: Você já "abriu" com o <?php no começo, não precisa abrir de novo basta concatenar com a variavel
echo "";

Ou
echo "";

Comment: Utilizei o seu exemplo 2 concatenando e funcionou perfeitamente. Agradeço a sua grande ajuda Taynan


Versão do PHP sem phpinfo() ou phpversion()

Question: Alguém sabe informar como verificar a versão do php sem utilizar o retorno de métodos?
Olhei o php.ini e lá também não tem muita coisa útil. O mais perto que cheguei foi a versão do php.exe e php-cgi.exe que é 188.8.131.52.
Posso confiar na informação dos executáveis ou essa não é a versão real que está instalada?
Publicação IIS(6 ¬¬)... Tem como saber por lá? Googlei mas não achei nada de útil...
Comment: `php -v` no terminal
Answer: Por linha de comando:
php.exe --version

Mas cuidado: se você tiver mais de uma versão do php na máquina, o executável de linha de comando pode ser de uma, e o que roda no webserver, de outra.
Comment: **Muito obrigado!**
Fui até a pasta de instalação do php e executei o comando e fucionou perfeitamente.
Comment: Fiz o teste na minha maquina Win7-32 e ele gerou uma mensagem dizendo que o "CLI parou de funcionar" (isso acontece com qualquer parâmetro passado para o php.exe).

Mas após ver o que esse cara diz:
http://web2.0entrepreneur.com/31/cli-has-stopped-working-on-windows-vista.html

 Ficou claro que o erro não era o sistema operacional ou uso do "XAMP".. O  problema é a versão do PHP... Apesar do "erro", o php não para de funcionar e o CLI(command line interface) também não.

Parece que na versão 5.2.0 e 5.2.3 esse erro não acontece.
Answer: No meu computador existem duas versões do PHP, como sou desenvolvedor WEB eu testo as versões principalmente para visualizar a performance.
A versão que está configurada no meu IIS, eu verifico com phpversion(); (que na pergunta você não quer) em um arquivo do PHP dessa forma:
<?php
   phpversion();

Ou pelo plugin que eu instalo, que é PHP Manager (apesar que a versão correspondente para usá-lo é a IIS 7+).
Por linha de comando, igual @bfavaretto já relatou, consigo verificar dentro da respectiva pasta qual versão é aquele PHP.
As duas maneiras são confiáveis e lhe dão o resultado esperado.


How to display the output of my module without clearing cache and refresh page?

Question: I created a very simple module which generates a tag cloud based on user input; you can see the code here.
<code>// wow.module
function wow_menu() {
    $items = array();
    $items['wall/of/words'] = array(
        'title' => 'Wall of Words',
        'page callback' => 'wow_page',
        'access arguments' => array('access content'),
        'file' => 'wow.inc',
        'weight' => 1,
    );
    $items['admin/settings/wall/of/words'] = array(
        'title' => 'On this date module settings',
        'description' => 'Description of your On this date settings page',
        'page callback' => 'wow_admin_page',
        'page arguments' => array('wow_admin'),
        'access arguments' => array('administer wow settings'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

function wow_admin_page() {
    return 'hey';
}

// wow.inc
function wow_page() {
    $output = array(
        'form' => drupal_get_form('wow_cake'),
        'words' => _getWords(),
        'min_count' => 0,
        'max_count' => 999
    );
    drupal_add_js(drupal_get_path('module', 'wow') . '/js/jquery.tagcloud.js');
    drupal_add_js('jQuery(function(){jQuery("#wow-container .cloud a").tagcloud({size:{start:20,end:40,unit:"pt"},color:{start:"#46A7E3",end:"#0969A3"}})})', 'inline');
    return theme('wow_template', array('output' => $output));
}

function wow_theme($existing, $type, $theme, $path) {
    return array(
        'wow_template' => array(
            'template' => 'wow_template'
        ),
    );
}

function wow_cake($form, &$form_state) {
    $form = array();

    $form['title'] = array(
        '#type' => 'textfield',
        '#title' => t('Thank you for...'),
        '#size' => 60,
        '#maxlength' => 128,
        '#required' => TRUE,
    );

    $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function wow_cake_validate(&$form, &$form_state) {

    if (empty($form_state['values']['title'])) {
        form_set_error('title', t('Please leave a thank you message in highlighted field below.'));
    }
}

function wow_cake_submit(&$form, &$form_state) {

    if (_create_node($form_state['values']['title'], $form_state['values']['title'])) {
        drupal_set_message(t('Thank you for your kind words!'), 'status');
    }
}

function _getWords() {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node', '=')
            ->propertyCondition('status', 1, '=')
            ->propertyCondition('type', 'wall_of_words', '=');
    $result = $query->execute();
    $nodes = $result['node'];
    $fields = field_info_instances('node', 'wall_of_words');
    $field_id = $fields['body']['field_id'];
    field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
    $wall = '';

    foreach ($nodes as $node) {

        if (!empty($node->body['und']['0']['value'])) {

            $wall .= trim($node->body['und']['0']['value']);
            $wall .= " ";
        }
    }
    if (!empty($wall)) {
        $cloud = explode(" ", $wall);
    }

    return array_count_values($cloud);
}

function _create_node($title = "", $body = "", $language = "und") {

    $node = (object) array();
    $node->type = 'wall_of_words';
    $node->status = 1;
    $node->promote = 0;
    $node->sticky = 0;
    $node->revision = 0;
    $node->language = $language;
    $node->title = $title;
    $node->body[$language][0] = array(
        'value' => $body,
        'format' => 'full_html',
    );
    if ($node = node_submit($node)) {
        node_save($node);
    }

    return $node;
}
</code>
My issue: when I visit another page and come back to the page that I generated with my module the output of the content does not get displayed unless I clear the cache and visit the page again.
Answer: there's this method here :
drupal_page_is_cacheable
actually i never used it, but cacheexclude module does,
maybe you have to hook_init too and check for your path there !
Comment: I tried the cache exclude module and it didn't seem to fix the problem, not sure if its related to cache or an issue with my module's code.
Comment: could you add your path in cacheexclude ?
Comment: wall/of/words ?
Comment: yup, added it, cleared cache after too
Comment: give $GLOBALS['conf']['cache'] = FALSE; a try
Comment: Call this method  drupal_flush_all_caches();
Answer: If you get different results between generating a page from scratch and fetching from cache, then that generally means that something in the page generation cycle is not stored in cache. The fact that cacheexclude does not solve the problem suggests that it isn't the page cache that's the problem.
One thing I note is that you are declaring a template for your output, but it's not shown. The declaration in your hook_theme() function is missing the variables argument, so this may well be a theme-related problem.
On a stylistic note, all functions in a module should be named either modulename_otherstuff or _modulename_otherstuff, to minimise the chance of duplicates.
Comment: I took your advice and added a variables array and re-factored the code a bit: http://pastie.org/private/ewspqhstsak8gq1ltauh0q same issue though, i'll keep playing around with it today


How can I increase the accuracy of my playing?

Question: I am a musician who used to play the piano a lot, but now plays the pipe organ in churches, recitals, and competitions. At age 17, with 13 years of musical experience, I very rarely play a piece 100% accurately note-wise, despite having tirelessly honed and refined my posture and practice techniques. However, I am told that I excel at inspiring an emotional reaction in the audience.
It may be because I have so much fun playing the music that the details get lost and there is greater sloppiness.
Why am I not playing accurately? What is the secret to being able to play a piece accurately, while still enjoying the music?
Comment: Organ music is multilayered.  You need to get each layer self-consistent.  Try working on your listening skills, so that you can enjoy the multi-layered experience without either getting lost in a general mushiness or just tracking a single voice.  If you play with fun and emotion, you are deviating from a mechanically exact execution and it is important that *all* voices and deviations stay in their own shape and character.  That's really hard to do consistently, and the way to start is to *notice* it.  So practice listening to contrapuntal music.
Answer: I've found that inaccurate playing is usually a result of trying to play something that is ahead of your ability.  If it's still sounding good, this likely means not that you lack the skill but that you have not put enough time and effort into learning and practising rather than performing.  You should slow the piece down while practising and focus on accuracy.  Only increase the speed when you can play it correctly.
Of course, there are other reasons including familiarity with the instrument (a bigger problem with changing pianos than with a portable instrument), nervousness, or failing to warm up.  These are largely solved by practice as well.
I do not expect playing better to decrease your enjoyment — quite the opposite!
Answer: Forgive me for a back-to-basics answer.  But this technique has worked for me in music, language learning and even farming.  I know you said you have really  sharp practice techniques but:
If the inaccuracies are always with the same passages, the time-honored metronome-repetition-speed up metronome-repeat method still might be of use - I find that I want to be able to play problematic phrases at least twice as fast as ultimately desired before I can work on expression and interpretation without having to 'think' about the notes.  But I start considerably slower than than ultimately desired to be sure I have proper fingering. (could there also be fingering alternatives that would be more natural for you? (just a  thought)).
On guitar, I have spent hours on 8 measures.  Not really fun but the result was worth it.
The point is not the blazing speed - it is to get the finger-memory strong.  Then the brain can trust the fingers with the technical execution.
Answer: A reason why you don't pay as much attention to detail as the next performer is as broad as a field. My only solution would be to start paying more attention to the detail and try and train yourself to enjoy performing with as much attention to detail as you can.
I personally get quite a lot of enjoyment out of performing music with as much attention to detail as I can. Sure, it can be a lot of fun to slug out a few tunes over a few beers (probably wouldn't be doing this on a pipe organ in church) but there's always room for detail.
Your original question

Why am I not playing accurately?

you haven't made the commitment to yourself to do so.

What is the secret to being able to play a piece accurately, while
  still enjoying the music?

There isn't one. It's a mindset that you need to achieve yourself.
Answer: I became frustrated with my own playing for the same reason.  Decided to do some research and came across some great books, including "The Practice Revolution" by Philip Johnston.   It completely turned my playing around.   There are a number of well known but often forgotten steps to practicing music perfectly.    Another useful book was "The Perfect Wrong Note" by William Westney.
The methods outlined in the book show how to practice properly so that the music comes out fluently.    Too often musicians practice mistakes into their playing.   Following a good practice routine helps move away from these bad practice habits.   Best of all, a good practice technique will help you to learn faster!
A lot of the practice methods focus on relaxation and concentration.   Lack of these two will make your playing prone to errors.
Answer: I am not an expert but I think that playing inaccurately is in fact "inaccurately" (with quotes).
I think you just put in your own twist at the moment (some sort of improvisation). I think it is of the utmost importance not to copy pieces 100% but to have your own swing in it. At least, that is my opinion. Some people can be recognized that way because they create their own sound and you would recognize that within a song.
Btw, you aren't nervous on stage, are you?
Comment: "your own twist" would be under his control.  His question, however, was about things coming out different than he wants them.  Sloppy phrasing or a run segmented by its fingering distribution rather than the musical accents is not an art form.  There is a world of difference between sloppy playing and deliberately expressive playing.  The former bores and/or irritates the audience, the latter captures it.  The former takes away from the music, the latter adds to it.  Not every addition may be wise, but it should be coherent and intentional.


I am creating an shopping cart and i get some error

Question: I get such output error:

Exception while loading the app : java.lang.IllegalStateException:
  ContainerBase.addChild: start: org.apache.catalina.LifecycleException:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'myDBAuthenticationService': Injection of
  autowired dependencies failed; nested exception is
  org.springframework.beans.factory.BeanCreationException: Could not
  autowire field: private
  org.o7planning.springmvcshoppingcart.dao.AccountDAO
  org.o7planning.springmvcshoppingcart.authentication.MyDBAuthenticationService.accountDAO;
  nested exception is
      org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDAO': Injection of autowired
  dependencies failed; nested exception is
  org.springframework.beans.factory.BeanCreationException: Could not
  autowire field: private org.hibernate.SessionFactory
  org.o7planning.springmvcshoppingcart.dao.impl.AccountDAOImpl.sessionFactory;
  nested exception is
  org.springframework.beans.factory.BeanCreationException:
      Error creating bean with name 'sessionFactory' defined in org.o7planning.springmvcshoppingcart.config.ApplicationContextConfig:
  Bean instantiation via factory method failed; nested exception is
      org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method
  'getSessionFactory' threw exception; nested exception is
      java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V

<code><!-- language: none -->

In MYDBAuthenticationService.java

    package org.o7planning.springmvcshoppingcart.authentication;

    import java.util.ArrayList;
    import java.util.List;

    import org.o7planning.springmvcshoppingcart.dao.AccountDAO;
    import org.o7planning.springmvcshoppingcart.entity.Account;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;

    @Service
    public class MyDBAuthenticationService implements UserDetailsService {

        @Autowired
        private AccountDAO accountDAO;

        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            Account account = accountDAO.findAccount(username);
            System.out.println("Account= " + account);

            if (account == null) {
                throw new UsernameNotFoundException("User " //
                        + username + " was not found in the database");
            }

            // EMPLOYEE,MANAGER,..
            String role = account.getUserRole();

            List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>();

            // ROLE_EMPLOYEE, ROLE_MANAGER
            GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);

            grantList.add(authority);

            boolean enabled = account.isActive();
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;

            UserDetails userDetails = (UserDetails) new User(account.getUserName(), //
                    account.getPassword(), enabled, accountNonExpired, //
                    credentialsNonExpired, accountNonLocked, grantList);

            return userDetails;
        }

    }

    In applicationcontextconfig.java
    package org.o7planning.springmvcshoppingcart.config;

    import java.util.Properties;

    import javax.sql.DataSource;

    import org.hibernate.SessionFactory;
    import org.o7planning.springmvcshoppingcart.dao.AccountDAO;
    import org.o7planning.springmvcshoppingcart.dao.OrderDAO;
    import org.o7planning.springmvcshoppingcart.dao.ProductDAO;
    import org.o7planning.springmvcshoppingcart.dao.impl.AccountDAOImpl;
    import org.o7planning.springmvcshoppingcart.dao.impl.OrderDAOImpl;
    import org.o7planning.springmvcshoppingcart.dao.impl.ProductDAOImpl;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.support.ResourceBundleMessageSource;
    import org.springframework.core.env.Environment;
    import org.springframework.jdbc.datasource.DriverManagerDataSource;
    import org.springframework.orm.hibernate5.HibernateTransactionManager;
    import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    import org.springframework.web.multipart.commons.CommonsMultipartResolver;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;

    @Configuration
    @ComponentScan("org.o7planning.springmvcshoppingcart.*")
    @EnableTransactionManagement
    // Load to Environment.
    @PropertySource("classpath:ds-hibernate-cfg.properties")
    public class ApplicationContextConfig {

        // The Environment class serves as the property holder
        // and stores all the properties loaded by the @PropertySource
        @Autowired
        private Environment env;

        @Bean
        public ResourceBundleMessageSource messageSource() {
            ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
            // Load property in message/validator.properties
            rb.setBasenames(new String[] { "messages/validator" });
            return rb;
        }

        @Bean(name = "viewResolver")
        public InternalResourceViewResolver getViewResolver() {
            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
            viewResolver.setPrefix("/WEB-INF/pages/");
            viewResolver.setSuffix(".jsp");
            return viewResolver;
        }

        // Config for Upload.
        @Bean(name = "multipartResolver")
        public CommonsMultipartResolver multipartResolver() {
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();

            // Set Max Size...
            // commonsMultipartResolver.setMaxUploadSize(...);

            return commonsMultipartResolver;
        }

        @Bean(name = "dataSource")
        public DataSource getDataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();

            // See: ds-hibernate-cfg.properties
            dataSource.setDriverClassName(env.getProperty("ds.database-driver"));
            dataSource.setUrl(env.getProperty("ds.url"));
            dataSource.setUsername(env.getProperty("ds.username"));
            dataSource.setPassword(env.getProperty("ds.password"));

            System.out.println("## getDataSource: " + dataSource);

            return dataSource;
        }

        @Autowired
        @Bean(name = "sessionFactory")
        public SessionFactory getSessionFactory(DataSource dataSource) throws Exception {
            Properties properties = new Properties();

            // See: ds-hibernate-cfg.properties
            properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
            properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
            properties.put("current_session_context_class", env.getProperty("current_session_context_class"));

            LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

            // Package contain entity classes
            factoryBean.setPackagesToScan(new String[] { "org.o7planning.springmvcshoppingcart.entity" });
            factoryBean.setDataSource(dataSource);
            factoryBean.setHibernateProperties(properties);
            factoryBean.afterPropertiesSet();
            //
            SessionFactory sf = factoryBean.getObject();
            System.out.println("## getSessionFactory: " + sf);
            return sf;
        }

        @Autowired
        @Bean(name = "transactionManager")
        public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
            HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);

            return transactionManager;
        }

        @Bean(name = "accountDAO")
        public AccountDAO getApplicantDAO() {
            return new AccountDAOImpl();
        }

        @Bean(name = "productDAO")
        public ProductDAO getProductDAO() {
            return new ProductDAOImpl();
        }

        @Bean(name = "orderDAO")
        public OrderDAO getOrderDAO() {
            return new OrderDAOImpl();
        }

        @Bean(name = "accountDAO")
        public AccountDAO getAccountDAO()  {
            return new AccountDAOImpl();
        }

    }

    In pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                         http://maven.apache.org/maven-v4_0_0.xsd">

        <modelVersion>4.0.0</modelVersion>
        <groupId>org.o7planning</groupId>
        <artifactId>SpringMVCAnnotationShoppingCart</artifactId>
        <packaging>war</packaging>
        <version>1.0.0</version>
        <name>SpringMVCAnnotationShoppingCart Maven Webapp</name>
        <url>http://maven.apache.org</url>

        <properties>
            <java-version>1.7</java-version>
        </properties>

        <repositories>
            <!-- Repository for ORACLE JDBC Driver -->
            <repository>
                <id>codelds</id>
                <url>https://code.lds.org/nexus/content/groups/main-repo</url>
            </repository>
        </repositories>

        <dependencies>

            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>

            <!-- Servlet API -->
            <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
                <scope>provided</scope>
            </dependency>

            <!-- Jstl for jsp page -->
            <!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>

            <!-- JSP API -->
            <!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
                <scope>provided</scope>
            </dependency>

           <!-- Apache Commons FileUpload -->
           <!-- http://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
           <dependency>
               <groupId>commons-fileupload</groupId>
               <artifactId>commons-fileupload</artifactId>
               <version>1.3.1</version>
           </dependency>

            <!-- Spring dependencies -->
            <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>

            <!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>

            <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>

            <!-- http://mvnrepository.com/artifact/org.springframework/spring-orm -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>

            <!-- Spring Security Artifacts - START -->
            <!-- http://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>4.0.4.RELEASE</version>
            </dependency>

            <!-- http://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>4.0.4.RELEASE</version>
            </dependency>

            <!-- http://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs -->
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-taglibs</artifactId>
                <version>4.0.4.RELEASE</version>
            </dependency>

            <!-- Spring Security Artifacts - END -->

            <!-- Hibernate -->
            <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.1.0.Final</version>
            </dependency>

            <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
                <version>4.3.1.Final</version>
            </dependency>

            <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-c3p0</artifactId>
                <version>5.1.0.Final</version>
            </dependency>

            <!-- MySQL JDBC driver -->
            <!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.34</version>
            </dependency>

              <!-- Email validator,... -->
            <!-- http://mvnrepository.com/artifact/commons-validator/commons-validator -->
            <dependency>
                <groupId>commons-validator</groupId>
                <artifactId>commons-validator</artifactId>
                <version>1.5.0</version>
            </dependency>

        </dependencies>

        <build>
            <finalName>SpringMVCAnnotationShoppingCart</finalName>

        </build>

    </project>
</code>
Comment: it looks like hibernate spring version mismatch
Comment: how can i chaneg it where is the error barath plzz help
Comment: share the pom.xml
Comment: check this out http://stackoverflow.com/questions/31547015/hibernate-5-java-lang-nosuchmethoderror-org-jboss-logging-logger-debugf
Comment: plz look a my pom.xml if there is some error i am just begginer of spring and these code are copied by me to learn it but it didnot run
Comment: There are some conflic with Hibernate 5. Please using Hibernate 4. Remove Hibernate 5.1.0.Final in pom.xml.
Comment: @searching9x i have done the same but i get the same error "
Comment: has it fully runned on your computer??
Comment: You wrong code ApplicationContextConfig.java : import org.springframework.orm.hibernate5.HibernateTransactionManager;  ==> Change package hibernate5 ==> hibernate4.
Comment: sorry i didnt get you??
Comment: i m using mysql not oracle ... doesnt it run on mysql??
Comment: ok wait for some tym if it runs i will answer you :)
Comment: @searching9x  hlo bro the program is running but the css is not opening?
Answer: Try, Commenting out below :
<code>        <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
      <!--  <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>5.1.0.Final</version>
        </dependency> -->
</code>
Comment: i can provide u github link will you fix the error??? i have used netabeans


The derivative of $ \ln\left(\frac{x+2}{x^3-1}\right)$

Question: I know it is a simple question, but what would be the next few steps in this equation to find the derivative?
$$f(x)= \ln\left(\frac{x+2}{x^3-1}\right)$$
Comment: You could use the property $\ln \frac{u}{v} = \ln u - \ln v$ before you differentiate.
Comment: Have you tried using the chain rule here?
Comment: do i find the derivative of ln for both the numerator and denominator?
Comment: Yes, you'll have to find the derivative of them combined, using the quotient rule.
Comment: oh wow, makes sense
Comment: @HDE226868 : You're mistaken.  One does not _have to_ use the quotient rule for this.  See my answer below. ${}\qquad{}$
Comment: @MichaelHardy I used "have" for the first part of my response; Cheng was asking whether or not both the numerator and the denominator needed to be dealt with. The answer to that is, of course, yes. I apologize if I caused confusion.
Answer: Let:
$$h(x) = \ln(x) \hspace{.3cm} \text{and} \hspace{.3cm} g(x) = \frac{x + 2}{x^3 - 1}$$
so that:
$$f(x) = h(g(x))$$
Now using the chain rule:
$$f'(x) = h'(g(x))g'(x)$$
Comment: I don't think that is the best way to do this.  (See my answer.)
Comment: Definitely agree, breaking up the logarithm gets rid of using the quotient rule
Answer: For $$f(x)= \ln\left(\frac{x+2}{x^3-1}\right)$$
Start by re-writing the logarithm as
$$\frac{d}{dx}\left(\ln\left(\frac{x+2}{x^3-1}\right)\right)=\frac{d}{dx}\left(\ln({x+2})-\ln({x^3-1})\right)$$$$=\frac{d}{dx}\left(\ln({x+2})\right)-\frac{d}{dx}\left(\ln({x^3-1})\right)= \color{blue}{\frac{1}{x+2}-\frac{3x^2}{x^3-1}}$$
Answer: It would also be advantageous here to apply a property of logarithms, specifically:
$$
\ln(a/b)=\ln(a)-\ln(b).
$$
Applying this to your given equation will considerably simplify your derivative, as it will eliminate your need to use the quotient rule as part of your chain rule calculation.
Answer: I would NOT use the chain rule before doing this:
\begin{align}
f(x) = \ln\frac{x+2}{x^3-1} & = \ln (x+2) - \ln(x^3-1) \\[10pt]
& = \ln(x+2) - \ln((x-1)(x^2+x+1)) \\[10pt]
& = \ln(x+2) - \ln(x+1) - \ln(x^2+x+1).
\end{align}
Answer: I suppose that you know that the derivative of $y=\ln(x)$ is $y'=\dfrac{1}{x}$, and you know the chain rule that gives the derivative of a composite function:
$y=f(g(x)) \rightarrow y'=f'(g(x))g'(x)$.
Use these  and you have:
$$y=\ln\frac{x+2}{x^3-1} \rightarrow y'=\frac{x^3-1}{x+2} \left(\frac{x+2}{x^3-1} \right)'$$
Now use the derivative of a fraction.... and you find the result.
Answer: Look up the chain rule on youtube. There is a lot of songs ect that will make this easy as cake.
Answer: $$f'_{(x)}=\frac{1}{\frac{x+2}{x^3-1}}\left (\frac{(x^3+1)-(x+2)3x^2}{(x^3-1)^2}\right)$$
$$f'_{(x)}=\frac{-(2x^3+6x^2-1)}{(x+2)(x^3-1)}$$
Comment: would the first term then become x^3-1/x+2?
Comment: yes.now you can simplify this.
Comment: @Cheng I have edited the answer.
Comment: Innumerable postings here recommend this needlessly complicated way of doing this.


Is this correct ? (generating a Truncated-norm-multivariate-Gaussian)

Question: If $X\in\mathbb{R}^n,~X\sim \mathcal{N}(\underline{0},\sigma^2\mathbf{I})$
i.e.,
$$
f_X(x) = \frac{1}{{(2\pi\sigma^2)}^{n/2}} \exp\left(-\frac{||x||^2}{2\sigma^2}\right)
$$
I want an analogous version of a truncated-normal-distribution in a multivariate case.
More precisely, I want to generate a norm-constrained (to a value $\geq a$) multivariate Gaussian $Y$ s.t.
$$
f_Y(y) = \begin{cases} c.f_X(y), \text{ if } ||y||\geq a \\[2mm]
0, \text{ otherwise }.
\end{cases}
$$
where $c=\frac{1}{Prob\big\{||X||\geq a\big\}}$

Now I observe the following:
If $x=(x_1,x_2,\ldots,x_n)$, $||x||\geq a$
$\implies |x_n|\geq T\triangleq \sqrt{\max\left(0,\left(a^2-\sum_1^{n-1}x_i^2\right)\right)}$
Therefore by choosing $x_1,\ldots,x_{n-1}$ as Gaussians samples, one may restrict $x_n$ as a sample out of a Truncated-normal-distribution (following a Gaussian-tail $\geq T$) distribution $\mathcal{N}_T(0,\sigma^2)$, except for its sign chosen randomly with probability $1/2$.
Now my question is this,

If I generate each vector sample $(x_1,\ldots,x_n)$ of $(X_1,\ldots,X_n)$ as,

$x_1,\ldots,x_{n-1}\sim \mathcal{N}(0,\sigma^2)$
and
$x_n = Z_1 *Z_2~$ where, $~Z_1\sim\{\pm1 ~\text{w.p.}~ 1/2\}$, $Z_2\sim\mathcal{N}_T(0,\sigma^2)$, (i.e. a truncated-scalar-normal RV with $T(x_1,\ldots,x_{n-1})\triangleq \sqrt{\max\left(0,\left(a^2-\sum_1^{n-1}x_i^2\right)\right)}$

Will $(X_1,X_2,\ldots,X_n)$ be a norm-constrained ($\geq a$) multivariate Gaussian? (i.e. same as $Y$ defined above).
  How should I verify?
  Any other suggestions if this is not the way?

EDIT:
Here is a scatter-plot of the points in 2D case with norm truncated to values above "1"

Note: There are some great answers below, but the justification of why this proposal is wrong is missing. In fact, that's major point of this question.
Comment: @Xi'an Thanks for your query & interest. Here is my reasoning for your point: The algorithm in question needs RVs $X_1\ldots X_n$, that are $n-1$ Gaussians and a Truncated-Gaussian when they are seen **per sample**; more specifically, one of the distributions varies every sample. They are *not* the respective marginals. Because, each $x_i,i=1,\ldots,n-1$ appears in two terms: $x_i$ and $x_n$; and $x_n$ is clearly time varying as the truncation threshold varies for every sample. The decomposition proof that you provided has a problem in exactly the same sense. Marginals are just not available.
Comment: @Xi'an Thanks a lot for your patient answers. I finally understood my mistake with your stimulation, and I have also written [my own detailed answer](http://stats.stackexchange.com/a/158814/38377) explaining the same. But sorry, hope you don't mind, I should probably accept whuber's answer for his detailed explanation that helps in actually solving the problem.
Comment: Your (incorrect) algorithm generates$$X_1,\ldots,X_{n-1}\sim \mathcal{N}(0,\sigma^2)$$first and then$$X_n\sim\mathcal{N}_T(0,\sigma^2)$$given $X_1,\ldots,X_{n-1}$. Hence, the first generation is from the marginal and the second generation is from the conditional. My proof shows the marginal is not a (n-1) dimensional Gaussian distribution.
Comment: @Xi'an Conditional Gaussian does not mean Marginal Gaussian!!
Comment: @Xi'an Okay, my point is this. When $X_1,\ldots,X_{n-1}$ are generated as Gaussians, and later terms depend on these values, marginals of $X_1,\ldots,X_{n-1}$ *won't* be Gaussians. What you said is exactly the same. They might be "Conditionally Gaussian" but definitely not "marginally Gaussian". My earlier comment means that.
Comment: I am afraid you are misunderstanding the notion of a [marginal distribution](https://en.wikipedia.org/wiki/Marginal_distribution): If $X\sim f(x)$ and $Y|X=x\sim g(y|x)$, $f$ is the marginal density of $X$. If nothing else, because $$\int f(x)g(y|x)\text{d}y=f(x)$$
Answer: The multivariate normal distribution of $X$ is spherically symmetric. The distribution you seek truncates the radius $\rho=||X||^2$ below at $a$.  Because this criterion depends only on the length of $X$, the truncated distribution remains spherically symmetric.  Since $\rho$ is independent of the spherical angle $X/||X||$ and $\rho\,\sigma$ has a $\chi(n)$ distribution, you therefore can generate values from the truncated distribution in just a few simple steps:

Generate $X \sim \mathcal{N}(0,\mathbb{I}_n)$.
Generate $P$ as the square root of a $\chi^2(d)$ distribution truncated at $(a/\sigma)^2$.
Let $Y = \sigma P\, X/||X||$.

In step 1, $X$ is obtained as a sequence of $d$ independent realizations of a standard normal variable.
In step 2, $P$ is readily generated by inverting the quantile function $F^{-1}$ of a $\chi^2(d)$ distribution: generate a uniform variable $U$ supported in the range (of quantiles) between $F((a/\sigma)^2)$ and $1$ and set $P = \sqrt{F(U)}$.
Here is a histogram of $10^5$ such independent realizations of $\sigma P$ for $\sigma=3$ in $n=11$ dimensions, truncated below at $a=7$.  It took about one second to generate, attesting to the efficiency of the algorithm.

The red curve is the density of a truncated $\chi(11)$ distribution scaled by $\sigma=3$. Its close match to the histogram is evidence of the validity of this technique.
To get an intuition for the truncation, consider the case $a=3$, $\sigma=1$ in $n=2$ dimensions.  Here is a scatterplot of $Y_2$ against $Y_1$ (for $10^4$ independent realizations).  It clearly shows the hole at radius $a$:

Finally, note that (1) the components $X_i$ must have identical distributions (due to the spherical symmetry) and (2) except when $a=0$, that common distribution is not Normal. In fact, as $a$ grows large, the rapid decrease of the (univariate) Normal distribution causes most of the probability of the spherically truncated multivariate normal to cluster near the surface of the $n-1$-sphere (of radius $a$).  The marginal distribution must therefore approximate a scaled symmetric Beta$((n-1)/2,(n-1)/2)$ distribution concentrated in the interval $(-a,a)$. This is apparent in the previous scatterplot, where $a=3\sigma$ is already large in two dimensions: the points limn a ring (a $2-1$-sphere) of radius $3\sigma$.
Here are histograms of the marginal distributions from a simulation of size $10^5$ in $3$ dimensions with $a=10$, $\sigma=1$ (for which the approximating Beta$(1,1)$ distribution is uniform):

Since the first $n-1$ marginals of the procedure described in the question are normal (by construction), that procedure cannot be correct.

The following R code generated the first figure.  It is constructed to parallel steps 1-3 for generating $Y$.  It was modified to generate the second figure by changing variables a, d, n, and sigma and then issuing the plot command plot(y[1,], y[2,], pch=16, cex=1/2, col="#00000010") after y was generated.
The generation of $U$ is modified in the code for higher numerical resolution: the code actually generates $1-U$ and uses that to compute $P$.
The same technique of simulating data according to a supposed algorithm, summarizing it with a histogram, and superimposing a histogram can be used to test the method described in the question.  It will confirm that method does not work as expected.
a <- 7      # Lower threshold
d <- 11     # Dimensions
n <- 1e5    # Sample size
sigma <- 3  # Original SD
#
# The algorithm.
#
set.seed(17)
u.max <- pchisq((a/sigma)^2, d, lower.tail=FALSE)
if (u.max == 0) stop("The threshold is too large.")
u <- runif(n, 0, u.max)
rho <- sigma * sqrt(qchisq(u, d, lower.tail=FALSE))
x <- matrix(rnorm(n*d, 0, 1), ncol=d)
y <- t(x * rho / apply(x, 1, function(y) sqrt(sum(y*y))))
#
# Draw histograms of the marginal distributions.
#
h <- function(z) {
  s <- sd(z)
  hist(z, freq=FALSE, ylim=c(0, 1/sqrt(2*pi*s^2)),
       main="Marginal Histogram",
       sub="Best Normal Fit Superimposed")
  curve(dnorm(x, mean(z), s), add=TRUE, lwd=2, col="Red")
}
par(mfrow=c(1, min(d, 4)))
invisible(apply(y, 1, h))
#
# Draw a nice histogram of the distances.
#
#plot(y[1,], y[2,], pch=16, cex=1/2, col="#00000010") # For figure 2
rho.max <- min(qchisq(1 - 0.001*pchisq(a/sigma, d, lower.tail=FALSE), d)*sigma,
               max(rho), na.rm=TRUE)
k <- ceiling(rho.max/a)
hist(rho, freq=FALSE, xlim=c(0, rho.max),
     breaks=seq(0, max(rho)+a, by=a/ceiling(50/k)))
#
# Superimpose the theoretical distribution.
#
dchi <- function(x, d) {
  exp((d-1)*log(x) + (1-d/2)*log(2) - x^2/2 - lgamma(d/2))
}
curve((x >= a)*dchi(x/sigma, d) / (1-pchisq((a/sigma)^2, d))/sigma, add=TRUE,
      lwd=2, col="Red", n=257)

Comment: As near as I can tell, you propose drawing $X_1,\ldots,X_{n-1}$ iid from a Normal distribution and $X_n$ from a two-sided truncated Normal. That is so obviously not a truncated MVN distribution, as a scatterplot for $n=2$ will easily reveal, that I believe I have been unable to understand that part your question.  More generally, the burden of questions that ask why something does *not* work is on the asker to provide evidence that it *does* work. Perhaps if you supplied such evidence, the nature of your question would become clear.
Comment: Thats a wonderful answer! But, can you also kindly throw some light on **why the proposal-in-question fails?** (Xi'an answer is not satisfactory enough, I see some problem with his argument e.g. when he integrates)
Comment: Thank you very much. But, may I also request you to answer on my first comment above? It seems, my proposal also gives a good histogram close enough. I am confused!! Where is the mistake? Note that, this is the main point of the question and **IF CORRECT**, the method needs just one "truncated-Gaussian" sample PLUS With the availability of existing fast algorithms, it leads to a huge savings (avoids divisions and multiplications, in addition to avoiding the need of relatively more complex truncated-ChiSquare)
Comment: Thanks for the details. I added a 2-D scatter-plot as you said and fixed a few sentences. By the way, sorry I didn't really mean to transfer the total burden of proof to you. My proposal seems to work okay with all simple checks, therefore I am curious why its wrong, which is also the main purpose of this question.
Comment: Looking at the marginal distributions is the most straightforward way I could find to illustrate the differences in the procedures.  I added a figure and some code to show these marginals.
Comment: I think you meant $F((a/\sigma)^2)$ instead of $F^{-1}((a/\sigma)^2)$ when you explained step-2. Is that right?
Comment: @Loves Yes I did--thank you for catching that. The code confirms you, too.  I'll make the change.
Answer: I have written this assuming that you don't want any points having ||y|| > a, which is the analogue of the usual one dimensional truncation. However, you have written that you want to keep points having |y|| >= a and throw out the others. Nevertheless, the obvious adjustment to my solution can be made if you really do want to keep points having |y|| >= a.
The most straightforward way, which happens to be a very general technique, is to use Acceptance-Rejection https://en.wikipedia.org/wiki/Rejection_sampling .  It will be fairly fast as long as Prob(||X|| > a) is fairly low, because then there will not be many rejections.
Generate a sample value x from the unconstrained Multivariate Normal (even though your problem states that the Multivariate Normal is spherical, the technique can be applied even if it's not).  If ||x|| <= a, accept, i.e., use x, otherwise reject it and generate a new sample.  Repeat this process until you have as many accepted samples as you need.  The effect of applying this procedure is to generate y such that its density is c * f_X(y), if ||y|| <= a, and 0 if ||y|| > a, per my correction to the opening portion of your question. You never need to compute c; it is in effect auto-determined by the algorithm based on the frequency with which samples are rejected.
Comment: +1 I like that your proposal works with non-spherically symmetric MVNs, that you have clearly described the circumstances under which it will be effective, and that you emphasize the need to assess the rejection rate when deciding whether to use rejection sampling.
Comment: Yes, and also note that it can work for arbitrarily shaped acceptance region(s), not just 2-norm being above or below a threshold as here.
Answer: This is a nice attempt but it does not work because of the "normalisation constant": if you consider the joint density
$$f_X(x) \propto \frac{1}{{(2\pi\sigma^2)}^{n/2}} \exp\left(-\frac{||x||^2}{2\sigma^2}\right)\mathbb{I}_{||x||>a}=\frac{1}{{(2\pi\sigma^2)}^{n/2}} \exp\left(-\frac{x_1^2+\ldots+x_n^2}{2\sigma^2}\right)\mathbb{I}_{||x||>a}$$the decomposition
$$f_X(x) \propto \frac{1}{{(2\pi\sigma^2)}^{(n-1)/2}} \exp\left(-\frac{||x_{-n}||^2}{2\sigma^2}\right)\frac{1}{{(2\pi\sigma^2)}^{1/2}} \exp\left(-\frac{x_n^2}{2\sigma^2}\right)\mathbb{I}_{||x||>a}$$
$$=\frac{1}{{(2\pi\sigma^2)}^{(n-1)/2}} \exp\left(-\frac{||x_{-n}||^2}{2\sigma^2}\right)\frac{1}{{(2\pi\sigma^2)}^{1/2}} \exp\left(-\frac{x_n^2}{2\sigma^2}\right)\mathbb{I}_{||x_{-n}||^2+x_n^2>a^2}$$
$$=\frac{\mathbb{P}(X_n^2>a^2-||x_{-n}||^2)}{{(2\pi\sigma^2)}^{(n-1)/2}} \exp\left(-\frac{||x_{-n}||^2}{2\sigma^2}\right)\qquad\qquad\qquad\qquad\qquad$$
$$\qquad\qquad\qquad\times\frac{\mathbb{P}(X_n^2>a^2-||x_{-n}||^2)^{-1}}{{(2\pi\sigma^2)}^{1/2}} \exp\left(-\frac{x_n^2}{2\sigma^2}\right)\mathbb{I}_{x_n^2>a-||x_{-n}||^2}$$
which integrates to
$$f_{X_{-n}}(x_{-n}) \propto \frac{\mathbb{P}(X_n^2>a^2-||x_{-n}||^2)}{{(2\pi\sigma^2)}^{(n-1)/2}} \exp\left(-\frac{||x_{-n}||^2}{2\sigma^2}\right)$$
in $x_n$,  shows that

The conditional distribution of $X_n$ given the other components, $X_{-n}$, is a truncated normal distribution;
The marginal distribution of the other components, $X_{-n}$, is not a normal distribution because of the extra term $\mathbb{P}(X_n^2>a^2-||x_{-n}||^2)$;

The only way I can see in taking advantage of this property is to run a Gibbs sampler, one component at a time, using the truncated normal conditional distributions.
Comment: Thanks a lot for the detailed answer. Just a clarification, the area under your density $f_X(x)$ (second eq) doesn't sum to 1!! --- I think, once it is corrected, it will cancel out the "normalization factor" that you are talking about. Any thoughts?
Answer: The question originates from the idea of using -- the basic conditional-decomposition of joint distributions -- in order to draw vector samples.
Let $X$ be a multivariate Gaussian with i.i.d. components.
Let $\text{Prob}(||X||>a) \triangleq T$  and
$Y\triangleq X.\mathbb{I}_{||X||>a}$
The algorithm in question is proposed based on the following (all-correct but deceiving-interpretation) conditional-factorization:
$$f_Y(y) = \frac{1}{T}\frac{1}{{(2\pi\sigma^2)}^{n/2}} \exp\left(-\frac{||y||^2}{2\sigma^2}\right)\mathbb{I}_{||y||>a}\\
=\frac{1}{T}\frac{1}{{(2\pi\sigma^2)}^{n/2}}
\exp\left(-\frac{y_1^2+\ldots+y_n^2}{2\sigma^2}\right)\mathbb{I}_{||y||>a}\\
=\left(\prod_{i=1}^{n-1} \frac{1}{\sqrt{2\pi\sigma^2}}
\exp\left(-\frac{y_i^2}{2\sigma^2}\right)\right)
\left(\frac{1}{T}\frac{1}{\sqrt{2\pi\sigma^2}}
\exp\left(-\frac{y_n^2}{2\sigma^2}\right)\mathbb{I}_{||y||>a}\right)\\
=\underbrace{\left(\prod_{i=1}^{n-1} \frac{1}{\sqrt{2\pi\sigma^2}}
\exp\left(-\frac{y_i^2}{2\sigma^2}\right)\right)}_{\text{Gaussians}}
\underbrace{\left(\frac{1}{T}\frac{1}{\sqrt{2\pi\sigma^2}}
\exp\left(-\frac{y_n^2}{2\sigma^2}\right)\mathbb{I}_{y_n^2>(a^2-y_1^2-\ldots y_{n-1}^2)}\right)}_{\text{Truncated Gaussian??}}
$$
The shortest answer is that the latter factor is not a truncated Gaussian, (more importantly) not even a distribution.

Here is the detailed explanation of why the above factorization itself has some fundamental flaw. In a single sentence: any conditional-factorization of a given joint distribution must satisfy some very fundamental properties, and the above factorization doesn't satisfy them (See below).
In general, if we ever factorize $f_{XY}(x,y)=f_X(x)\cdot f_{Y|X}(y|x)$ then $f_X(x)$ is the marginal of $X$ and $f_{Y|X}(y|x)$ is the conditional distribution of $Y$. Which means:

The factor of $f(x,y)$ "assumed as" $f_X(x)$ must be a distribution. And,
The second factor "assumed as" $f_{Y|X}(y|x)$ must be a distribution for every choice of $x$

In the above example, we are trying to condition as $Y_n|(Y_1\ldots Y_{n-1})$. It means the property-1 should hold for the factor of Gaussians and property-2 should hold good for the latter part.
It is clear that the property-1 holds good on the first factor.
But The problem is with the property-2. The last factor above is unfortunately not a distribution at all (forget about Truncated Gaussian) for almost any value of $(Y_1\ldots Y_{n-1})$!!

Such a proposal of algorithm is probably a result of the following misconception: Once a distribution naturally factors out of a joint distribution (such as Gaussians in above), it leads to a conditional factorization. ---- It does not! ---- The other (second) factor must also be good.

Note: There is a great answer by @whuber earlier, that actually solves the problem of generating a norm truncated multivariate Gaussian. I am accepting his answer. This answer is only to clarify & share my own understanding and the genesis of the question.
Comment: +1 Thank you for sharing your thoughts: they add valuable insight to this thread.


Let A be $\subset \mathbb{R}$ and $A_1........A_n$ be $\subset \mathbb{R}$, such that. A = $\bigcup_{i=1}^{N}A_i$

Question: If each $A_i$ is closed in $A$, show that a given function $f:A \to B$ is continuous, if and only if the restrictions $f_{A_i} \to B$ is continuous.
I'm not sure how to go about solving this question. I know that a set is only closed if its complement is open but I don't see how that helps me here unfortunately.
Comment: The difficulty of this question depends on how much mathematical background you have. Are you are allowed to use the standard fact that a function $f:A \to B$ is continuous if and only if for every subset $C$  closed in $B$,  $f^{-1}(C)$ is closed in $A$? If so then it's fairly easy. You need also that a finite union of closed subsets of $A$ is closed in $A$.
Comment: Also if you know the Pasting lemma or Gluing lemma that can be used to prove this easily.
Comment: @MichaelCohen Would that mean that this wouldn't work if i was from 1 to infinity? It has to be finite?
Comment: @dk1233 Yes the index set has to be finite. However if you replaced the word "open" by "closed" throughout then the proposition would also work for an infinite index set.
Comment: @MichaelCohen Can you explain why it wouldn't work for an infinite set?
Comment: @dk1233 Essentially because an infinite union of closed subsets of $A$ need not be closed. Given a closed subset $C$ of B, $f^{-1}(C)$ is the union of the closed sets $f_{A_i}^{-1}(C)$ but if the index set is infinite we can't deduce this union is closed in $A$.
Comment: Please do not vandalize your question, in particular not after receiving answers.
Answer: If $f:A\longrightarrow B$ is continuous, obviously $f|_{A_i}$ is continuous for all $i\in\{1,\ldots,n\}$.
Now assume that all the $f|_{A_i}$, $i\in\{1,\ldots,n\}$ are continuous, and let $x_0\in A:=\bigcup_{i=1}^n A_i$. Let $i_1,\ldots,i_k\in\{1,\ldots,n\}$ be the indexes of all the sets $A_{i_j}$ such that $x_0\in A_{i_j}$.
Also, because the $A_i$ are all closed, $\mathbb{R}\setminus A_i$ are all open.
Then, if $x_0\not\in A_i$ for $i\not\in\{i_1,\ldots,i_k\}$,  we can take $\delta_i\in\mathbb{R}^+$ such that $B(x_0,\delta_i)\cap A_i=\emptyset$. Let then $\delta_M=\min\{\delta_i :i\not\in\{i_1,\ldots,i_k\}\}$. We have that $B(x_0,\delta)\cap A_i=\emptyset$ for all $i\not\in\{i_1,\ldots,i_k\}$.
Let $\epsilon\in\mathbb{R}^+$, and let $\delta_{i_j}\in\mathbb{R}^+$ such that $|f|_{A_{i_j}}(x)-f(x_0)|<\epsilon$ for all $x\in B(x_0,\delta_{i_j})\cap A_{i_j}$ and $j\in\{1,\ldots,k\}$.
If we choose $\delta:=\min\{\delta_M,\delta_{i_j} : j\in\{1,\ldots,k\}\}$, then, if $x\in B(x_0,\delta)\cap A$,  $x\not\in A_i$ for all $i\not\in\{i_1,\ldots,i_j\}$ because $B(x_0,\delta)\cap A_i=\emptyset$. As $x\in A=\bigcup_{i=1}^n A_i$, there must exist $i_j\in\{i_1,\ldots,i_k\}$ such that $x\in A_{i_j}$. Then, $x\in B(x_0,\delta)\cap A_{i_j}\subset B(x_0,\delta_{i_j})\cap A_{i_j}$, and we get that: $$|f(x)-f(x_0)|=|f|_{A_{i_j}}(x)-f(x_0)|<\epsilon$$
Which concludes the proof.


Do we really need constant symbols in first-order theories?

Question: Are constant symbols really necessary in first-order theories? And I am not talking about replacing them with unary predicates like here, but instead I would like to remove any sign of their existence from the language and only hint to their existence using the axioms.
Take for example the Peano axioms. Is the zero symbol $0$ really necessary? Assume $\varphi(x)$ is an unary predicate and $\varphi(0)$ is an axiom of PA containing the symbol for the zero. Couldn't I just replace it by the following axiom?
$$(\exists x)\varphi(x) \quad\wedge\quad (\forall x \forall y)[\varphi(x)\wedge\varphi(y)\rightarrow x=y].$$
The first part states that there is an individual satisfying this predicate, the second parts states that it is unique. I can think about ways to generalize this to several and even countably infinite many constant symbols.
If it is about simplicity, then why doesn't ZFC uses a constant symbol for the empty set? Just for historical reasons?

I posted follow up questions here and here.
Comment: First of all: What do you have against constants ? That's constantism. Second all the constants you mention are definable. There are theories with constants not representing definable elements. What do you say to the theory of infinitely many different constants $c_n\neq c_m$ for $n\neq m$.
Comment: The theory of an infinite set which you describe and the theory of infinitely many constants are very different. One has a unique constable model, the other has infinitely many countable models.
Comment: @ReneSchipperus I think you should incorporate that example into your answer - it's really important (or rather, an example of a really important class of constructions) and should be explicitly mentioned.
Comment: You can formalize the Empty Set axiom without a constant: $\exists x \ \forall y \ \lnot (y \in x)$ and by Extensionality prove that it is unique.
Comment: Having done this, what are the benefits of **not** introducing a "name" for the unique set such that .... ?
Comment: @MauroALLEGRANZA The question is *what* distinguishes ZFC from PA in this point, so that we introduce $0$ in PA, but not $\emptyset$ in ZFC? I know that we don't need a constant in ZFC and I know that $0$ comes in handy in PA. But this should be more a question about possibilities.
Comment: @ReneSchipperus I think I can handle this, at least when I restrict myself to countable languages. If the constants should not satisfy any further axioms, then I can just add axioms $a_n$ for each $n\in\Bbb N$ where $a_n$ says that any mode should have more than $n$ elements. I am pretty sure I can do something similar if there are additional axioms involving the constantes. Maybe I will post a follow up question with my idea and I would be glad if you people can check it.
Comment: I think that the difference is: if we try to dispense with $0$ in PA, using $\exists x \ \forall y \ \lnot (x=S(y))$, we cannot prove its uniqueness. Thus, we have to assume the existence of **the** unique $x$ such that, and this amounts to using from the beginning the constant $0$.
Comment: @ReneSchipperus I am not an expert here. Can you please give me an example of a structure which is a model of only one of them? I cannot think about one myself.
Answer: The trick you outlined in the question has some drawbacks as the example of natural numbers already shows: consider the two formulas
$$\varphi_1(z) \equiv \forall x\ s(x) \ne z$$
$$\varphi_2(z) \equiv \forall x\ x+z = x$$
we know that $\{\varphi_1(0),\varphi_2(0)\}$ is a sub-theory of PA, if you try to replace this two axioms in the way you described you get the theory with axioms
$$\exists z\ \varphi_1(x) \land \forall y\ \varphi_1(y) \rightarrow y=z$$
$$\exists z\ \varphi_2(x) \land \forall y\ \varphi_1(y) \rightarrow y=z$$
that is not equivalent the previous one, that's because you could have models of this theory having two distinct elements satisfying separately the two axioms.
You could solve this problem by taking the the axiom
$$\exists z \varphi_1(z) \land \varphi_2(z) \land \dots$$
but this doesn't help when you have infinitely many formulas $\varphi_i(z)$.
While I don't have a proof at the moment, I'm afraid that you cannot eliminate constants from the language unless you add unary-predicate symbols to the language with some axioms that allow to obtain an equivalent theory.
On the other hand constants are incredibly useful because they allow to build Henkin theories that are theories $T$'s such that for each formula $\varphi(x)$ if $T \vdash \exists \varphi(x)$ then there's a constant $c$ such that $T \vdash \varphi(c)$.
These theories are the key instrument for proving the completeness theorem: indeed it's easy to show that for an Henkin consistent theory the term model, that is the structure build out of the terms quotiented up to provable equality, is actually a model of the theory.
But that's not all of it, lots of constructions in model theory make use of constants. For instance for every structure $M$, in a given language $L$, it's possible to define the elementary diagram which is a theory in a language $L'$ obtained by $L$ adding a constant for each element in $M$, the models of this theory are basically the same as the elementary extensions of $M$.
There are other applications of constants inside logic but I hope that these examples gave you an idea of why constants matter.
Comment: #constantlivesmatter
Answer: Constants affect the model theoretic properties of the theories. There are many examples of this, to give a simple one:
You say for example that the structures (or their theories)
$$(\mathbb{N},<,0)$$ and
$$(\mathbb{N},<)$$ are similar. But the set $(\{1,2,\cdots\},<)$ is a substructure of the second model, but not a substructure of the first.
Another example occurs in ring theory, we often require homomorphisms to preserve the unit element, this is only the case (in general) if $1$ is included as a constant.
Comment: But isn't it isomorphic to a substructure of $(\Bbb N,<)$ which is essentially the same as being a substructure itself?
Comment: Or is it not a substructure because it is defined over another language. Is there terminology for substructures that are defined over a sub-language?


What, if any, asymptotic arguments are used in moving between various statements of the central limit theorem?

Question: What, if any, asymptotic arguments are used in moving between the various statements of the central limit theorem (e.g. in terms of sample means compared with standardised sample means)?
Context.
My question is somewhat trivial, and perhaps pedantic, but I would appreciate some concrete insight on it in any case.
In terms of the asymptotic normality of sample means, one version of the central limit theorem is
$$\overline{X}_n \overset{d}{\longrightarrow} \mathcal{N} \left(\mu, \frac{\sigma^2}{n} \right) \tag{1}$$
for i.i.d. $X_1, \dots, X_n$ with mean $\mu$ and variance $\sigma^2$. An equivalent formulation in terms of standardised sample means might be
$$\frac{ \sqrt{n}(\overline{X}_n - \mu)}{\sigma} \overset{d}{\longrightarrow} \mathcal{N}(0,1). \tag{2}$$
Most intermediate statistics references I have seen prove $(2)$ using some assumptions about the moment generating function, and Taylor approximations. I have noticed that pedagogically, they either present:

$(1)$ and $(2)$ as equivalent formulations of the same theorem.
Or they prove $(2)$ and assume that in asymptopia, we can move from $(2)$ to $(1)$. No further, explicit justification for how we move between $(2)$ and $(1)$ is presented, possibly because it is so fundamental and "standard".

In the latter case, could we view going from $(2)$ to $(1)$ as an instance of the continuous mapping theorem?
Answer: When you take a limit $n \to\infty$ then $n$ cannot occur on the right hand side, the limit expression cannot depend on $n$.  So your $(1)$ is incorrect, while $(2)$ is the correct expression.
The way $(1)$ arises (but not as a limit, a an approximation) is that you decide that your $n$ is large enough to trust the CLT as an approximation. So you write
$$ \frac{ \sqrt{n}(\overline{X}_n - \mu)}{\sigma} \overset{d}{\approx} \mathcal{N}(0,1). \tag{2} $$
where we have replaced $\overset{d}{\longrightarrow}$ by $\overset{d}{\approx} $, meaning approximately distributed as. Multiplying by $\sigma$ and dividing by $\sqrt{n}$ we then get
$$
   \overline{X}_n \overset{d}{\approx} \mathcal{N}(\mu,\frac{\sigma^2}n)
$$
This does not involve any use of the continuous mapping theorem.  As a fact, from the point that we decide to use the CLT result as an approximation, there is no asymptotics involved.
Comment: +1. Thank you for assisting in clarifying some of my erroneous preconceptions.


Show internal website through iframe

Question: I have a public website with an iframe pointing to a private website (only visible inside my company's lan).
I'd like that the iframed pages could also be visible from the outside.
Is it possible to achieve?
My public server is a Windows Server 2003 with IIS 6 and the server can browse easily to the private server webpage.
My private server is an Ubuntu 8.04 machine.
I tried with an IIS virtual directory redirection but it's not working.
Answer: Remember your regular webserver is only sending the client's web browser a URL to the internal site. This means that my machine going to your web page and gets a page and an iframe with a URL that by definition it cannot access to your internal web page.
Assuming the web server has access to the internal site, the easiest way to do this is to have a script on the webserver that fetches the requests page from the internal site and some how securely hands it out to authenticated users. This script will also have to take requests from an authenticated web client and pass them to the internal site. That sounds really complicated, untested, and limited and it seems to be the easiest way to do exactly what you want.
If you can change you exact goal slightly...
It is probably easier and more secure to setup a VPN and allow users to connect to the internal network, or at least just the internal web server. There are VPN clients that can be installed on clients ahead of time or via a web browsers add ons (activex, xpi, etc...), and can make the whole setup fairly seemless. This option will likely involve purchasing equipment and/or software, but VPNs are secure, easy and reliable.
Another alternative is to review the internal site, and ask why it is internal? Can you simply make it external? Can the code be audited for security then posted externally? Maybe the data would be safe enough behind a web login and SSL encrypted. This option could be very easy or moderately difficult depending on what the internal site is. This option also doesn't involve any software on the clients machine.
Comment: +1 couldn't have said it better myself.

Show internal website through iframe


Directory Folders/Files list to Array php

Question: I have small function which gives me Directory Folders/Files list as multidimensional Array.
How can I have directory list with following structure. (Schema no : 3)
function dirToArray($dir) {
    $contents = array();
    foreach (scandir($dir) as $node) {
        if ($node == '.' || $node == '..') continue;
        if (is_dir($dir . '/' . $node)) {
            $contents[$node] = dirToArray($dir . '/' . $node);
        } else {
            $contents[] = $node;
        }
    }
    return $contents;
}

My current folder list as array
$files = array (
  0 => 'do-update.php',
  1 => 'sitemap.xml',
  2 => 'sitemap.xml.gz',
  3 => 'wp-config.php',
  'wp-content' =>
  array (
    'uploads' =>
    array (
      2013 =>
      array (
        '05' =>
        array (
          0 => 'kabeduvarkad-1024x768.jpg',
          1 => 'kabeduvarkad-150x150.jpg',
          2 => 'kabeduvarkad-300x225.jpg',
          3 => 'kabeduvarkad-940x198.jpg',
        ),
        10 =>
        array (
        ),
      ),
      2014 =>
      array (
        '02' =>
        array (
        ),
      ),
      2015 => 'de.php',
    ),
  ),
  'wp-update' =>
  array (
    0 => 'wp-update.tar',
    1 => 'wp-update.tar.gz',
    2 => 'wp-update1.tar',
    3 => 'wp-update1.tar.gz',
  ),
  4 => 'wp-update.tar.gz',
);

Expected folder list as array
$expected = array (
  0 => 'do-update.php',
  1 => 'sitemap.xml',
  2 => 'sitemap.xml.gz',
  3 => 'test.php',
  4 => 'wp-config.php',
  5 => 'wp-content/',
  6 => 'wp-content/uploads/',
  7 => 'wp-content/uploads/2013/',
  8 => 'wp-content/uploads/2013/05/',
  9 => 'wp-content/uploads/2013/05/kabeduvarkad-1024x768.jpg',
  10 => 'wp-content/uploads/2013/05/kabeduvarkad-150x150.jpg',
  11 => 'wp-content/uploads/2013/05/kabeduvarkad-300x225.jpg',
  12 => 'wp-content/uploads/2013/05/kabeduvarkad-940x198.jpg',
  13 => 'wp-content/uploads/2013/05/kabeduvarkad.jpg',
  14 => '...'
);

Comment: [This](http://mechanics.flite.com/blog/2013/09/30/how-to-do-an-upsert-in-mysql/) appears to be the source of your script. There are some differences with yours.
Comment: I could not understand relationship with this
Comment: Sorry. I pasted a link I put in another question. Try using the 'find_all_files' function [here](http://www.php.net/manual/en/function.scandir.php#107117)
Comment: This function does not returns empty folders.
Answer: $path = realpath('yourfolder/examplefolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename) {
    echo "$filename\n";
}

here is what you are looking for
Comment: This script does not returns empty directories
Answer: Try
  function dirToArray($dir){
  $contents = array();
  foreach (scandir($dir) as $node)
  {
     if($node == '.' || $node == '..' ) continue;
     if(is_dir($dir . '/' . $node )) { $contents[]=$dir . '/' . $node;
     $contents[]=dirToArray($dir.'/' . $node);
     }
     else
     {
     $contents[] = $dir.'/' .$node;
     }
   }
   return $contents;
 }

     $dir='abcd'; $result=dirToArray($dir);
     $it= new RecursiveIteratorIterator (new RecursiveArrayIterator($result));                                 $l=iterator_to_array($it,false);
     echo '
';
     print_r($l);
     echo '
';

Comment: Thank you very much for your effords
Comment: Needs to actually return the $contents array


Gsub on a list according to pattern occurence in R

Question: Hello everyone I have a list such as :
my_list<-c("YP_0092.1_CP","C_scaffold_1017_18403-23022_-__Homo_sapiens","F_scaffold_1710_2458-7549_+__Pan_troglodys","ACPDHDDHH.2","X_scaffold_3287_5022-8483_-__Neandertalensis")

and I would like to change "__" to "_" for each element on the list when it begins with a X or F
I should then get a new list :
c("YP_0092.1_CP","C_scaffold_1017_18403-23022_-__Homo_sapiens","F_scaffold_1710_2458-7549_+_Pan_troglodys","ACPDHDDHH.2","X_scaffold_3287_5022-8483_-_Neandertalensis")

does someone have an idea please?
Answer: Sure!

i <- grepl( "^(XF)", my_list )
my_list[i] <- gsub( "__", "_", my_list[i] )


Correct way to find non-parametric confidence intervals using bootstrap

Question: I'm using a bootstrap method to find the 95% confidence interval for Sen's slope, but I'm not sure if my methodology is correct. My steps are as follows:
<code>#create data.frame
set.seed(123)
df <- data.frame(x = 1:100,
             y = rnorm(100))

#Sen's slope

slope <- zyp.sen(y~x,data = df)
slope <- slope$coef[1] + slope$coef[2]*df$x

#bootstrap the tau statistic of zyp.trend.vector (pre-whitening step)

pw_tau_func <- function(z) zyp.trend.vector(z, method = "yuepilon")[5]
boot.out <- tsboot(df$y, pw_tau_func, R=999, l=5, sim="fixed")

#find confidence intervals from boot object using boot.ci

ci_upr <- boot.ci(boot.out, type="norm")$normal[3]
ci_upr <- slope + abs(ci_upr)
ci_lwr <- boot.ci(boot.out, type="norm")$normal[2]
ci_lwr <- slope - abs(ci_lwr)

#plot output

plot(slope, type = "l", ylab = "Simulated Data", ylim = c(-1,1))
points(ci_upr, col = "red")
points(ci_lwr, col = "red")
</code>
Is bootstrapping the tau statistic the correct method for generating confidence intervals? I've seen conflicting information around the internet.
Answer: The Mann-Kendall test for trend and Thiel-Sen slope estimate are two different things. The MK test tests the null hypothesis of no trend, whereas the Sen's slope estimate the trend's magnitude. In the above example I was bootstrapping the tau statistic, and not Sen's slope. To find the 95% CI for Sen's slope:
<code>beta <- function(df) zyp.sen(y~x, df)$coefficients[2]
boot.out <- tsboot(df, beta, R = 250, l = 5, sim = "fixed")
ci_lwr_mk <- boot.ci(boot.out, conf = 0.95, type = "norm")$normal[[2]]
ci_upr_mk <- boot.ci(boot.out, conf = 0.95, type = "norm")$normal[[3]]
</code>


Denoise of Financial Time Series Data using Wavelet Transform

Question: I need to denoise financial time-series data for a machine learning problem and don't understand how a wavelet transform is computed.
My understanding is that you need multiple points of a time signal to identify frequencies.
What does a wavelet transform do with the first point(s)? If there are not enough points, does it use future data to identify the frequencies? If yes, is it possible to give a wavelet transform to use data only from and in "t"?
Comment: I'm voting to close this question as off-topic because it is not about programming as defined in the guidelines, plus it is too-broad (asking 3-4 different questions) and asking for external resources
Answer: Generally, there are three types of methods to process your [financial] time-series data:

Time domain methods (e.g., regression, statistical analysis on your financial time-series data such as mean, skewness, standard deviation, kurtosis, Black–Scholes model)
Frequency domain methods (e.g., Fourier Transform, Power Spectral Density)
Time-frequency domain methods (e.g., Short-Time Fourier Transform, Wavelet Transformation, Gabor Transform)

You may use time-frequency methods to denoise, categorize or classify financial time-series data, if you will. Time-frequency methods transform your [1-D] financial time-series data into a new [2-D] domain that you can see both time and frequency information .
[1-D] Frequency domain methods only return frequency information of your [1-D] financial time signals, which means that your [1-D] time data will be lost in exchange for having [1-D] frequency data.
[1-D] Time domain methods only return [1-D] time analysis of your financial signals, which also cannot help you to capture the frequency information.
You may use a Continuous Wavelet Transform or a Discrete Wavelet Transform to denoise financial time-series data.
There are many tools/languages that might help you to do so: MatLab, Python, and such. If you might have a programmer around you, s/he can probably help you in a few hours or a day to pass your [1-D] financial time data through one of these [2-D] time-frequency methods and visualize the outputs.
Your question is primarily about sampling rate. If your sampling rate is too low, thus frequency domain method may not return accurate resolution for you (regardless of Nyquist theorem). However, if you use such method for denoising, it normally means you have high-frequency data and [usually] you may want to down-sample or filter your data.
I suggest you to read about mathematics of wavelets with respect to mother and child (e.g., Morlet, Daubechies, etc.) which will help you to understand how a base function maps throughout your financial time-series data, the transformation occurs, and a new time and frequency representation of your initial financial time-series data result in.
As you know, Wavelet is a mathematical transform. As you wish, you may give almost any input data to the transform equation and will transform it for you. You may initially pick a window size. Imagine, you have a 1X1000 vector of [0,1,0.3,1.2,-1,...] equity or derivative information as your window, or any other larger size window 1X1,000,000. It may not matter, if your data is from the past or you predict from the future and transform it via wavelet.
As you know, financial [chart] data usually as time passes, have an additional [data point] record, either a real data point or a forecasted one. In that case, It is absolutely fine, and you may shift your window in near-real-time on a new window, either making your window larger or removing the first data point and appending your new data point to your window. That delata time can be any fraction of time. You may just need to also consider computation, later for scale-up, which may not be an issue for you at this time.
My general view about your approach, not knowing many assumptions, is that you are in a challenging yet really great direction.

Image Courtesy: Harvard University
Good project, best wishes, thank you for your question and welcome to stackoverflow.com!
Answer: By now, I found an answer to my initial question and want to share what I found out.
This paper was a great source: https://www.sciencedirect.com/science/article/pii/S0022169418303317?via%3Dihub .
The MODWT (maximal overlap discrete wavelet transformation) is the only transformation that you can use for real-world applications as other WTs use future data points in every timestep t.
Due to the "boundary constraint" when using MODWT, the first L = (2 ** J - 1) * (L - 1) + 1, where J equals the filter level and L the number of wavelet coefficients of a particular wavelet, values have to be removed.
I saved the deleted MODWT values and add them back to my predictions after training my neural network. Then, I can perform the inverse MODWT and ensure that the points at the end don't become distorted. When calculating the metrics, I delete the first L values again.


How to expire views cache in code or with rule?

Question: I have a view with block display that shows a user's picture and profile info. The view is cached for 1 hour.
How can I expire that cache when the user updates the profile?
Answer: I ended up using Views Cache Actions. It allows to use rules to expire a specific view or views displays when a certain event occurs (like user profile save).
Answer: Give it a try Views Content Cache

This module implements a views cache plugin that is aware of content
  and can provide caching for views, until the content in those views
  changes.

Since, profile content is saved as a node the above module should work as it tell. Try and let us know !
OR
If above module doesn't address the isue we are looking for then use hook_profile2_update to hook into profile update and use the logic in above module to clear cache of a respective views block.
Comment: I looked at the code but the way views builds the cache keys doesn't look trivial to me.
Comment: I'm not using Profile2 module so my user profile aren't nodes. But good idea to take a look how it's done in that module.


Navigate to a view thats within a navigation controller

Question: I have a Tab Bar Controller which contains 4 views. 3 views are very basic. Just a tableview with data (Call one of these views SimpleTableView). The 4th view points to a Navigation Controller with two buttons on its view (Lets call this view MainNavView). Both buttons point to different views (Lets call them ViewA and ViewB) and a user can go back to the view with two buttons (MainNavView) when pressing the back button on the Navigationbar. Works great.
Now here is my problem. I want the didSelectRowAtIndexPath from SimpleTableView to show ViewA from the Navigation Controller. And when a user lands on that page he can press the back button on the navigationbar and the MainNavView appears.
Navigating from MainNavView to ViewA is done with a (push) segue:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self performSegueWithIdentifier:@"segueIdentifier" sender:nil];
}

The MainStoryBoard contains a segue from a tableviewcell inside MainNavView to ViewA called "segueIdentifier".
I tried making another segue from a tableviewcell inside SimpleTableView to ViewA and executing this code again:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self performSegueWithIdentifier:@"segueIdentifier" sender:nil];
}

but then I get this error
NSGenericException', reason: 'Push segues can only be used when the source controller is managed by an instance of UINavigationController

Now this error is easily fixed when I embed SimpleTableView inside a Navigation Controller but thats not what I want because the back button returns the user to SimpleTableView and not MainNavView.
I hope everything is clear and someone can help me with this navigation problem. Is this maybe possible with a modal segue instead of push?
Answer: You can't use push segue from a controller that isn't anUINavigationController, you should use the modal segue pointing directly to ViewA. I just tried it, it works flawlessly !
From the user's point of view, push segues are explicit transitions from/to the same view hierarchy... I think that using a push segue from another tab could disorient the user...
Comment: I've tried it with a modal and it works but then ViewA wont show a navigation bar with a back button to "MainNavView".


How do I install libDb from source on OSX

Question: I cloned this repo and then...
cd build_unix
../dist/configure
make
sudo make install

Then I go to the project I am trying to compile and run stack install I get the following...
Configuring BerkeleyDB-0.8.7...
    Cabal-simple_mPHDZzAJ_184.108.40.206_ghc-8.0.2: Missing dependency on a foreign
    library:
    * Missing C library: db
    This problem can usually be solved by installing the system package that
    provides this library (you may need the "-dev" version). If the library is
    already installed but in a non-standard location then you can use the flags
    --extra-include-dirs= and --extra-lib-dirs= to specify where it is.

This is on OSX
Answer: Rather than compiling from source, you could use homebrew:
brew install berkeley-db

Comment: This didn't ask using homebrew. Notice the "from source"


String a = "x"; then String x = a.substring(1) Wouldn't there be an error like indexOutOfRange?

Question: I am so confused. I thought to use str.substring(1), str has to be at least 2 characters, otherwise there should be index of of bound. But when I typed in, Java doesn't give any error. Why?
Comment: The [official documentation](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-) shows a fine example of that behaviour: `"emptiness".substring(9)` returns `""` (an empty string)
Comment: Because an empty string is still a string. Given `String a = "x";`, then `a.substring(1)` is `""`.
Answer: Read the Javadoc:

String java.lang.String.substring(int beginIndex)
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

Your beginIndex is equal to the length of the String, so no exception is thrown and an empty String is returned.
Answer: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

It is legal to have the index equal to the length in order to return an empty string.


Converting list to formatted string, then writing string to text file in said format

Question: I need to convert a list into a string which I want to format as follows:
Enter your Account Number: 1
l 0.0 l
2 0.0 2
3 0.0 3
4 0.0 4

I then want to write that string into a text file keeping the same format.
account= ["a1", "a2", "a3"]
balance= ["b1", "b2", "b3"]
names= ["n1", "n2", "n3"]

length = len(account)

i = 0
for i in range(i, length):
    new_list = ''.format(account[i] + " " + balance[i] + " " + names[i])
    print(new_list)
    i += 1
string = new_list

data_file = open("bank.txt", 'a')
data_file.write(str(string))
data_file.close()

If I print the string, it prints out in the right format, but only the last line of the string is written to the text file.
Comment: You need to put the for-loop between the opening and the closing of the file.
Comment: You need to use '\n' if you write to a file.
Comment: If you just run your code in the Python interpreter (using [IPython](http://ipython.readthedocs.io) is the best), you'll see that `string` is `''`.
Comment: @sequeL Welcome to [so]! Please type your format into your question, instead of sharing a link. This makes it much easier for someone to answer your question, and helps future readers, even if the link disappears one day.
Answer: Code:
account= ["a1", "a2", "a3"]
balance= ["b1", "b2", "b3"]
names= ["n1", "n2", "n3"]

length = len(account)
data_file = open("bank.txt", 'w')

for i in range(length):
    new_list = '{} {} {}\n'.format(account[i], balance[i], names[i])
    data_file.write(new_list)
data_file.close()

Comment: Thank you very much, been trying to find the solution for the past 4 hours