How can I use one of the pre-set email texts for user registration in a custom module

Question: At /admin/config/people/accounts, there are several stock email messages set.
How can I use one of these when I am sending emails from a custom module?
The text that's being used in "Welcome (new user created by administrator)" is all that I need, plus there's the bonus that our client can edit this email in the future if they want to.
I can send the message easily enough using:
$params = [
   'title' => "My Title",
   'subject' => "An Account Has Been Created for you",
   'message' => Html::escape("Some text here")
 ];

$result = $mailManager->mail($module, $key, $to, $language_code, $params, NULL, true);

Is there a variable somewhere to get the pre-entered text?
Answer: I guess this should be possible via configuration API. Look for the suitable entry where the message body is saved, call it via the service to put it into a variable. Then you can do additional coding with the string variable.
More information you can find here:
Configuration override system in the docs
Comment: For the specific case of email sent by the core Drupal `user` module, yes the messages are stored in config. You can see them with `drush config-get user.mail`. But this is not true in general - it is a feature of the user module. Other modules which define pre-set messages do NOT store these message in config. In general, given a module name and a message key, it is not possible to access the text of the message, as it is probably just in code or in a template. Also, in general it is not possible to programmatically find out the message keys.
Answer: All emails in Drupal are uniquely identified by their sending module and key. In the case of the welcome message for admin-created users, the sending module is user and the key is register_admin_created. This is all you need. The subject and the message body is defined by the sending module and you don't need access to it in order to send the message.
If you want to send this message from your own module, the correct way to do it is:
\Drupal::service('plugin.manager.mail')->mail('user', 'register_admin_created', $to, $langcode); where $to is a string containing the email address of the recipient, and $langcode is a RFC 5646 language code. There are also a few optional parameters you can pass to mail(). See the MailManager::mail() API documentation for more information about how to use mail() and what the arguments mean.
Also note that if you are calling mail() from object-oriented code, you really should inject the plugin.manager.mail service instead of using the static \Drupal call shown above. But explaining that is outside the scope of this question.
Answer: Thanks for the guidance on this @dercheffe. I found what I needed in the config file user.mail.yml and was able to pull the strings outs as an array with :
$config_txt = \Drupal::config('user.mail')->get('register_admin_created');
However, I had the problem of how to replace the user and site variables in the strings from the config file.
Long story short, I didn't even need that config information.
The answer was to just use the Drupal function
 _user_mail_notify('register_admin_created', $newuser);
The email is sent out based on the text in the configuration to our new user.
Comment: `_user_mail_notify()` is not part of the Drupal API, and should not be used by contributed modules or site-specific code. You can tell this by the '_' prefix - this is an old naming convention in PHP and Drupal which indicates the function is private and for internal use only. In the future, you should expect this to be turned into a real method on a real Drupal service, and you should expect this function to disappear without any deprecation notice (since it's not part of the public API).


How to reverse a binary tree

Question: Let us assume a  binary tree
         a
        /     \
       b       c
     /  \     /  \
    d    e    f    g
   / \  / \  / \  / \
   h  i j  k l  m  n  o

How to reverse it i.e
          a
        /     \
       c       b
     /  \     /  \
    f    g    d    e
   / \  / \  / \  / \
   l  m n  o h  i  j  k

How i should keep track of the value of a binary tree which is going to be reversed. Since when i travel through a tree i will be in left half how to swap it with left half
Answer: void reverseLevelOrder(struct node* root)
{
    int h = height(root);
    int i;
    for (i=h; i>=1; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER
        printGivenLevel(root, i);
}

/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level)
{
    if (root == NULL)
        return;
    if (level == 1)
        printf("%d ", root->data);
    else if (level > 1)
    {
        printGivenLevel(root->left, level-1);
        printGivenLevel(root->right, level-1);
    }

}
Answer: void mirror(struct node* node)
{
  if (node==NULL)
    return;
  else
  {
    struct node* temp;

    /* do the subtrees */
    mirror(node->left);
    mirror(node->right);

    /* swap the pointers in this node */
    temp        = node->left;
    node->left  = node->right;
    node->right = temp;
  }
}

How to reverse a binary tree


unable to render nested props from Github's GraphQL

Question: I am attempting to fetch some of Github's GraphQL data and display it using React & Relay. The two problems I have are that it appears relay is adding aliases to the response (making it difficult to reference), and not all the item's queried are getting passed into my component props. In the code below I can render this.props.relay.variables.name but get undefined when trying to loop over this.props.relay.variables.issues

// AppQuery.js
import Relay from 'react-relay'
export default {
  relay : Component => Relay.QL `
    query {
      relay {
        ${Component.getFragment('relay')}
      }
    }
  `
};

// AppContainer.js
import Relay from 'react-relay'
import App from './AppComponent'

export default Relay.createContainer(App, {
  initialVariables: {
    owner: "rails",
    name: "rails",
    count: 10
  },
  fragments: {
    relay: () => Relay.QL `
      fragment on Query {
        repository(owner: $owner, name: $name) {
          name
          owner
          description
          issues(first: 20) {
            edges {
              node {
                title
              }
            }
          }
        }
      }`
  }
});

//AppComponent.js
export default class App extends React.Component {
  render() {
    return (

{this.props.relay.variables.name}

          { this.props.relay.variables.issues.edges.map((issue) => {
            return(
{issue.node.title}
)
          })}

    );
  }
}

In the response preview it appears that I am successfully fetching the specified data.

But when I console log this.props some properties from the fetch are missing.
Answer: Instead of accessing the variables of the fragment you have to access the query response by using this.props.relay.repository in yout App component.
For example, to map over all issues:

  { this.props.relay.repository.issues.edges.map((issue) => {
    return(
{issue.node.title}
)
  })}

Comment: that makes sense but I am still getting `TypeError: Cannot read property 'issues' of undefined`. Could it have anything to do with my response getting aliased? `{"data":{"relay":{"_repository41jr1f":` I'm not sure why this is happening to certain properties.
Comment: do you try to access the data on the Relay container, or in the inner component? based on your output, it seems like you try to access it in the Relay container where it does not belong. The Relay container passes the data to the inner component as props, once the query has finished.


lvm over two raid1's - one slow, one fast. What will happen?

Question: Two software RAID1's,
0: 2x 15K SAS drives, 73GB
1: 2x WD Caviar Green, 3TB
So the first RAID is a faster one, the second a slower data grave. What happens when I add both to a LVM logical volume so they form one large partition?
I don't expect lvm to intelligently move more often used data to the quicker hardware... right?
Any suggestions for simple multi-tiered storage with these 4 drives?
Unanswered so far: Will the lv slow down, as in "the weakest link"? Or will it randomly slow down, with some blocks coming from fast, some from slow disks?
Comment: Not exactly what you need but using the LVM caching feature might be handy: https://rwmj.wordpress.com/2014/05/22/using-lvms-new-cache-feature/
Answer: Right. LVM is not that smart. I'm afraid that best bet at this is ZFS. But I have no idea what's the ZFS on linux code status...
Comment: Do you really need this kind of data management for root partition? If you need such speed from root, then what you describe seems as a good idea ... but then, there's no point in using ZFS. It all depends on what do you want to store on those drives and/or how do you use the computer.
Comment: For the root partition, ZFS is not really natively avail. Could be it might be smarter to make the fast/slow decisions myself, separating RAIDs, the fast one (root) an md raid, the slow one, a ZFS RAID. Good idea?
Comment: It's just a shame to "waste" a few gigs after I've got the root system and my dbs on the fast spindles. Manually allocating stuff seems the only option (I hate when it's not automagic! ;) ).
Answer: No, LVM will not magically relocate 'hot blocks' to the faster disks.
As far as I know, there is no standard and/or open-source method to do this (ZFS comes close).
You could (manually) decide on a per filesystem (or directory-tree) basis to host it on the SAS or SATA disks.
I myself have a somewhat equal setup, with the OS and databases on fast disks, and backups, logging and other less time-critical bulk data on slower sata disks.
I think there are a few experimental filesystems coming around that will do more in this area, but nothing production-ready.


map.setcenter & map.setzoom not working properly

Question: I have a left side menu bar which when someone clicks on the a link, it jumps to the marker location on the map.  This works fine.
But, I'd like to update this so that as they click the link in the left-side bar, the map centers on the marker and zooms to a certain level.  But this isn't working proplerly.
The error I'm receiving in Firebug is:
missing ) after argument list
map.setCenter(latlng:latLng);

Code:

        [[Address]]

        [[City]], [[State]] [[Zip]]

myclick = function(i) {
  google.maps.event.trigger(gmarkers[i], "click");
}

// Associate the markers with the links in the side bar.
  gmarkers[i] = marker;

// Display the info window when someone clicks on a marker or it's associated side bar link.
  google.maps.event.addListener(marker, 'click', function () {
    map.setCenter(latlng:latLng);
    map.setzoom(zoom: 16);
    InfoWindow.setContent(this.html);
    InfoWindow.open(map, this);
  });

Comment: I was able to get it working properly.  Edited the code as follows:  "map.setCenter(this.position);map.setZoom(16);".  Thanks..
Comment: I was able to get the setmapcenter and setmapzoom working properly.

But, how would I go about resetting the MapTypeID?

I tried the following code, but it's not working properly.

    map.setMapTypeId(ROADMAP);

But the map isn't changing back to the Roadmap style map and Firebug is reporting:

"ROADMAP is not defined"

Thanks..
Comment: Got this second part figured out as well:
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
Thanks..
Answer: map.setCenter() and map.setZoom() need specific arguments, and the documentation doesn't really help with its syntax.
map.setCenter() requires a LatLng object:
myLatLng=  new google.maps.LatLng(0,0);
map.setCenter(myLatLng);

map.setZoom() takes a simple integer: for example map.setZoom(16);
Colons have a particular use in object definitions, but have no place here. This is what is causing your error message.
Additional issue: what is latLng here...?
map.setCenter(latlng:latLng);
That will need to be defined somewhere. Perhaps you want the map centred on the marker?
map.setCenter(this.getPosition());
Comment: NB: The `.position` attribute mentioned in the OP comment is not documented. Use the documented method `.getPosition()`.


syntax error, unexpected '['

Question: hi im new to php and i have this error i don't know what is the cause and i tried to solve it but no luck ..
  here is the error
syntax error, unexpected '[' in C:\wamp\www\co\admin\modules\common\lib\classes\modules.php on line 169

here is my code
                foreach ( $parts as $part )
                {
169=>               $value = explode( "=", $part )[1];
                    $key = explode( "=", $part )[0];
                    if ( !$key )
                    {
                        continue;
                    }
                    $temp[$key] = $value;
                }

thanks in advance for your help
Answer: PHP can only subscript array elements from a variable, not from a returned value on the stack.
You need an intermediate variable or use this construct which looks like what you need...
list($key, $value) = explode('=', $part);

Now $key and $value will have the values you require. It's also shorter and nice to read :)
Comment: list is a good idea, +1!
Comment: Nice brief version. I like it!
Answer: PHP does not allow this syntax. You have to store the value from explode, then choose which part you want :
$value = explode("=", $part);
$value = $value[1];
// etc

Comment: For those landing here from google: This syntax **is** supported as of php version 5.4.
Answer: You cannot use the return value of explode() function as an array immediately. You should store it in a variable:
$value = explode("=", $part);
$value = $value[1];

Though, this feature will be introduced in PHP 6.
Answer: You need to do:
$set = explode( "=", $part );
$key = $set[0];
$value = $set[1];

Answer: foreach ( $parts as $part )
{
  $array = explode( "=", $part );
  $key = [0];
  $value = $values[1];
  if ( $key )
  {
     $temp[$key] = $value;
  }
}

You have to split it up  ... and get rid of the continue ...
Answer: You cannot use the indexer immediately after the explode function. Try something like this:
$array = explode("=", $part);
$value = $array[1];

syntax error, unexpected '['


Which is the most recommended syntax for attaching Vue object to an element?

Question: When attaching an instance of Vue to a HTML element, I can do in two ways.

By property reference, el:"#rooty"
By method call, $mount("#rooty")

I can't decide between them. Are they precisely equivalent? If one is newer or obsolete'ish, which one is recommended? Is there any other difference and in such case, what would it be?
By property reference.
const app = new Vue({
  store,
  router,
  el: "#rooty",
  ...
});//.$mount("#rooty");

By method call.
const app = new Vue({
  store,
  router,
  //el: "#rooty",
  ...
}).$mount("#rooty");

Answer: As it seems from the documentation, purpose of $mount() is to have an unmounted vue instance and mount it later. From the docs:

If a Vue instance didn't receive the el option at instantiation, it will be in "unmounted" state, without an associated DOM element. vm.$mount() can be used to manually start the mounting of an unmounted Vue instance.

I believe el:"#rooty" is just a syntactic sugar provided to users over $mount as internally $mount is used to attach an instance to HTML element. see the code below from vue repo:
export function initRender (vm: Component) {
  ...
  ...
  // bind the createElement fn to this instance
  // so that we get proper render context inside it.
  // args order: tag, data, children, needNormalization, alwaysNormalize
  // internal version is used by render functions compiled from templates
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
  if (vm.$options.el) {
    vm.$mount(vm.$options.el)
  }
}

Comment: True, I've seen that passage too. Perhaps I'm wording the question inappropriately. Should I aim at not having unmounted instances? Should I try to achieve the opposite? Does it matter? Is there any significance? What's likely to be most common? I have my opinion but it's based on C# and configurations from there.
Comment: @KonradViltersten I don't think it matters, what matters is do you have some use-case of unmounted instance where you want to mount same component on different HTML elements. I have updated my answer, it seems vue internally uses `$mount` to mount a component, `$el` is for convenience of users, as it is always easy to pass a hash.


Stopping same data to be added while reading from a file

Question: <code> public static void getContacts() throws SQLException{
 String[] splited=null;
 BufferedReader br = null;

    try {
       String sCurrentLine;
                br = new BufferedReader(new FileReader("C:\\Users\\Wijdan\\Desktop\\2016_07_09.txt"));
       while ((sCurrentLine = br.readLine()) != null) {
         String checkSql = "select count(*) from contacts where Name = '"+name+"' and Phone='"+age+"'";

    Statement st = con.createStatement();
     ResultSet result = st.executeQuery(checkSql);
   result.next();

      splited = sCurrentLine.split(":");
     name=splited[0];
     age=splited[1];
     String sql="Insert into contacts(Name,Phone) values('"+name+"','"+age+"')";
   pst=con.prepareStatement(sql);

  pst.executeUpdate();

   String pp=splited[0];
    String pp1=splited[1];

        }
     } catch (IOException e) {
        e.printStackTrace();
     } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
                    }
    }

       }
