ipv6 address configuration on serial interfaces

Question: I tried to configure Ipv6 static routing on three routers, I configured ipv6 addresses on all three routers using ipv6 address auto config, The middle router have been configured with different global unicast addresses perfectly on it's both serial interfaces, but I saw those serial interfaces have been configured with same link local addresses, I'm a bit confused, can someone please answer!
Answer: Link local addresses have, as the name implies, only local relevance on the link. Every link uses the same link local address block, and duplicate addresses on different links are no problem. They only have to be unique on each link.
Interface identifiers (the rightmost bits of an address) for link local addresses are often generated based on the MAC address of the interface. Because serial interfaces don't have a MAC address the router has to use something else that is likely to be unique. It might for example take a random number, the MAC address of a different interface, it's serial number etc. So if it has multiple interfaces that don't have their own MAC address it is perfectly normal to reuse the same interface identifier on all of them.
Comment: P.S. The same is true for all IPv6 nodes, not just routers


Critical points of a differential equation

Question: One of the first exercises in Arnold's mechanics book is

Problem. Determine with what velocity a stone must be thrown in order that it fly infinitely far from the surface of the earth. Answer. $\geq 11.2$ km/sec.

To this point the only thing presented about the system is a governing differential equation:
$$\ddot x=-g\frac{r_0^2}{(r_0+x)^2}$$
I don't know how to solve this differential equation. I anticipate there is a way to solve the problem without solving the DE directly, instead somehow producing an expression which gives x's velocity "at time infinity" and then solving for the critical initial condition. How can this be done?
Answer: $ \ddot x= \frac{dv}{dt}= \frac{dx}{dt} \cdot\frac{dv}{dx}=v\frac{dv}{dx}  $
So integrating from the surface of the Earth to infinity ...
$$  \int _{v_o}^{v_f} v dv =-gr_0^2 \int _0 ^\infty \frac{dx}{ (r_0 + x)^2} $$
To get the slowest velocity solve for $v_0$ when $v_f=0$. You should get $v_o = \sqrt{2gr_0} $


How do I correct the scale and order of the y axis in R on a barplot

Question: Working with borehole data, attempting to plot the cross section with R. I'm rusty and am having trouble organizing the plot the way I want. From the image, my bar plot is not tracking with y axis values displaying the depth of the borehole, instead it tracks with the Layers (categorical data).
Very similar question was asked here but I could not get the code to work for my situation because my data is formatted differently.
Just to clarify, I want to put the y axis in increasing numerical order, starting at 0, with the categorical layer data mapped to the correct part of that depth.
my code:
g2 <- ggplot(data=df3,
        mapping = aes(x=PointID,y=End_Depth,
                      fill=`Layer`)) +
  geom_col(colour="black") +
  labs(y="Depth")

The Data
Comment: Please do not post code or data as images. It's easier to help you if you include a simple reproducible example with sample input that can be used to test and verify possible solutions (for example, with dput()). See the link for ways to improve your question: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Comment: (There are plenty of reasons to not provide an image of data, see https://meta.stackoverflow.com/a/285557 for several of them.)
Comment: FYI, for formatting: the "fence" for demarcating a code block is three **backticks**, `\`\`\``, not three single-quotes `'''`; *and* they must be on a line of their own, shared with no code. This means something like `\`\`\`\ng2 <- ggplot(...) +\n  geom_col(...) +\n  labs(...)\n\`\`\``. The one exception is that with the Stack interface, one can provide a syntax "hint" for aesthetics, such as `\`\`\`r` ... but that must still be on a line of its own. Please see https://stackoverflow.com/editing-help and https://meta.stackexchange.com/a/22189. Thanks!
Comment: @r2evans Amazing! Thanks for the help. My first time in stackoverflow
Answer: The question you were pointing to contains a very good idea, to use geom_rect instead. You could do something like the following (comments in code)
library(tidyverse)

# just some fake data, similar to yours
foo <- data.frame(id = "id", layer = letters[1:6], depth = c(5,10,12,15,20,25))

foo2 <-
  foo %>%
  # using lag to create ymin, which is needed for geom_rect
  # transforming id into integers so i can add / subtract some x for xmin/xmax
  mutate( ymin = lag(depth, default = 0),
         id_int = as.integer(factor(id)))

# I am turning off the legend and labelling the layers directly instead
# using geom_text
# this creates a "wrong" y axis title which I'm changing with labs(y = ... )
# the continuous x axis needs to be turned into a fake discrete axis by
# semi-manually setting the breaks and labels
ggplot(foo2) +
  geom_rect(aes(xmin = id_int - .5, xmax = id_int +.5,
                ymin = ymin, ymax = depth,
                fill = layer), show.legend = FALSE) +
  geom_text(aes(x = id_int, y = (depth + ymin)/2, label = layer)) +
  scale_x_continuous(breaks = foo2$id_int, labels = foo2$id) +
  labs(y = "depth")

Created on 2021-10-19 by the reprex package (v2.0.1)
Comment: Amazing! How would I reverse the y-axis (making 0 the top and showing blank space past 25 to represent that the hypothetical ground continues from that point)? Also how would I make the bar itself thinner (making the plot look more cylindrical like a vertical pipe)? How should I go about editing/customizing the colors myself? Finally, how do I add the label information back?
Comment: @allencadbim1 these are many follow up questions and I guess you can find answers to them elsewhere on SO. If you don't succeed, please ask new questions, and don't forget to link to your previous questions, so people know what work has been done on that before.


Theme filter for a view

Question: How can I theme filters for a view in drupal 8?
I would like to place the filters to the sidebar menu, and rather than having standard either dropdown or autocomplete field, I would like to have something like a rendered block, so that a user could see all options at a glance.
Answer: Install Better Exposed Filters and if you want to have a filter as a rendered block you can edit view and see Exposed form in block: option under EXPOSED FORM. Enable it as Yes and place block in any page as you like.
Answer: You need install module Better Exposed Filters

Theme filter for a view


Series of Beta Function

Question: Solve:
$$\int_0^\frac{\pi}{2}\frac{\sqrt{\sin{x}\cos{x}}}{\cos{x}+1}dx$$
I tried
$$\int_0^\frac{\pi}{2}\frac{\sqrt{\sin{x}\cos{x}}}{\cos{x}+1}dx=\sum_{k=0}^\infty(-1)^k\int_0^\frac{\pi}{2}(\sin{x})^\frac{1}{2}(\cos{x})^{k+\frac{1}{2}}=\sum_{k=0}^\infty(-1)^kB\left(\frac{3}{4},\frac{k}{2}+\frac{3}{4}\right)$$ but it did not work, did it?
Comment: Wolfram says the answer is $\pi\left(\frac{\sqrt{2}}2-\frac{4\sqrt{\pi}}{\Gamma^2\left(\frac14\right)}\right)$
Comment: Can you post a solution, please? I would help me a lot
Answer: We are given:
$$ \int_0^{\pi/2} \frac{\sqrt{\sin x\cos x}\,dx}{1+\cos x} $$
Put $t=\tan\tfrac{x}{2}$; then
$$
\sin x = \frac{2t}{1+t^2}
\quad\quad
\cos x = \frac{1-t^2}{1+t^2}
\quad\quad
dx = \frac{2\,dt}{1+t^2}
$$
Then
$$ \sqrt{\sin x\cos x} = \frac{2t(1-t^2)}{1+t^2} $$
and
\begin{align}
1 + \cos x &= 1 + \frac{1-t^2}{1+t^2} \\
&= \frac{1+t^2+1-t^2}{1+t^2} = \frac{2}{1+t^2}
\end{align}
so that
$$ \int_0^{\pi/2}\frac{\sqrt{\sin x\cos x}\,dx}{1+\cos x} = \int_0^1\frac{\sqrt{2t(1-t^2)}\,dt}{1+t^2} $$
This is an elliptic integral. Here's my attempt at expressing it in terms of the Legendre canonical forms: put $t^2=v$; then $dt=2v\,dv$ and the integral becomes
\begin{align}
\int_0^1 \frac{\sqrt{2t(1-t^2)}\,dt}{1+t^2} &= \int_0^1 \frac{\sqrt{2v^2(1-v^4)}(2v\,dv)}{1+v^4} \\
&= 2\sqrt2 \int_0^1 \frac{v^2(1-v^4)}{1+v^4}\frac{dv}{\sqrt{1-v^4}} \\
&= 2\sqrt2 \int_0^1 \left(\frac{i}{1+iv^2}-\frac{i}{1-iv^2}-v^2\right)\frac{dv}{\sqrt{1-v^4}} \\
&= 2\sqrt2(i\Pi(-i,i)-i\Pi(i,i)-E(i)+K(i))
\end{align}
where $K,E,\Pi$ are the first, second and third complete elliptic integrals, in terms of the modulus $k$.

Wolfram Alpha gives an exact value
$$ 2\sqrt 2(K(i)-E(i)) = -\frac{4\pi^{3/2}}{\Gamma(\tfrac{1}{4})^2} $$
which, given Peter Foreman's comment, looks right. But W|A does not give an exact value for the term involving the $\Pi$'s, so I think I made a mistake there. I'll look into that later. I'll also try and see if I can prove these values for the integrals.

Update: In
$$ E(i) - K(i) = \int_0^1\frac{v^2\,dv}{\sqrt{1-v^4}} $$
put $r=v^4$; then $dv=v^{-3}\,dr/4$ and the integral becomes
\begin{align}
\int_0^1 \frac{v^2\,dv}{\sqrt{1-v^4}} &= \frac{1}{4}\int_0^1 (1-r)^{-1/2}r^{1/2}r^{-3/4}\,dr \\
&= \frac{1}{4}{\rm B}(\tfrac{1}{2},\tfrac{3}{4}) = \frac{1}{4}\frac{\Gamma(\tfrac{1}{2})\Gamma(\tfrac{3}{4})}{\Gamma(\tfrac{5}{4})} \\
&= \frac{\Gamma(\tfrac{1}{2})\Gamma(\tfrac{3}{4})}{\Gamma(\tfrac{1}{4})}
\end{align}
By the reflection formula,
$$ \Gamma(\tfrac{1}{4})\Gamma(\tfrac{3}{4}) = \frac{\pi}{\sin\tfrac{\pi}{4}} = \pi\sqrt 2 $$
Using next $\Gamma(\tfrac{1}{2})=\sqrt\pi$ we put everything together yielding
$$ E(i) - K(i) = \frac{\pi^{3/2}\sqrt2}{\Gamma(\tfrac{1}{4})^2} $$
I'll look into the case of the $\Pi$'s next.

Series of Beta Function


Looking for multiple solutions with Stochastic gradient descent?

