How to format correctly my data to show them as a table

Question: I have a group of classes on monday and they take place in 5 different rooms. I'd like to present them in columns based on location using divs and sort by location, start. I get the data no problem (find all classes that run on monday) but it simply lists it in one column so my foreach arrays are incorrect.
here's $data
$calendar = array();
foreach ($data as $row) {
    $calendar[$row[0]][] = $row;
}
foreach($calendar as $key => $row) {
       foreach($row as $field => $value) {
           $recNew[$field][] = $value;
       }
}

here's array exerpt
    array(1) {
     [""]=> array(20)
     {
     [0]=> array(1) {
     ["calendars"]=> array(9) {
     ["id"]=> string(3) "742"
     ["title"]=> string(4) "Yoga"
     ["start_date"]=> string(10) "2015-09-14"
     ["end_date"]=> string(10) "0000-00-00"
     ["start_time"]=> string(8) "20:00:00"
     ["end_time"]=> string(8) "21:00:00"
     ["location"]=> string(8) "Studio 1"
     ["calendar_category_id"]=> string(1) "3"
     ["recur_mon"]=> string(1) "1"
      }
     }
     [1]=> array(1) {
     ["calendars"]=> array(9) {
     ["id"]=> string(3) "743"
     ["title"]=> string(2) "GX"
     ["start_date"]=> string(10) "2015-09-14"
     ["end_date"]=> string(10) "0000-00-00"
     ["start_time"]=> string(8) "18:00:00"
     ["end_time"]=> string(8) "18:45:00"
     ["location"]=> string(8) "Studio 1"
     ["calendar_category_id"]=> string(1) "3"
     ["recur_mon"]=> string(1) "1"
    } }
    [2]=> array(1) {
    ["calendars"]=> array(9) {
    ["id"]=> string(3) "447"
    ["title"]=> string(4) "Spin"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "09:15:00"
    ["end_time"]=> string(8) "10:00:00"
    ["location"]=> string(8) "Studio 1"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
     } }

    [3]=> array(1) {
    ["calendars"]=> array(22) {
    ["id"]=> string(3) "448"
    ["title"]=> string(4) "Spin"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "12:15:00"
    ["end_time"]=> string(8) "13:00:00"
    ["location"]=> string(8) "Studio 1"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"  } }

    [4]=> array(1) {
    ["calendars"]=> array(22) {
    ["id"]=> string(3) "684"
    ["title"]=> string(4) "Spin"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "16:30:00"
    ["end_time"]=> string(8) "17:15:00"
    ["location"]=> string(8) "Studio 1"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [5]=> array(1) {
    ["calendars"]=> array(22) {
    ["id"]=> string(3) "545"
    ["title"]=> string(4) "Yoga"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "18:15:00"
    ["end_time"]=> string(8) "19:00:00"
    ["location"]=> string(8) "Studio 1"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

[6]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "549"
    ["title"]=> string(4) "Yoga"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "09:00:00"
    ["end_time"]=> string(8) "10:00:00"
    ["location"]=> string(8) "Studio 2"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"  } }

    [7]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "688"
    ["title"]=> string(7) "Weights"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "10:10:00"
    ["end_time"]=> string(8) "11:00:00"
    ["location"]=> string(8) "Studio 2"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [8]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "572"
    ["title"]=> string(4) "Yoga"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "12:10:00"
    ["end_time"]=> string(8) "13:10:00"
    ["location"]=> string(8) "Studio 2"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [9]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "548"
    ["title"]=> string(4) "Spin"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "16:00:00"
    ["end_time"]=> string(8) "16:55:00"
    ["location"]=> string(8) "Studio 2"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [10]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "573"
    ["title"]=> string(11) "Power Yoga"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "18:45:00"
    ["end_time"]=> string(8) "19:45:00"
    ["location"]=> string(8) "Studio 2"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [11]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "742"
    ["title"]=> string(4) "Yoga"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "20:00:00"
    ["end_time"]=> string(8) "21:00:00"
    ["location"]=> string(8) "Studio 2"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [12]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "552"
    ["title"]=> string(5) "Zumba"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "10:15:00"
    ["end_time"]=> string(8) "11:15:00"
    ["location"]=> string(8) "Studio 3"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [13]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "622"
    ["title"]=> string(4) "Yoga"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "11:30:00"
    ["end_time"]=> string(8) "12:00:00"
    ["location"]=> string(8) "Studio 3"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [14]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "570"
    ["title"]=> string(22) "Body Pump (Doriana P.)"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "12:15:00"
    ["end_time"]=> string(8) "13:15:00"
    ["location"]=> string(8) "Studio 3"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [15]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "740"
    ["title"]=> string(4) "Spin"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "13:30:00"
    ["end_time"]=> string(8) "14:00:00"
    ["location"]=> string(8) "Studio 4"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1
    } }

    [16]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "623"
    ["title"]=> string(7) "Weights"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "16:45:00"
    ["end_time"]=> string(8) "17:45:00"
    ["location"]=> string(8) "Studio 4"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [17]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "586"
    ["title"]=> string(2) "GX"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "18:00:00"
    ["end_time"]=> string(8) "18:30:00"
    ["location"]=> string(8) "Studio 5"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [18]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "613"
    ["title"]=> string(7) "Weights"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "18:45:00"
    ["end_time"]=> string(8) "19:30:00"
    ["location"]=> string(8) "Studio 5"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
    } }

    [19]=> array(1) { ["calendars"]=> array(9) {
    ["id"]=> string(3) "621"
    ["title"]=> string(5) "Zumba"
    ["start_date"]=> string(10) "2015-09-14"
    ["end_date"]=> string(10) "0000-00-00"
    ["start_time"]=> string(8) "19:45:00"
    ["end_time"]=> string(8) "20:45:00"
    ["location"]=> string(8) "Studio 5"
    ["calendar_category_id"]=> string(1) "3"
    ["recur_mon"]=> string(1) "1"
} }
    }

    <?php foreach ($recNew as $key => $classes) { ?>

<?php echo $location[$key]; ?>

        <?php foreach ($classes as $class) : ?>

<?php echo $class['calendars']['title']; ?>

        <?php endforeach; ?>

    <?php } ?>

This is what I get

Might need the locations to be the key for this to work.
Comment: I don't see exactly how your script generates the output you need, but if it does, floating the locations with their content left in css would solve your problem. In general, if you can get the right html structure with your php, the styling can be pretty much anything you want with css.
Comment: consider rotating the table so that `Studio 1, Studio 2,...` are stacked on top of each other with their classes going out to the right. it'll be easier to code and style
Comment: You could add another layer to the array for the location. would go `"" => array( 0 => array(  'calendars' => array(   'Studio 2' => array     "id"=> "742",...` easier to for-loop through
Comment: Yeah I have a left float on div with set width but my problems are in the script and getting the different locations to start in a new column.
Comment: @sloga: add your $data array in your code for I can help you
Comment: @developer added more data
Answer: You can try using html table for printing result:
<?php
$calendar = array();
foreach ($data as $row)
{
    for($i=0;$i<count($row);$i++)
    {   if(!array_key_exists($row[$i]["calendars"]["location"], $calendar))
            $calendar[$row[$i]["calendars"]["location"]] = array();
        array_push($calendar[$row[$i]["calendars"]["location"]], $row[$i]["calendars"]);
    }
}
?>

<?php
foreach($calendar as $key => $row):
?>

<?php echo $key;?>

<?php
foreach($row as $r):
?>

<?php echo $r["title"]; ?>

<?php endforeach;?>

<?php endforeach;?>

Comment: sweet! I was able to use this and design with divs and css. Thanks!

 $row):
?>

Comment: @developer,  I don't understand this question,  but if you do, please edit it to give it a more indicative title.
Comment: @mickmackusa, done, title is updated
Comment: I am afraid the title is still too vague/ambiguous to be helpful.  Please try to give it unique context.  "Formatting data" can mean a thousand different things.  Probably better to try to describe how the data is grouped atypically in the HTML table.


Why has my nav element 100% width?

Question: This is my nav:

    a{
text-decoration:none;
color:black;
}
nav{
display:inline;
margin:auto;
margin-bottom:0;
padding:0;
background-color:white;
border: 1px solid white;
border-radius:12px;
}
nav > ul{
list-style-type:none;
display:inline;
}
nav > ul > li{
display:inline;
font-size: 20px;
font-weight: 200;
border:2px solid transparent;
border-bottom: 2px solid #078930;
margin-right:2%;
}

Info

Nature

Cayenne

Kourou

The problem is that the nav has always 100% width of it's parent tag.
I cant specify a width, because I work with percent and images.
So what can I do that the nav takes only the space it needs?
The ul is has a lower height than the images.
Comment: simply because this the default behavior of block element and nav is block element
Comment: Have you tried simply changing the display property of the nav, just like you did with the ul? By the way, your `font-size` is missing a unit.
Comment: Ok it solved the width problem but now the ul has a lower height than the images. I tried to make the css height the same as the images, but it doesnt work.
Comment: @Manuxx Probably the descender issue. Can you edit the question with the code you now have?
Answer: As you mentioned in comments, I suppose you're trying to vertically align middle img and ul elments. If so, you should add vertical-align: middle; to those elements, like so:

a{
text-decoration:none;
color:black;
}
nav{
display:inline;
margin:auto;
margin-bottom:0;
padding:0;
background-color:white;
border: 1px solid white;
border-radius:12px;
}
nav img {
    vertical-align: middle;
}
nav > ul{
list-style-type:none;
display:inline;
vertical-align: middle;
}
nav > ul > li{
display:inline;
font-size: 20px;
font-weight: 200;
border:2px solid transparent;
border-bottom: 2px solid #078930;
margin-right:2%;
}

Info

Nature

Cayenne

Kourou

Answer: Why not simply use Flexbox...use inline-flex for the nav and flex for the ul

a {
  text-decoration: none;
  color: black;
}

nav {
  display: inline-flex;
  margin: auto;
  margin-bottom: 0;
  padding: 0;
  background-color: white;
  border: 1px solid white;
  border-radius: 12px;
}

nav>ul {
  list-style-type: none;
  display: flex;
  padding: 0;
  margin: 0;
  align-items: center;
  background: #efefef;
}

nav>ul>li {
  font-size: 20px;
  font-weight: 200;
  border: 2px solid transparent;
  border-bottom: 2px solid #078930;
  margin: 0 5px;
}

Info

Nature

Cayenne

Kourou

Why has my nav element 100% width?


Cryptography friends: How to prove that a hash function can produces a length-fixed output?

Question: Consider the following hash function based on RSA. $M_i < n$. The hash value of a message consisting of two blocks is calculated by
$H(M) = H(M_1,M_2) = ((M_1^e\ mod\ n)\ XOR\ M_2)^e mod\ n$
Q1.Does this hash function can produce fixed output size?
My answer: Because any output is limited to the modulus(n), the hash function can produce fixed output size?(I think of it for a long time, but I still wonder about it)
Q2.Is the hash function easy to calculate?
My answer: Because the hash function just contain encryption and XOR operations, it is easy to calculate.(Is it right or completed?)
Comment: Welcome to MS£. Please use Mathjax/Latex for the formulae in your question. See this excellent [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: Thanks you very much!
Comment: This seems to be about RSA Digital Signatures or alternatively about the first crude attempts to use RSA for encryption. The problems were nothing to do with speed/efficiency, but were about insecurity. I agree with your answers to Q1, Q2. For Q3, the answer today would be Y provided the block size is not too long (eg 64 or 128 bits fine). Because "is it efficient?" usually means "is it efficient enough to be feasible with today's computers?"
Comment: Sorry, I had edited it.
Answer: It's a weird chaining mode of RSA, and the output can be seen as a string of the length equal to that of $n$, as we output a number modulo $n$. So yes to Q1, provided you output a fully padded string.
It's not easy to calculate, but that's a bit subjective. The cost is two RSA operations essentially (xor is very cheap on computers) and those are relatively expensive compared to real hash functions (like SHA256 or SHA3 and many others). It's easily doable, but relatively expensive.
It's very insecure though.
Comment: Thanks! Have a good day!

Cryptography friends: How to prove that a hash function can produces a length-fixed output？


Definir diretório para subdomínio via HTACCESS

Question: Criei um sub-domínio e gostaria que o diretório dele fosse uma pasta específica.
Por exemplo:
Sub-domínio: teste.site.com.br
Pasta: site/pasta/
Eis o que tentei:
RewriteCond %{HTTP_HOST} ^teste.site.com.br$
RewriteRule ^(/)?$ pasta/ [L]

Comment: Você pode definir isso no próprio apache, mas vou responder com um possível que adequei a seu caso, veja e funciona.
Answer: Segue a possível solução.
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^teste.site.com.br$
    RewriteRule ^(.*)$ pasta/$1 [L]
</IfModule>

Testa ai é me fala, se funciona para o seu caso.
Mas pra adiantar já vou deixar o sites-enabled do apache pra você aqui:
"Acesse o diretório /etc/apache2/sites-enabled/ crie o um arquivo com o nome do seu domínio terminado por .conf por exmeplo: abcd.com.br.conf, eu por costume já tenho um modelo aqui pronto e vou usa-lo como exemplo."
<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin email@example.com
    DocumentRoot /var/www/AdmMedico/public
    ServerName  pinheiro.com.br
    ServerAlias www.pinheiro.com.br

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
<Directory "/var/www/pinheiro/public">
    AllowOverride All
</Directory>

</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Referencia :Deploy aplicação Laravel
Comment: Sim, cada vez que é criado um diretório é um parto. É uma empresa de cyber security aí eles bloqueiam praticamente tudo aí cada vez tem que entrar em contato com eles para eles ir dando permissões aos poucos até que dê certo. Mas acredito que está correto este código, pq coloquei o subdomínio/ um diretório que não existe e deu erro diferente. Assim que me liberarem eu confirmo a resposta, acredito estar correta...
Comment: Eu testei o teu código do htaccess, mas apareceu um erro: https://i.imgur.com/vBjvczC.png

Acredito que seja por falta de permissão da pasta, entrei em contato com a hospedagem para verificar...
Comment: Isso é erro de ssl, seu site tem https ? pode ser que o certificado seja só para o domínio principal. tenta acessar como http:// (eu não se se você realmente tem https. caso sim veja com a hospedagem o certificado)
Comment: @Lucas Blz, eles certamente trabalham com regras restritivas, se não funcionar comentar o erro aqui que vamos alinhando até ficar certo.
Comment: você que manja mais: o problema realmente é no https, tirei o direcionamento do htaccess e o site ao menos mostrou, porém erro 404 (ou seja, não está buscando o diretório correto), mas a minha dúvida, pode ser sem sentido: eu direciono tudo para https, mas gostaria de direcionar somente esse sub-domínio para http, tem como fazer isto?
Comment: Da uma olhada nisso https://pt.stackoverflow.com/questions/364158/redirecinamento-301-htaccess-com-e-sem-www-para-https/364160#364160 ele e pega parte do https. no caso remove o redirecionamento o diretório, e testa, se funciona realmente o problema está no caminho, atente para caso for colocar o diretório completo.


How can I give paid access to content?

Question: I am looking to manage user access to website content using Rules and the suggested access control module i.e. ACL, TAC etc.
There 3 levels of access to manage:

Unregistered - No access to any Course Content
Registered - Access to certain Preview nodes (see Preview Module below)
Paid - Access to the content to which they have paid (as well as Preview nodes)

Unregistered

Unregistered users will have no access to any Course Content nodes
However there may be pages on the site (Cookie, Terms etc.) which anonymous will need access to to keep the site functioning during registration/payment etc.

Registered Users / Preview Module

For each Course, 1 or more Modules (taxonomy term) will be marked as a Preview Module
Preview Modules are identified by the term with a boolean check box: field_module_preview
This should allow access to Registered uses to access the nodes within this Module.

Content types:
Course – setup as a product
Content
Taxonomy:
Topic
Module
Example:
> Course
> - Module
> - - Topic
> - - - Course Content NO Access
> - Module (Preview checked)
> - - Topic
> - - - Course Content: Access
> - - - Course Content: Access
> - - Topic
> - - - Course Content: Access
> - - - Course Content: Access
> - Module
> - - Topic
> - - - Course Content NO Access

Paid Access

Payment processing will be carried out using Drupal Commerce and PayPal. The setup of this is not required. Drupal install will be supplied with Commerce and product types setup.
Once a course is paid, then access is granted to the entire Course and all its nodes

I have tried to integrate rules but no hope to make it working.
Can anyone help me to apply this scenario in my drupal 7?
Thank you in advance.
Comment: Organic groups using organic groups access module solves this use case. The complexity arises with creating group memberships to courses based on payment, but that is do-able with some glue / custom code.
Comment: Hi @mradcliffe,  Thank you for your answer. I was thinking in same of choosing OG. But i want this with current taxonomy structure. So the taxonomy term reference given to course content type and course content type having product entity reference. I am very much confuse at one point. When User checkout process gets completed, I was setting up component to fetch ordered entity. But some how i am not getting the proper inputs in components.
Comment: Seriously, I can't believe that stack exchange can have this kind of limitation.. I have asked a simple normal question and added each and every possible detail.. I will find it by my self it ok. Thank you.
Comment: Let me know your email id. We can discuss on that.. I will give each and every detail.. Thanks for help in advance.
Answer: You should be able to get this to work using the Rules module, using a variation of the rule shown/explained in the answer to "How to make the permissions of a module more granular?". I.e in your case:

you can use the same Rules Event (Drupal is initializing), which to my knowledge is the only Rules Event you can use for this (for any other Rules Event you're just "too late", i.e. the content is already being displayed).
you can perform similar Rules Actions (to perform an appropriate redirect and display a message that fits your needs).
you should use one or more of these Rules Conditions (combined with "OR", not with "AND"!):

check if the current user's role is "anonymous".
related to your field field_module_preview.
Answer: I would use roles and permissions based on roles.  Two roles you get without doing any thing:

Anonymous User
Authenticated User

Use the first for Unregistered and the second for Registered.  You can create a Paid Role for registered users that pay up.
You can use the rules module to add/remove the Paid role when users pay and lapse payment.
Comment: I am following same way. You can see my above comment.  I am getting stuck when retrieving entities from course content. there might be n number of line items which is taxonomy term behaves as a node. So i need to give paid role permission to each and every node. But its not actually happening. I spend my two full days. But i felt that i lost somewhere. So posted here.
Answer: There is a per-configured package in Drupal known as Telekonsum .
by default this has the possibility to sale the user roles. I hope this will helpful for you.
Comment: Thank you for your help mukesh.. I need rules to be compatible to the current taxonomy i have setup. I don't want to use any other options.
Comment: Oh ok!. You just install and take a lok on telekonsum. form this you may gain any ideas for your requirement.

How can I give paid access to content?


Probability that a system fails before another given both their survival functions

Question: Question is pretty much self explanatory. Given two components A and B, and given their survival functions Ra(t) and Rb(t), how do you calculate the probability that component B fails before component A ?
Answer: Not much you can do here. If we assume they are independent,
$$ \Pr\{A > B\} = -\int_{0}^{+\infty} \Pr\{A > t\} dR_B(t)
= -\int_{0}^{+\infty} R_A(t) dR_B(t)$$
Comment: Thank you for your reply. May I ask how the middle operand comes from ? (first integral in your equation).
Comment: It is the law of total probability.


What model to use for multiple observations per participant with likert ratings

Question: We ran a study in which participants were presented with four items (let's call them service requests) and to each of these requests, two user profiles of people who could satisfy those requests were matched. Our participants had to rate each of those matched profiles on four Likert scales, each concerned with different aspects of the matched profiles.
We want to know if factors such as word length of the request, profile bio word length and number of past services listed in the profile are related to how participants rate those profiles. We have multiple observations per participant and the observations themselves are paired in terms of post.
I am assuming we need some kind of mixed effects regression analysis but I'm not sure how to structure the data and/or what model to apply. I'm using R for analysis and, as well as recommendations, a good example to copy as well as pointers to clear tutorials would be helpful.
Comment: You presumably want a mixed-effects version of ordinal logistic regression. I have an example here: [Is there a two-way Friedman's test?](http://stats.stackexchange.com/a/161872/7290)
Comment: Thanks, but data are Likert scale, so not logistic. There is debate about treating Likert scales as parametric (e.g., http://www.theanalysisfactor.com/can-likert-scale-data-ever-be-continuous/). But seems fine by this: http://pure.au.dk/portal/files/70360382/SimulationPosterJK.pdf. We're using lmer from R's lme4 package with participant as a group (of 8 observations) and nested request within participant (within participant group, 4 requests, each with 2 grouped observations). I think this is OK. See: http://jaredknowles.com/journal/2013/11/25/getting-started-with-mixed-effect-models-in-r.
Comment: Certainly not *binary* logistic regression, but you do need *ordinal* logistic regression. Try reading the linked thread.
Answer: A generalised linear mixed model for an ordinal outcome is what you need. This can be fitted with the ordinal package in R using the clmm which fits a cumulative link mixed model.


Boot/ScreenOn Broadcast Receiver not working

Question: I have a blank HelloWorld Application:
package tutorials.TestReceivers;

import android.app.Activity;
import android.os.Bundle;

public class TestReceiversActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

With this BootReceiver.Java:
package tutorials.TestReceivers;

import android.content.BroadcastReceiver;

public class BootReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent arg1) {
    Intent intent = new Intent(context, TestReceiversActivity.class);
        context.startActivity(intent);
    }
}

and this manifest:

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".TestReceiversActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android-permission="android.permission.RECEIVE_BOOT_COMPLETED"
            android:name="development.TestReceiversActivity.BootReceiver" >
            <intent-filter >
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.SCREEN_ON" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

After running the application and closing it.
When I unlock screen (SCREEN_ON) nothing happend.
And when i boot the decive I'm getting next msg like:
"The application TestReceiversActivity (tutorials.TestReceivers process) stop unexpectedly. Try again"
Comment: SCREEN_ON not working from manifest
Answer: After a long time of frustration, I solved the problem above.
The right way to register Boot Broadcast Receiver (and open activity according to it), is:
Blank HelloWorld Application (TestReceiversActivity.java):
package tutorials.TestReceivers;

import android.app.Activity;
public class TestReceiversActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Another Boot Receiver Class (BootReceiver.java)
package tutorials.TestReceivers;

import android.content.BroadcastReceiver;
public class BootReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
         Log.d("DAVID", "Hi, Boot reciver was catch!");
         Intent i = new Intent(context, TestReceiversActivity.class);
         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(i);
       }
}

Note: You must set the flag to make it work!
Set the manifest to:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tutorials.TestReceivers"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
            <receiver android:name=".BootReceiver" >
            <intent-filter >
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <activity android:name=".TestReceiversActivity"
                  android:label="@string/app_name">
                <intent-filter >
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
        </activity>
    </application>
 </manifest>

Enjoy!
Answer: Delete android-permission="android.permission.RECEIVE_BOOT_COMPLETED". Add a <uses-permission> element for this permission as a child of the <manifest> element.
If the problems continue, use adb logcat, DDMS, or the DDMS perspective in Eclipse to look at LogCat and examine the stack trace associated with your crash.
Here is a sample project showing how to get control at boot time.
SCREEN_ON will not work from the manifest.


C++11 new feature of delegating constructors in visual studio 2012

Question: I'm trying to use the new C++11 feature by using visual studio 2012. I don't really know if I'm not using it right or I need to add this feature to the visual studio?
struct Student{
  Student(double avgGrade, double avgProject): _avgGrade(avgGrade),_avgProject(avgProject){…}
  Student() : Student(0,0){…}
  Student(double avgGrade) : Student(avgGrade,0){…}
   private:
    double _avgGrade;
    double _avgProject;
};

Comment: Are you referring to the constructors calling the other constructors? That is called delegating constructors, not non-static data member initializers. Non-static data member initializers is when you give default values to your members inside the class body, not as part of any constructor.
Comment: Well, I can't remember if delegating constructors were supported in the 2012 CTP as well, but I'm fairly sure in-class member initializers were. If you can't use 2013 and you don't mind using a CTP, there's an option.
Comment: IIRC, only the CTP in 2012 supports that.
Comment: But you're not using it. You're just using regular old constructor initialization lists.
Comment: This is an c++11 feature, and it doesn't work in my visual studio 2012
Comment: I took the liberty of making the title match the question. I hope this is OK.
Answer: Delegating constructors are not supported out of the box in Visual Studio 2012. You can, however, install the Visual C++ Compiler November 2012 CTP, which, among other things, introduces support for delegating constructors.
After installing, you need to set your project to use the CTP as toolset. To do this, right click on the project file and select Properties. Under Configuration Properties -> General find the Platform Toolset entry. Set it to Microsoft Visual C++ Compiler Nov 2012 CTP (v120_CTP_Nov2012), which should be an entry in the combo box.
Comment: how do I set my project to use CTP?
Comment: @GuyGuetta I've edited the answer to include how to set your project to use the CTP.


Book recommendation for understanding more about distributions in econometrics/data analysis

Question: I have taken a few econometrics courses and I know some things about distributions; things like skewedness, kurtosis, ect. However, there are other areas regarding distributions that I know I am weak on. I am particularly confused with the great variety of distributions out there. Surely, there is a plethora of choices regarding distribution in the existing literature. So here is a small list of questions I'd like to resolve to narrow the scope as well as some other preferences.
Subject Matter

True population distributions vs small-medium sample-size distributions, sometimes
the underlying assumptions change? (I believe the Mahalanobis Distance equation is an
example of this, in some sample sizes it assumes a chi sq, others a
fishers T?)

Application

Intend to use in conjunction with econometric analysis and/or machine learning

Preferences

Math literacy is not my strong point, prefer a book with conceptual
explanation, not just a slew of equations
(optional) I use eviews and python, so if any book has companion data
files using either of these packages, that would be a plus

Question: From the above, are there any suitable books for me? Thank you!
Comment: Your criteria cover a great deal of the field of statistics!  If you could narrow the focus it might help get more useful responses.
Comment: Thank you.  Could you clarify what you mean by "true parameter distributions" and "small-medium distributions"? And could you explain the mechanism by which a distribution might "change"?
Comment: It's important to change your post to clarify its meaning--many (most?) readers will not wade through these comments.
Comment: If you really want to understand distributions in the long term it is much better to go via mathematical way. From measure theory standpoint, distribution is such a trivial thing.
Comment: @whuber I was afraid that would be the case. I have updated the post with some added clarity to the main focus.
Comment: @whuber I meant to say big and small n, and the theoretical true population distribution (can't be measured, where n is everything in existence). I suppose by change I meant the assumptions change. But I believe as n increases the distribution could take on a new form and I'd be curious to know how researchers use techniques to work on non-normal distributions. Still a bit broad, any little bit will help though
Answer: I think I know where you are coming from, and so I will recommend Statistical Rethinking, by Richard McElreath, since it helped me so much. It only assumes you are decently familiar with linear regression and at least some math.
It explains theories very clearly, elaborating on them as needed with pedagogical (read: excellent) examples, that also demonstrate the limits of all statistical models (which I think is crucial), and is decently thorough. Toward the middle you'll learn about the exponential family of distributions and the models they each define, and why to use them.
The only drawback to this book is that it does not go into time series models, since they are not its focus.


Expressões regulares para um ou mais números de telefone

Question: Tenho uma expressão regular que valida telefone celular e fixo, mas o usuário só consegue adicionar um fixou ou um celular, ela não permite adicionar mais de um número.
Como faço pra expressão aceitar mais de um número?
Eu até consigo que ela aceite mais de um número se eu fixar ela dentro de um grupo e repetir, só que aí aceita se eu colocar dois números, se eu coloco 1 não aceita, e eu precisava que aceitasse 1 ou mais números.
/^[1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}$/

Exemplo: 11 91111-1111

Utilizo uma ferramenta para criar requisições para usuários. Foi solicitado para que se criasse uma opção para o usuário inserir um ou mais telefones, nesse formato: "11 91111-1111".
Essa ferramenta tem uma opção que eu posso utilizar regex. A expressão que eu estou utilizando acima está correta, porém, ela só permite que o usuário insira apenas um número.
Eu tentei dessa forma também:
(/^[1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}$/) (/^[1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}$/)

Mas aí ela só permite que o usuário insira dois números, não menos ou mais que isso.
Comment: Não entendi, vc quer achar um ou mais número dentro de um input? é no javascript que isso é aplicado?
Comment: E como seria os exemplos com dois ou mais números de telefone?
Comment: Utilizo uma ferramenta para criar requisições para usuários. Foi solicitado para que se criasse uma opção para o usuário inserir um ou mais telefones, nesse formato:11 91111-1111. Essa ferramenta tem uma opção que eu posso utilizar regex. A expressão que eu estou utilizando que eu coloquei na criação do post esta correta, porém, ela só permite que o usuário insira apenas um número. Eu tentei dessa forma também: (/^[1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}$/) (/^[1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}$/), mas ai ela só permite que o usuário insira dois números não menos ou mais que isso
Answer: A regex correta depende de como os números serão aceitos. Por exemplo, se quiser que eles  estejam na mesma linha e sejam separados por espaço, uma opção seria:
^[1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}( [1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4})*$

Esta regex basicamente se resume a:
^regex_numero( regex_numero)*$

Ou seja, a regex para o número é a mesma que você usou ([1-9]{2} etc...). A ideia é que eu tenha uma ocorrência desta regex (para o caso de ter apenas um número), e depois eu posso ter ( regex_numero)*.
Repare que logo depois do ( há um espaço. Isso indica que depois do primeiro número de telefone pode ter um espaço, seguido de outro número. Eu agrupo tudo isso dentro dos parênteses e uso o quantificador *, que significa "zero ou mais ocorrências". Isso quer dizer que todo esse grupo (espaço + outro número de telefone) pode se repetir zero ou mais vezes.
Sendo assim, a regex aceita um ou mais números de telefone no formato indicado, separados por espaço. Exemplos de casos aceitos:
11 91129-1231
11 91231-2343 11 2322-4332
15 98221-9540 12 93853-2343 45 4332-0593

Veja a regex funcionando no regex101.com.

Outro detalhe importante é o uso dos marcadores ^ e $, que são respectivamente o início e fim da string. Assim eu garanto que a string só tem o que está na regex (então se tiver qualquer outro caractere antes ou depois dos números, a regex falha).

Se quer limitar a quantidade, basta trocar o * por algum dos quantificadores {min,max}. Ex:
^[1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}( [1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}){0,3}$

Em vez do *, eu usei {0,3} (no mínimo zero, no máximo 3 ocorrências), o que quer dizer que a sequência "espaço + número" pode se repetir no máximo 3 vezes. Portanto agora a regex aceita entre 1 e 4 números de telefone, separados por espaço.

Repetir a regex inteira pode ser meio chato e até causar problemas de manutenção futura (pois uma alteração na regex exigiria uma mudança em 2 lugares).
Caso a ferramenta que você usa suporte sub-rotinas, é possível fazer algo assim:
^(?<numero>[1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4})( (?&numero))*$

A sintaxe (?<numero> define um named group cujo nome é numero. Em seguida, (?&numero) signfica "a mesma regex que foi definida no named group numero". Assim você não precisa repetir a mesma regex duas vezes (veja aqui ela funcionando).
Outra opção é usar grupos sem nome:
^([1-9]{2} (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4})( (?1))*$

Nesse caso, o primeiro número está entre parênteses, e este pode ser referenciado posteriormente através de (?1) (que referencia o primeiro par de parênteses - no caso, a expressão que corresponde a um número de telefone).
Importante notar que as sub-rotinas referenciam a mesma expressão (e podem portanto dar match em números diferentes), diferente do que acontece com grupos de captura, que referenciam o trecho que foi capturado (e só dariam match se o mesmo número se repetisse).
Mas este recurso de sub-rotinas não é suportado em todas as engines/linguagens/ferramentas (e nesse caso, o jeito é repetir a expressão mesmo).


Best way to user current user in android

Question: When i get a user by json request in android i have a one class, example:
public class CurrentUser {
    public static String first_name = "";

    public static String getFirst_name() {
        return first_name;
    }

    public static void setFirst_name(String first_name) {
        CurrentUser.first_name = first_name;
    }
 }

and i class in mi activity class
my_text.settext(CurrentUser.getFirst_name());

But when app is in background i lose the data, existing any options without shared preferences?
Comment: you need to save the data persistently such as in a database.  Just use asynchronous request to send your data in your database, you will need to create apis(urls) that will be hit on request to send and obtain the data as needed, those urls will be hosted on your webservice.
Answer: There is more than one option but all leads to the same. You need to store this data manually. Using a saveInstanceState is an option, but it won't survice app closing. Other hand you can store it to the database using sqlite/realm or whatever you like.
Comment: my dude.. its correct use static variables in class for current user?
Comment: no just dont do it. You don't have control on static variable lifecycle.


"Mail Conflict Resolution"

Question: I have several of these messages:

11:36:30 Mail Conflict Resolution

11:36:30 Subject: {SU:}

11:36:30 EntryID: {CB:70,

LPB:00000000F13DCECA469BD311B527009027654AF5070043373E82DE99D311B524009027654AF50000000003F80000A4D9C2306C47F74B89AC01C78EB52D5C0016D0EFD3C00000}

11:36:30 Checking local modifications

11:36:30 Compare property: 0x0080001F

11:36:30 Compare property: 0x0081001F

11:36:30 Getting remote properties

11:36:30 Checking remote modifications

11:36:30 Compare (conflict) property: 0x0080001F

11:36:30 Local{SU:displayed}

11:36:30 Remote{Error (0x8004010F)}

11:36:30 Not equal (conflict) property: 0x0080001F

11:36:30 Local modification: {D:18, M:6, Y:2009 H:15, M:36, S:1, MS:776}

11:36:30 Remote modification: {D:18, M:6, Y:2009 H:15, M:36, S:40, MS:204}

11:36:30 Conflict generated, remote item is winner

I'm sure they mean something to somebody, but it isn't me. I haven't been able to find a way to disable these though - any idea what causes their generation and any settings I can change?
Thanks!!!
Comment: I'm still having this issue in 2023. So, I am not sure what it will take for Microsoft to fix this.
Answer: This error relates to a difference between a mail item stored on the Exchange Server, and the item stored locally on the machine. Often this issue occurs when using OST files in outlook to work offline.
A common reason for this error is different timestamps on messages, modification of an email in both outlook (offline) and owa, or a out of date OST file. If its an issue with the OST file then a common solution is just to rebuild the OST file, this will ensure everything is up to date. If it is because the mail has been edited in 2 places, there's not alot you can do about that other than not do it!
Comment: Do you think that verifying the time on both deviced might help? The remote devices almost certainly sync to a broadcast time service, but his internal PC or maaybe the server itself doesn't. I will check there, any thoughts?
Comment: Yes, its worth checking, particularly if its only occurring on one machine.
Answer: I'd guess you have two clustered ldap servers (maybe AD?) trying to synch an entry/check that an entry is synched.
I'd say that two instances representing the entry conflict for attribute 0x0080001F and the remote instance is older so it is the one that is used.
I.e. the local version of 0x0080001F is synchronised (chnaged to match the value of) with the remote version.
E.g.
local:
dn: ou=blah,dc=banan,dc=edu
cn=fred
remote:
dn: ou=blah,dc=banan,dc=edu
cn=freddy
Then the local copy's cn would get set to "freddy" because the remote copy is more recent.
Comment: We actually do not implement ldap here. I'd guess this is either iPhone or BlackBerry related, but I haven't yet found anything helpful. I know with remote devices, conflict messages are bound to happen. What I mainly want to do is find out where these are generated and shut them off...
Comment: Well whatever it is I'm pretty sure its just some property/value getting sync'd between 2 copies of it.
Comment: If your using Exchange, it means your using Active Directory, which means your using LDAP
Answer: To make the reports go away if you don't want end users to receive them, create a DWORD value called EnableConflictLogging at HKEY_CURRENT_USER\ Software\Microsoft\Office\xx.0\Outlook\Options and set the value to 0.  Replace "xx" with 14 if you use Outlook 2010 or 15 if you use Outlook 2013 and so forth.  You can use Group Policy to create this registry item to apply to all end users.
Generally I don't find it necessary to know which copy of a modified email the synch function chooses when end users are running multiple copies of a mailbox (i.e. phone, Exchange Servers / Office 365, laptop, etc).
Answer: I found the below answer helpful.
Lisa C
Jalapeno
Lisa C Sep 29, 2009 at 5:31 PM
My understanding is that this is due to the Outlook clients being set up with Cached Exchange mode. With this setting enabled it will allow users to go into "offline" mode when the connection to the Exchange server is interrupted.
http://office.microsoft.com/en-us/outlook/HP010000671033.aspx?pid=CH010045991033
At the client you can turn that off in Outlook
http://office.microsoft.com/en-us/outlook/HP010223431033.aspx
On the Tools menu, click E-Mail Accounts, click View or change existing e-mail accounts, and then click Next.
In the Outlook processes e-mail for these accounts in the following order list, click the Exchange Server e-mail account, and then click Change.
Under Microsoft Exchange Server, clear the Use Cached Exchange Mode check box.
Exit and restart Outlook.
Globally you can enable/disable various settings under "Cached Exchange Mode" if you have the Exchange Admin template installed, but I have not yet found the right combination to actually work in production. One states that it will disable on new profiles only but not on existing. If anyone actually gets this to work I'd love to see the magic setting!
(I don't have an answer for why this feature doesn't work as advertised. There should never be so many conflicts IMO.)
Thank you.
Best regards,
Sujith.
Comment: What do you mean, you found the below answer helpful? Did you copy this post from somewhere??? If so: That's not how things work - you can't just copy and paste someone's content into your own, especially without attribution / link to original post. Plus I don't see where you added your own content. And... you're responding to a question from six years ago. With an already-accepted answer. I don't understand the objective here.

"Mail Conflict Resolution"


Função Javascript que recebe dois números (input) e exibe em uma lista (alert) com todos os números pares entre eles

Question: Olá, Pessoal!
Podem me ajudar com o código abaixo?
Gostaria que ele retornasse uma lista com todos os números pares que entrarem nos inputs.
document.querySelector("#btnNumPar").addEventListener("click", function() {
    const inputNumUm = document.querySelector("#inputNumPar").value.trim();
    const inputDoisNum = document.querySelector("#inputNumParDois").value.trim();
    let todosPares=[];
    for (let i = 0; i <= inputDoisNum; i++) {
        if (i % 2 === 0) {
            todosPares.push();
            console.log(todosPares)
            // alert(`Os números pares entre ${inputNumUm} e ${inputDoisNum} são: ${todosPares}`);

        }
    }
})

Comment: Você precisa dizer ao método push o que quer inserir na array!
Answer: Considerando que o primeiro numero sempre será maior que o segundo, e que você deseja os numeros pares dentro do intervalo de valores recebidos dos inputs, você deve deixar seu loop da seguinte forma:
for (let i = parseInt(inputNumUm); i <= parseInt(inputDoisNum); i++) {
        if (i % 2 === 0) {
            todosPares.push(i);
        }
    }

Após isso basta realizar o alert:
alert(`Os números pares entre ${inputNumUm} e ${inputDoisNum} são: ${todosPares}`);

Comment: Gabriel, muito obrigada!
Só mais uma dúvida.
O alert está retornando um por um os itens do array, como eu poderia retornar todos os itens de uma só vez?
Comment: Você precisa deixar seu alert fora do `for`, caso contrário sempre que o número for par ele irá executar seu `alert`
Comment: Obrigada novamente, Gabriel!


Diferença entre promise.then( sucess, error ) e promise.then() .catch()?

Question: Olá,
Gostaria de esclarecer a diferença e quando usar cada dos modelos de tratamento das promessas:
obj.promessa( parametro ).then( function ( resposta ) {
    console.log("Resposta: " + resposta);
}, function ( erro ) {
    console.log("Erro: " + erro);
});

e
obj.promessa( parametro ).then( function ( resposta ) {
    console.log("Resposta: " + resposta);
}).catch( function ( erro ) {
    console.log("Erro: " + erro);
});

Considerando que o método obj.promessa fosse algo do tipo:
promessa: function( parametro ) {
   var deferred = q.defer();
   if ( fun_assincrona(parametro) ) {
      return deffered.resolve("sucesso");
   } else {
      return deferred.reject("error");
   }
   return deferred.promise;
}

Abraços!
Answer: Em termos gerais eu diria assim:

usa .catch() 1 vez por encadeamento de promises, para apanhar erros imprevistos
usa localmente a função de erro para corrigir erros e permitir ao encadeamento continuar

Vou dar dois exemplos, um que sofre um erro, mas que é corrigido, outro que sofre um erro, sem o corrigir:
Corrigindo erros localmente com função erro.

function resolve(contador) {
    contador++
    console.log('Iteração', contador);
    return new Promise((res, rej) => {
        setTimeout(() => res(contador), 200);
    });
}

function falha(contador) {
    contador++;
    console.log('Eu vou falhar na iteração', contador);
    return new Promise((res, rej) => {
        setTimeout(() => rej(contador), 200);
    });
}
resolve(0)
    .then(resolve)
    .then(falha) // <-----------------
    .then(function() {
        // esta função é do success e não vai ser chamada
    }, function(nr) {
        console.log('Houve um erro, mas eu vou dar sinal para continuar...');
        return resolve(nr)
    })
    .then(resolve)
    .catch(e => console.log(e));

Deixando erros para o .catch()

function resolve(contador) {
  contador++
  console.log('Iteração', contador);
  return new Promise((res, rej) => {
    setTimeout(() => res(contador), 200);
  });
}

function falha(contador) {
  contador++;
  console.log('Eu vou falhar na iteração', contador);
  return new Promise((res, rej) => {
    setTimeout(() => rej(contador), 200);
  });
}

resolve(0)
  .then(resolve)
  .then(falha) // <-----------------
  .then(resolve) // nunca é chamada
  .catch(e => console.log('Erro no encadeamento!', e));

Portanto:

para permitir a um encadeamento se recompor usa a função erro, e assim "apanhar" e tratar um possível erro usa a função erro
para apanhar erros e de código que parte algures a meio usa o .catch() no final de um encadeamento.

O .catch() não é chamado se o erro for "tratado" e não houver uma nova Promise como retorno dessa função erro:

function resolve(contador) {
  contador++
  console.log('Iteração', contador);
  return new Promise((res, rej) => {
    setTimeout(() => res(contador), 200);
  });
}

function falha(contador) {
  contador++;
  console.log('Eu vou falhar na iteração', contador);
  return new Promise((res, rej) => {
    setTimeout(() => rej(contador), 200);
  });
}

resolve(0)
  .then(resolve)
  .then(falha) // <-----------------
  .then(resolve) // nunca é chamada
  .then(function() {
    console.log('Serei chamado?');
  }, function(err) {
    console.log('Houve erro?', err);
  })
  .catch(e => console.log('Erro no encadeamento!', e)); // não é chamado!

Por isso o .catch() funciona também como o ultimo recurso para reiniciar o encadeamento todo, ou pelo menos evitar N funções erro em cada nó do encadeamento.
Comment: Valeu! Entendi! Muito obrigado pela ajuda! Abraços!
Comment: @Rafael de nada. Boa pergunta!


How to avoid submissions with the same e-mail address?

Question: How can I prevent that someone submits a form with the same address in an e-mail field again?
Answer: Check the unique box in the Form validation settings.
Comment: Ah, thank you! The help text is saying "Check that all entered values for this element are unique", so I thought it means that in case that the field allows multiple values, it should only allow unique ones...


How to override "active configuration" when the theme is installing?

Question: I have a theme that imports configuration when is installed. The problem is when the configuration is already there and is active.

Unable to install MYTHEME, field.field.user.user.user_picture,
  field.storage.node.body, field.storage.node.field_image,
  field.storage.user.user_picture, node.type.article,
  views.view.frontpage already exist in active configuration.

I know these errors are because the configuration is already on the site.
How can I override the configuration with a new configuration that is carried from my theme?
Answer: You cannot. You can provide only configuration for your module or create new configuration entities. You can "override" the default configuration only by profile, not module or theme.
But you can use hook_install to programmatically override whatever you want.
When it comes to themes, the only configuration that you should provide is block instances and your theme's settings. Of course if you have some advanced blocks you can also provide block types and field storage and instances for them.
Comment: I have run to so many issues try to "overwrite" configuration. Its better to avoid doing that..
Comment: its possible to override all my configuration files ? If so how ? hook_install example that I have seen are very specify to a value but I have not seen an example that it overrides the entire file.
Comment: To override existing configuration use \Drupal::configFactory()->getEditable($name) instead of \Drupal:config($name) since the latter is read-only.
Comment: $name = to the name of file ?


Mentally prepare for performing

Question: Some background: I play the violin. Next spring, I will play in school. This will be graded and part of my final grade for music class.
The problem is that I have almost no experience playing in front of people (except my family). The last time I performed was more than three years ago, so I tend to be very nervous when playing in front of people (you might be asking how I can know when I never do - last summer, I played in a quartet, so not really solo, but sort of).
I realized that when I changed my teacher one year ago, I first was nervous playing in front of them, but after a while it became better and I am now completely comfortable. So I concluded that I get less nervous when I often play in front of the same people.
However, this is not possible for the above described case. So I somehow have to emulate this situation while practicing at home to make my brain think that I am performing for my grade.
What are tips for practicing to be less nervous when performing?
Answer: Obviously you are not going to be able to hire a crowd for every practice performance you do, especially right now with what's going on in the world. However, I have experienced plenty of ways to prepare for this so let me share my tips:
1. Do a lot of pretend recitals
I don't know what the format of your performances and whether you have introduce yourself, the piece, talk about it, etc. but whatever you have to do, do it out loud and in front of people. Your best bet will be in front of your parents or teacher, but you can be creative and even livestream this kind of stuff to your friends. The idea is to make your practice feel as real as possible, so that the difference between a practice recital and real one is minimal. You can also dress up in your performance attire, this helps a lot to because you feel more important (I can't find the time stamp but in this interview Julian Casablancas mentioned how when he dressed up a certain way he played music in that particular fashion, specifically a wedding band)
2. Destress
Performances in front of big crowds is nerve-wracking for 99% of people naturally. However, don't overthink it. Sleep well, eat healthy, take deep breaths, relax your shoulders, maintain good posture - basically anything a chiropractor or doctor would tell you. If you are operating like you are when you are relaxed, that will help you approach the recital in a more collected fashion then if you are pulling 4-hour of sleep a night and binging on alcohol
3. Reprogram your mind
Reprogramming is kind of a cheesy technique, but it personally worked for me. Keep repeating a positive mantra in your head (for me it was "You're the boss" because I felt like I didn't have control, but it's just anything reaffirming and confidence-boosting) every single day many times a day. You'll be amazed at what you can fool yourself (a paradigm shift :) ) into believing
Those are just some techniques that worked in my experience. Good luck!
Answer: Adding to Andrew's answer - record yourself, especially video yourself. Imagine that camera is the audience. Because it's recorded, the pressure will still be there to play well. And - after, wher you press play, you'll be able to see for yourself what your audience would see. There will be positive parts, which need emphasising, and not-so-good bits that you can then work on. Body language, facial expressions, etc.
It should be a given that the piece/s you are playing can be played at the same time as you recite the alphabet, say the 2x table, in other words you know them well enough that you don't have to worry about mistakes happening. That's actually all part of the nervousness. Eliminate that factor, and you'll lose a lot of the inconfidence.
Keep the recordings, and take them every few days. Look back at the earlier ones, to give you a yardstick as to what has/n't improved.
Couple of other pointers. Nervousness is useful. It keeps you on your toes. That bit of adrenalin flow is there for a purpose, so use it. Mistakes may happen. Carry on as if they hadn't. It's impossible to 'unmake' a mistake. Smile and continue - or just continue. People are listening to what you play at that moment, not the mistake you made several bars ago.
All this can be done without involving anyone else - important at this covid-ridden time. Go for it !
Comment: "Mistakes may happen... Smile and continue" Fantastic and often understated point. Perfomance, unlike recording, is an audiovisual spectacle. You can play flawlessly but if you glare menacingly at everyone you'll leave an odd impression. Just be happy and proud to show off whatever you learned, regardless of what happens during the actual performance

Mentally prepare for performing


Error running Node.js' fs.rename() inside of a loop

Question: I'm developing an application that has to organize some uploaded files, I'm separating them in folders with the ID of their request (I'm using express-request-id to get this ID).
The problem is that everytime I have more than a single file the "moving" process fails and I can't seem to fix it.
let request_folder = path.resolve(tmp_folder + "/" + req.id);

/* Checking if the folder exists */
fs.access(request_folder, fs.constants.F_OK, function(error) {
    if(error) { // it doesn't
        /* Trying to create it */
        fs.mkdir(request_folder, function(error) {
            if(error) {
                console.log("Error: Couldn't create the directory.");
                console.log(error);
            }
        });
    }
});

/* Moving uploaded files to their respective request folder */
req.files.forEach(function(file) {
    let new_file_path = path.resolve(request_folder + "/" + file.filename);
    fs.rename(file.path, new_file_path, function(error) {
        if(error) {
            console.log("Error: Couldn't move " + file.filename + ".");
            console.log(error);
        }
    });
});

I'm one hundred percent sure both the folders and the files exist, but I when trying to move two files at once I get:
Error: Couldn't move Desert.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Desert.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f5725a73
\Desert.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Desert.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Desert.jpg' }
Error: Couldn't move Chrysanthemum.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Chrysanthemum.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f
5725a73\Chrysanthemum.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Chrysanthemum.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Chrysanthemum.jpg' }

Does anyone know what am I doing wrong? Thanks!
Answer: The fs operations you are using are async meaning they can happen in any order.
Your loop will ask node to create a folder and move the files basically at the same time. In other words, it will run a synchronous loop that will dispatch all fs actions concurrently. Meaning that you have no guarantees what will actually run first.
Try creating the folder before moving all the files:
fs.access(request_folder, fs.constants.F_OK, function(error) {
    if(error) {
        return fs.mkdir(request_folder, function(error) {
            if(error) {
                return;
            }
            moveFiles();
        });
    }
    moveFiles();
});

function moveFiles() {
  req.files.forEach(function(file) {
    // ...
  });
}

Using promises might make this a bit cleaner:
const access = util.promisify(fs.access);
const mkdir = util.promisify(fs.mkdir);
const rename = util.promisify(fs.rename);

access(request_folder, fs.constants.F_OK)
  .then(moveFiles, makeDirAndMoveFiles)
  .catch(console.error);

function moveFiles() {
  return Promise.all(
    req.files.map(file => {
      const new_file_path = path.resolve(request_folder + "/" + file.filename);
      return rename(file.path, new_file_path);
    })
  )
}

function makeDirAndMoveFiles() {
  return mkdir(request_folder).then(moveFiles);
}

Comment: You're absolutely right, I failed to realise the operation order could be inverted since both functions are asynchronous. I chose your answer as it shows a way to fix it both with callbacks and promises.
Answer: It is possible you are trying to move the file even before the destination folder exists.
try the new await keyword to structure the code.
const {promisify} = require('util');

const fs = require('fs');
const accessFileAsync = promisify(fs.access);
const mkdirFileAsync = promisify(fs.mkdir);
const renameFileAsync = promisify(fs.rename);
try{
  await accessFileAsync(request_folder, fs.constants.F_OK);
}
catch(ex)
{
  await mkdirFileAsync(request_folder);
}
req.files.forEach(function(file) {
    let new_file_path = path.resolve(request_folder + "/" + file.filename);
    try{
      await renameFileAsync(file.path, new_file_path);
    }
    catch(ex)
    {
      console.log(ex);
    }
});

Comment: `await` can only be used in an `async` function
Comment: Thank you for your answer, you're indeed right I'm using two asynchronous functions without guaranteeing the precedence order. I ended up accepting the other answer though, as it shows both a way to code it with callbacks and with promises though.
Comment: as suggested above you can only use await inside an async function.


String gauge, scale, and tuning relationship? (Guitar in particular)

Question: Does anyone have general guidance or a good resource on this, specifically considering scale length, string tension, string gauge, and tuning? I've found loads of anecdotal research and a even few calculators, but while these are often useful they don't actually explain the technical aspects or anything. I suppose I'm either looking for some sort of guide/explanation, the math behind it, and any helpful extraneous information you might have.
If it helps at all, I'm starting to get into non-standard tunings (major thirds in particular) and I'm trying to figure out why specific string gauges feel and/or sound 'better' than others from a technical standpoint.
Comment: I think the answers you want are here: http://music.stackexchange.com/questions/7877/how-do-i-use-string-gauge-tables?lq=1
Comment: Have you seen [this guide from D'Addario](http://daddario.com/upload/tension_chart_13934.pdf)?
Comment: -And would be kind to the neck of your guitar !
Comment: Yes, but while it has a good section on string tension and an overall product guide, it doesn't really explain how everything works together, nor their effects on playability or tone.
Comment: possible duplicate of [How does string gauge affect a guitar's sound and playability?](http://music.stackexchange.com/questions/4593/how-does-string-gauge-affect-a-guitars-sound-and-playability)
Comment: @jonrsharpe I don't think so, as, while there is some overlap in the question, I'm not specifically asking how the gauge itself affects tone, at least not so much as asking how all the elements that affect tuning and tension work together and how they affect the tone and feel of an instrument. In addition, the top response by slim seems to fall under the category of 'anecdotal research.' I'm not saying it's a bad answer, and I agree with his responses, he doesn't actually explain any of it.
Comment: How objective an assessment are you expecting for *"why specific string gauges feel and/or sound 'better'"*? A good starting point would be to work out the string tensions at concert pitch with the strings you normally use, then identify gauges that provide similar tension at the altered pitch - this would give a consistent feel, at least.
Comment: @jonrsharpe the main idea of my question is to understand the relationship between the strings, scale length, and tuning, not to find some sort of sweet spot for tuning. I'm more interested in A) choosing the right gauges for particular tensions at particular tunings B) finding the actual math/physics behind it all. When I said "I'm trying to figure out why specific string gauges feel and/or sound 'better' than others" I meant that having the mechanics explained would help me understand, not that I wanted people's opinions.
Answer: If you want a really technical discussion that uses serious math, you can get
Richard Mark French, Engineering the Guitar. (It's available as an ebook on Kindle.) He deals with scale length, intonation, the physics of ideal and real strings, etc., etc. The math is, frankly, beyond me, but it is an exhaustive treatment.
Answer: See this previous post of mine.
And this one from @slim.
They both refer you to a PDF guide published by the D'Addario String Company which provides a comprehensive resource for determining which gauges strings to use for different guitar-family instruments of different scale lengths and tuning schemes. It also takes into account different types of strings, such as steel-string and nylon. The charts and measurements generally can be used for any brand of strings, not just D'Addario's. This is a gold mine of information.
Comment: I have seen that guide before, I was looking for a resource that actually goes through and explains the relationship between tuning, scale, tension, and string gauge. While the D'Addario has a partial explanation on pages 4 and 5 it doesn't seem to cover everything.


Tell the linux kernel to put a file in the disk cache?

Question: Is there any command to for a file to be read in and loaded into the linux disk cache? This is on an up-to-date debian system.
I know in the general case, it's better to let the linux kernel figure this out. But I have an edge case. I have a laptop that has an NFS director mounted, and i want to play a long video file, but I don't want to have a network problem interrupt the playnig. I know that (largeish) file will be read in it's entirety later on. I know that nothing else (really) will be running  while playing this video. There is enough free memory to store this file.
(I know I could just copy the file into a new tmpfs filesystem, but I'm curious if there's an even shorter way to do it)
Answer: A small program that mmap()ed the file with the MAP_LOCKED flag set would do the trick.  You'll need to run this program as root, or a user with an RLIMIT_MEMLOCK value greater than the size of the file you want to map.
As SaveTheRbtz has mentioned, vmtouch has this capability built-in.  The manpage suggests that vmtouch -l /some/file will do the trick.
Comment: And don't forget to munlock() that file afterwards again! :)
Comment: There is a tool for that: http://hoytech.com/vmtouch/
Comment: Not necessary; as per `mlock`(2), "Memory locks are [...] automatically removed (unlocked) [...] when the process terminates.".
Comment: @SaveTheRbtz: Thanks for that -- I expected someone would have written it already.
Answer: If you really control the local environment that strictly, a simple cat $file >/dev/null should be sufficient.
It's quite non-deterministic, when cache eviction removes that file - but if you have plenty of RAM and noone consuming it, it should be kept.
If there is a sticky and deterministic way to keep a file in cache - dunno...
Comment: Is that guaranteed to put the file into the cache though?
Comment: Yes, thats the way it works. It's read through the cache.


Property of zero mean and unit variance random variable

Question: Assume an arbitrary random variable $X$ is zero mean and unit variance, and $Y\sim \mathcal{N}(0,1)$. I have a guess, but I don't know whether it is correct,
\begin{align}
E \left[ X^{2n} \right] \le E \left[ Y^{2n} \right]
\end{align}
where $n \ge 1$. I check some random variables, and find they always satisfy the above inequality. Is this a general law? If not, is there any counter example?
Many thanks for any idea!
Answer: In general, a random variable with finite mean and variance does not even need to have a finite fourth moment. Even if we require a finite fourth moment your conjecture does not hold, as shown by this counterexample:
Let $Z$ follow a Student t-distribution with $\nu=5$. Then for $Y = \sqrt{\frac{3}{5}} Z$ we have $E[Y]=0$, $E[Y^2]=1$, and $E[Y^4]=9$, whereas $E[X^4]=3$ for $X \sim \mathcal{N}(0,1)$.
In other words, $Y$ is a distribution with positive excess kurtosis.


How the cricket ball's swing measured instantly?

Question: In the recent test series between India and England, Star Sports, which is the official broadcaster in the Indian sub-continent, showed a new graphics after each ball is bowled. It was the amount of ball swing (in-swing/out-swing). The data was in centimetres & the measuring axis was the trajectory of the ball if it doesn't undergo any swing.
So, what new technology was used to measure this deviation? Or was it just the good old Hawk-eye with some data processing?
Answer: This BBC article confirms that Hawk-eye can track any types of bounce, spin, swing and seam with 99.99% accuracy. So, it's basically a hawk-eye that is used to calculate cricket ball's swing instantly.
Answer: That's essentially what Hawkeye measures, the path of the ball once it leaves the bowler's hand. In this case it can determine the deviation from the initial trajectory, plot the curve and give measurements though some swift data processing.
The slightly controversial part of Hawkeye is the predictive element, describing what the ball would have done if it had not hit the bat/pad/person of the batsman in the meantime.
Comment: The technology looks derived from Hawkeye but without authentic sources, we cant be sure.
Comment: Whether it's the same machine as Hawkeye or another one, it's the same science.


Como adicionar um array dentro de um array de array?

Question: <code>$regras = array(
    array(
        'field' => 'cpf',
        'label' => 'CPF',
        'rules' => 'required'
    ),
    array(
        'field' => 'senha',
        'label' => 'SENHA',
        'rules' => 'required|trim'
));
// o array $maisUmCriterio tem que ser inserido dentro de $regras
$maisUmCriterio =
    array(
        'field' => 'nome',
        'label' => 'NOME',
        'rules' => 'required|trim'
);

// já tentei fazer

$regras = $regras + $maisUmCriterio;

// mas não funciona, preciso que o array $regras fique assim :

$regras = array(
    array(
        'field' => 'cpf',
        'label' => 'CPF',
        'rules' => 'required'
    ),
    array(
        'field' => 'senha',
        'label' => 'SENHA',
        'rules' => 'required|trim'
    ),
    array(
        'field' => 'nome',
        'label' => 'NOME',
        'rules' => 'required|trim'
    )
);
</code>
Answer: Falta-te uma coisa, que é "[]" no final do nome da variável onde queres inserir o novo array:
Temos:
<code>$regras = array(
    array(
        'field' => 'cpf',
        'label' => 'CPF',
        'rules' => 'required'
    ),
    array(
        'field' => 'senha',
        'label' => 'SENHA',
        'rules' => 'required|trim'
    ),
);
</code>
Para adicionar mais um array dentro desse array:
<code>$regras[] = array(
    'field' => 'nome',
    'label' => 'NOME',
    'rules' => 'required|trim'
);
</code>
DEMONSTRAÇÃO
Na realidade até tens mais metodos:
array_unshift, adcionas ao princício do array:
<code>$add = array(
    'field' => 'nome',
    'label' => 'NOME',
    'rules' => 'required|trim'
);

array_unshift($regras, $add);
</code>
array_push, adionas no fim (semelhante ao primeiro exemplo que dei):
<code>$add = array(
    'field' => 'nome',
    'label' => 'NOME',
    'rules' => 'required|trim'
);

array_push($regras, $add);
</code>


Weight shrinking in linear regression by L2 regularization

Question: Quoting Prof. Bengio from his Deep Learning text (http://www.iro.umontreal.ca/~bengioy/dlbook/regularization.html),

$ w = (X^{T}X + \alpha I)^{-1}X^{T}y $
We can see L2 regularization causes the learning algorithm to
  "perceive" the input X as having higher variance, which makes it
  shrink the weights on features whose covariance with the output target
  is low compared to this added variance

After spending an hour, I can't understand how to approach the proof of this. Can anybody help me get an intuition for this?
Comment: Shouldn't we consider the entire $ (X^{T}X + \alpha I )^{-1} X^{T} $ for the proof? Can you please elaborate?
Comment: $X^Ty$ is your cross product matrix (akin to $E[XY]$). $X^TX+\alpha I$ is the variability of your $x$ values, with added ridge weights.
Comment: Yes, you should, but I was offering pointers on what the compoents of the results are.
Comment: Basically $ w_{new} - w = (( X^{T}X + \alpha I)^{-1}X^{T} - ( X^{T}X)^{-1}X^{T})y $ and due to the addition of $ \alpha \delta_{ij} $, the values should be lesser in $ ( X^{T}X + \alpha I)^{-1}X^{T} $, since $ \alpha > 0 $ and the resulting matrix has greater determinant, hence lesser value. Though this indicates towards a more stronger result. Am i correct in my reasoning?
Answer: The solution was along the similar lines of previous approach taken for the hessian approximation in the book. For getting exact relationship between $ w^{\sim} $ and $ w^{*} $, one has to do some kind of decomposition. Here, instead of eigenvalue decomposition (which is not possible, since $ X $,is not a square matrix) we do an SVD decomposition.
For unregularized version,

\begin{align} \newcommand{\new}{{\rm new}}
X &= UDV^{T}  \\
w &= (X^{T}X)^{-1}X^{T}y
\end{align}

Putting the values of the decomposition into $w$, we get:

$$ w = D^{-1}U^{T}y $$

However if you consider the least square regularized version,

$$ w_{\new} = (X^{T}X + \alpha I)^{-1}X^{T}y $$

We get:

$$ w_{\new} = (D^2 + \lambda I)^{-1}D^{2}U^{T}y $$

We can see that $ w_{\new} $ is nothing but a scaled version of $ w $, namely $  w_{\new,j} = d_{j}^{2}/(d_{j}^{2} + \lambda_{j})w_{j} $. Hence proved.
Comment: @user3303, do not edit someone else's answer to 'correct' it. If you think it is wrong, leave a comment, downvote, or post your own (correct) answer to set the record straight.
Comment: shouldn't it be $w_{new, j} = d_{j}/(d_{j}^{2} + \lambda_{j})w_{j} $ because  $w$ contains $D^{-1}$ so it cancels out the square of $d_{j}$?


Question about limit and continuity

Question: I have that $u_0>0$ , $u_n=u_n^+-u_n^{\raise{1pt}{-}}$ and $u\mapsto u^{±}$ is continuous
if $u_n\rightarrow u_0$ why we have that $u_n^+\rightarrow u_0$ and $u_n^{\raise{1pt}{-}}\rightarrow 0 $
where $u^+=\max(u,0)$ and $u^-=\max(-u,0)$
Thank you.
Comment: Ah, that would be good to include in the question.
Comment: what are $u_n^+$ and $u_n^{\raise{1pt}{-}}$? different sequences? Do we know, for instance, $u_n^+\ge u_n^{\raise{1pt}{-}}$?
Comment: $u^+=\max(u,0)$ and $u^-=\max(-u,0)$
Comment: so how to do ?please
Answer: By the definition of convergence, since $u_0\gt0$, there is an $N$ so that for all $n\ge N$, we have
$$
\left|u_n-u_0\right|\le u_0\tag{1}
$$
Inequality $(1)$ implies that for all $n\ge N$, $u_n\ge0$. That is, for $n\ge N$,
$$
u_n^+=u_n\tag{2}
$$
and
$$
u_n^{\raise{1pt}{-}}=0\tag{3}
$$
Now just take limits of $(2)$ and $(3)$.
Comment: $|u_n-u_0|\leq u_0$ why ? , we dont use the continuity of $u\mapsto u^{\pm}$ ?
Comment: @Vrouvrou: by the definition of convergence, for *any* $\epsilon\gt0$, there is an $N$ so that for $n\ge N$, $$\left|u_n-u_0\right|\le\epsilon$$ I just chose $\epsilon=u_0$.
Comment: Ohhh ok, and for the continuity because in the paper they precise the use of the continuity
Comment: and the continuity please?
Comment: @Vrouvrou: read my answer carefully and find where I use the continuity of $u\mapsto u^\pm$. In the current question, the continuity of $u\mapsto u^{\raise{1pt}{-}}$ is not relevant. However, because we have $(2)$ and $(3)$, I don't know we actually need to use the continuity of either function.
Comment: where we pass to the limits ?
Comment: @Vrouvrou: that would be the only place, but since we have $(2)$ and $(3)$, we simply get $$\lim_{n\to\infty}u_n^+=\lim_{n\to\infty}u_n=u_0$$ and $$\lim_{n\to\infty}u_n^{\raise{1pt}{-}}=\lim_{n\to\infty}0=0$$ with no reference to the continuity of those functions.
Comment: so we dont use the continuity ?
Comment: @Vrouvrou: I would say that we have not used their continuity, just their definitions.
Answer: This is because of your assumption that $u_0 > 0$.  If $u_n \to u_0$, then the negative parts of $u_n$ must vanish
Comment: can we see this using $||u_n-u_0||$ ? thank you , and please where is using the continuity of $u\mapsto u^{±}$ ?
Comment: please need your help

Question about limit and continuity


How to show all 3 urls are null in following table in postgresql/sql

Question: I want to show records where url is null and typeurl of type1 & type2 also null.
Output should be productname : Oil
ProductName     Url    Type     TypeUrl
Shampoo         null   Type1    null
Shampoo         null   Type2    www.domain.com
Conditioner     null   Type1    null
Conditioner     null   Type2    www.domain.com
Oil             null   Type1    null
Oil             null   Type2    null

postgresql query I want
Answer: We can use a simple aggregation here:
SELECT ProductName
FROM yourTable
GROUP BY ProductName
HAVING COUNT(Url) = 0 AND
       COUNT(TypeUrl) FILTER (WHERE Type IN ('Type1', 'Type2')) = 0;

For versions of Postgres which do not support FILTER, use this version:
SELECT ProductName
FROM yourTable
GROUP BY ProductName
HAVING COUNT(Url) = 0 AND
       COUNT(CASE WHEN Type IN ('Type1', 'Type2') THEN TypeUrl END) = 0;

Comment: Thanks Tim for ur help.I am using Postgresql where I am getting syntax error near where.
Comment: @Pinky Check the updated answer for another version which should work.


Why is mongodb updating or upserting instead of inserting?

Question: I'm inserting a lot of test records in a mongodb instance, via a mongo shell script.
I use batch inserts for performance db.messages.save(messagesBatch);
However, mongo upsert or update my data instead of inserting it !
After cleaning the collection, I run a loop for 200 inserts, via batches of 50. I end up with 51 (??) records after 4 batches, with following reports from db.getLastErrorObj():
/* 0 */
{
"n" : 0,
"connectionId" : 166,
"err" : null,
"ok" : 1
}

/* 1 */
{
"updatedExisting" : false,
"upserted" : ObjectId("527141c72a1ae75210d3a705"),
"n" : 1,
"connectionId" : 166,
"err" : null,
"ok" : 1
}

/* 2 */
{
"updatedExisting" : true,
"n" : 1,
"connectionId" : 166,
"err" : null,
"ok" : 1
}

/* 3 */
{
"updatedExisting" : true,
"n" : 1,
"connectionId" : 166,
"err" : null,
"ok" : 1
}

my insertion code is the following :
var batchLimit = 50;
var messagesBatch = [];

function flushMessages() {
print("* flushing... (" + messagesBatch.length + ")");
var inserted = false; // so far
do {
    db.messages.save(messagesBatch);
    var errObj = db.getLastErrorObj();
    print(errObj);
    if(errObj.ok && errObj.err === null) {
        // no error, fine
        inserted = true;
        messagesBatch.length = 0;
        print("* flushed. (" + messagesBatch.length + ")");
    }
    else {
        // insertion error !
        failedInsertions++;
        print(errObj);
    }
} while(!inserted);
}

function addMessage(message) {
messagesBatch.push(message);
if(messagesBatch.length >= batchLimit) {
    flushMessages();
}
msgGenerated++;
if(msgGenerated % 100000 == 0)
    print("* " + msgGenerated);
}

Can someone see why this code is upserting instead of inserting ? What am I doing wrong ?
Note : of course, the documents I'm inserting don't have an _id field.
Comment: Can you show some sample messages?
Comment: @ithcy I'd rather not (company data) but they don't have an `_id` field, though they have a bunch of `xyzID` fields.
Comment: Save will do an upsert if the document contains an _id field.
Comment: @Martin which they have not (unless I made an error somewhere) and how do you explain the strange 51 ? All records are created from scratch via `new XYZ()` which doesn't set an `_id` field.
Comment: You're doing (trying to do) 200 inserts total - the final count of inserted records could be anywhere from 0 to 200, no?
Comment: @ithcy yes, and I expect 200 and I check for errors with `db.getLastErrorObj();` Did you see the returned errObjs in my question ? They clearly say `updatedExisting: true` but why ?
Comment: @Offirmo what I meant was 51 is not an impossible result... it does suggest that your process is stopping after 1 batch + 1 record, though.
Comment: @itchy however I correctly get 4 (200/50) traces and 4 reports
Comment: Have you inspected the 51 inserts to see if they relate to any one particular batch of records?
Comment: @ithcy yes they're all from the first batch, but the 51th is empty --> that is strange ! I'm inspecting subsequent batches before insertion and they contain correct data...
Comment: It seems it comes from using the `messagesBatch.length = 0;` technique for emptying the array. When "reseting" (sort of) by creating a new array with `messagesBatch = [];` it works as expected. I can't explain why since I'm waiting for getLastErrorObj. Or is the insertion asynchronous ? Then it should insert no records at all. (The empty 51th record comes from a bad systematic "safety" flushing of an empty array at the end of the script and is not related to the problem)
Answer: It seems it comes from using the messagesBatch.length = 0; technique for emptying the array to prepare the next batch. When instead "reseting" (sort of) by creating a new array with messagesBatch = []; it works as expected.
I guess the insertion is asynchronous and works directly on the array ref, and it seems that waiting for getLastErrorObj() is not enough to be sure that all data has been written. This seems wrong.
The empty 51th record came from a bad systematic "safety" flushing of an empty array at the end of the script and was not related to the problem.


Is there a subring that has a different identity element from the original ring?

Question: Let $(S,+,.)$ be some ring.
Is there a subring of $(S,+,.)$ that has a different identity element from the identity element in $(S,+,.)$?
I am new to ring theory so please let answers simple.
Comment: This depends on your definition of "(sub)ring" and what $S$ is.
Answer: Take rings $R,S$ and look at the cartesian product $R \times S$ with componentwise addition and multiplication. The subsets $R \times \{0\}$ and $\{0\} \times S$ should do it if I'm not mistaken.
Edit: Of course, this depends on the definition of subring. Sometimes you call $S \subseteq R$ a subring if $1 \in S$ (and the rest of the ring axioms).
Answer: $2\Bbb{Z}/10\Bbb{Z} \subset \Bbb{Z}/10\Bbb{Z}$.  Can you figure out the multiplicative identity of the subring?  Can you generalize this?
Answer: $ 2\mathbb Z_{10}\subset\mathbb Z_{10}$ has identity $6$.
With functions: $\{f\in L^\infty [0,1]:\ f|_{[1/2,1]}=0\}\subset L^\infty[0,1] $, with identity $1_{[0,1/2)} $.
With matrices:
$$
\left\{\begin {bmatrix}a_{11}&a_{12}&0\\ a_{21}&a_{22}&0\\0&0&0\end {bmatrix}:\ a_{kj}\subset S\right\}\subset M_3 (S).$$
With direct sums: if $R,S $ are rings, then $R\oplus0\subset R\oplus S $ with identity $1_R\oplus 0_S $.
Comment: I wish I understood your answer, but I just started studying ring theory and  abstract algebra. So my knowledge is very limited. But is seem If I Understand you correctly, there is a subring that has a different identity element from the original ring. Is that right?


Extjs6 Custom button with custom config binding

Question: I've created a custom button(extend from Ext.button.Button). The new custom button has a new span in the template and a new config.
This custom button is used in a toolbar docked on a grid.
{
    xtype: 'customButton',
    text: 'Custom button',
    //customConfig: 5    //this line works
    bind:{
        customConfig: '{customConfigData}',
        lazy: false
    },
    listeners: {
        click: function(btn, ev){
            debugger
        }
    }
}

The grid is a child of an container.
Ext.define('MyApp.view.myview.MyView', {
        extend: 'Ext.container.Container',
        xtype: 'main-view',
        requires: [
            'MyApp.view.myview.MyGrid'
        ],
        viewModel: {
            type: 'myModel'
        },
        items: [{
            title: 'Home',
            layout: 'fit',
            items:[{
                xtype: 'panel',
                layout: {
                    type: 'vbox',
                    align: 'stretch'
                },
                items: [{
                    xtype: 'myGrid',
                    margin: '10 0 0 0'
                }]
            }]
        }]
    });

The container has a view model attached. Inside the view model I, in the data section I've added new value.
Ext.define('MyApp.view.myview.MyModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.myModel',
    data: {
        customConfigData: 99
    },
    stores: {
        users: {
            type: 'users'
        }
    }
});

I tried to bind the custom config of my custom button with the value in the view model but with no success. I read that by default all the configs are bindable but in my case somehow, the custom button config doesn't sees the view model.
I've created a fiddle. Here you can also find my full custom button code.
What is the prop way to bind to a custom config?
Comment: The stores, models, grid are all irrelevant for a start. The whole thing could easily be reduced to a single file of about 30-40 lines to get the point across.
Comment: In future if you're going to post a test case, leave out all the extraneous stuff.
Comment: @EvanTrimboli Can you please highlight some extraneous stuff? I did not understand to what stuff you refer to
Answer: 2 things, both of which go in your button class:
1) Add an updater for the config to react to changes:
updateCustomConfig: function(v) {
    this.innerSpan.setHtml(v);
}

2) To facilitate #1, use childEls to allow your component to have an easy reference to innerSpan:
childEls: ['innerSpan']

Comment: Working example: [link](https://fiddle.sencha.com/#view/editor&fiddle/21u0)