</code>
I have a method which reads Phone contacts from a file and saves data in database, how to stop repeating contacts from saving if there are some? and move to the next contact.
Answer: One solution would be to set a unique constraint on the field you don't want to see duplicated
<code>ALTER TABLE contacts
ADD CONSTRAINT contact_unique_name_phone UNIQUE (Name,Phone)
</code>
Then catching SQLIntegrityConstraintViolationException
Yout while loop would become something like:
<code>    while ((sCurrentLine = br.readLine()) != null) {
        try {
        // your code

        } catch(SQLIntegrityConstraintViolationException e){
            sCurrentLine = br.readLine();
        }
    }
</code>


Usar função de arquivo externo sem dar include

Question: Tenho uma função getHeader() no arquivo include.php.
É possível chamar essa respectiva função no meu arquivo index.php sem precisar dar um include, parecido com o Wordpress?
Comment: Não sei se entendi. Você quer chamar uma função que está em um arquivo sem nunca incluir/carregar esse arquivo?
Answer: Não é possível devido à tabela de símbolos.
Tabela de símbolos
A tabela de símbolos define o contexto nas linguagens de programação. Variáveis, funções, classes, objetos, constantes, etc terão uma referência armazenada na tabela de símbolos quando definidas e, dentro de um contexto, só é possível utilizar os itens referenciados na tabela.
Contexto de variáveis
Não fez sentido? Vejamos um exemplo.
$x = "Variável X";
$y = "Variável Y";

function myFunction ()
{
  return "Função myFunction";
}

No arquivo index.php definimos duas variáveis e uma função. Podemos verificar a tabela de símbolos referente às variáveis utilizando a função get_defined_vars:
print_r(get_defined_vars());

O retorno será algo como:
Array
(
    [_GET] => Array
        (
        )

    [_POST] => Array
        (
        )

    [_COOKIE] => Array
        (
        )

    [_FILES] => Array
        (
        )

    ...

    [x] => Variável X
    [y] => Variável Y
)

Perceba que todas as variáveis de escopo global do PHP também são retornadas, pois, pertencendo ao escopo global, estarão presentes em todas as tabelas de símbolos, independente do contexto. Para fins didáticos, vamos remover as variáveis globais, de forma a exibir apenas as variáveis que declaramos:
$_globals = get_defined_vars();

$x = "Variável X";
$y = "Variável Y";

...

print_r(array_diff(get_defined_vars(), $_globals));

Neste caso, a saída será apenas:
Array
(
    [x] => Variável X
    [y] => Variável Y
)

Ou seja, as variáveis $x e $y pertencem ao contexto atual e, por isso, são definidas na tabela de símbolos. Agora, se alterarmos o contexto, por exemplo, chamando uma função e verificarmos a tabela de símbolos do novo contexto:
$_globals = get_defined_vars();

$x = "Variável X";
$y = "Variável Y";

function myFunction ()
{
  global $_globals;
  print_r(array_diff(get_defined_vars(), $_globals));
  return "Função myFunction";
}

O retorno será uma lista vazia. Isso porque as variáveis não fazem mais parte do contexto.
Array
(
)

Se definirmos uma variável interna à função:
function myFunction ()
{
  global $_globals;
  $z = "Variável Z";
  print_r(array_diff(get_defined_vars(), $_globals));
  return "Função myFunction";
}

O resultado será:
Array
(
    [z] => Variável Z
)

Pois $z é a única variável existente no contexto atual. Saindo da função, ao verificarmos novamente a tabela de símbolos, teremos o mesmo resultado que no início, com as variáveis $x e $y, pois retornamos ao mesmo contexto. A variável $z deixa de existir por ela era uma variável local à função e só existirá dentro do contexto da mesma.
Contexto de funções
Se fizermos a mesma análise, mas agora verificando as funções existentes no contexto, através da função get_defined_functions, veremos para o contexto do arquivo:
$x = "Variável X";
$y = "Variável Y";

function myFunction ()
{
  return "Função myFunction";
}

print_r(get_defined_functions());

Temos a saída:
Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
                ...
            [1074] => xmlwriter_output_memory
            [1075] => xmlwriter_flush
            [1076] => dl
            [1077] => cli_set_process_title
            [1078] => cli_get_process_title
        )

    [user] => Array
        (
            [0] => handle_fatal
            [1] => output
            [2] => error_handler
            [3] => myFunction
        )
)

O que nos interessa é a parte final, identificado pelo índice user, onde encontra-se a função myFunction, que definimos no programa. Se verificarmos agora a tabela de símbolos para as funções dentro da função:
$x = "Variável X";
$y = "Variável Y";

function myFunction ()
{
  print_r(get_defined_functions());
  return "Função myFunction";
}

O resultado será exatamente o mesmo. Isso se dá ao fato que em PHP as funções pertencem ao escopo global, existindo em qualquer parte do programa, uma vez que a mesma é definida.
Respostas
Mas por quê, então, eu não consigo fazer a chamada de uma função definida em outro arquivo sem fazer o include do mesmo?
Pelo fato que se não haver o include ao arquivo onde a função é definida, o mesmo não será executado pelo PHP e a função nunca estará definida na tabela de símbolos.
Mas estou usando o Wordpress e não preciso dar include em arquivos para chamar as funções. Por quê?
Isso se dá ao fato que o Wordpress faz o "trabalho sujo" para você. Toda a programação que você faz é em um dos arquivos do tema da ferramenta: page.php, single.php, etc. Esses arquivos não tratam a requisição HTTP diretamente. Quem faz isso é o próprio arquivo index.php do Wordpress e, neste arquivo (ou em algum outro, seguindo a linha de execução), os arquivos do tema são incluídos. Neste caso, o contexto que você está trabalhando nos arquivos do tema existem as funções que são definidas em outro arquivo, mas porque o Wordpress fez com que existissem.
Nada acontece por mágica.
Comment: doideira mesmo rsrs
Answer: Para conseguires utilizar funções de um outro ficheiro php terás de o incluir, seja utilizando include, require ou seja la o que for, tal como o wordpress o faz, podem tu não sabes é onde...
O ficheiro wp-includes/rest-api/class-wp-rest-request.php, tem a função lá criada e o wp-settings.php faz o require desse mesmo ficheiro em
require( ABSPATH . WPINC . '/rest-api/class-wp-rest-request.php' ); na linha 226...
Como vez, não é possível fazer o que tu queres
Link para código do wordpress no Github
Comment: entendi, então como não sou expert no php, muito meno no wordpress achei que ele dava um jeito de fazer um get sem include, mas como explicou ele implicitamente em algum arquivo ele faz essa configuração, é isso?
Comment: sim, desta maneira ou de outra, esses "imports" são feitos
Comment: A meu ver, o que fica melhor é a utilização de namespaces
Answer: Não, mas da para esconder.
Não há como não incluir o outro arquivo, entretanto existe como esconder ele, assim não exigindo adicionar o include(...) sempre em seu código.
Um exemplo é usar o auto_prepend_file no PHP.ini:
auto_prepend_file=C:\caminho\para\funcao.php

Isso irá fazer um require do arquivo definido (ou seja, não é "sem dar include"). Porém, o seu código estará sem qualquer tipo de include(...), por exemplo:
funcao.php
function teste(){
    return 'Isso é um teste';
}

index.php
<?php

echo teste();

Uma vez definido o auto_prepend_file=C:\caminho\para\funcao.php sempre o C:\caminho\para\funcao.php será incluído implicitamente em todas as páginas, isso vai fazer funcionar o index.php. ;)

Sempre defina caminhos absolutos, não defina como auto_prepend_file=funcao.php, pois isso vai incluir o funcao.php da mesma pasta. Logo, acessar o /www/index.php vai incluir o /www/funcao.php, mas se acessar do /www/pasta/index.php irá incluir o /www/pasta/funcao.php.
Comment: ah ta! Tipo predefinido antes só pra depois usar, no caso do linux, então seria o caminho /var/www/sistema/include ?
Comment: Sim, no linux também deve especificar todo o caminho do arquivo, `/var/www/sistema/include/arquivo.php`.


Infinite series of tangential circles?