Question: Say I have some data and some graph fitting function.
Just using gradient descent will find one particular local solution.
Now what I want to do is also put "feelers" out for other solutions. In essence I want to run the gradient descent many times in parallel to find different local solutions. And select the best one.
Once it has one, it could put it's feelers out again, by running another gradient descent with a random difference in variables. (Say a short difference, a medium distance, and a long distance).
Then it could run all these other trials and see if it can find another local minimum. (But keeping the local minimum it already found).
This way, hopefully over time it can eventually arrive at the best fit.
To visualise this imagine climbing to the top of a mountain. Then dropping people randomly around that mountain to see if they climb up to another mountain that is higher.
Well my question is, what is this kind of procedure called? In APIs like tensor flow would you have to implement something like this yourself?
Another related question is that in higher dimensions, are things less likely to get stuck in local minima? So this is not needed?
Answer: I think you'd call this SGD with multiple restarts (see here for people doing that kind of stuff).
I'm going to assume you're talking about running SGD in the context of training a deep neural network. The problem is doing one run of SGD until it has converged is often sufficiently computationally expensive that you're likely to get some pretty serious diminishing returns. In general if your optimisation problem is not convex then you're not even guaranteed to converge to a minima, just a stationary point.
I think there is some evidence that stochastic component of SGD allows it to avoids saddle points. There is also some evidence that local minima for linear deep neural networks are close to the global minima. but I am not aware of any evidence that suggests high dimensionality means you're less likely to get stuck in a local minima for nonconvex problems.


Display root terms based on child in a view

Question: I've a city vocabulary (see example below) which I import from 3-th party service. Each city may be spelled differently (either with wrong spelling or with special characters). In my example let's assume that TEST is a different variation of Oslo city.

These cities are already used in Content Type 'Person'. I built a view that display Persons with a category City. Everything works well and my view looks like this:

Now I need to substitute/replace TEST with Oslo (as it is different spelling of Oslo city).
On a view I expect to not see TEST and Oslo must get +1 as a counter.

Oslo (34)

UPDATE
Here are my settings for the view.