Question: I want to show that for all $n$ there is some collection of $n + 2$ circles such that two of the circles ($A$ and $B$) are tangential to each of the remaining $n$ circles (but not to each other) and each of the $n$ circles are tangential to both $A$ and $B$ but not to any of the other $n$ circles.  My initial conception was to let $A$ and $B$ be two large circles (as large as necessary) that are extremely close to each other but not tangential.  Then we draw one circle beneath $A$ and $B$ that is tangent to both of them.  Slightly above it and in between the "AB crevice" we draw another circle.  Then slightly above that we draw another.  And so on and so forth until all the circles have been drawn.  It seems to me in an intuitive sense that we could draw an infinite number of such circles, but I can$t seem to find a rigorous mathematical expression of this idea.
Note that if this idea is simply wrong, or if you have a simpler way to approach this problem, those would be acceptable answers as well.
Comment: Isn't it simpler to have two concentric circles of close but distinct diameters and a lot of circles in between?
Comment: Maybe - honestly I'm not sure how to prove that there's an infinite number of circles you could draw in that case either.
Comment: I was under the impression that you wanted a given finite number of circles and not an infinite number? You can't get that in this manner.
Comment: Yes, sorry, a finite number `n`, but where `n` can be any value.
Comment: You might be interested in [Steiner Chains](http://en.wikipedia.org/wiki/Steiner_chain). In such a construct, the $n$ circles other than $A$ and $B$ make a tangential chain, which isn't strictly what you want, but that's easy to remedy: Make a Steiner Chain with $2n$ circles, and simply erase every other one. (I'll note that Steiner chains are usually depicted with circle $A$ inside circle $B$, but inversion can put them outside each other.)
Answer:
Can you find a collection in which the two large circles (A and B) are also disjoint (not overlapping)?

Yes. "Not overlapping" apparently means that interiors should be disjoint.
Ignoring at first the non-overlap condition, the only position of the circles where there is an easy way to construct many additional tangent circles is when $A$ and $B$ are concentric circles of an annulus (thin enough relative to its radii that more than $n$ tangent circles fit in the ring).
Inversion (http://en.wikipedia.org/wiki/Circle_inversion) in a point not on any of the circles transforms the circles to circles, preserving all relationships of tangency, non-tangency, intersection and non-intersection.  The center and radius of the inversion can be chosen to arrange that the interiors of the transformed versions of $A$ and $B$ and (I think) the other circles, are disjoint.
Comment: It doesn't matter if the small circle intersects the rest of the diagram, because inversions take circles to circles.
Comment: Can you give a simple sketch of how it looks like after the inversion?
Comment: $A$ and $B$ are required not to be tangent to each other in the original question. That's not too hard to arrange, but inverting parallel lines will not do.
Comment: Thanks [and the answer updated accordingly]. It means that the solution is essentially unique, in that one has to start with concentric circles. @Rahul
Comment: @ErelSegalHalevi, I'm not sure how to make diagrams, but to draw the picture, take two external circles A and B, then start drawing externally tangent circles between them by first drawing one (C), then another (D) externally tangent to A B and C, then another E tangent to A B and D, then F tangent to A B and E, etc.  As in Blue's comment, A and B and the odd-numbered circles one has just drawn (C and E and G and ...) are a particular example of what the end result could look like.
Answer: You could take the vertices of a $m$-agon width unit length sides as the centers of $m$ circles with radius equal to $\frac{1}{2}$, then take $A$ and $B$ as two concentric circles, with center in the center of the $m$-agon, having radii $\frac{1}{2\sin\frac{\pi}{m}}\pm\frac{1}{2}$. As pointed by @zyx, circular inversion brings this configuration into any configuration you may like more, like the one in which $A$ and $B$ are external circles with equal radii: just invert with respect to a circle centered on the incircle of the $m$-agon.
The following picture shows the $m=5$ case, for instance: $A$ and $B$ are the orange circles.

As pointed by @Blue, you can simply carry on this construction for $m=2n$ then erase the even-indexed red circles, or just invert a chain of $n$ non-touching circles inscribed in a circular annulus, as depicted below ($n=5$).
Comment: Just to make sure I understand - the black circles are before the inversion, and the red (and orange) circles are after the inversion?
Comment: @ErelSegalHalevi: yep ;)
Answer: For the $k^{th}$ small circle where $1 \le k \le n$, we first center them along the
$x$-axis at $(k-1,0)$ with some radius $r_k$ to be determined. Now pick a $R$ so large such that $\sqrt{R^2 + n^2} \le R + \frac16$.
We then center the two big circle at $(0,R)$ and $(0,-R)$ with radius $R -\frac13$.
It is clear $A$ and $B$ are disjoint from each other.
In order for the $k^{th}$ small circle to tangent to both $A$ and $B$, $r_k$ is
given by
$$\begin{align}
& r_k = \sqrt{R^2 + k^2} - \left(R-\frac13\right)\\
\implies & r_k < \sqrt{R^2 + n^2} - \left(R-\frac13\right) \le \left(R +\frac16\right) - \left(R-\frac13\right) = \frac12
\end{align}$$
This means the $n$ small circles are also disjoint from each other and yet tangent to both $A$ and $B$.

Infinite series of tangential circles?


How to align navbar items to the top?

Question: I created a navbar with an ordered list, I want to position these list items to against the top of the navbar, I tried margin-top: 0 but that didn't work.
Could anyone please help?

#widgets:hover #widgetssub {
  display: block;
}

#widgetssub {
  display: none;
}

#kabobs:hover #kabobssub {
  display: block;
}

#kabobssub {
  display: none;
}

ol {
  list-style-type: none;
}

.menu-item {
  display: inline-block;
  margin-left: 30px;
  border: 1px solid black;
  height: 40px;
  ;
  width: 100px;
  float: left;
  vertical-align: top;
  margin-top: 0px
}

.menu {
  display: flex;
  height: 40px;
  border: 1px solid black;
  justify-content: center;
}

body {
  margin: 0;
}

Home

About

        Widgets

Big Widgets

Bigger Widgets

Huge Widgets

        Kabobs

Shishkabobs

BBQ kabobs

Summer kabobs

Contact

Answer: You just need to add margin: 0 and possibly padding: 0 (depending on what you need) to the ol element:

#widgets:hover #widgetssub{
  display: block;
}
#widgetssub{
  display: none;
}

#kabobs:hover #kabobssub{
  display: block;
}
#kabobssub{
  display: none;
}
ol{
  list-style-type: none;
  padding: 0;
  margin: 0;
}
.menu-item{
  display: inline-block;
  margin-left: 30px;
  border: 1px solid black;
  height: 40px;;
  width: 100px;
  float: left;
  vertical-align: top;
  margin-top: 0px

}
.menu{
  display: flex;
  height: 40px;
  border: 1px solid black;
  justify-content: center;
}
body{
  margin: 0;
}

Home

About

      Widgets

Big Widgets

Bigger Widgets

Huge Widgets

      Kabobs

Shishkabobs

BBQ kabobs

Summer kabobs

Contact

Comment: if this answer help you, you should accept this answer @Chenius
Comment: @Chenius Yes i have checked, Its just for helping the answerer so that they can gain some reputation :)
Comment: @Zuber I did, I checked the tick, it is green
Answer: You need to remove margin of ol. just add this css
.menu ol {
  margin-top: 0;
  margin-bottom: 0;
}

Answer: Add margin: 0; to the
 tag

 #widgets:hover #widgetssub{
  display: block;
}
#widgetssub{
  display: none;
}

#kabobs:hover #kabobssub{
  display: block;
}
#kabobssub{
  display: none;
}
ol{
  list-style-type: none;
  margin: 0;
}
.menu-item{
  display: inline-block;
  margin-left: 30px;
  border: 1px solid black;
  height: 40px;;
  width: 100px;
  float: left;
  vertical-align: top;
  margin-top: 0px

}
.menu{
  display: flex;
  height: 40px;
  border: 1px solid black;
  justify-content: center;
}
body{
  margin: 0;
}

Home

About

      Widgets

Big Widgets

Bigger Widgets

Huge Widgets

      Kabobs

Shishkabobs

BBQ kabobs

Summer kabobs

Contact

Answer: I just solved the same problem for my website navbar.
When the element locates at low point, use margin-top=0, padding-top=0 will let you move the element to top of its own container. But in many cases like my case, this tip does not help because by default alignment it already starts low position.
To push the element upwards within its parents' container, have to use margin-top= -40px; for my navbar
Below code is the ul when I forced its margin top and padding top of zeros (Bootstrap 4 syntax mt-0, pt-0; or equivalently CSS syntax style="margin-top: 0px; padding-top:0px").
But this way did not move the ul upwards from its default alignment, i.e. at mid height of the navbar. I want to have the ul the same height level as the top edge of the yellow logo block

Home

Below code is when margin-top=-40px is applied to the ul. Now the ul is the same  level with the top edge of the yellow logo block

Home

How to align navbar items to the top?


Colocar na função o Required

Question: Quero que a caixa de texto seja obrigatória de forma a ter de a preencher, conseguem ajudar?

Please input a number between 1 and 10:

        <input id="numb">

        <button type="button" onclick="myFunction()">Submit </button>

Answer: No seu

Com isso, caso o Input esteja OK, ele engatilha o submit do seu formulário.
Comment: Agradeço a sua ajuda! Um muito obrigado!
Comment: Se esta respota te ajudou, você poderia marca-la como correta! Caso contrátio, se não tiver conseguido, podemos continuar tentando te ajudar.
Answer: Olá, tudo bem?
Não sei se entendi muito bem sua pergunta, mas vamos lá.
Obs.: tomei a liberdade de fazer algumas alterações no código.

Please input a number between 1 and 10:

        <input id="numb">

        <button type="button" onclick="myFunction()">Submit </button>

Answer: Utilizando o próprio HTML dá para validar seu formulário cara basta colocar REQUIRED no seu campo input, segue um link bom para você entender e facilitar sua vida, economizando tempo ao invés de criar scripts http://wbruno.com.br/html/validando-formularios-apenas-com-html5/
Answer: Assim fica bem mais fácil, deve te ajudar:
<!DOCTYPE html>

    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/style.css" rel="stylesheet">

    <form action="">

Please input a number between 1 and 10:

        <input id="numb" type="number" max="10" min="1" required name="teste">

        <button type="submit">Submit </button>

    </form>