What should I do in order to achieve that? Thanks.
Answer: Try this:
You can use relationship, and add "Taxonomy term: Parent term" field relation in it. Now make relationship with city field. It will give root term name based on child term name.
I have recently done this, it works.
Hope it will works for you.
Comment: I already have these relationship (look on 1-st image in question, TEST is sub for Oslo).
I can't figure out how to display parent instead of 'sub'.
Comment: I am asking to add relationship in views settings (look on 3rd image in question), there is no relationship defined in your views settings.
Comment: Could you please look on screen3 again (I've updated it). Is that what you mean? So far it does not work.
Comment: I did not get what was wrong first time, I've re-created relationship and it started to work.
Comment: Thanks for your comment, I just watch it. Anyways, it helps you that's important.
Comment: I have an issue with that solution. It works only for child elements, in case if my Term is root - it will not see it and not show in the view.


Is the continuity of a vector field enough for the existence of the solution of a differential equation?

Question: I've recently seen the existence-uniqueness theorem for ordinary differential equations from Arnold's book. I understand that the theorem as stated guarantees both existence and uniqueness if the corresponding vector field is continuously differentiable. I've also noticed that in most examples where unique solutions don't exist, the differentiability of the vector field is missing. My question is, will any weaker condition suffice to guarantee only the existence (and not necessarily the uniqueness) of an ODE? Is it for example true that if the vector field is just continuous, a solution exists even if not unique?
I went through Existence of Solution to Differential Equations., but this doesn't seem to answer my doubts completely.
Answer: Yes. Peano's existence theorem says that there exists (locally, as usual) at least one solution if the right-hand side is continuous.


json_encode retornando TAGS HTML

Question: Ao realizar echo json_encode($data);, estou a receber ,via console.debug(data), o seguinte:

( ! ) Notice: Undefined variable: v_prod_total in C:\wamp64\www\nfe\admin\nfephp-master\exemplos\NFe\4.00testaMakeNFe.php on line 464

Call Stack

#	Time	Memory	Function	Location

1	0.0020	424896	{main}(  )	...\4.00testaMakeNFe.php:

O que pode estar acontecendo?
Script:
$http({
          method  : 'POST',
          url     : 'enviar.php',
          dataType: 'json',
          data : dados: dados ,
          headers : {'Content-Type': 'application/x-www-form-urlencoded'}
         })
         .success(function(data) {
            if (data.errors) {
              $scope.erroValidar = "Erro";
            } else {
              $scope.key = data.chave;
              console.debug(data);
            }
          })

Obs.: o json_encode esta entre uma "infinidade" de código em PHP

try{
        $query = $conecta->prepare('SELECT * FROM empresas WHERE situacao=1');
        $query->execute();
        $resultado = $query->fetchAll(PDO::FETCH_ASSOC);
    }catch (PDOexception $erro){
        echo 'Erro ao selecionar: '.$erro->getMessage();
    }

    foreach($resultado as $res){
        $razao_social_emt   = $res['cidade'];
        $nome_fantasia_emt  = $res['nome_fantasia'];
        $cnpj_emt           = $res['cnpj'];
        $insc_estadual_emt  = $res['insc_estadual'];
        $logradouro_emt     = $res['logradouro'];
        $numero_emt         = $res['numero'];
.
.
.
echo json_encode($data);
.
.
.
else {
    header('Content-type: text/html; charset=UTF-8');
    foreach ($nfe->erros as $err) {
        echo 'tag: <'.$err['tag'].'> ---- '.$err['desc'].'
';
    }
}
?>

Comment: o json_encode não esta retornando uma string contendo a representação JSON dos valores.
Comment: do tipo: {"a":1,"b":2,"c":3,"d":4,"e":5}
Answer: Seu código está retornando uma mensagem de erro:
A variável v_prod_total não está definida.
No arquivo: C:\wamp64\www\nfe\admin\nfephp-master\exemplos\NFe\4.00testaMakeNFe.php
Linha: 464
Além desta, cheque se há outras variáveis não definidas.
Se forem numéricas e estiverem em loop, coloque os valores das mesmas antes do loop com o valor inicial igual a ZERO.
Comment: Só um instante @AllanAndrade, vou verificar.
Comment: Posso criar um chat pra te explicar alguns detalhes?
Comment: Pode sim. Tranquilo.
Comment: http://chat.stackexchange.com/rooms/51455/json-encode-retornando-tags-html
Answer: Deixa eu traduzir o que aconteceu:
1 - Esse HTML aí com essa classe x-debug não me é estranho. Você provavelmente está usando a extensão Xdebug no PHP.
2 - Esse HTML só aparece quando tem erro.
3 - Há um erro. Ele é Notice: Undefined variable: v_prod_total. Você está tentando acessar uma variável que não foi definida.
4 - O problema não é função json_encode. Se você resolver o erro, o retorno JSON ficará correto (se não tiver outro erro, é claro).
Comment: O x-debug está desabilitado: `[xdebug]
zend_extension ="c:/wamp64/bin/php/php5.6.25/zend_ext/php_xdebug-2.4.1-5.6-vc11-x86_64.dll"
xdebug.remote_enable = off
xdebug.profiler_enable = off
xdebug.profiler_enable_trigger = off
xdebug.profiler_output_name = cachegrind.out.%t.%p
xdebug.profiler_output_dir ="c:/wamp64/tmp"
xdebug.show_local_vars=0`
Comment: Já corrigi o valor de `v_prod_total`.
Comment: Seguindo o conselho do @nottherealhemingway, agora o seguinte erro é apresentado no console: `angular.min.js:117 SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse () at wc (angular.min.js:17) at dc (angular.min.js:91) at angular.min.js:92 at q (angular.min.js:7) at gd (angular.min.js:92)`
Answer: Eu uso os seguintes cabeçalhos para retornar JSON:
<?php

// No topo da página
header("Access-Control-Allow-Orgin: *"); // CORS
header("Access-Control-Allow-Methods: *"); // Verbos HTTP[S]: PATCH, PUT, DELETE, GET, POST
header("Content-Type: application/json");

Outra coisa é que seu código está lendo a condição passada no IF e retornando o que está em ELSE, que contém um cabeçalho (header) que retorna HTML. Esse HTML está simplesmente formatando a mensagem de erro gerada pela linha 464 (4.00testaMakeNFe.php).
Você pode gerar o erro de outra forma:
.
.
.
else {
    // Remove o cabeçalho
    foreach ($nfe->erros as $err) {
        errors[] = $err;
    }
    echo json_encode($err, JSON_NUMERIC_CHECK);
}

Comment: Realizei as modificações @nottherealhemingway, agora o seguinte erro é apresentado no console:

`angular.min.js:117 SyntaxError: Unexpected token A in JSON at position 0
    at JSON.parse ()
    at wc (angular.min.js:17)
    at dc (angular.min.js:91)
    at angular.min.js:92
    at q (angular.min.js:7)
    at gd (angular.min.js:92)`
Comment: Por favor, não use o trecho de código para marcar coisas como PHP ou códigos que não são executáveis dentro do site, o uso do `Trecho de código` (Stack Snippet) é executar CSS, HTML e JS. PHP não roda dentro do site. Para colocar PHP use o `Amostra de código` (ou pelo Atalho Ctrl+K). Leia para entender melhor: http://meta.pt.stackoverflow.com/a/4463/3635
Comment: tudo bem. É que eu estava preocupado em solucionar um problema.
Answer: Com a ajuda do @AllanAndrade, via chat, conseguimos descobrir que o problema estava nas variáveis não inicializadas e na chamada de outras funções/bibliotecas que estavam utilizando print_r, var_dump e echo.

json_encode retornando TAGS HTML


How can I use a remote admin tool (puppet or chef) combined with a sync tool (e.g. rsync) to send log files from several servers to a central server?

Question: Summary
How can I use a remote admin tool (puppet or chef) combined with a sync tool (e.g. rsync) and scheduler (cron) to send log files from several servers to a central server?
Context
Our sysadmins have (rightly) tightened up developer access to production servers. One consequence: developers in particular will no longer have easy access to log files when supporting customer problems.
Goal: Send Files to Common Log Server
I'd like to set up automatic copying of logs to a central "log server". Developers/support would have read access to the 'log server' filesystem when supporting problems.
Here's an example of our filesystem structure. One directory per customer. Within this, one directory per application. Each application has different sub-directory structure and log file names.
Server A
d:/
  Instances/
     CustomerFoo
         App 101/
            logs
               server.log
               access.log
         App 201/
            logs
               stdout.log
               jdbc.log
               timing.log
     CustomerBar/
         App 101/
          ....
         App 301/
             logs/
                monitor.log

These would go to a central server with a structure like this. (Customer name is unique within the enterprise so we will not have any collision)
LogServer
d:/
  logfiles/
     CustomerFoo
         App 101/
            logs/
         App 201/
            logs/
               ...
     CustomerBar/
         App 101/
          ....
         App 301/
             logs/

Desired outcome

I'd like a combination of  a remote admin tool (puppet or chef) combined with a sync tool (rsync) and scheduler (cron) to do periodic syncing
Easy remote administration for multiple boxes. i.e. edit the 'config file' in one place and push it out to all the servers.

Environment

Windows Server 2008
Windows shop. However open to installing cygwin.
I personally am familiar with rsync and cron, but neither puppet nor chef. fwiw.

Thanks in advance!
Comment: Why not use a proper log shipping app to get your logs in realtime?
Comment: Right - what's wrong with using, er, syslog?
Comment: Additionally, if you need access to these logs to do your job, there's no reason your access to them should be restricted.
Comment: what mfinni said
Comment: Maybe consider something like [logstash](http://logstash.net).
Comment: @EEAA : "proper log shipping" app. Please suggest one. Also, for some reason I only seee the term "log shipping" in the context of database transaction logs. Hence I used log copying/sending
Comment: @mfinni re syslog. Tell me more, especially in a Windows environment. That said, these windows sysadmins look suspiciously on unixy stuff.
Comment: Your application needs to be able to speak syslog, preferably to a remote syslog server. Looks like you're using Java? Hope you're using Log4J, because that will speak syslog. Then you point them at your syslog server. there are commercial and free syslog servers available for Windows.
Answer: I suggest syslog. It's a (the) standard for what you want.
Your application needs to be able to speak syslog, preferably to a remote syslog server. Looks like you're using Java? Hope you're using Log4J, because that will speak syslog. Then you point them at your syslog server. there are commercial and free syslog servers available for Windows.
Alternatively, you could write everything from your application to the Windows Event Log, and then use event log subscriptions/collection to get those to another Windows machine that you're allowed access to.
Doing this with only plain-text logs, when you have multiple nodes, is tough to manage, as you're finding out. Of course, you could just request read-only access to the directories where the logs currently live.


How can I have a node with the URL /themes

Question: I've created a node and have given it the URL /themes. In full: http://site-name.com/themes.
Permissions on the Drupal system folder 'themes' mean that the URL /themes gives: 403 forbidden.
Is there anyway to have a node with /themes? I'd prefer if possible to keep my current file structure as I think it would be difficult to change with my current host (Pantheon).
Comment: Though I don't know if it is possible to use a path which is actually a core folder, I want to point out that you cannot change the file structure of Drupal, doesn't matter what hosting you have.
Comment: Yes, [it's possible](http://drupal.stackexchange.com/questions/52882/using-profiles-in-a-url-alias) in theory, but you'll need to get Pantheon to change their Nginx config to actually do it. That's not very likely in my experience, as they use a shared version for a lot of stuff. I'm not 100% sure, but I don't think even enterprise customers can get the web server conf changed (we tried once before). Either way, you really need to direct your query to them to find out if they can facilitate
Comment: Have you tried the Pathauto module to generate an alias?

http://www.drupal.org/project/pathauto
Answer: In your .htaccess file, the URL re-write has the a code to point the path to the respective folder, if present.. you can change that!
Comment: No, it's not a solution. You're assuming the OP's web server is Apache, which it isn't.
Comment: Danger danger!! Please don't mess with that
Comment: Yes, it's not advisable; but its the only solution to do that.


Accessing content for a specific node revision via a relationship in Views

Question: A module I've written implements hooks defined by the Field API to provide a custom field for defining references to specific node revisions by storing vids. (The module borrows functionality from the Entity Reference, Node Reference and Node Revision Reference modules.)
I have a requirement for "parent" nodes to reference a specific version of one or more "child" nodes. The child node(s) may be modified (i.e. new revisions created) after a reference to it is stored against a parent node. It's essential that the reference on the parent node continues to refer to the same revision of the child node unless the reference is manually updated to a newer revision by a user with sufficient permissions.
I'm currently working on Views integration for the field defined by my module. When creating displays containing one or more parent nodes, I'd also like to be able to display field data for any referenced revisions of child nodes. I've defined the following relationship in my module:
<code>/**
 * Implements hook_field_views_data().
 */
function mymodule_field_views_data($field) {
  $data = field_views_field_default_views_data($field);

  // Get database table info for $field.
  $storage = $field['storage']['details']['sql'];

  foreach ($storage as $table_data) {
    $table = key($table_data);
    $columns = current($table_data);
    $id_column = $columns['vid'];

    if (isset($data[$table])) {
      // Relationship: node revision referenced from $field.
      $data[$table][$id_column]['relationship'] = array(
        'title' => t('Referenced node revision'),
        'label' => t('Node revision referenced from !field_name', array(
          '!field_name' => $field['field_name'],
        )),
        'help' => t('A bridge to the node revision that is referenced via !field_name.', array(
          '!field_name' => $field['field_name'],
        )),
        'group' => t('Node revision reference'),
        'handler' => 'views_handler_relationship',
        'base' => 'node',
        'base field' => 'vid',
      );
    }
  }

  return $data;
}
</code>
This relationship allows me to display field content for child nodes where the referenced revision is the current revision. However, if an old revision is being referenced by a parent node, the field data is empty. This behaviour occurs when I create a view displaying either content or content revisions.
Does anyone know of a way of accessing field data for a specific node revision via a relationship in Views regardless of whether it's the current revision or not?
Thanks in advance to anyone who can offer any suggestions!
Answer: One thing you could try is creating a class that extends views_handler_relationship and override it's query() method using logic that's specific to your use case rather than the generalised logic that's in views_handler_relationship->query().  Then change the "handler" in your relationship declaration to point at your subclass.
Hope it helps.
Comment: Thanks, Paul! Fancy seeing you here! I think extending views_handler_relationship is the way to go, and I'd already started creating a class before I posted the question above. I still feel like I'm missing something obvious in Views that'll give me what I'm after, but perhaps not... It seems as though Drupal handles revisions in a bit of an unusual way, so perhaps what I'm experiencing is a symptom of that.
Comment: Yep, it's a crazy old world alright! I've just been looking at the code of some of some of the moderation modules (like workbench moderation) to see if I can see a silver bullet for this.  No luck so far.  One thing though, could we be over-thinking it... do you think a simpler approach using a view of revisions manipulated with hook_views_query_alter to pick out the correct revision could be the way to go?
Comment: I think altering the query one way or the other will need to be done, as Views simply isn't including the necessary tables in the query its generating for some reason. Extending views_handler_relationship to alter the query feels a bit "cleaner" to me, so that could still be the way to go. I've parked this feature for the time being, but I'll be coming back to it soon...


The building blocks of $\mathbb{R}$

Question: In an introductory class to analysis, a theorem we prove is the characterization of intervals (I'm sure there is more than one by this name, but its not important for this question) but we don't prove anything about the "importance" of intervals in the context of $\mathbb{R}$. Something seems rather fundamental about them, and I am trying to pinpoint what it is. My first intuition was to prove that every subset of the real numbers can be written as a union of intervals, but this is trivially true since a single point can be considered a closed interval with the same upper and lower bounds.
My next idea was to think in terms of Topology, and prove something along the lines of "every subset of real numbers can be written as a union of non-trivial intervals and isolated points", this I think is more along the lines of what I wanted to capture, but then I thought of a description that act as an even stronger condition:
Define the coarser pre-order on families of sets of real numbers, formally let
$$\preceq \subseteq P(P(\mathbb{R}))^2 $$
Satisfying
$$\mathcal{A}\preceq \mathcal{B} \iff \\
\forall_{S\in \mathcal{A}}\exists_{S'\in \mathcal{B}}[S\subseteq S']  \land \\ \bigcup A = \bigcup B
$$
Specifically if the sets in the families in question are disjoint, then when $\mathcal{A}\preceq \mathcal{B}$ we say that $\mathcal{B}$ is coarser that $\mathcal{A}$ (on a restriction to families with disjoint sets, the pre-order also becomes a partitial order)
This pre-order order allows us to then say something which is stronger than simply the isolated point-interval condition, which is that for every $S\subseteq\mathbb{R}$ there is some family of intervals, $\mathcal{K}$ such that $\mathcal{K}$ is a disjoint cover of $S$, and $\mathcal{K}$ is the maximal disjoint cover with respect to $\preceq$
To illustrate why I think this condition is stronger (in a general context) than the isolated-point interval condition, I remark that the isolated point interval condition holds even if you consider only closed sets, since an open set can be written as a union of non-trivial closed sets, but with the maximal condition relating to $\preceq$, closed sets are not enough to guarantee a maximum.
My questions then are:
Is this an interesting or useful way to characterise the role that intervals play in $\mathbb{R}$? Is there an analogous concept to the one described above, both in $\mathbb{R}$ and in general topological spaces (or some other generalisation of $\mathbb{R}$) ?
And lastly how would one go about proving the theorem of a maximal element? (I would include an attempt here, but my question is getting quite long)
Comment: "Every subset of $\mathbb{R}$ can be written as union of intervals and isolated points" This is not true as Cantor set can't be written in such a way
Comment: Also, I would assume that your families of subsets are actually families of intervals, otherwise the maximal is always $\{S\}$
Comment: intervals get a lot more important when you introduce the Borel sets, that, said in very simple term, is every real subset that has any hope of sanity. You can prove that you can always approximate them from the inside and from the outside with non-trivial intervals
Comment: @Jakobian,  I had no idea, this seemed like a very obvious statement, I would then not be surprised if my proposition about the maximal family also turns out to be false, but we shall see
Comment: @Exodd, yes this is what I meant, will edit now
Comment: Can you give an example of a result that is important? In introductory analysis, it is assumed that we don't already know what a topology is or even a rigorous definition of continuity. Intervals are classified as closed and open because these form the basis of closed and open sets in general. Is it possible that you have read the punchline of a joke before hearing the joke and now wonder why it is supposed to be funny?
Comment: @JohnDouma I took a topology course before my real analysis course, which may be what you are referring to. I consider the classification theorem for intervals as important, because it strengthens our intuition about the types of sets that are intervals, but I don't think I (or anyone else) can give a general criterion for the importance of a result
Comment: @Carlyle That could explain the confusion. The concepts we learn in topology are abstractions of the concepts we learn in real analysis. I love Munkres' book  "Topology: A first course" but my main criticism of that book is that he defines an abstract topology with no connection to analysis. I believe that is pedagogically backwards.
Answer: It is easy to prove that a maximal element always exists by Zorn's lemma, and with few additional reasoning, you can also prove that it is unique, so actually we always have a maximum, and it is represented by the collection of the connected components of $S$.
Comment: I appreciate the answer, I have not really looked at Zorn's lemma before so I would appreciate if you could elaborate a bit on the statement, I am however aware that Zorn's lemma relies on AC, and if this theorem were true, I would not expect it to require AC, not sure if this is the case
Comment: You don't need Zorn's lemma since $\mathcal{K}$ can be explicitly stated as the collection of all components of $S$. This is nothing more than doing so. For example, the Cantor set would be written in terms of one-point sets

The building blocks of $\mathbb{R}$


Determine if this should be a group

Question: When anonymous users are registering and creating a group - the field:
Determine if this should be a group.
Shows up on registration.

In the field settings on the content type I'm using I have the values checked to "Hide" this portion.  I've even hid the values on Manage Display.
Screen shots attached.  All I want to do with is hide the field to NOT show to users.  There's no reason for this field to be visible in my scenario.

I don't want to hide it with css if at all possible.
Any guidance is appreciated.
Answer: You could use hook_form_alter() to change the field type for the field you want to hide to "hidden". The code would be something like this:
mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case "user_register_form":
      $form["fieldname"]["#type"] = "hidden";
      $form["fieldname"]["#value"] = $form["fieldname"]["#default_value"];
      break;
  }
}

This function will get called for every form displayed, so the switch statement makes sure it's the right form. That being the case, the next line changes the type of the field to a hidden field. Finally, it copies the default value of the field into the actual value (hidden fields don't have a default value).
Unfortunately I don't know what the name of the field you want to change is, so you'll have to investigate that.
Hope this gets you on the right track.
Comment: The field in question that I want to hide is in a "content type."  In the case switch, is that where I'd reference the type of form i want to alter?

Determine if this should be a group


good way to model y=f(x1)+f(x2)+...+f(x30)?

Question: In a football manager game, there are many players as in this screenshot:

My y is the average rating of a player, my sample size N is big enough, and
x1,x2,x3,...,x30 are the attributes like finishing, acceleration and pace (which can take values from 1 to 20). No attribute has a negative effect.
Can I use regression or another technique to find parameters such as:
y=f(x1)+f(x2)+...+f(x30)

In other words, after sampling N players, I want to know which attribute has the most effect in average rating, and which the least, and a scale to know how much more important is one attribute compared to the least important one.
Comment: You could do non-negative linear least squares, i.e.. linear least squares in which the coefficients being estimated are constrained to be non-negative.  Or you could try something other than a linear model.
Comment: When you write `f(x1)`, what kind of function `f` do you have in mind?
Comment: I have tried giving the text a brief copyedit and improved some of the formatting. Please feel free to revert any of my changes that you disagree with.
Comment: @Silverfish I would think the most simple form of f(x1) would be a parameter, say a1, f(x1) = a1*x1. And f(x2) = a2*x2. Eventually what I am looking is a way to rank a1, a2,....,a30 and find out the least important a, and see how much the rest scale compared to it.
Comment: If every $f$ is a linear function, this is a linear regression problem.
Comment: The problem with linear regression, is that it gives me negative coefficients, while there is no such a thing as a negative attribute effect.
Answer: First you should graph the correlation between the average rating and each of the variables separately to get an idea of the data. You also want to check the amount of variation in your Y variable (you don't want too much) and the variation in your X variable (you want a lot).
Next run a linear regression. You said in the comments that the coefficients were negative, but what were the standard errors? I am guessing the variables are correlated so you may suffer from multicollinearity making inference about specific coefficients difficult. Just because the coefficients aren't what you ``want'' at first glance doesn't mean the functional form is wrong.
Next, consider grouping the categories into larger categories and doing tests of joint significance for the larger categories. Or you could try other kinds of functional forms like squaring your variables to bring out more variation.
Also check the R^2 to see if your RHS is getting at most of the variation in Y. If it is low, while the marginal effects may be meaningful, there is much more determining Y than what you are estimating.
Comment: I don't yet understand what the negative coefficients mean and the multicollinearity is and how to deal with it. I am going to try to increase x variety by squaring x. Finally I strongly suspect that there is much more determining Y than what I am estimating.
Comment: @n17n That's why I said you should do some graphs/basic analysis to get an idea of how your variables are varying. If you go straight to regressions before any basic summary statistics, you will likely not understand the output. Mutlicollinearity just means the variables on the right hand side are strongly related. If that is the case then you may want to try running the regression but remove some of them.
Comment: Regarding multicollinearity i could just get more data? Because there are some rows, where X is not varying at all.
Comment: Multicollinearity is about the relationship between Xs. So if the 2 Xs are measuring a very similar attribute, then they will stay highly correlated even with more observation, but yes, more data will likely lead to more variation, so that should help.Do some summary statistics to see how much variation there is in each X variable. Don't include those that barely have any (or square them).
Comment: I did a linear regression giving negative coefficients. the standard error is .137 and the Collinearity VIF is less than 3000
Comment: So are those standard errors large? Meaning, what are the p-values for each coefficient? If each variable is statistically insignificant but in aggregate they are, then you are suffering from high correlation between Xs.


Prove that $\mathbb{Q} \left( \sqrt[n]{p}\right) \neq \mathbb{Q} \left( \sqrt[n]{q}\right)$.

Question: Given two distinct prime numbers $p$ and $q$, how can we prove that $\mathbb{Q} \left( \sqrt[n]{p}\right) \neq \mathbb{Q} \left( \sqrt[n]{q}\right)$ where $\sqrt[n]{p}$,$\sqrt[n]{q}\in \mathbb{R}$ and $n>1$.
Comment: $\mathbb{Q}(p)=\mathbb{Q}(q)$.
Comment: How familiar are you with algebraic number theory? You can do this using the fact that if two number fields are isomorphic then so are their rings of integers, and then using e.g. discriminants or ramification.
Comment: Discriminant? Can you show me the integral basis of $ \mathbb{Q} \left( \sqrt[n]{p}\right) $ easily? Or how can you compute the discriminant?
Answer: This task really depends upon how much you know.  It is easy to calculate the discriminants of these fields and see that they are different and so the fields must different, and even more obviously but equivalent, $p$ is the only prime that ramifies in the first and $q$ in the second. I suspect you haven't gotten there yet.
Here are some suggestions, as I don't have time to work it out.

Show that the minimal polynomial of $p^{1/n} + q^{1/n}$ has degree larger than $n$.
Write $q^{1/n}$ = rational linear combination of the powers of $p^{1/n}$.  Multiply both sides by the lcd of the coefficients and play around to show that $p$ must divide $q$ or vice versa.
Comment: You don't really to compute *exactly* the discriminants to show that they are different. What are the discriminants of the rings of integers $\Bbb Z\[\sqrt[n]{p}\]$ and$\Bbb Z\[\sqrt[n]{q}\]$?
Comment: Discriminant? Can you show me the integral basis of $ \mathbb{Q} \left( \sqrt[n]{p}\right) $ easily? Or how can you compute the discriminant?
Comment: $p$ and $q$ are not the only primes that ramify in $\mathbb{Q}(\sqrt[n]{p})$ and $\mathbb{Q}(\sqrt[n]{q})$, respectively.


Can't connect to Neo

Question: I've installed Docker on OSX and downloaded the neo image.  when I run it (using the args in the home page of the image), everything seems to work, but the last lines of the log indicate something like:

00:20:39.662 [main] INFO  org.eclipse.jetty.server.Server - Started
  @4761ms 2015-10-05 00:20:39.663+0000 INFO  [API] Server started on:
  http://022b5f3a38fc:7474/ 2015-10-05 00:20:39.663+0000 INFO  [API]
  Remote interface ready and available at [http://022b5f3a38fc:7474/]

which seem odd and attempting to connect my browser to either http://localhost:7474/ or the indicated http://022b5f3a38fc:7474/ results in an error
what am I missing here?
Answer: You'll want to use the IP address of the docker VM, which you can determine with this command:
docker-machine inspect default | grep IPAddress

The default IP address is 192.168.99.100
So depending on which port you exposed when running the Neo4j docker container you can access the Neo4j browser at:
http://192.168.99.100:7474

or
http://192.168.99.100:8474

Port 8474 is the the binding specified by this command:
docker run -i -t --rm --name neo4j -v $HOME/neo4j-data:/data -p 8474:7474 neo4j/neo4j

which is the example given in the documentation here
Comment: one other note: seems like Neo needs to figure out a better way to display the operating url
Comment: ah! I knew I'd read somewhere about the VM's IP.  thanks for clearing that up.  it works. +1

Can't connect to Neo


Why doesnt the market show the system app on "my apps" when an update is available?

Question: First i've asked this question: Can a system app be updated?
I did a little experiment that managed to confirm that answer:
Just added an app to the /system/app with same package, keystore and lower version on manifest and and after reboot i see the app on drawer (the app is indeed installed - i manage to do this with a rooted phone).
But now the market doesn't show the app on the My Apps list... but when i search for it on the market, it appears as installed and having a update.
The update can be done there (as answered here Can a system app be updated?) without a problem.
The real question is Why doesn't the market show the installed app on "My Apps"? It's because it wasn't installed from the market itself? But why then do Google Maps appear?
It's just a matter of time? Or do i have to do something for the market to recognise it?
Comment: Why would you want to do that? If you need to post new updates, the user wouldn't want to update it via an apk but from the market.
Comment: You didn't understand the question. The app doesn't appear listed in "My apps" section on the Market. This makes the notifications of new versions not appear when available...
Comment: I totally understood but I think your problem is that you didn't install the app from the market that's it. After that it's just a matter of version code in the manifest.
Comment: Ok. I didn't. But is there a way to make a "ping" to the market so it knows it's installed and shows notifications of new updates?
Answer: As I can remember, Google first packaged their apps as system apps. But from 2.1 (I can not remember exactly) they started to put them as ordinary apps. And in their words, explanation was something like "we want to update our apps more frequent, so you can download updates from Android market and don`t have to wait for new Android system version that have packaged new system apps in it". Also I read some post from ROM developer that they put some app in system/app (system app folder) and that it did not behaved as you want (uploaded app on market with greater version did not updated their system app and behaved like a different app in respect to installing it). Some others report that when they install market version of the app, android deletes their system app with same package name and leaves just that app version from market installed as ordinary app. So, I would say you can not get desired behaviour.
Comment: Thanks. I've tested in some versions and in fact i was able to update the app.. (after searching for it on the market).
Comment: Hi I realize this is an old questions but - @NeTeInStEiN You're saying that a system app cannot be automatically updated like other data apps, but they can be updated only if they are searched in GooglePlay and press update? Is that correct?

I see in [developers site here](https://support.google.com/googleplay/android-developer/answer/113476?hl=en) that they are supposed to be shown in MyApps.
Answer: According to the approved answer the system apps cannot be shown in MyApp and be updated.
Maybe this questions was asked and answered too long ago, but according to Google developers site though, it looks like the system apps should appear in MyApps and could be updated.

The user's system apps (including any pre-loaded apps) are shown in the My Apps section of the user's device in the Google Play store as soon as an application with the same package name is uploaded to the Google Play Developer Console, even if the application is unpublished.

according to the same page, Google Play can manage updates to preloaded applications, provided the following conditions are met:

The preloaded app needs to be in the system partition
  The preloaded app needs to be free
  The preloaded app needs to be signed with the same signature as the app published in Google Play
  The Package Name of the preloaded and updated app needs to be the same
  The Version Code of the updated app needs to be greater than that of the preloaded app


Probability density function of max(0, z)

Question: Question
The full question is from Exercise 4.6 in Statistical Inference (Casella, Berger). It is

A and B agree to meet at certain place between 1 PM to 2 PM. Suppose they arrive at meeting place independently and randomly during the hour. Find the distribution of the length of time that A waits for B (If B arrives before A, define A's waiting to be 0)

My answer
Here we can assume $A$ and $B$ to be uniform (that is $U(0,1)$) and we are interested to find the PDF of $T = max(0, B-A)$ where
$$
f(a, b) = 1
$$
To solve this, what I did is that first find out the PDF of $C = B - A$ as shown below
Define $D = B + A$, then joint distribution of (C, D) will be
$$
g(c, d) = f\left(\frac{d-c}{2}, \frac{d+c}{2}\right)\left|\begin{vmatrix}\frac{-1}{2}&\frac{1}{2}\\\frac{1}{2}&\frac{1}{2}\end{vmatrix}\right|
$$
that is $g(c,d) = \frac{1}{2}$ where $-1<c<0$ and $-c<d<c+2$, $0<c<1$ and $c<d<2-c$
Now the marginal distribution of $C$ will be
$$
h(c) =
\begin{cases}
1 + c & \text{if $-1 < c < 0$} \\
1 - c & \text{if $0 < c < 1$}
\end{cases}
$$
Now our required variable $T$ will be $T = \max(0, C)$ and this is where I am stuck that is how to find out the distribution of $T$.
Comment: What have you tried ? where are you stuck ?
Comment: Welcome to StackExchange! Your question is quite vague as it is, what exactly is it that you are curious of?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: I have update the question with more details.
Comment: The difference between two uniform variables is not uniform.
Comment: (Between two _independent_ uniform variables, I mean.)
Comment: Yeah, you are right. Huge mistake from my side when calculating the bounds for c and d and the joint distribution. Have corrected the calculation and also the question title.
Answer:
To solve this, what I did is that first find out the PDF of C=B−A as shown below

Indeed, or you could do $$\begin{align}f_{A,B-A}(a,c) &=\begin{vmatrix}\partial a/\partial a&\partial a/\partial c\\\partial (a+c)/\partial a&\partial(a+c)/\partial c\end{vmatrix} f_{A,B}(a, a+c)\\f_{B-A}(c) &=\int_\Bbb R f_A(a)f_B(a+c)\,\mathrm d a\\[1ex]&=\int_\Bbb R \mathbf 1_{0<a<1, 0<a+c<1}\,\mathrm d a\\[1ex]&= \int_{-c}^1 \mathbf 1_{-1\leqslant c<0}\,\mathrm d a+\int_0^{1-c}\mathbf 1_{0\leqslant c\leqslant 1}\,\mathrm d a\\[1ex]&=(1+c)\,\mathbf 1_{-1\leqslant c<0}+(1-c)\,\mathbf 1_{0\leqslant c\leqslant 1} \end{align}$$

Now our required variable $T$ will be $T=max(0,C)$ and this is where I am stuck that is how to find out the distribution of $T$.

The issue is that $T=0$ is the event $C\leq 0$, which will not have a probability density.  Rather it will have a probability mass of $1/2$ .
You might use the Dirac Delta generalised function for this.
$$f_T(t) = \tfrac 12\delta(t)+(1-t)\,\mathbf 1_{0<t\leqslant 1}$$


Validação de email junto a senha com jQuery

Question: Preciso dar um alerta quando der "tudo certo" no meu formulário.
A situação é que eu preciso verificar sem o email possui "@" e "." e também junto com isso se os dois campos de senha tem valores iguais.
Eis o código.
$("#passo2_cad").click(function() {

    email = $("#user_email").val();
    filtro = /^([\w-\.]+@@([\w-]+\.)+[\w-]{2,4})?$/;
    senha = $("#user_password").val();
    senha_confirma = $("#user_confirm_password").val();

    if (senha === '' && senha_confirma === '' && email === '') {
        $("#user_password").css({
            border: '2px solid red'
        })
        $("#user_confirm_password").css({
            border: '2px solid red'
        })
        $("#user_email").css({
            border: '2px solid red'
        })
        $("#user_email").css({
            border: '2px solid red'
        })
    } else if (!filtro.test(email)) {
        $("#user_email").css({
            border: '2px solid red'
        })
    } else if (senha === senha_confirma && filtro.test(email)) {
        $("#user_password").css({
            border: '2px solid #70e870'
        })
        $("#user_confirm_password").css({
            border: '2px solid #70e870'
        })
        $("#user_email").css({
            border: '2px solid #70e870'
        })
        alert("Deu tudo certo!");
    }

})

Só que tá meio que enrolando pra caramba, valida uma coisa, trava em outra, o que tem mais de errado aí?
OBS: Não é um submit, estou fazendo por etapas, a etapa 1 você precisa colocar o email e a senha, só quando estiver de acordo as informações que você pode passar para a etapa 2, por isso quero validar dessa forma
Comment: Recomendo vc usar este plugin: https://jqueryvalidation.org/
vai te auxiliar na validação e muito mais pratico de trabalhar!
Comment: JQuery validation, para a validação ->
https://github.com/jquery-validation/jquery-validation Sweet Alert, para o alerta -> https://sweetalert.js.org/guides/
Answer: 1 - Aqui seu código em execução e os erros encontrados!

Filtro errado, com 2 @ (corrigido para dar continuidade aos testes)
No primeiro if se todos os campos forem nulos funciona ok.
Outras situações no primeiro if baubau.
Na primeira condicional } else if (!filtro.test(email)) {
se digitar email errado e demais campos nulos também OK. Obs: coloquei para dar cor azul nas bordas do campo email nessa condicional.
No segundo else if se digitar email correto passa pelo primeiro else if e demais campos nulos vai dar como Deu tudo certo!
porque essa condicional } else if (senha === senha_confirma && filtro.test(email)) { é verdadeira  ou seja, senha === senha_confirma senha e confirma senha nulos são iguais e email está correto.

$("#passo2_cad").click(function() {

    email = $("#user_email").val();
    filtro = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    senha = $("#user_password").val();
    senha_confirma = $("#user_confirm_password").val();

    if (senha === '' && senha_confirma === '' && email === '') {
        $("#user_password").css({
            border: '2px solid red'
        })
        $("#user_confirm_password").css({
            border: '2px solid red'
        })
        $("#user_email").css({
            border: '2px solid red'
        })
        $("#user_email").css({
            border: '2px solid red'
        })
    } else if (!filtro.test(email)) {
        $("#user_email").css({
            border: '2px solid blue'
        })
    } else if (senha === senha_confirma && filtro.test(email)) {
        $("#user_password").css({
            border: '2px solid #70e870'
        })
        $("#user_confirm_password").css({
            border: '2px solid #70e870'
        })
        $("#user_email").css({
            border: '2px solid #70e870'
        })
        alert("Deu tudo certo!");
    }

})

 <input size="42" value="" id="user_email" placeholder="Email">
 <input size="42" type="password" value="" id="user_password" placeholder="Senha">
 <input size="42" type="password" value="" id="user_confirm_password" placeholder="Confirma senha">
 <button id="passo2_cad">Verificar</button>

2 - Exemplo de validação correta

Coloquei $(document).ready(function() { no script pois nunca se sabe onde o script foi colocado na página, com essa linha pode colocar o script em qualquer lugar.

$(document).ready(function(){

   $("#passo2_cad").click(function(){

      var email = $("#user_email").val();
      // filtros
      var emailFilter=/^.+@.+\..{2,}$/;
      var ilegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/

      var senha = $("#user_password").val();
      var senha_confirma = $("#user_confirm_password").val();

      if(!senha || !senha_confirma || !email){
         if(!(emailFilter.test(email))||email.match(ilegalChars)){
            $("#user_email").css('border', '2px solid red');
            alert("email incorreto!");
            $( "#user_email" ).focus();
            return;
         }else{
            $("#user_email").css('border', '2px solid #70e870');
         }

         if((!senha)||(senha.length<4)){
            $("#user_password").css('border', '2px solid red');
            $("#user_password").attr("placeholder", "Minimo de 4 caracteres!");
            $( "#user_password" ).focus();
            return;
         }else{
            $("#user_email").css('border', '2px solid #70e870');
         }

         if(senha_confirma){
            $("#user_confirm_password").css('border', '2px solid red');
            return;
         }else{
            $("#user_email").css('border', '2px solid #70e870');
         }
      }

      if(senha !== senha_confirma){
         $("#user_confirm_password").val("");
         $("#user_password").css('border', '2px solid red');
         $("#user_confirm_password").css('border', '2px solid red');
         $("#user_confirm_password").attr("placeholder", "senhas não conferem!");
         $( "#user_confirm_password" ).focus();
         return;
      }

      $('input[id^="user_"]').css('border', '2px solid #70e870');
      alert("Deu tudo certo!");

   });
});

<input size="42" value="" id="user_email" placeholder="Email">
<input size="42" type="password" value="" id="user_password" placeholder="Senha">
<input size="42" type="password" value="" id="user_confirm_password" placeholder="Confirma senha">
<button id="passo2_cad">Verificar</button>
Comment: @dvd dei uma incrementada no código!!!
Comment: @dvd feito e sem errar, hahaha : D
Comment: ixi, eu editei por cima ;/
Comment: precisava daquela flag não, era só usar return;
Answer: Problema
Começo por dizer que a regex que está a utilizar para validar o email:
/^([\w-\.]+@@([\w-]+\.)+[\w-]{2,4})?$/

Tem um @ a mais, e por esse motivo não funciona corretamente. Independentemente disso a lógica que tem também não funciona:
if (senha === '' && senha_confirma === '' && email === '') {

Aqui está a dizer que se estas 3 coisas acontecerem ao mesmo tempo então marca estes campos a vermelho. O que significa que se a senha for vazia mas a confirmação e o email não forem, já não os vai marcar a vermelho.
O que significa que a seguir vai testar o email, mesmo podende este ser vazio:
...
} else if (!filtro.test(email)) {

E de seguida testar novamente o email com a regex, e comparar as senhas:
} else if (senha === senha_confirma && filtro.test(email)) {

Quando na verdade é possível que o usuário tivesse deixado ou a senha ou a senha_confirma vazia, que o não entrava no primeiro if.
Solução
Uma solução pegando mais ou menos na lógica que tem é testar cada campo em separado e marcar com a cor apropriada, consoante esteja certo ou não. De forma a poder perceber se todos estão certos também precisa de mais lógica.
Exemplo:
//variavel para saber se algum não está correto
let erros = false;

if (senha === '' || senha !== confirma_senha) {
    $("#user_password").css({
        border: '2px solid red'
    });
}
else {
    $("#user_password").css({
        border: '2px solid #70e870'
    });
    erros = true;
}

//falta aqui a mesma lógica para a confirmacao da senha
//que não coloquei para não ser extenso

if (email === '' || !email.test(filtro)) {
    $("#user_email").css({
        border: '2px solid red'
    });
}
else {
    $("#user_email").css({
        border: '2px solid #70e870'
    });
    erros = true;
}

if (erros === false){
    //tudo certo
}

Neste exemplo a variável erros memoriza se algum campo para trás tem erros e caso tenha não faz o cadastro com sucesso. Embora esta lógica funcione,e seja de certa forma parecida à sua, é muito repetida e duplica bastante o código.
Para contornar este problema podemos utilizar arrays memorizando todos os campos a serem testados. Isto facilita a aplicação dos estilos em massa. No intuito de aproveitar esta lógica também os erros podem ser guardados num array:

//todos os campos existentes num array
const campos = [$("#user_email"), $("#user_password"), $("#user_confirm_password")];

$("#passo2_cad").click(function() {
    email = $("#user_email").val();
    filtro = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    senha = $("#user_password").val();
    senha_confirma = $("#user_confirm_password").val();

    let erros = []; //erros agora é um array para os campos errados

    if (senha === '' || senha !== senha_confirma){
        erros.push($("#user_password")); //se errado adiciona ao array de erros
    }
    if (senha_confirma === '' || senha_confirma !== senha){
        erros.push($("#user_confirm_password"));
    }
    if (email === '' || !filtro.test(email)){
        erros.push($("#user_email"));
    }

    //marcar todos os campos a verde
    for (let campo of campos){
        campo.css({border: '2px solid #70e870'});
    }

    if (erros.length === 0){
        alert("Deu tudo certo!");
    }
    else { //não deu certo, logo marca os errados a vermelho
        for (let campoErrado of erros){
            campoErrado.css({border: '2px solid red'});
        }
    }
});

Email <input type="email" id="user_email">

Password <input type="password" id="user_password">

Confirmação <input type="password" id="user_confirm_password">

<input type="submit" value="Cadastrar" id="passo2_cad">

Neste cenário já muita da duplicação de código foi eliminada, deixando-o mais pequeno, fácil de manter e adicionar outros campos.
Como próximo passo será importante colocar a informação do que correu mal em cada passo da validação, para que o usuário não fique perdido tentando achar o que não fez certo.


Does Apache with PHP use same connection pool for streaming files?

Question: Say that I have a PHP site running on that hosts larger images. Each page is very simple and takes virtually no time to process in PHP, but it might contain couple MB large image.
The question is, if I have Apache set up to handle 100 connections, and the page itself takes couple ms to generate, does it keep the connection blocked for the image transfer, or is this handled on some other connection pool?
Because in the first case, it might take couple seconds to download the image, so I would be able to serve only 100 clients at a time.
Comment: To improve the performance, you can increase the connection count limit if your hardware can process all the connections. Otherwise, you may need to upgrade your server or add more servers.
Answer: Every connection to the server whether PHP or static file serving are from the same 100 connection pool. Once PHP serves up the HTML the connection is free to be used for something else. If it's a persistent connection then it will probably be re-used to download an image.
Keep in mind that modern browsers will create at least 2 to 6 persistent connections so it'll be less than 100 clients at a time.
Example scenario assuming KeepAlive is on: One connection handles the PHP script then that same connection will start downloading an image and the browser opens or uses existing connections to download the other images.
Answer: It depends on the keepalive setting. If you set it to 'on' connections are reused. If you set it to 'off' new connections are made for every page element (html/php,image,javascript files, css etc). Keeping it on means a better experience for your users at the expense of server CPU load. Keeping it off means a slower browsing experience but server load is slightly reduced. Also you can tune the keepalivetimeout setting. Set it to 5 or less.


When exporting .sql via phpMyAdmin do you need to include cache tables?

Question: So I built the D7 site on one server and then moved it to other server and I noticed that .sql size is 8MB in total. I then exported .sql without any cache tables, including cache_* files like cache_block, cache_views and etc. I skipped all tables starting with cache_ and the total .sql size was below 2MB!
So when moving site from one server to other do I need to include cache tables when exporting the .sql or not? Because looks like those cache tables takes 80% of .sql size. And as I understand cache is something temporal?
I came up with this question after moving site to new server and I noticed that tmp folder has 100% copies of images that I uploaded to nodes, but those original images are held in separate files/ folder. So now I got those original images 50MB and copies of those images in tmp/ dir and its also 50MB. So I get extra 50MB taken. I was thinking maybe its because I moved the site with all caches without running cron and etc. and maybe somehow those images in the tmp dir got lost and forgotten by Drupal system or something? I now removed those from tmp dir and it seems to be all working fine.
Strange, can't really understand that.
Answer: You can typically skip the data in all of the cache tables.  That is temporary data that Drupal will recreate when as needed.  Basically, the cache tables store data the Drupal creates so that it doesn't need to create it the next time.
You can also usually skip the data in the watchdog table if you don't need the system logs.  Depending on your situation, you may also be able to skip sessions.
There are a few others you can skip (like flood), but they don't usually don't have much data in them in most situations.
Just remember that you want to back up the table structure (ie, the CREATE statements) and just skip the data.
The Backup and Migrate will take care of most of this for you.  drush sql-dump can skip table, data too.
Normally, I just transfer everything when moving between servers.  I just clear cache as part of the restoration process.  I would rather have a bigger file than have the chance of missing something.


Quick question on orthogonal subspaces.

Question: Let $V$ be a vector space with a bilinear form defined on it.
let $U$ and $W$ be subspaces of $V$. Then $U \subset W^{\perp} \iff W \subset U^{\perp}$.
Why is this? maybe one can prove one direction and I will try to prove the other.
Answer: Suppose $U\subset W^\perp$ and let $w\in W$. Then $\langle w,\hat{w}\rangle = 0$ for all $\hat{w}\in W^\perp$. Since $U\subset W^\perp$ it follows that $\langle w,u\rangle = 0$ for all $u\in U$, which implies that $w\in U^\perp$. Since $w$ is arbitrary, it follows that $W\subset U^\perp$.
Comment: Thank you K. Miller, so bilinearity is never used?
Comment: I used $\langle\cdot,\cdot\rangle$ as my bilinear form, but I probably should have been more explicit about this with my notation.

Quick question on orthogonal subspaces.


Identify encryption scheme - possibly DSA or Diffie Hellman - only client shares key

Question: I could use a hand in identifying the encryption scheme used in this scenario. (Its from source code known to work)
There is a client connecting to a server such that:
client_private_key = rand
p = 131 # known prime
client_public_key = ((client_private_key ** p) % known_server_public_key)

Client shares its client_public_key to the server, and encrypts and decrypts using its client_private_key which is totally random.
Now, I have a hard time identifying the encryption scheme here and how the server generates its shared key to decrypt/encrypt messages to and from the client knowing that the client uses its private random key. Which to me means the server must be able to recreate this exact secret random key from what is known.
I can see the client_public_key is calculated equivalent to a DSA signing key, but I always though with my limited knowledge that this only could be used for verifying and not decryption.
I am used to the idea that client and servers generate mutual shared keys. This seems outside the realm of Diffie Hellman, and probably more into some DSA branch I do not know about. But it may very well be that its a branch of DH that I do not know about as well.
Or even something similar to Clifford Cocks non-secret encryption.
Any nudge in the right direction appreciated, and a readable solution with how the keys are made even more appreciated. Hoping to solve this and learn how to use this method.
Answer: It may be assumed that the server knows both $p$ and the prime factorization  of known_server_public_key, hence knows an integer $m$ such that $pm\equiv 1\pmod{\phi(\text{known_server_public_key})}$, which allows the server to compute client_private_key from client_public_key. So if client_private_key were really something to be kept private, this is bad code. Instead, it looks rather like the messgae client_public_key is RSA encrypted using the server_public_key and can thus - after transmission to the server - be used as a shared secret among the two parties. Insofar, the names client_private_key and client_public_key may be misleading.
Comment: Yes, the naming is all mine, and I think you are absolutely right that the client_private_key is in fact a shared secret. It couldn't possibly work unless it is. A better name would probably be shared_key or shared_secret.
Comment: It is suggested that the key is secretly shared using the Chinese remainder theorem. Which is a bit beyond me anyways.


How to locally export config from a remote environment?

Question: If I have config that's out of sync on production, I may want to export it without copying down the database, or I may have environment-specific config that interferes with exporting config from the local environment. Is there a way to export config from a remote environment locally?
Answer: Edit: Turns out drush has a config-pull command to handle exactly this:
https://drushcommands.com/drush-8x/config/config-pull/
However, it doesn't work with config_ignore as far as I can tell.
The original answer for posterity:
I've found that this bash command does the trick (on Mac OS X):
yes n | drush @site.env cim sync --preview=diff | \
sed -E 's/([\-]{3} ).*(\/.*.yml)/\1a\/config\/sync\2/' | \
sed -E 's/([\+]{3} ).*(\/.*.yml)/\1b\/config\/sync\2/' > cim.patch && \
interdiff -q cim.patch /dev/null > cex.patch && \
git apply cex.patch && \
rm cex.patch cim.patch

We use the preview argument of drush config-import (passing in 'n' when it prompts to import), clean up path names with sed, reverse the patch from import to export, and finally apply it and clean up. Note that you have to be on the same git branch as production.
With drush 9, the output and yes functionality changes a little, so you can instead use:
drush @site.env cim sync --no --preview=diff 2>/dev/null | \
sed -E 's/([\-]{3} ).*(\/.*.yml)/\1a\/config\/sync\2/' | \
sed -E 's/([\+]{3} ).*(\/.*.yml)/\1b\/config\/sync\2/' > cim.patch && \
interdiff -q cim.patch /dev/null > cex.patch && \
git apply cex.patch && \
rm cex.patch cim.patch

Comment: `cpull` doesn't export active config, it just rsync's the staged config from the @source directory.


webRTC - pushing stream through webAudio gainNode keeps mic engaged even after call hangup

Question: I have below pieces of code
function modifyGain(stream){
    var AudioContext = window.AudioContext || window.webkitAudioContext;
  var ctx = new AudioContext();

  var src = ctx.createMediaStreamSource(stream);
  var dst = ctx.createMediaStreamDestination();

  var gainNode = ctx.createGain();
  gainNode.gain.value = 3.5;
  src.connect(gainNode);

  gainNode.connect(dst);

  return dst.stream;
}

I tried addTrack() and removeTrack() on original stream but no luck.
This is how use that function above.
webcamStream = await navigator.mediaDevices.getUserMedia(mediaConstraints);
webcamStream = modifyGain(webcamStream);

document.getElementById("local_video").srcObject = webcamStream;

webcamStream.getTracks().forEach(
        function (track){
            myPeerConnection.addTrack(track, webcamStream);
        });

This is how I stop the tracks on call hangup
webcamStream.getTracks().forEach(track => {
            track.stop();
        });
webcamStream = null;
localVideo.srcObject = null;

All works fine before I apply that gain related code. But once I add that the browsers don't release mic and I have to refresh the page in order to have any audio exchange with other end.
Please help.
Comment: Can't repro: https://jsfiddle.net/fL5adw69/
Comment: I am unable to reproduce using your fiddle too.
Comment: I tried below given code and it seems to work. But I am not sure is it good way to do it or no. `preGainLocalStream = await navigator.mediaDevices.getUserMedia(mediaConstraints);
  webcamStream = modifyGain(preGainLocalStream);`

Then I stopped `webcamStream` and `preGainLocalStream` using the `preGainLocalStream.getTracks().forEach(track => {
   track.stop();
  });` and same for the other stream.
Answer: There are two streams. You're only stopping the tracks in the second stream, the one created by ctx.createMediaStreamDestination().
To relinquish the microphone, you instead need to stop the tracks in the original stream obtained from navigator.mediaDevices.getUserMedia.


Getting 400 Error as A client error happened

Question: On our multi-site platform using Drupal 8 hosted on acquia we are getting 400 error response on all the hosted websites
The error is not persistent but only occurs when user comes through a referrer like google/bing or even a link from JIRA/slack.
During this error, we see an error about 400 in Drupal Watchdog as

drupal-watchdog.log-20181003:133708:Oct  2 13:46:06  d8: https://www.example-domain.com|1538487966|php||https://www.example-domain.com/|https://www.google.com/|0||Symfony\Component\HttpKernel\Exception\BadRequestHttpException: Untrusted Host "www.google.com". in Symfony\Component\HttpKernel\HttpKernel->handle() (line 71 of /mnt/www/html/d8/vendor/symfony/http-kernel/HttpKernel.php). request_id="v-8187594e-c649-11e8-b00d-67f570bebe6a"

As an attempt to fix the issue we tried adding 'www.google.com' in trusted_host_pattern in settings.php
  $settings['trusted_host_patterns'] = array(
    '^example-domain\.com$',
    '^.+\.example-domain\.com$',
    '^google\.com$',
    '^.+\.google\.com$',
  );

but that did not fix the issue either, we are still getting errors with that same logs.
We are using varnish for reverse proxy and cloudflare, if that looks to be an issue, since that's the thing between Drupal and client request.
Any help would be much appreciated.
Comment: load balancers?
Comment: Yes @LittleCoding we do have load balancers, that are part of acquia infrastructure.
Answer: To avoid this, make sure you have an up-to-date Drupal install, adding this code to your settings.php file (or post-settings-php hook for Site Factory customers):
unset($_SERVER["HTTP_FORWARDED"]);
Source: https://acquia.my.site.com/s/article/360044285973-Troubleshooting-the-A-client-error-happened-message-in-content


Copy every three cells in a column from one sheet and paste to another sheet

Question: I've seen posts regarding copying a range of data and pasting with added blanks, but I need something a bit more complicated.
I have a range of data which I need to copy from one sheet and paste into another.  The other sheet has data every 4th cell that I don't want to overwrite.  So I basically have a long range of data and I need copy three cells and paste to another sheet under this 4th cell I described, over and over again until I get to the end of the range of data.
Example:
This data from sheet 1
Sheet 1 data
Needs to be pasted onto this sheet 2
sheet 2 test
So the final result has sheet 2 where the "test" cells haven't been overwritten
sheet 2 with data pasted
Thanks!
edit
Here is the code I'm using now:
<code>'Now, copy specimen results from wb1:

wb1.Sheets(1).Range("D53", wb1.Sheets(1).Range("D53" & NumOfwells * 4 + 44)).Copy

'Now, paste to y worksheet:
wb2.Sheets("Worksheet").Range("J6").PasteSpecial
</code>
As you can see, it's a dynamic range being copied that could be more or less depending on an input number (NumOfwells), hence the calculation for the range.
And you can see where in the sheet the copying being done, i.e. D53 and down on from sheet one on wb1.  Then pasted onto the second workbook starting at J6.
Comment: You should still [edit your question](https://stackoverflow.com/posts/52763400/edit) and add the code you have to it.
Comment: What have you tried so far?
Comment: Well I started by doing a simple macro to add a row after every three cells and was going to copy that, but then realized that would still overwrite the cells I'm copying to.
Answer: Welcome to StackOverflow.  If you post questions in the future please
include the code that you've tried, and identify where it is failing.
From your question & samples you really don't need to find every 4th row
you are really just trying to paste data in places there isn't anything in
the target area.
The code uses the same basic loop to do either to show both cases.  The following procedure lets you choose your range, and target sheet.
<code>Sub test2()
    Call CopyData(Sheet1.Range("A3:A13"), sheet2)
End Sub

Private Sub CopyData(ByVal SourceRange As Range, ByRef TargetWorksheet As Worksheet)
    Dim oIndex As Long

    For oIndex = 1 To SourceRange.Rows.Count + 1
        ' Check for blanks
        'If TargetWorksheet.Cells(SourceRange.Row + oIndex - 1, 1) = "" Then
        '    TargetWorksheet.Cells(SourceRange.Row + oIndex - 1, 1).Value = SourceRange.Cells(oIndex, 1).Value
        'End If

        ' Skip every 4th row
        If (oIndex - 1) Mod 4 <> 0 Then
            TargetWorksheet.Cells(SourceRange.Row + oIndex - 1, 1).Value = SourceRange.Cells(oIndex, 1).Value
        End If

    Next
End Sub
</code>
Comment: Thanks for your suggestions!  I've added the code I'm using in my original post.  I guess I'm not sure how to integrate your code into my workbook.  I tried copying it and running the macro as is, but it didn't do anything.


Backing Out One Folder To Obtain Sourcepath

Question: In a program that I am building I have a file which is dependent on an import (import SScomp.EMeasure;). Using build.xml, I am trying to specify that the sourcepath is one folder back. However, while the program will compile and run, I am still getting many errors saying "error: package SScomp does not exist" which refers back to "import SScomp.EMeasure;"
To be more specific, the build.xml file is located in D:\projects\December\PhaseIV\JELDoclet\build.xml.
The EMeasure.java file that is needed is located in D:\projects\December\PhaseIV\Library\src\SScomp\EMeasure.java. How can I specify the location of the sourcepath so that I no longer get any errors concerning SScomp.EMeasure?
<code><target name="run" depends="main">
    <javadoc doclet="com.jeldoclet.JELDoclet"
        docletpath="build\jar\jeldoclet.jar"
        sourcefiles="${sourcefiles}"
        sourcepath= "cd..\Library\src\SScomp\*.java"
        destdir="${distmodelnotebook}"
        additionalparam="-d ${distmodelnotebook} -filename eKAADs.xml -outputEncoding UTF-8 -sourcepath"
        private="yes">
    </javadoc>
</target>
</code>
Comment: This is nonsense `sourcepath= "cd..\"` ! There is no miraculous searchpath of commands like `cd ..` performs. If you can not get it to work with `sourcepath= "..\Library\src\SScomp\*.java"` you must set the absolut path `sourcepath= "D:\projects\December\PhaseIV\Library\src\SScomp\*.java"`
Answer: To get the correct sourcepath I had to use the variable ${basedir} which was in an ant script that I was unaware of. The reason I didn't use a literal path was due to the fact that this program is going to be sent to other people. This means that using a literal path would have caused other users errors.


Checagem campo vazio e valor zero

Question: Abaixo tem dois exemplos dos meus códigos, eu tenho um text box peso que o usuário precisa colocar algum peso, e não pode ser 0.
No primeiro código abaixo, ele faz a checagem porém, ele executa o restante do meu código onde eu comentei, o que não era para acontecer. Já que se for 0 ou em branco deve parar o código.
No segundo código ele funciona quando eu uso 0, porém se for em branco da erro por tentar transformar para int já que não existe nada no textbox.
Alguém tem uma solução para isso?
CÓDIGO 1
 protected void BT_Cadastrar_Click(object sender, EventArgs e)
    {
        if (TB_Peso.Text.Trim().ToString() == "")
            LBL_Peso.Visible = true;
        else
            LBL_Peso.Visible = false;
        {
            int zero = Int32.Parse(TB_Peso.Text);
            if (zero == 0)
                LBL_Peso.Visible = true;

            // meu código continua
        }
     }

CÓDIGO 2
 protected void BT_Cadastrar_Click(object sender, EventArgs e)
    {
        int zero = Int32.Parse(TB_Peso.Text);
        if (TB_Peso.Text.Trim().ToString() == "" || zero == 0)
            LBL_Peso.Visible = true;
        else
            LBL_Peso.Visible = false;
        {

Comment: Esse abre chaves, após `LBL_Peso.Visible = false;` existe de fato? Não era nem pra compilar com isso. Enfim, para corrigir seu erro de executar o resto do código, basta colocar todo ele dentro de um else.
Answer: Tinha uma parte do seu código que estava fora das chaves do ELSE.
        protected void BT_Cadastrar_Click(object sender, EventArgs e)
        {
        if (!string.IsNullOrEmpty(TB_Peso.Text))
            LBL_Peso.Visible = true;
        else
        {
            LBL_Peso.Visible = false;

                int zero = Int32.Parse(TB_Peso.Text);
                if (zero == 0)
                    LBL_Peso.Visible = true;

            // meu código continua
        }
    }

Comment: Porém quando eu coloco 0 ele continua meu código, o que não deve acontecer. Como faço para resolver?
Answer: Tente assim:
int zero = 0;
int.TryParse(TB_Peso.Text, out zero);
if(String.IsNullOrWhiteSpace(TB_Peso.Text) || zero == 0)
    LBL_Peso.Visible = true;
else
    LBL_Peso.Visible = false;

Answer: Voce pode usar o TryParse para checar se o que tem no textBox pode ser convertido para Int
Exemplo:
 //Cria uma variável int
 int number;

 //Pega o retorno, se vier, se vier true e por que pode ser convertido para int
 bool result = Int32.TryParse(TB_Peso.Text, out number);
 if (result)
 {
    int zero = Int32.Parse(TB_Peso.Text);
 }
 else
 {
     //Faz alguma coisa ou só retorna
     return;
 }

Answer: Do jeito que seu codigo está ele só tem uma opção ou faz o que está no IF ou no ELSE.
Se você quer algo direfente disso faça assim:
protected void BT_Cadastrar_Click(object sender, EventArgs e)
        {
        if (!string.IsNullOrEmpty(TB_Peso.Text))
            LBL_Peso.Visible = true;
        else
        {
            LBL_Peso.Visible = false;
        int zero = Int32.Parse(TB_Peso.Text);
        if (zero == 0)
            LBL_Peso.Visible = true;
        else {
            // meu código continua
        }
    }
}

Talvez você consiga melhorar a construção assim:
protected void BT_Cadastrar_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(TB_Peso.Text)) || ( Int32.Parse(TB_Peso.Text) == 0 )
        LBL_Peso.Visible = true;
    else
    {
        LBL_Peso.Visible = false;
        // meu código continua
    }
}

Deve resolver. Conforme ja postado acima pelo dil_oliveira.

Checagem campo vazio e valor zero


Quais as diferenças entre o Decoradores e Atributos?

Question: Eu fiz uma pergunta recentemente sobre o uso de atributos que foi introduzido no PHP 8. Atributos para mim acaba não soando como novidade, porque lembro de ter visto algo parecido quando trabalhei com C#.
Lembro até que a sintaxe não é muito diferente do PHP:
<code>[Serializable]
public class SampleClass
{
    // Objects of this type can be serialized.
}
</code>
Porém surgiu uma certa dúvida quando me lembro que vi algo parecido no Python. Sei que em Python é chamado de decorators.
<code>@app.route('/')
 def home(response):
     return template(response, 'meu_template.html')
</code>
Lembro-me de ter feito uma pergunta referente à sintaxe do C#, mas fico na dúvida se não fiz confusão entre Decorator e Attributes hoje em dia.
As minhas dúvidas são:

Os Decoradores e os Atributos são/fazem a mesma coisas? Os decoradores do Python por exemplo têm a mesma finalidade que as do C# e PHP?
Caso não sejam a mesma coisa, quais são as diferenças entre eles?
Existem outras linguagens além do Python que usa o termo "decoradores"? Isso é um termo padrão da linguagem ou é familiar na programação?
Os termos "decoradores" e "atributos" podem ter outros nomes dependendo da linguagem de programação usada?
Comment: Pelo que percebo, tem uma diferença pratica importante, alguns apenas adicionam uma informação extra ao ponto (classe, método, função, etc) onde são definidos, portanto, por si só, não fazem nada, precisam de algum meio de reflexão pra serem usados. Enquanto outros, são sempre executados quando definidos, não precisam de nada além deles mesmo (não que não possa ter), por isso são (pelo menos os que conheço) uma função. Agora, qual termo é uilizado pra cada um, não sei dizer, nem como funciona em cada linguagem, no TypeScript, sei que é do 2° modo, provavelmente, por necessidade
Answer: Certos termos podem ser usados em contextos um pouco diferentes e podem ter grandes ou pequenas diferenças de interpretação.
Sobre PHP eu respondi O que são atributos no PHP? (Annotations/Attributes/Decorators).
Geralmente o atributo (de verdade, não a confusão que as pessoas fazem) é um mecanismo usado, frequentemente, para atingir o objetivo do chamado Decorator Pattern. Outros mecanismos podem ser usados, até porque algumas linguagens não possuem formas próprias.
Uma forma de decorar algo é encapsular uma função em outra, então em vez de chamar diretamente a função que deseja, chama outra que "prepara o terreno" e eventualmente finaliza a função principal.
Quando se usa atributo geralmente precisa de algum mecanismo que automatize isso e faz algo extra, geralmente através de reflexão, em tempo de execução ou em tempo de compilação. Fica uma sintaxe mais limpa e pode ser menos confuso, quando a pessoa sabe o que faz.
Uma linguagem pode chamar o atributo de outros nomes, como anotação (Java) ou até decorador, como visto acima.
A forma exata de funcionar pode ser diferente em cada linguagem, mas a essência é a mesma. Meu entendimento é que Python, C# e PHP possuem os mesmos mecanismos, ainda que possam ter pequenas diferenças de funcionamento.
Não lembro de todos detalhes de todas linguagens para falar sobre os termos delas, lembro de ver o uso de decorador só em Python.
Nem sei os detalhes de várias linguagens. Eu sei que em Python o decorador é efetivamente uma função. Em C# é uma classe e Java também, ainda que mais difícil de fazer, e parece que PHP copiou igual. Pode ser que as maiores diferenças estejam nos métodos de reflexão para acessar os atributos e mudar o comportamento ou configurar como uma função deve ser executada. Acho que seria até amplo falar disso porque seriam várias linguagens e muitos detalhes.
Curiosamente em C# eu vejo muito as pessoas usando atributos de forma muito descritiva, mas ele pode ser muito mais que isso, a classe que cria um atributo pode ter virtualmente qualquer código. É verdade que na maioria das vezes não é necessário ter, mas quando pode ser útil as pessoas esquecem ou não sabem que pode.
Eu gostaria que existissem decoradores só em tempo de compilação, porque a maioria só é usado nesse caso, e se a linguagem tem reflexão em tempo de compilação (C# agora tem), quase não precisa de outra forma. C# tem proposta para ter esses decoradores que não vão para o executável.
Eu acho curioso quando uma linguagem adota um mecanismo bem tarde, e assim ela pode fazer melhor porque aprendeu com os erros dos pioneiros, e ela comete os mesmos erros, pior ainda quando outras linguagens estão consertando. Aí eu falo que a linguagem não evolui bem, as pessoas acham que eu sou hater de linguagem, eu lido com fatos.
Coloquei no GitHub para referência futura.


Apache multiviews unexpected behaviour

Question: I have Apache multiviews enabled on my site but it's causing an unexpected behaviour.
my site www.example.com has an images folder like www.example.com/imgs/ where I store all images
so if I have www.example.com/imgs/pic1.jpg there and I try to access it, it's all fine and it shows the image on my browser.
Now if I go ahead and delete pic1.jpg from the imgs folder, and try to access www.example.com/imgs/pic1.jpg again, I was expecting a 404 but somehow I get served the page www.example.com/index.php (although css styling is lost). It's not a redirect, the URL in the address bar still shows www.example.com/imgs/pic1.jpg but loads the script at www.example.com/index.php
I suspect it's something related to multiviews, my htaccess has only the multiviews option. So how can I fix this? And why apache+multiviews would serve the site's index.php script one folder above?
Thanks
Just to mention that a request to www.example.com/script corretly loads www.example.com/script.php
Comment: What is the content of your .htaccess?
Comment: It only has: Options +MultiViews and nothing else
Comment: No, the _other_ .htaccess at your top level. And your Apache virtualhost configuration while you're at it.
Comment: @Michael example.com is an addon domain to primarydomain.com which is a shared hosting acct - i'm not sure if you  mean the .htaccess file on the primarydomain.com but here it is `# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress`
Comment: Please edit your question to add the config there instead of in a comment, it's really hard to read without proper formatting.
Answer: I've found what was causing this behaviour. As Michael mentioned, it was the primary domain's .htaccess affecting the add-on domain. In my case the solution was simple because I don't need rewrite rules in the add-on domain directory so I just added a line to the .htaccess file for the add-on domain:
RewriteEngine Off

Apache multiviews unexpected behaviour


General Behavior of Euler Totient Function

Question: If we have two integer M and N such that
$$GCD(M,N) = k$$
Then what is
$$\phi(MN)$$
There is a famous identity which states:
$$GCD(M,N)= 1 \rightarrow \phi (MN) = \phi(M)\phi(N)$$
And now I am curious about generalizing this result to other numbers. Is there any literature on this problem?
Answer: Let $\gcd(m,n)=k$.   Then the following identity is valid:
$$\varphi(m\cdot n)=\varphi(m)\cdot\varphi(n)\cdot\frac{k}{\varphi(k)}$$
If you want to learn more about Euler's totient function you could have a look here.


how can I get final embeddings from word2vec.py?

Question: I am using word2vec.py from Google, see the link below:
https://github.com/tensorflow/tensorflow/blob/r0.7/tensorflow/models/embedding/word2vec.py
I want to extract the final embeddings of words and save it to a txt file. How can I find the final embeddings?
Comment: @tanjir word2vec is to represent words by vectors in some embedding space. The embedding vectors are learned/updated through some neural network. In word2vec.py, they test the results by some analogy questions. Now, I want to extract the final embedding vectors for all words in corpus.
Answer: I figured out how to do it.
I created a self._nemb_final in build_eval_graph model to transfer the nemb out.
After the model is trained, we can then do sth. like below:
<code>final_embedding = self._nemb_final.eval()
np.savetxt('/.../final_embedding_dic.txt',final_embedding)
</code>
Comment: that just saves the vectors what about the vocabulary ?
Comment: @Michelle Owen :  how to get the vectors with vocabulory?
Comment: @ThomasNT  you can simply join the vocabulary with the embedding vectors together.
Comment: @trailblazer see above please


Replace with Regex

Question: In our application, user is entering data from MS word to asp.net textarea control and finally data is saved in SQL Server. For some reason, there are few junk characters which looks like small squares when viewed from SQL Server Management Studio.
This is causing error while generating Crystal Reports.
I need a regex which will strip all such characters along with bullets. The only valid input is
A-Z, a-z , 0-9, ~ ! @ # % $ ^ & *  ( ) _ + | ` - = \ {}:">? < [ ] ; ' , . /

Also, tab spaces should be replaced with single space. Enter key or New line is allowed.
Currently I am using
Regex.Replace(data, @"[^\u0000-\u007F]", " ");

but it won't work to remove bullets or tab spaces.
Can any regex ninja help me with this problem? Thanks in advance.
Comment: I know it's not exactly what you're after, but how about enabling a WYSIWYG editor on the `textarea` that gives an option to paste from Word. [TinyMCE](http://www.tinymce.com/wiki.php/Plugin:paste) has a plugin for just this task?
Comment: That is not an option for me as of now.
Comment: Use the `ASCII` SQL function to find out exactly what character it is, my guess is that you are looking for the wrong one: http://msdn.microsoft.com/en-us/library/ms177545.aspx
Comment: Have a look at [regex - Finding tabs or 4 spaces](http://stackoverflow.com/questions/11713212/finding-tabs-or-4-spaces-in-c-sharp-code). Bullets are ASCII characters, so you can just copy them into your RegEx pattern and replace it.
Answer: You can use two regexes. The first, with the pattern "\t|<bullet>" (where <bullet> stands for the representation of the bullet) is used first, to replace TABs and bullets with spaces (" "). The second, the pattern of which is a negated character set containing your list of valid characters, is used second, to replace invalid characters with the empty string (""), that is, to get rid of them. Since you need to keep CR and LF characters (and space), these must be added to the set of valid characters:
using System;
using System.Text.RegularExpressions;

static class Program
{
  public static void Main()
  {
    string pattern1 = @"\t";
    Regex regex1 = new Regex(pattern1, RegexOptions.Compiled);
    string pattern2 = @"[^A-Za-z0-9~!#$^&*()_+|`\-=\\{}:"">?<\[\];',./ \r\n]";
    Regex regex2 = new Regex(pattern2, RegexOptions.Compiled);

    string input = "ABZabz09~!#$^&*()_+|`-=\\{}:\">?<[];',./ \r\nárvíztűrő\ttükörfúrógép";
    string temp = regex1.Replace(input, " ");
    string output = regex2.Replace(temp, "");
    Console.WriteLine(input);
    Console.WriteLine(output);
    Console.ReadKey(true);
  }
}

Output:
ABZabz09~!#$^&*()_+|`-=\{}:">?<[];',./
árvíztűrő       tükörfúrógép
ABZabz09~!#$^&*()_+|`-=\{}:">?<[];',./
rvztr tkrfrgp

Note that the TAB after árvíztűrő was replaced with a single space.
About bullets:
I made a bulleted list in Word and copied it into a textarea in a webpage. Then I saved the HTML and figured out that the bullets are saved as the UTF-8-encoded character E280A2. This is what I called above the "representation of the bullet". You should figure out the binary representation of possible bullet characters and add them to the first pattern: either OR them to the TAB character, or put all of them into a character set:
using System;
using System.Text;
using System.Text.RegularExpressions;

static class Program
{
  public static void Main()
  {
    byte[] bulletBytes = new byte[] { 0xE2, 0x80, 0xA2 };
    string bullet= Encoding.UTF8.GetString(bulletBytes);

    string pattern1 = @"[\t" + bullet + "]";
    Regex regex1 = new Regex(pattern1, RegexOptions.Compiled);
    string pattern2 = @"[^A-Za-z0-9~!#$^&*()_+|`\-=\\{}:"">?<\[\];',./ \r\n]";
    Regex regex2 = new Regex(pattern2, RegexOptions.Compiled);

    string input =
      bullet + "ABZabz09~!#$^&*()_+|`-=\\{}:\">?<[];',./ \r\n" +
      bullet + "árvíztűrő\ttükörfúrógép";
    string temp = regex1.Replace(input, " ");
    string output = regex2.Replace(temp, "");
    Console.OutputEncoding = Encoding.UTF8;
    Console.WriteLine(input);
    Console.WriteLine(output);
    Console.ReadKey(true);
  }
}

Output (you should change the console font to Lucida Console to see the bullet):
•ABZabz09~!#$^&*()_+|`-=\{}:">?<[];',./
•árvíztűrő      tükörfúrógép
 ABZabz09~!#$^&*()_+|`-=\{}:">?<[];',./
 rvztr tkrfrgp

Now in addition to TAB, the bullet at the beginning of each line has also been replaced with a space.
Comment: Thanks a lot @kol , as users are copying data from MS word, I would like to support "  and ' chars. How do i add it to above regex. I tried adding these chars as it is, but it wont filter as expected. Any help on this is highly appriciated. Thanks again.
Comment: You are welcome. I think " and ' could be added to the set of valid characters as Unicode character escape sequences. I would try \u2018-\u201f, see here: http://www.techabulary.com/u/unicode/
Answer: I think that you should be diagnosing the underlying problem, rather than saying "some reason" and trying to fix the symptom, but that's not your question:
You'll want this regex:
 [^A-Za-z0-9~!\#\$\^&\*\(\)_\+\|`\-\=\\\{\};"\>\?\<\[\]:',\.\/]

To match any character that isn't allowed, and then you'll want to replace it with String.Empty.  Then you'll just want to match:
\t

And replace it with " ".
Comment: you dont need to escape anything within `[]` except `[]`
Comment: Absolutely untrue.  Try the regex [\s] against "s".  By your logic the regular expression matches either backslash or s, but you'll find that it actually matches any whitespace character.  Also, when you edit someone's post make sure your edits don't change the answer and render it invalid.

Replace with Regex