Observe que eu coloquei a propriedade max e min no input, isso já valida pra você o intervalo dos números que você quer que seja permitido dentro do input.
Comment: Funcionou desta forma também! Desconhecia essa propriedade, muito obrigado!
Comment: De nada @RicreedM. Depois acesse esse link: [O que eu devo fazer se alguém responder minha pergunta?](https://pt.stackoverflow.com/help/someone-answers) e dê uma lida

Colocar na função o Required


Is it ok to keep a very strong predictor and other weak predictors in the model? The model built is GBM

Question: Age is coming out as a really strong predictor compared to other variables. This is a classification problem, the dependent variable is a (0/1)
Comment: So age is the major determinant of the outcome? What's the problem?
Answer: Hard to know exactly without knowing what kind of model you're using, but it would be worth repeating the model without age to see what you get. It could be that you're missing important correlations by adjusting for age. Collider bias is one potential issue here.
I would report univariable correlations and a multivariable model in this case.
Comment: OP is estimating a Gradient Boosting algorithm it seems so may not be predominantly interested in consistent estimates of some coefficient, but you're right that some context would be helpful
Comment: I assumed they were just running some multivariable logistic regression to predict the 0/1 dependent variable
Comment: Yes, I'm using gradient boosting algorithm to classify, building a look-alike model. When I look at the feature importance plot the age variable just overshadows all other variables. I'm not sure if it is right using a such a strong predictor, would it over shadow any other variable? I am getting a good AUC of 0.787.. Please let me know if you need any other details.


Normal distribution for discrete values

Question: I understand that a normal distribution is a continuous distribution, but I came across this question in my test set that baffles me.
Question:
The toy cars produced in a factory have an average weight of 20 lb. The standard deviation of the individual toy cars is 3 lb. We know the weights of each toy car follow a normal distribution. Compute the proportion of 200 toy cars that weigh 14 lb each.
Comment: This is not a very well-worded question, but it is not your fault! The key thing is whether weight is rounded. If it is, then I think your solution is sound. If not, then think about what exactly a "continuous" distribution means.
Comment: Is this the exact question? Or was it "at least 14 lb"? or something like that?
Comment: This was the exact question. And hence why im confused. I'm thinking i should do a P(13.5<x<14.5) but im not 100% sure
Answer: Taking the question at face value, the answer is zero.
The area under the standard normal density curve at any single point is the area of a line segment, which is always zero.

Normal distribution for discrete values


Homoscedasticity Assumption in Linear Regression vs. Concept of Studentized Residuals

Question: Having read about studentized residuals I do not understand how the idea of different residual variances conditional on certain values of a predictor $X$ (as implied by the concept of studentized residuals) is not inherently conflicting with the assumption of homoscedasticity in linear regression models with a single predictor variable.
It says in my textbook that the assumption of homoscedasticity means that the variance of $Y$ (dependent variable) conditional on $X = x$ (a certain realization of the independent predictor variable) is constant across the value range of this predictor. This conditional variance, it says, is also equal to the conditional variance of the residual variable $\varepsilon$ for a given $x$. To my understanding this is a statement at the population level. Together that would be:
$Var(Y|X) = Var(\varepsilon|X) = \sigma^2_\varepsilon$
Later the book deals with the detection of outliers in the dependent variable and suggests using standardized and studentized residuals. A standardized residual is an individual residual $\varepsilon_i$ divided by the estimated standard deviation $\hat\sigma_\varepsilon$ of the residual variable in the population. In the case of the standardized residual each residual $\varepsilon_i$ is thus standardized using the same constant value $\hat\sigma_\varepsilon$ if homoscedasticity can be assumed:
$Stand.Res_i = \frac{\varepsilon_i}{\hat\sigma_\varepsilon}$.
However, in the next paragraph the studentized residual is introduced. The book says: "It can be shown that the precision of the estimation of the residuals increases with the distance of $x_i$ from its mean $\bar x$. In the case of the studentized residual, residuals are not divided by their overall estimated standard error but by the estimated standard deviation of the residuals at the location $x_i$. This standard deviation can be obtained from this formula:
$Student.Res_i = \frac{\varepsilon_i }{\hat\sigma_\varepsilon \cdot \sqrt {1-h_i}} $
with $h_i$ being the leverage score of a (in this simple case: singular) predictor $x_i$. So it seems to me that in this case the residuals are not all divided by the same constant value (like they were in the case of the standardized residual) but instead there is now a distribution of residual standard errors that depends on the leverage values. These leverage values are larger at the extreme ends of the predictor variable as has been explained in other questions on this site. On Wikipedia (https://en.wikipedia.org/wiki/Errors_and_residuals#Regressions) it says:

In regression analysis, the distinction between errors and residuals is subtle and important, and leads to the concept of studentized residuals. Given an unobservable function that relates the independent variable to the dependent variable – say, a line – the deviations of the dependent variable observations from this function are the unobservable errors. If one runs a regression on some data, then the deviations of the dependent variable observations from the fitted function are the residuals. [...] However, because of the behavior of the process of regression, the distributions of residuals at different data points (of the input variable) may vary even if the errors themselves are identically distributed. Concretely, in a linear regression where the errors are identically distributed, the variability of residuals of inputs in the middle of the domain will be higher than the variability of residuals at the ends of the domain[citation needed]: linear regressions fit endpoints better than the middle. This is also reflected in the influence functions of various data points on the regression coefficients: endpoints have more influence.

While this makes sense to me intuitively I don't quite understand how it doesn't contradict the assumption of homoscedasticity. Is this because at the population level the error variance can be equal for all levels of $X$ but when we estimate that error variance by fitting a regression line (so that we can then use the residuals as estimates of the errors at population level) we automatically and artificially create a distribution of residual standard deviations conditional on $X$ instead of having that residual standard deviation be the equal singular value for every residual? So that would mean that the standardized residual is only really useful at the (unobservable) population level, right? Because for a given sample the standardized residual can impossibly be an accurate estimator for all values $x_i$ that are far from $\bar x$ simply due to the way that the regression model is fitted?
However, if that were the case I don't understand the recommendation that I have read in so many places to test for homoscedasticity by plotting the studentized residuals against the predictor variable and testing if the variance of the residuals will be equal at all levels of $X$. If in a fitted regression line the variance of residuals can be different for different levels of $X$ (as I think the concept of the studentized residual and that excerpt from Wikipedia imply) how does it make sense that everybody recommends testing the equality of residual variances across $X$ by using the scatterplots of studentized residuals against the level of the predictor $X$? Can somebody please point out what mistakes I am making here?
Do I mix up error and residual values or population and sample levels? I have been looking everywhere and couldn't find a satisfying answer that discussed why this is not a conflict (or at least none that I understood). Thank you so much in advance!
Answer: I do not really understand your confusion, but let me give this a try. Consider a linear regression
$$
y=X\beta+\varepsilon
$$
with errors $\varepsilon$ and residuals $e:=y-X\hat\beta=(I-H)y$ where $I$ is an identity matrix and $H:=X(X^\top X)^{-1}X^\top$ is the hat matrix. Suppose the linear model is correctly specified and all the assumptions, including unconditional and conditional homoskedasticity of errors, are met.
While $\varepsilon$ are homoskedastic by the assumption I just introduced, the model residuals $e$ are conditionally heteroskedastic w.r.t the level of $X$: their variance can be shown to be $\text{Var}(e)=\sigma^2_\varepsilon(I-H)$. This is an artifact of OLS estimation in a linear model.
Now suppose you do not know whether all of the assumptions are met (which is the realistic perspective) and you would like to check them. You would perhaps be tempted to use the residuals $e$ in place of the unobserved errors $\varepsilon$ to do model diagnostics, e.g. assess the assumption of conditional homoskedasticity of $\varepsilon$. Unfortunately, a conditionally homoskedastic $\varepsilon$ translates into a conditionally heteroskedastic $e$ as evidenced by the variance formula above. Thus you cannot learn much about the conditional homoskedasticity of $\varepsilon$ by inspecting the variability in $e$ vs. $X$.
But there is a remedy. You can adjust for the variance distortion in $e$ by "undoing" the scaling due to multiplication by $(I-H)$ in $e$. This results in (internally or externally) studentized residuals $\tilde{e}_{int}:=\frac{e}{\hat\sigma_{int}\sqrt{1-h_{ii}}}$ or $\tilde{e}_{ext}:=\frac{e}{\hat\sigma_{ext}\sqrt{1-h_{ii}}}$ where $\hat\sigma_{int}$ and $\hat\sigma_{ext}$ are internal and external estimates of error variance, respectively. Studentization of residuals allows putting the residuals back to the same level of conditional variance as the unobserved model errors $\varepsilon$ are, up to a scaling factor that is uniform across the data points and thus does not affect conditional homo- or heteroskedasticity.
This is why it makes sense to use studentized residuals $\tilde{e}$ in place of raw residuals $e$ when assessing conditional heteroskedasticity of the model errors $\varepsilon$ w.r.t. to the regressor $X$.


Override Profile2 with account fields and values

Question: I have created a new Profile Type with Profile2 module. Now I want to override it, importing three existing fields from my original Account (First Name, Last Name, Email) with their own values (that have already been set in the registration process).
I think I must try copying profile2.tpl.php on my theme page, but no changes seems to happen. Any idea about how to do it?
Comment: I am not clear with your requirement. Why do you mention using profile2.tpl.php?..You just want this for a display purpose or you want those fields in the profile you created to actually hold the corresponding values from user registration form?
Comment: I need to repeat those fields in my new Profile Type, so the user can see and change their values, if they want.
Answer: Profile2 modules gives profile entity apart from we have in default as user.I am not putting the codes , but here is my idea,

manually add those three fields to the profile you have created.
loop through all users, load their profile, I guess you can use profile2_load_by_user() to load the profile inside the loop
Check if you are getting the added fields in the loaded profile object.
Map the fields on user entity to profile entity.
save the profile using profile2_save() 5.
Delete the fields from user entity, once you ensure mapping is in the way you want.

NOTE: function listed may need a replacement,as I have not tested the workflow.


How do we prevent/discourage users to keep editing question/answer for no reason?

Question: First of all, is this the right place to post these kind of questions?
It's been few times I have seen some users are editing the question or answer for no reason.
Even though you reject them, someone else will accept them eventually and that is what they want to take advantage of loop hole.
I might be the one not getting/seeing this thing right, but I want to raise the issue here.
Take a look: https://magento.stackexchange.com/posts/98079/revisions
Comment: I think this editing is for +2 rep.
Comment: If the "edit" button on this post wasn't greyed out I'd edit it to fix your grammar
Answer:
First of all, is this the right place to post these kind of qsts?

Yes. What you can do is flag one of these questions for moderator attention and explain the issue in the "other" text field. The mods have the possibility to take action and should decide if there is need to. There's nothing more you as a user can do, except raising the issue here, as you did, to remind people not to approve edits carelessly.
Answer: Its good that you have reported this.
Stackexchange has a number of self correction mechanisms to prevent such behaviour. It seems we found a weakness here.
Probably after flagging the post for Moderator attention, he will fast see they try to game the system and is able to handle this.
In this case the moderators should think about escalating the issue behind this to the main plattform, as it may be solveable for the future via improvement of the detection mechanics
Comment: Your third point is good one and we need to do that (I mean our moderators).
Answer: There is nothing wrong with someone submitting a tag edit. I would suggest you approach the particular user in SE chat and ask them what their rationale is. IIRC you have the ability to reject the change on a question that you personally asked, so go ahead and reject if you feel it was an unnecessary addition.
Comment: Correct me if I am wrong. In above link the user added tag and later removed the same one. I believe you could get double points by doing this.
Comment: No. This kind of forgery would be caught by the moderation platform
Comment: You may not be able to get extra points using this technique, but I thought that the activity on the question would allow the question to remain higher up on the initial questions list page, at least if it is being sorted by Activity.  Although less egregious than attempting to scrape underserved rep points, it could still represent a  way to (albeit in a minor impact sort of way) game the system and keep a question higher up on the page and thus get more eyeballs and potentially more up votes.
Answer: Having started to become more active on Magento StackExchange from being a regular contributor at Stackoverflow I can say for a fact that the quality of the content on this site is terrible. I often see posts that have not been proof read, have terrible English or are riddled with grammatical errors, or are covered with seemingly random formatting (bold and code blocks) which appear to be trying to emphasize certain points.
If users want to take time to improve the quality of this site, let them. If they don't have enough reputation to do it without having their edits reviewed, that's why the higher rep users review them. There's probably more of a problem in that mid-rep users (1-5k often) tend to blast through a review queue and accept or decline something without paying any attention to what it's doing, in which case seeing a very minor edit might appear to some as not worthy of approval. These users often do this to achieve badges.
At the end of the day, +2 reputation for an edit that improves the quality of a post is well spent.
Now: the context of that particular revision that you've linked to is obviously a waste of everyone's time.


NTP can't synchronise or find a suitable server

Question: The problem I'm trying to solve is that NTP won't synchronize:
<code>$ sudo ntpstat
unsynchronised
  time server re-starting
   polling server every 64 s
</code>
Edit: Here's some ntpq output:
<code>$ sudo ntpq -c peers
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 ntp.eecs.wsu.ed .INIT.          16 u    -   64    0    0.000    0.000   0.000
 188.8.131.52   .INIT.          16 u    -   64    0    0.000    0.000   0.000
 ntp4.vps.net    .INIT.          16 u    -   64    0    0.000    0.000   0.000
 mercury.z0p.org .INIT.          16 u    -   64    0    0.000    0.000   0.000
 li506-17.member .INIT.          16 u    -   64    0    0.000    0.000   0.000
 184.108.40.206     .INIT.          16 u    -   64    0    0.000    0.000   0.000
 ntp1.ResComp.Be .INIT.          16 u    -   64    0    0.000    0.000   0.000
</code>
I have the default RHEL6 /etc/ntp.conf configuration. Servers bit:
<code>server 0.rhel.pool.ntp.org
server 1.rhel.pool.ntp.org
server 2.rhel.pool.ntp.org
</code>
When I stop ntpd and try to run ntpdate manually, I get a "no server suitable for synchronization found" for all of those servers. Here's ntpdate with debug output:
<code>$ ntpdate -dq 1.rhel.pool.ntp.org
10 May 10:02:42 ntpdate[13320]: ntpdate firstname.lastname@example.com Thu May 13 14:38:25 UTC 2010 (1)
Looking for host 1.rhel.pool.ntp.org and service ntp
host found : caprica.willglynn.com
transmit(126.96.36.199)
transmit(220.127.116.11)
transmit(188.8.131.52)
transmit(220.127.116.11)
transmit(126.96.36.199)
transmit(126.96.36.199)
transmit(22.214.171.124)
transmit(22.214.171.124)
transmit(184.108.40.206)
transmit(18.104.22.168)
transmit(220.127.116.11)
transmit(184.108.40.206)
transmit(184.108.40.206)
transmit(18.104.22.168)
transmit(126.96.36.199)
transmit(18.104.22.168)
transmit(188.8.131.52)
transmit(22.214.171.124)
transmit(18.104.22.168)
transmit(22.214.171.124)
184.108.40.206: Server dropped: no data
126.96.36.199: Server dropped: no data
184.108.40.206: Server dropped: no data
184.108.40.206: Server dropped: no data
server 188.8.131.52, port 123
stratum 0, precision 0, leap 00, trust 000
refid [220.127.116.11], delay 0.00000, dispersion 64.00000
transmitted 4, in filter 4
reference time:    00000000.00000000  Thu, Feb  7 2036  1:28:16.000
originate timestamp: 00000000.00000000  Thu, Feb  7 2036  1:28:16.000
transmit timestamp:  d5377c86.25dd5f5a  Fri, May 10 2013 10:02:46.147
filter delay:  0.00000  0.00000  0.00000  0.00000
         0.00000  0.00000  0.00000  0.00000
filter offset: 0.000000 0.000000 0.000000 0.000000
         0.000000 0.000000 0.000000 0.000000
delay 0.00000, dispersion 64.00000
offset 0.000000

server 220.127.116.11, port 123
stratum 0, precision 0, leap 00, trust 000
refid [126.96.36.199], delay 0.00000, dispersion 64.00000
transmitted 4, in filter 4
reference time:    00000000.00000000  Thu, Feb  7 2036  1:28:16.000
originate timestamp: 00000000.00000000  Thu, Feb  7 2036  1:28:16.000
transmit timestamp:  d5377c86.591061f7  Fri, May 10 2013 10:02:46.347
filter delay:  0.00000  0.00000  0.00000  0.00000
         0.00000  0.00000  0.00000  0.00000
filter offset: 0.000000 0.000000 0.000000 0.000000
         0.000000 0.000000 0.000000 0.000000
delay 0.00000, dispersion 64.00000
offset 0.000000

server 188.8.131.52, port 123
stratum 0, precision 0, leap 00, trust 000
refid [22.214.171.124], delay 0.00000, dispersion 64.00000
transmitted 4, in filter 4
reference time:    00000000.00000000  Thu, Feb  7 2036  1:28:16.000
originate timestamp: 00000000.00000000  Thu, Feb  7 2036  1:28:16.000
transmit timestamp:  d5377c86.8c427d35  Fri, May 10 2013 10:02:46.547
filter delay:  0.00000  0.00000  0.00000  0.00000
         0.00000  0.00000  0.00000  0.00000
filter offset: 0.000000 0.000000 0.000000 0.000000
         0.000000 0.000000 0.000000 0.000000
delay 0.00000, dispersion 64.00000
offset 0.000000

server 126.96.36.199, port 123
stratum 0, precision 0, leap 00, trust 000
refid [22.214.171.124], delay 0.00000, dispersion 64.00000
transmitted 4, in filter 4
reference time:    00000000.00000000  Thu, Feb  7 2036  1:28:16.000
originate timestamp: 00000000.00000000  Thu, Feb  7 2036  1:28:16.000
transmit timestamp:  d5377c86.bf762a87  Fri, May 10 2013 10:02:46.747
filter delay:  0.00000  0.00000  0.00000  0.00000
         0.00000  0.00000  0.00000  0.00000
filter offset: 0.000000 0.000000 0.000000 0.000000
         0.000000 0.000000 0.000000 0.000000
delay 0.00000, dispersion 64.00000
offset 0.000000

10 May 10:02:47 ntpdate[13320]: no server suitable for synchronization found
</code>
I can ping some of the NTP servers the pool directs me to:
<code>$ ping caprica.willglynn.com
PING caprica.willglynn.com (126.96.36.199) 56(84) bytes of data.
64 bytes from caprica.willglynn.com (18.104.22.168): icmp_seq=1 ttl=52 time=60.2 ms
64 bytes from caprica.willglynn.com (188.8.131.52): icmp_seq=2 ttl=52 time=59.6 ms
64 bytes from caprica.willglynn.com (22.214.171.124): icmp_seq=3 ttl=52 time=59.9 ms
64 bytes from caprica.willglynn.com (184.108.40.206): icmp_seq=4 ttl=52 time=59.8 ms
</code>
Netstat for port 123:
<code>$ netstat -ano|grep 123
udp        0      0 10.0.116.6:123              0.0.0.0:*                               off (0.00/0/0)
udp        0      0 127.0.0.1:123               0.0.0.0:*                               off (0.00/0/0)
udp        0      0 0.0.0.0:123                 0.0.0.0:*                               off (0.00/0/0)
udp        0      0 :::123                      :::*                                    off (0.00/0/0)
</code>
iptables and ip6tables are off, but there is an external firewall that should have port 123 open for UDP.
Comment: Your client is not able to reach the NTP server.. It may be because of many issues.. Is there a firewall that is preventing the access?.. This would be my likely guess...
Comment: can you close this question so people dont waste their time trying to answer open questions?
Comment: "external firewall that should have port 123 open.." to me means you haven't verified and confirmed there are no weird NAT/access rules in place on the external firewall preventing communication. From my point of view, the evidence looks like it points to a firewall/connectivity issue.
Comment: It turned out to be a corporate firewall issue between the zone the server was in and the rest of the internet. I have now been able to run ntpdate manually, and I'm assuming ntpd will start working shortly.
Answer: Make sure there isn't an external firewall between the machine and the rest of the internet. If there is, request that the people administering the firewall open port 123.


Modify data structure of a view REST export

Question: I need to build a sitemap.xml with a REST export with a view.
By default I get this data structure with a REST export.
<?xml version="1.0"?>
  <response>
    <item key="0">
      <field1>...

How can I modify the tags of this structure? I need to get this tags.
<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
      <loc>...

These tags must be changed.
<response> > <urlset...
<item> > <url>

Do I write a custom serializer for the REST export or a specific encoder? How do I proceed?
Answer: In D8 you need to create custom serializer and encoder to alter the XML tags.

Create custom serializer
Ref :  https://gist.github.com/BERRAMOU/dd21e009eec0e3d98733e78360122892
Write custom encoder

-
namespace Drupal\custom_serializer;
use Drupal\serialization\Encoder\XmlEncoder as SerializationXMLEncoder;
use SimpleXMLElement;
 /**
 * Encodes xml API data.
 *
 * @internal
 */
class myXMLEncoder extends SerializationXMLEncoder {

  /**
   * The formats that this Encoder supports.
   *
   * @var string
   */
  protected static $format = ['myxml'];

  /**
   * {@inheritdoc}
   */
  public function getBaseEncoder() {
    $base_encoder = parent::getBaseEncoder();
    $base_encoder->setRootNodeName('jobs');
    return $base_encoder;
  }
}

Then in View under 'FORMAT' you will see both options.
After save, you should get XML with required tag.


Select specific data Google Sheets with Javascript without OATH on client side

Question: I have an  which "url" needs to be dynamically and remotely changed. I don't want to define the "src" in the  but pass it through a variable.
Therefore, I created a Google Sheets file with two cells: A1 is the title ("URL"), B1 is the actual url (eg. https://youtube.com/...) that will be manually changed from time to time.
I activated Google Sheets API.
This is the JSON:
{
  "range": "'RangeTitle'!A1:Z1000",
  "majorDimension": "ROWS",
  "values": [
    [
      "URL",
      "https://www.youtube.com/..."
    ]
  ]
}

This is the example code it provides:

    <button id="signin-button" onclick="handleSignInClick()">Sign in</button>
    <button id="signout-button" onclick="handleSignOutClick()">Sign out</button>

I filled the required fields. However, in the end, it requires the user to login to read the data. Therefore I would like to ask you:

If there is a way to read Google Sheets API data without OATH login from the users' side.
How can I pass the URL from B1 cell to the  as a variable.

Finally, I am open to another way to achieve the same result (dynamically pass the url to the  from an external source).
Comment: 1. fulfil the request via your server - i.e. a request comes from the browser to your server, and your server does the *authenticated* communication with google sheets API - 2. you stick the response in the `.src` property of that iframe
Answer: I understand that you want to use Sheets API without login from the user account. If that is correct, then you could create a service account to reach your goal. Then you could delegate domain-wide authority to the service account from the Admin console. By that way, you only have to OAuth 2.0 login from the service account and use it to access user's data. Please, ask me any additional doubt.


Find maximas and minima of time series values using SQL

Question: I have a certain set of index values that increase and decrease over time . I wish to identify the time periods during which values rise and values fall. The data looks like this:

I tried partitioning the values by the range and I definitely don't think I'm doing it right. Here's the query I wrote which at best is giving me ordered dates
SELECT
  date,
  MAX(index) OVER (PARTITION BY MAX(CAST(index AS numeric))
  ORDER BY
    date)
FROM (
  SELECT
    (value1 - value2) AS index,
    date
  FROM
    `project.dataset.table` )
GROUP BY
  date,
  index
ORDER BY
  date

My ultimate goes is that I want to implement a query that results in something like this when asked for minima values and likewise for maximas
Row |    date    |       minimas
-------------------------------------
1   | 2017-02-04 | 0.3149100257069409
2   | 2017-12-05 | 0.5784622847441183

Comment: What if two values are the same in a row?
Comment: In that case, both would have different dates and I would need both the dates.
Answer: Handling adjacent duplicate values is tricky.  You don't specify how you want these handled.  If you only want the first such value, then filtering works:
For local minima:
SELECT Row, date, f0 AS minimal
FROM (SELECT t.*,
             LEAD(f0) OVER (ORDER BY DATE) as f0_lead
      FROM (SELECT t.*,
                   LAG(f0) OVER (ORDER BY date) AS f0_lag
            FROM `project.dataset.table` t
           ) t
      WHERE f0_lag IS NULL or f0_lag <> f0
     ) t
WHERE (f0 < f0_lag or f0_lag is null) and
      (f0 < f0_lead or f0_lead is null);

Or, if you like, you can simplify the comparisons:
SELECT Row, date, f0 AS minimal
FROM (SELECT t.*,
             LEAD(f0) OVER (ORDER BY DATE) as f0_lead
      FROM (SELECT t.*,
                   LAG(f0) OVER (ORDER BY date) AS f0_lag
            FROM t
           ) t
      WHERE f0_lag IS NULL or f0 < f0_lag
     ) t
WHERE f0 < f0_lead or f0_lead is null;

Local maxima can follow the same logic with the <s changed to >s.
Here is a db<>fiddle (which uses Postgres, but that doesn't matter).
EDIT:
Returning all the minima/maxima in a row is more challenging.  The following works in BigQuery:
WITH t AS (
    SELECT 1 AS Row, '2017-01-19' AS date, 0.3904 AS f0 UNION ALL
    SELECT 2,  '2017-02-04', 0.3149 UNION ALL
    SELECT 2.5,  '2017-02-05', 0.3149 UNION ALL
    SELECT 3,  '2017-03-24', 0.3302 UNION ALL
    SELECT 4,  '2017-04-09', 0.5339 UNION ALL
    SELECT 5,  '2017-05-11', 0.7753 UNION ALL
    SELECT 6,  '2017-05-27', 0.8539 UNION ALL
    SELECT 7,  '2017-09-16', 0.8803 UNION ALL
    SELECT 7.5,  '2017-09-17', 0.8803 UNION ALL
    SELECT 7.7,  '2017-09-18', 0.8803 UNION ALL
    SELECT 8,  '2017-10-02', 0.8570 UNION ALL
    SELECT 9,  '2017-11-03', 0.7744 UNION ALL
    SELECT 10, '2017-11-19', 0.6092 UNION ALL
    SELECT 11, '2017-12-05', 0.5785
)
SELECT t.*
FROM (SELECT t.*,
             MAX(f0_lag) OVER (PARTITION BY grp) as grp_f0_lag,
             MAX(f0_lead) OVER (PARTITION BY grp) as grp_f0_lead
      FROM (SELECT t.*,
                   COUNTIF(f0_lag <> f0) OVER (ORDER BY DATE) as grp,
                   LEAD(f0) OVER (ORDER BY DATE) as f0_lead
            FROM (SELECT t.*,
                         LAG(f0) OVER (ORDER BY date) AS f0_lag
                  FROM t
                 ) t
           ) t
     ) t
WHERE (f0 < grp_f0_lag or grp_f0_lag is null) and
      (f0 < grp_f0_lead or grp_f0_lead is null) ;

Basically, this is identifies groups of adjacent values.  It then spreads the maximum lag() and lead() values through the group (for the maximum, you want to spread the minimum values).
The entire group is then treated as a unit and in the result set.
Comment: Thanks! This gives what I need. As per duplicate values in adjacent rows, the dataset is such that it's highly unlikely that it's possible.
Answer: Below is for BigQuery Standard SQL
#standardSQL
SELECT * EXCEPT(prev, next),
  CASE
    WHEN prev < next THEN 'min'
    WHEN prev > next THEN 'max'
    WHEN prev IS NULL THEN 'start'
    WHEN next IS NULL THEN 'finish'
  END extremum
FROM (
  SELECT *,
    SIGN(index - LAG(index) OVER(ORDER BY DAY)) prev,
    SIGN(LEAD(index) OVER(ORDER BY DAY) - index) next
  FROM `project.dataset.table`
)
WHERE IFNULL(prev != next, TRUE)

You can test, play with above using sample data from your question as in below example
#standardSQL
WITH `project.dataset.table` AS (
  SELECT DATE '2017-01-19' day, 0.39 index UNION ALL
  SELECT '2017-02-04', 0.31 UNION ALL
  SELECT '2017-03-24', 0.33 UNION ALL
  SELECT '2017-04-09', 0.53 UNION ALL
  SELECT '2017-05-11', 0.77 UNION ALL
  SELECT '2017-05-27', 0.85 UNION ALL
  SELECT '2017-09-16', 0.88 UNION ALL
  SELECT '2017-10-02', 0.85 UNION ALL
  SELECT '2017-11-03', 0.77 UNION ALL
  SELECT '2017-11-19', 0.61 UNION ALL
  SELECT '2017-12-05', 0.57
)
SELECT * EXCEPT(prev, next),
  CASE
    WHEN prev < next THEN 'min'
    WHEN prev > next THEN 'max'
    WHEN prev IS NULL THEN 'start'
    WHEN next IS NULL THEN 'finish'
  END extremum
FROM (
  SELECT *,
    SIGN(index - LAG(index) OVER(ORDER BY DAY)) prev,
    SIGN(LEAD(index) OVER(ORDER BY DAY) - index) next
  FROM `project.dataset.table`
)
WHERE IFNULL(prev != next, TRUE)
-- ORDER BY day

with result
Row day         index   extremum
1   2017-01-19  0.39    start
2   2017-02-04  0.31    min
3   2017-09-16  0.88    max
4   2017-12-05  0.57    finish

Answer: We can define a local minimum as being a point on an x axis of time where the response value both before and after is greater than the value at the minimum point.  In the case of an endpoint on either end, then only one value would need to be greater.  We can try using the LEAD and LAG functions here:
SELECT Row, date, f0 AS minimal
FROM
(
    SELECT Row, date, f0,
        LAG(f0, 1, f0 + 0.1) OVER (ORDER BY date) AS f0_lag,
        LEAD(f0, 1, f0 + 0.1) OVER (ORDER BY date) AS f0_lead
    FROM project.dataset.table
) t
WHERE f0 < f0_lag AND f0 < f0_lead;

Here is a demo in SQL Server using your sample data.  As I based my answer off SQL Server, as I don't have access to BigQuery, you may have to slightly tweak the syntax I used.


Expressões regulares com Java Patterns

Question: Preciso fazer um exercício da faculdade que é o seguinte:
Validar com os expressões regulares qualquer palavra que contenha exatamente dois caracteres 'a' e dois caracteres 'b' ou mais.
Fiz a seguinte expressão na classe Pattern:
Pattern pattern = Pattern.compile("a{2}b{2,}");

Esse Pattern só valida expressões que comecem com dois caracteres 'a' e posteriormente dois ou mais 'b'. Porém o exercício exige que os dois caracteres à possam estar em qualquer lugar na frase e não necessariamente no começo, assim como os caracteres 'b'.
Como faço essa expressão regular
Comment: `.*a{2}b{2,}.*` vê se serve.
Comment: Não funcionou, pois não validou a string "babba", e nesse exercicio, essa string seria válida
Answer: O que você deseja é uma verificação.
A regra diz, que contenha :

2 caracteres a
2 caracteres b ou mais

Note que no b a parte "ou mais" é irrelevante pois se tiver 2 b já é valido.
Resolução
(a.*){2}b.*b|(b.*){2}a.*a|(a.*b|b.*a){2}
Veja funcionando em REGEX101.
Explicação

(a.*){2}b.*b busca por sentenças que tenha a seguido de a, apos b seguido de b.
(b.*){2}a.*a busca por sentenças que tenha b seguido de b, apos a seguido de a.
(a.*b|b.*a){2} busca a seguido de b ou b seguido de a.
Comment: Mas caso a string seja `ccabcab` ele não identifica
Answer: Utilize um lookahead positivo.
(?=padrão)

Um lookahead permite verificar se o grupo pode ser encontrado iniciando-se na posição que se encontra, mas sem capturar nem avançar na leitura da string que está sendo analisada. Desta forma, você pode verificar se há duas condições na mesma expressão.
Por exemplo, para verificar se uma string contém pelo menos um caracter "a" e um caracter "b":
^(?=.*a).*b

Expressão regular
^[^ab]*+(?=(?:[^b]*b){2})(?:[^a]*a){2}[^a]*$

Exemplo online

Significado

^[^ab]*+ - Caracteres opcionais que não são a nem b no início da string.
(?=(?:[^b]*b){2}) - Lookahead para verificar se há duas b, mais não avança na leitura da string.
(?:[^a]*a){2}[^a]*$ - Casa exatamente dois caracteres a até o final da string, mas não mais que dois.

Código
import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "^[^ab]*+(?=(?:[^b]*b){2})(?:[^a]*a){2}[^a]*$";

String[] exemplos = new String[] {
    "---aabb+++", "---bbaa+++", "---abab+++", "---baba+++",
    "---babba++", "---bbbbbaa", "ababbb++++", "ccabcab+++",
    "----bcdbaa", "-ababd++++", "bbbaabbbbb", "bbbabbbbbb",
    "bbbaaabbbb", "baaaaaaaaa", "abbbbbbbbb", "ccacbcacbc"
};

final Pattern pattern = Pattern.compile(regex);

for (String palavra : exemplos) {
    Matcher matcher = pattern.matcher(palavra);

    if (matcher.find()) {
        System.out.println(palavra + " ✔");
    } else {
        System.out.println(palavra + " ✖");
    }
}

Resultado
---aabb+++ ✔
---bbaa+++ ✔
---abab+++ ✔
---baba+++ ✔
---babba++ ✔
---bbbbbaa ✔
ababbb++++ ✔
ccabcab+++ ✔
----bcdbaa ✔
-ababd++++ ✔
bbbaabbbbb ✔
bbbabbbbbb ✖
bbbaaabbbb ✖
baaaaaaaaa ✖
abbbbbbbbb ✖
ccacbcacbc ✔

Exemplo online
Answer: Resolvido. Utilizei o seguinte Pattern:
Pattern pattern = Pattern.compile("(bbb*ab*ab*)|(babb*ab*)|(baabb*)|(ababb*)|(aabbb*)|(abbb*ab*)");

Comment: O seu `Pattern` falha em alguns casos como `"bcdbaa"` ou `"ababd"`. Dê uma olhada na minha [resposta](http://pt.stackoverflow.com/a/186231/64560).
Answer: Tente o seguinte:
Pattern pattern = Pattern.compile("(?=^[.[^a]]*?a[.[^a]]*?a[.[^a]]*?$)^.*?b.*?b.*$");
//Use o find ou invés de matches
System.out.println(pattern.matcher("abdbbbabd").find());    //true
System.out.println(pattern.matcher("abdbbbbd").find());     //false

Answer: Tente o padrão ^((.*[^a])?[a]{2}[b]{2,}.*)$.
Explicação:
- O ^ no começo e o $ no fim da força o reconhecimento completo da string.
- O padrão (.*[^a]) evita o agrupamento de mais de dois a, e o ? permite que o [a]{2}[b]{2,} seja no começo da string.
- O padrão [a]{2}[b]{2,} faz o reconhecimento desejado.
- O padrão .* no final completa a string.
Answer: Sugiro a seguinte expressão regular:
Pattern pattern = Pattern.compile("(aa|bb)");

Veja o teste online.
Comment: Essa expressão não funcionou para o exercício, pois essa regex só valida a presença de "aa" ou "bb", e preciso validar palavras que tenham exatamente dois a em qualquer lugar da palavra e 2 ou mais b em qualquer lugar da palavra também
Comment: Tentei a seguinte regex "( a { 2 } | b { 2 , } )" mas não validou a palavra "babab"

Expressões regulares com Java Patterns


Restrict shared folder access to specific computer/IP

Question: How to configure a server [having DNS and ADS roles installed user account created/configured] to restrict its shared folder access to a specific computer in the network.
Sol-1: Solution proposed here https://superuser.com/questions/629099/how-to-block-an-ip-address-from-a-network-share doesn't work as "Windows Security Model restricts access per-user, not per-IP"
Sol-2: Another solution proposed here: https://support.managed.com/kb/a482/block-an-ip-or-ip-range-using-windows-ip-security-policy.aspx is completely blocking the connecting computer/IP as a result, specific computer (nomiated to block shared folder access) is even unable to resolve ADS user's credential when tried to logon.

More Details
Goal
We want ADS users (around 30 in numbers) on a company network to browse internet without any restrictions, download whatever they want, but prohibit upload of company data to cloud.
Situation
To satisfy this need,

Hosted a domain server with ADS setup. Call it MAIN-SERVER.
None of the users' computers are connected to internet, but they are all LANed.
No user is allowed to share a folder from his/her computer on the LAN.
We placed another server (call it NET-MACHINE) that is connected to internet and it is also connected to MAIN-SERVER (it has 2 network cards). All users who wish to browse internet can connect to NET-MACHINE through Remote Desktop using their ADS credential.

Now, users sometimes want to download something and use it on "their" computer, so there is a shared folder on NET-MACHINE, that is read-write on NET-MACHINE machine but read-only when accessed as shared folder over network.
Challenge
Users sometimes want to share data with their colleagues. So, there is a shared folder on MAIN-SERVER that is read-write for all users on network. Now, here is the interesting thing, this shared folder on MAIN-SERVER is also accessible to NET-MACHINE which we want to restrict. When a user logs in to NET-MACHINE using RDP, they shouldn't be able to access the shared folder on MAIN-SERVER.
Request

I am novice to this computer networking stuff, so please feel free
to comment if you see any other reliable approach to manage users to
restrict upload but in the same time give them complete freedom to
surf net.
How to restrict NET-MACHINE to access shared folder on MAIN-SERVER
Comment: This seems like a really silly way to go about this.  You company should be looking into Data Loss Prevention software and systems.  What happens in your setup when someone brings in a usb stick and copies all the data onto it?
Comment: Welcome to Server Fault! Questions on Server Fault must demonstrate a minimum understanding of the technology in question.  **Otherwise, the post often turns into a discussion forum**, instead of straight Q&A.  The best advice we can give you is to hire a consultant to help you out or do further research on the basics of this technology.
Comment: @tombull89 This is the *exact* reason why DLP is useless to stop intentional data leakage (well, that and/or the existence of pen and paper).  The only thing it can do to any degree is stop the accidental leakage of data.
Comment: Even better, what happens when someone brings in a camera and take a photo of their screen?
Comment: Guys! proposed setup is already implemented in one of the business premise and users are very happy as they now have unrestricted access to internet compared to previous facebook blocked/gmail blocked/dropbox blocked policies. Every user is having dual monitor, they find it easy to switch between local and remote computer screens placed side-by-side. Requesting geeks to suggest technical solutions or possibilities so that users have unrestricted internet access and company also enjoy secured environment setup.
Comment: @Cheekaleak The computer USB ports are blocked using software utilities. The mouse and keyboard connectors will PS/2.
Comment: @tombull89 Your comment is valid if the data I want to protect is some kind of business deeds with sensitive financial figures. But, consider I am doing it for a software company that wants to protect their programmers to upload their software source files to their private cloud storage (they are usually 1000+ files).
Comment: @PavanGR The short answer is that you can't stop them from making off with the source files if they want to, so I'd strongly advise that you not go down this path of making a complicated system that will ultimately do nothing but annoy your workers and make them less productive.
Answer: In response to your comment:

Your comment is valid if the data I want to protect is some kind of
  business deeds with sensitive financial figures. But, consider I am
  doing it for a software company that wants to protect their
  programmers to upload their software source files to their private
  cloud storage (they are usually 1000+ files).

and your comment in reply to Reaces:

I have gone through the link that you pointed in your answer before
  posting this question, but what i found out is Windows Security Model
  restricts access per-user, not per-IP. The post didn't help me much.
  After searching on the net, I found this,
  support.managed.com/kb/a482/… but it is completely restricting
  NET-MACHINE to access MAIN-SERVER.

Well, yes.  You don't want them to access their MAIN-SERVER files while browsing the internet.  It sounds like MAIN-SERVER is a massive dumping ground for sensitive source files.  The way to keep them from uploading files from MAIN-SERVER via NET-MACHINE is to block NET-MACHINE from talking to MAIN-SERVER, either by permissions or by IP.
I'm going to agree with Cheekaleek and the other commenters that what you want is really some kind of Data Loss Prevention Software.  (I had a friend who was working on one of those before he moved to a new company.  He unenthusiastically referred to it as "man-in-the-middle attack on your own users."  However, well.  If it's vital that your stuff not leave your premises... better than then an unenforced policy, IMHO.)
I'm also going to question your MAIN-SERVER share.  (Sorry.)  Your programmers want to share files with each other.  Forgive me, but I used to work at a small company where this wasn't the case--you are using source control, right?  I mean, I'm trying to figure out what the thousands of files they're sharing in a network share might be otherwise.  If not, you probably want to set up something like that as well.
Comment: Ofcourse, the source control is used and the scenario may not be sharing source file to each other when they have direct access from SCM. But in a day-to-day activities, think of someone wish to share a large SDK file (which she downloaded) for evaluation with another programmer..there can be any smaller file thing members quickly want to share with others in the team and doesn't have be the source file all the time. DLPs are expensive, as of now, going for it out of scope.


Como ter Appwidgets em apphibrido?

Question: Tenho uma aplicação hibrida como posso colocar widgets nativos nela ?
Answer: Para ter acesso a qualquer recurso nativo de um app híbrido você precisa de um plugin.
Como criar seus próprios plugins:
https://cordova.apache.org/docs/en/latest/guide/hybrid/plugins/
Lista de plugins Cordova: https://cordova.apache.org/plugins/
Lista de plugins que acessam recursos nativos no Ionic:
https://ionicframework.com/docs/native/

Como ter Appwidgets em apphibrido?


which of the following is better for eventhandling

Question: Ok so I'm just making a mock MVC app to get a handle on how things work
my model has some string in it (and more, but don't care at the moment)
my GUI has a bunch of radiobuttons and here is what I do
private class radioButtonEvent : Model.EventHandling.XObjectEvent{
        private List<RadioButton> myList;
        public radioButtonEvent() { }
        public override void execute(){
            foreach (RadioButton a in myList){
                if (a.Text == ((Model.InfoTree)myObj).Info){
                    a.Checked = true;
                    ((TabControl)a.Parent.Parent).SelectTab(a.Parent.Name);
                }
            }
        }
        public void setRadioList(List<RadioButton> a){
            myList = a;
        }
    }

I create one of these and add a list of all my radiobuttons then make it listen to a certain string, like so:
        radioButtonEvent locationEvent = new radioButtonEvent();
        List<RadioButton> radioList = new List<RadioButton>();
        radioList.Add(Location_Logged_Arena_radioButton);
        radioList.Add(Location_Logged_Market_radioButton);
        radioList.Add(Location_Logged_Mute_radioButton);
        radioList.Add(Location_Logged_Town_radioButton);
        radioList.Add(Location_Logged_Vault_radioButton);
        radioList.Add(Location_Logging_Home_radioButton);
        radioList.Add(Location_Logging_Select_radioButton);
        locationEvent.setRadioList(radioList);
        myModel.InformationTree.addInfoEvent(locationEvent);

one thing I should point out is that in XObjectEvent there is a method that gets inherited that handles the setting of myobj
now the two ways I've currently thought of going about having listenable strings are these:
Way 1:
    private ListenableString lstring = new ListenableString();
    public string Info{
        get
        { return lstring.Text;}
        set
        { lstring.Text = value;}

    }
    public void addInfoEvent(XEvent ev){
        lstring.addEvent(ev);
    }

and this uses the following
class ListenableString
{
    public ListenableString() { }
    private string me = "";
    private List<XEvent> Events = new List<XEvent>();
    public void addEvent(XEvent ev){
        Events.Add(ev);
    }
    public string Text{
        get
        { return me;}
        set{
            me = value;
            foreach (EventHandling.XObjectEvent x in Events){
                x.setObject(this);
                x.execute();
            }
        }
    }
}

Way 2:
    private List<XEvent> infoEvents = new List<XEvent>();
    public void addInfoEvent(XEvent ev)
    {
        infoEvents.Add(ev);
    }
    private string _Info = "";
    public string Info
    {
        get
        {
            return _Info;
        }
        set
        {
            _Info = value;
            foreach (EventHandling.XObjectEvent x in infoEvents)
            {
                x.setObject(this);
                x.execute();
            }
        }
    }

Way 3
got a better way? :)
Answer: Ye Olde New Answer
Here are some Stack Overflow questions that deal with implementing MVC in a Windows Form Application:

Implementing MVC with Windows Forms.
How would you implement MVC in a Windows Form Application?

Ye Olde Olde Answer
Use ASP.NET MVC 1.0.


Plate notation for a hierarchical regression model (bayesian)

Question: I've been recently studying hierarchical bayesian regressio (with pymc3), and I was wondering, how does the following example:
http://twiecki.github.io/blog/2014/03/17/bayesian-glms-3/
look like when shown in plate notation?
For reference, the model is defined as:
$\textrm{radon}_{i} = \alpha_{c}+\beta_{c}*floor_{i,c}+\epsilon_{c}$,
where for the final model,
$\alpha_{c} \sim \mathcal{N}(\mu_{\alpha},\sigma_{\alpha})$ and
$\beta_{c} \sim \mathcal{N}(\mu_{\beta},\sigma_{\beta})$, i.e.,
the coefficients all come from a common group distribution.
Thank you!
Comment: Would you mind copying down the model here for easy reference?
Comment: We actually just added plate notation graphs to the library and updated this very example.  See https://docs.pymc.io/notebooks/multilevel_modeling.html .
Answer: According to the comment by @colcarroll, the updated example with plate models is indeed given in:
https://docs.pymc.io/notebooks/multilevel_modeling.html

This corresponds to the PyMC3 model:
<code>with pm.Model() as hierarchical_model:
    # Hyperpriors
    mu_a = pm.Normal('mu_alpha', mu=0., sd=1)
    sigma_a = pm.HalfCauchy('sigma_alpha', beta=1)
    mu_b = pm.Normal('mu_beta', mu=0., sd=1)
    sigma_b = pm.HalfCauchy('sigma_beta', beta=1)

    # Intercept for each county, distributed around group mean mu_a
    a = pm.Normal('alpha', mu=mu_a, sd=sigma_a, shape=len(data.county.unique()))
    # Intercept for each county, distributed around group mean mu_a
    b = pm.Normal('beta', mu=mu_b, sd=sigma_b, shape=len(data.county.unique()))

    # Model error
    eps = pm.HalfCauchy('eps', beta=1)

    # Expected value
    radon_est = a[county_idx] + b[county_idx] * data.floor.values

    # Data likelihood
    y_like = pm.Normal('y_like', mu=radon_est, sd=eps, observed=data.log_radon)
</code>


how to pull parent term from nested array?

Question: I'm building a custom field and formatter in Drupal 8(and teaching myself how to use Drupal & PHP, so bear with me)
I'm not sure how to pull a parent term 'name' value from a nested array.
Right now, I've got this:
$tid = 15
$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($tid);

But I'm not sure how to get the 'name' field so I can use it in my #markup.
I used var_dump to see what was there (can't use kint at the moment. Devel caused issues with some other modules)
Here's the array that came back:
array(1) {
[3]=> object(Drupal\taxonomy\Entity\Term)#1187 (26) {
    ["values":protected]=> array(9) {
        ["tid"]=> array(1) {
            ["x-default"]=> string(1) "3"
        }

        ["vid"]=> array(1) {
            ["x-default"]=> string(10) "plant_part"
        }

        ["uuid"]=> array(1) {
            ["x-default"]=> string(36) "2xxxxxx6-5xxb-2xx5-8xx7-axxxxxxxxc"
        }

        ["langcode"]=> array(1) {
            ["x-default"]=> string(2) "en"
        }

        ["name"]=> array(1) {
            ["x-default"]=> string(11) "Term wanted"
        }

I was trying something like this, but no luck:
 $parent['values']['tid']['x-default']

Comment: Welcome to Drupal Answers! Please check my answer below. But also note, that this group is not intended to teaching you programming. ;)
Answer: If you check closely with the var_dump() output, you will see, that you actually load an array of entity objects with the type taxonomy term: https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.5.x
This object has a getter method getName() that returns the desired property:
$names = [];

foreach($parent as $term) {
  $names[] = $term->getName();
}

$names_list = implode(', ', $names);

Comment: Thank you! Sorry for asking such a generic programming question. getName() was exactly what I was missing!


Intellij IDEA: multiple goals, multiple projects, one button

Question: I find myself often running the same goals (clean install) of different, interdependent maven projects in Intellij IDEA one after another.
Does anyone know of a way to configure something like a maven goal combination, ideally such that you configure a button in IDEA's task bar that you can hit to execute these goals in sequence?  Possibly even with a keyboard short cut?
Similar things might be achieved with a maven run configuration, but then IDEA wouldn't automatically be aware of the changes the run does to the project's file system resources.
Cheers,
Johannes
Answer: Easy solution for me was to create a Run Configuration (type=Maven) per module, putting multiple goals (e.g: clean install) as cmd line for each of them, then linking them up into a chain, by adding an appropriate one under the "Before launch" section.
You can link up the last of the chain as a "Before launch" for the actual app Run.
Then you can, if required, just restart a running instance if your app which will rebuild your maven projects in order, and start the app again.
Comment: One thing to clarify - in the Before Launch section, don't choose "Run Maven Goal", choose "Run Another Configuration" and then from that list, choose the Maven Run Configuration that you want to run prior to this one.
Answer: I frequently run a clean install of my maven aggregator project from the command line while it is open in IntelliJ. In my experience the IDE seems to handle this quite well.
Comment: I do that, too, but my clean build includes a Jaxb run over a couple of xsds.  That means that a lot of Java classes (appear to) change and Intellij has to re-index them all.
Answer: when you open the MVN - 'Run Anything' appears - beside that there is a PROJECT drop down, from which you can select for which project you want to run  the maven command.


Is it possible to obtain a copy of Amazon Linux for use outside AWS

Question: How difficult (if at all possible) would it be run a copy of Amazon Linux on a private physical server or hypervisor (Virtualbox/KVM) ? (I am thinking something based in a office/home)
I realise it essentially RHEL/Centos with more up to date repositories and some minor changes but I can't help but feel many people would it find it useful to be able run their own copy for staging/development either in the office server room or on their desktops/laptops.
I have done some searches on google but can't seem to find any mention of anyone trying this.
As a follow on, if it is possible can anyone suggest some sane steps to actually doing it?
(Alternatively if this actually a really daft question and i haven't fully thought it through feel fee to pillory away) (or better yet, if you can think of an alternative - fire that off too!)
Comment: If it's essentially a repackaged RHEL/CENTOS then it's significantly GPL. So yes, he would have a license to do so. However, any Amazon specific packages may be under a different license. What he achieves is a development environment that exactly matches his intended production environment. A very valuable thing indeed.
Comment: @bahamat - exactly my reasoning along with a slight element of laziness, i'd rather put some effort into creating a process for cloning Amazon Linux, rather than expend a lot of effort repeatedly to bring CentOS up to the same state.
Comment: Do you have a license to do so? Wouldn't you miss the support for it? What do you try to achieve by doing so? What stops you from setting up your own Centos and using the same repositories?
Answer: You can use the ec2-undbundle tool to download any AMI you control. As you can make an AMI of an instance, this should be no trouble.
Comment: As a small addition incase anyone can't find the ec2-unbundle command, you have to download/install the ec2 AMI tools, the normal ec2 tools bundle does NOT contain this command.
Comment: Ah-ha, thanks, knew there would be something simplish I had missed, although this will probably lead to another question - what to do with the output of an unbundled AMI (Xen VM image?) - but i'll save that for when I get there


Is it possible to prevent multiple inheritance of specific base classes at compile time?

Question: What I am looking to do is develop two different base classes which should not be inherited together in the one derived class. Is there any way I can enforce this at compile time?
class Base1 {};
class Base2 {};
class Derived1 : public Base1 {} // OK!
class Derived2 : public Base2, public Other {} // OK!
class Derived3 : public Base1, Base2 {} // Can I force the compiler to complain?

Derived1 d1; // OK!
Derived2 d2; // OK!
Derived3 d3; // Or can I force the compiler to complain here?

I'm aware that documentation is a good idea, just wondering if it is possible.
Comment: I think having a private constructor will do the trick. But it will also disable the `Derived2` case.
Comment: Developers read documentation?
Comment: Isn't it enough to write "Don't do this!" in the documentation?
Answer: You are setting up some kind of coupling between Base1 and Base2 in that they cannot both be derived from.
You could make them both derive from Base0 in which case if you derive from Base1 and Base2 you would get the multiple inheritance diamond so you would get a compiler error assuming you do not use virtual inheritance and you do not resolve the duplication.
That might solve your problem but I question why you are trying to do this.
(Base0 should not be a totally empty class as there has to be something there ambiguous to cause the compiler to complain. And of course you could resolve it so it won't totally prevent you deriving from both, just that it will generate the required compiler "error" if you do it by mistake).
An example might be:
class Base0
{
  protected:
    virtual ~Base0(){};
    virtual void abstractMethod() const = 0;
};

class Base1 : public Base0
{
   protected:
     virtual void abstractMethod() const;

   // rest of Base1
};

class Base2 : public Base0
{
   protected:
     virtual void abstractMethod() const;

   // rest of Base1
};

class Derived : public Base1, public Base2
{
  // if I don't resolve abstractMethod it is ambiguous and the compiler will let me know
};

Comment: please give an example how you would make a compiler error show up with a common Base0 base class? doesn't seem obvious. just letting both Base1 and Base2 inherit from Base0 isn't giving any errors at all.
Comment: +1 for " I question why you are trying to do this": any programmer feeling the need to go the multiple inheritance way should know the consequences
Comment: @nyalathotep That is no reason to randomly downvote an answer from a question that is 2 years old that the user has accepted.

Just having an empty Base0 there will not cause an issue, there needs to be something there that is multiply inherited that causes the conflict.
Comment: An answer being accepted doesn't necessarily mean it's correct. And it is a reason to downvote if the answer states something which is clearly wrong. Quoting "You could make them both derive from Base0 in which case if you derive from Base1 and Base2 you would get the multiple inheritance diamond so you would get a compiler error" - you would **not** get a compiler error in that case (and never did, not even 2 years ago). Clarify that, and I will retract my downvote.
Comment: An answer being accepted might mean the user tried it and it worked for them. They probably understood that my answer had its limitations, and the purpose was to prevent someone deriving from both accidentally and not to totally block workarounds.
Answer: An interesting problem.  I found a solution that works for Microsoft (R) C/C++ Optimizing Compiler Version 18.00.31101 for x64:
#include <iostream>
#include <assert.h>
using namespace std;

class SuperBase {
public:
SuperBase():count(0) {
    cout << "SuperBase constructor..." << endl;
}
~SuperBase() {}
protected:
int count;
};
class Base1:virtual SuperBase
{
public:
Base1()
{
    SuperBase::count++;
    assert(SuperBase::count==1);
    cout << "Base1 constructor..." << endl;
}

~Base1()
{
    cout << "Base1 Destructor..." << endl;
}
};

class Base2:virtual SuperBase
{
public:
Base2()
{
    SuperBase::count++;
    assert(SuperBase::count==1);
    cout << "Base2 constructor..." << endl;
}

~Base2()
{
  cout << "Base2 Destructor..." << endl;
}
};

class Derived : public Base1, public Base2
{
public:
  Derived()
  {
  cout << "Derived constructor...."  << endl;
  }
  ~Derived()
  {
  cout << "Derived Destructor..." << endl;
   }
};

class Derived1 : public Base1
{
public:
  Derived1()
  {
  cout << "Derived1 constructor...."  << endl;
  }
  ~Derived1()
  {
  cout << "Derived1 Destructor..." << endl;
   }
};
class Derived2 : public Base2
{
public:
  Derived2()
  {
  cout << "Derived2 constructor...."  << endl;
  }
  ~Derived2()
  {
  cout << "Derived2 Destructor..." << endl;
   }
};

int main()
{
   cout << "Hello World" << endl;
   Base1 b1; Base2 b2;
   Derived1 d1;
   Derived2 d2;
   // Derived d; // - uncomment this line to get run-time error.

   return 0;
}

Comment: I think the user wanted a compile-time error not a runtime assert.
Answer: If you're now using some newer variant of C++ (not sure what you need for std::is_base_of), this might help you:
I faced a similar problem but had the luxury of constructing all possible instances of possible Derived classes through a common factory that hands out pointers to some other base class of Derived, which all possible derived classes share.
so I have this type of factory function templated on the actual derived type.
template <typename Derived>
    std::unique_ptr<Primordial_base>
    make_instance(nlohmann::json &data) {
      static_assert(
          not(std::is_base_of_v<Base1,Derived> and
std::is_base_of_v<Base2, Derived>),
         "Cant inherit from both Base1 and Base2.");

return std::make_unique<Derived>(data);
}

This is facilitated by the fact that all my classes have the same contructor arguments, namely a json type, I use N. Lohmann's library for that, but there are others.
This is not a method to strictly forbid ever deriving both Base1 and Base2 anywhere but maybe forbidding it only through this factory function is good enough for most use cases.