How to consume a web service using username?

Question: I have set up a very simple web service in another server, using plain PHP, which receives data as GET, does a database search, and retrieves a JSON string. From the server where Drupal is installed, I could get the data using CURL.
Now I need to do the same in Drupal, using username as parameter. How can I achieve this?
All I can find relates to creating web services in Drupal rather than consuming them.
Answer: OK, after a lot of research and guessing I think I've solved it, this is my solution in case anyone needs it
<code><?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use GuzzleHttp\Client;

class MyModuleController extends ControllerBase {
  protected $httpClient;

public function __construct(Client $http_client) {
  $this->httpClient = $http_client;
}

public static function create(ContainerInterface $container) {
  return new static(
    $container->get('http_client')
  );
}

public function content() {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $name = $user->get('name')->value;
  $myurl = 'http://(remote url)?doc='.$name;

  $request = $this->httpClient->request('GET',$myurl);

  if ($request->getStatusCode() == 200) {
     $datos = $request->getBody()->getContents();
     return ['#markup' => $datos,];
  }
}
}
?>
</code>
This only shows the answer as a string, now I'll have to parse it, etc, and add some security and validation.
Opinions are welcome.


jQuery last-child and insetBefore does not work

Question: My code:
$('#discussion li:last-child').insertBefore('
ciao
');

The above does not work. This erases the last
 element.
I wish it add another
 after the last

Here's a complete example
   https://jsfiddle.net/4q0eLkd1/13/
Answer: If you need to add new item after the last one last you should use $.fn.append:
$('#discussion').append('
ciao
');

This is the simplest and fastest solution. Behind the scene it will use native Node.appendChild method.
Here is a simple demonstration.

$(document).on('click', '#bott', function() {
  $('#discussion').append('
New last item
');
});

Item one

<button id="bott">click</button>
Comment: I bet you meant `$('#discussion').append('...');` ?
Answer: See this

$(document).on("click","#bott",function(){
    $('
ciao
').insertAfter("#discussion li:last-child");
});

ciao

<button id="bott">click</button>


Logging in django usig a custom formatter

Question: I'm using the following logging configurations in my code.
LOGGING = {
    'version': 1,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'stream': sys.stdout,
        }
    },
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)s- %(message)s'
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO'
    }
}

This is how I log.
logging.config.dictConfig(LOGGING)
logging.info('Hello World!')

The issue is that the format string is not being respected. How can I get the formatter to work?
Comment: What does the output look like?
Comment: ```Hello World!
```
Answer: You need to tell the handler to use your formatter.
LOGGING = {
    'version': 1,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'stream': sys.stdout,
            'formatter': 'simple',
        }
    },
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)s- %(message)s'
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO'
    }
}

>>> logging.config.dictConfig(LOGGING)
>>> logging.info('test')
INFO 2018-12-04 10:35:29,879 root.<module>:1- test

'formatter': 'simple',


How to change the number of Administration Views results in the Drupal back end?

Question: How can I change the number of list items (results), using Drupal's back end?
Is it possible to filter how many results, instead of having multiple pages of items? Something to select like 10, 50, 100, 500, ALL? Should be a simple setting, but can't find it.
I've installed Administration Views, but it's a pain since I have to adjust a dozen views, one by one.
Answer: To my knowledge, there is no such thing as a "global setting" within Drupal administration (what you call "back end") to set such "how many results".
The only way to do so (assuming you use Drupal 7), is to perform these steps for each of the individual views where you want to set "how many results" you want:

Use the Views UI to edit the view.
In the 2nd column, within Pager:

Use pager:  use the options "Display a specified number of items".
Pager options: set the "Items per page" to "how many results" you want.
Comment: Thank you Pierre, I guess I will have to live with clicking next..I have installed admin views, (and yes, it works perfectly) but with all the complexity of the site and dependencies it seems to break things up (exposed filters ect...) Is there a way to change these settings in PHP my admin?
Comment: I'm not aware of such setting in PhpMyAdmin either, sorry. Maybe create a feature request in the modules issue queue?
Comment: Hi Pierre, nope, not aware of anything actually I'm struggling to even learn about this site, I'll read the link you sent me for sure, thanks.
Comment: OK, don't worry, that's why I started to wonder (and dared to ask ...). Getting started with Drupal.SE isn't obvious I think. Especially to find out what is appropriate to ask (or answer), and what is not, and what people are expecting from newbees. Moreover there are so many thing to be aware of, to discover, etc ... Would you agree on that? BUT: it's worth learning and discovering, step by step, day by day. Because in the end it's a great Drupal resource, and community (if you can live with the things you don't like, like I do also ...)
Comment: Just 1 sample of what I mean by "learning and discovering": there seems to be a rule on any SE-site that you can only ask 30 questions during 50 days (forgot where I ever read that, but I did see it somewhere) ... I thought about it when I noticed that "you" asked 4 questions only today ...


The sum of two identical vector spaces

Question: Does the sum of two identical vector spaces, with the same dimension and basis, produces a greater vector space? or is it like in set theory, that if the two groups are the same then, the result is the same also?
Comment: can you please specify what is "vector spaces being identical", Do you mean having same dimension with same base field?? What is your notion of sum??
Comment: Depends what you mean by sum!
Comment: what are the options for ''summing''?
Comment: Basically, If you have these two spaces as subspaces of some bigger space, then you can define sum of these two spaces to be sum restricted to subspace. Another thing is if you have two vector spaces of same dimensions and same basis, you are just adding two elements of same space, then by very definition of vector space, their sum should be with in the space. So there is no point of getting bigger space. Do you really mean same basis???
Comment: lets suppose we have two vector subspaces with the same basis and dimension, and we add them up ,if it is at all possible. Do we get a larger subspace then?
Comment: well actually they do since they still have the same basis...
Comment: i have already mentioned that if you have same basis, you are going to get same space... I would rephrase my comment as :

If you have two spaces with same dimension, seem to be same at first sight (but they are different when seen as subspaces of a bigger space ) then the answer would be different. I would suggest you to look for the answer by Mr.Avitus below... I see both $\mathbb{R}$ in first co ordinate and second coordinate as same... but, they have different basis when considered as subspaces... and that makes the difference and we get a bigger space.... So, "Basis" plays a major role...
Comment: Thanks...that pretty much clarifies it..
Answer: Hint: consider two copies of $\mathbb R^2$, seen as vector spaces over $\mathbb R$. Then
$$\mathbb R\oplus \mathbb R=\mathbb R^2,$$
where the vector space on the r.h.s. is $2$-dimensional (again, over $\mathbb R$). Geometrically, you started with the $x$ and $y$-axis (i.e. the $2$ copies of $\mathbb R$) and you arrived, through the direct sum, to the real plane. A basis of the latter is given by $(1,0), (0,1)$, where $1$ denotes a basis in the corresponding copy of $\mathbb R$.
In summary, to answer to your question, the direct sum does not behave like "in set theory, that if the two groups are the same then, the result is the same also".
EDIT I used "sum" as direct sum and I considered as "same" the property of having the same dimension (for vector spaces). If the OP specified a bit more these concepts, I would modify the answer accordingly.

The sum of two identical vector spaces


In Jenkins, on a Windows remote connected through Cygwin sshd, how to run an sh pipeline step?

Question: We are porting our Jenkins pipeline to work on Windows environments.
The Jenkins' master connects to our Windows remote -named winremote- using Cygwin sshd.
As described on this page, the Remote root directory of the node is given as a plain Windows path (in this case, it is set to C:\cygwin64\home\jenkins\jenkins-slave-dir)
This minimal pipeline example:
    node("winremote")
    {
        echo "Entering Windows remote"
        sh "ls -l"
    }

fails with the error:
[Pipeline] echo
Entering Windows rmeote
[Pipeline] sh
[C:\cygwin64\home\jenkins\jenkins-slave-dir\workspace\proto-platforms] Running shell script
sh: C:\cygwin64\home\jenkins\jenkins-slave-dir\workspace\proto-platforms@tmp\durable-a739272f\script.sh: command not found

SSHing into the Windows remote, I was able to see that Jenkins actually created workspace subdirectory in C:\cygwin64\home\jenkins\jenkins-slave-dir, but it is left empty.
Is there a known way to use the sh pipeline step on such a remote ?
Answer: A PR from blatinville, that was merged a few hours after this question, solves this first issue.
Sadly, it introduces another problem, described in the ticket JENKINS-41225, with the error:
nohup: failed to run command 'sh': No such file or directory

There is a proposed PR for a quickfix of this issue.
Then there is a last problem with how the durable-task-plugin evaluate if a task is still alive using 'ps', with another PR fixing it.
Temporary solution
Until those (or equivalent) fixes are applied, one could compile a Cygwin compatible durable-task-plugin with the following commands:
git clone https://github.com/Adnn/durable-task-plugin.git -b cygwin_fixes
cd durable-task-plugin/
mvn clean install -DskipTests

Which notably generates target/durable-task.hpi file, which can be used to replace the durable-task.jpi file as installed by Jenkins in its plugins folder. It is then required to restart Jenkins.


CheckBox within an AlertDialog

Question: I have a following piece of code
   public void showAlert(final Context context) {

    mContext = context;
    AlertDialog.Builder builder = new AlertDialog.Builder(context);

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(
    Context.LAYOUT_INFLATER_SERVICE );
    View view = inflater.inflate(R.layout.alert_dialog_layout,null);
    builder.setView(view);
    final CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkBox);

    try {

        checkBox.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                      boolean isChecked) {
                        if (isChecked) {
                            Log.d(getClass().getSimpleName(), "CheckBox is
                          CHecked");
                        } else {
                            Log.d(getClass().getSimpleName(), "CheckBox is
                         Not Checked");
                        }
                        Log.d(getClass().getSimpleName(), "Inside ChecBox
                       CheckedListner");
                    }
                }
        );
    }
    catch (Exception e){
        Log.d("TAG","Exception-->"+e);
    }

    builder.setPositiveButton(PositiveButton, new
   DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

       //some code here:

       }
       });

    builder.setNegativeButton(NegativeButton, new
    DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    final AlertDialog alert = builder.create();
    alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    alert.show();
   }

Whenever someone press the CheckBox it closes the Alert Dialog, which i dont want.
Actually when user click the checkbox i have some data which will be passed to a another listener(an Interface) but my dialog is getting closed when checkbox is clicked.
Can anybody tell me how to keep the alertdialog intact even if somebody click the checkbox.
Comment: use **builder.setCancelable(false);**
Answer: Use below method while creating alert dialog.
 builder.setCancelable(false);

Answer:
Use alert.setCanceledOnTouchOutside(false).
Remove alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)

Try this:
.....
...........

final AlertDialog alert = builder.create();
alert.setCanceledOnTouchOutside(false)
alert.show();

Answer: Try this with your code just copy and paste
public void showAlert(final Context context) {

    mContext = context;
    AlertDialog.Builder builder = new AlertDialog.Builder(context);

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(
    Context.LAYOUT_INFLATER_SERVICE );
    View view = inflater.inflate(R.layout.alert_dialog_layout,null);
    builder.setView(view);
    builder.setCanceledOnTouchOutside(false);
    builder.setCancelable(false);
    final CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkBox);

    try {

        checkBox.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                      boolean isChecked) {
                        if (isChecked) {
                            Log.d(getClass().getSimpleName(), "CheckBox is
                          CHecked");
                        } else {
                            Log.d(getClass().getSimpleName(), "CheckBox is
                         Not Checked");
                        }
                        Log.d(getClass().getSimpleName(), "Inside ChecBox
                       CheckedListner");
                    }
                }
        );
    }
    catch (Exception e){
        Log.d("TAG","Exception-->"+e);
    }

    builder.setPositiveButton(PositiveButton, new
   DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

       //some code here:

       }
       });

    builder.setNegativeButton(NegativeButton, new
    DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    final AlertDialog alert = builder.create();
    alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    alert.show();
   }

CheckBox within an AlertDialog


Capturar e filtrar resultado

Question: Possuo uma string

[........]

Ola meu nome é pseudomatica (sou normal), etc. Meu nome é assim pq sim

[........]

Como faço para o conteudo da primeira
, ou seja a Ola meu nome é pseudomatica (sou normal), etc. Meu nome é assim pq sim
e desse conteúdo remover tudo que tiver entre parênteses (inclusive os parenteses) e por ultimo pegar o texto que antecede o primeiro ponto final, ficando o resultado final:
Ola meu nome é pseudomatica, etc.
Answer: Apanhar o valor do primeiro

Uma maneira prática é pegar nesse HTML e gerar um DOM do mesmo através da classe de PHP DOMDocument:
$html = '

Ola meu nome é pseudomatica (sou normal), etc. Meu nome é assim pq sim

';

$dom = new DOMDocument;
$dom->loadHTML($html);

// de todos os p, fica com o texto do primeiro
$p = $dom->getElementsByTagName('p')->item(0)->nodeValue;

// divide o texto por '.' e fica com a primeira parte
$texto = explode(".", $p)[0];

Exemplo no Ideone:
var_dump(explode(".", $p)[0]); // string(48) "Ola meu nome é pseudomatica (sou normal), etc"

Retirar parênteses e seu conteúdo
Depois, podes fazer uso de uma expressão regular para retirares o texto entre parênteses incluindo os parênteses:
$texto = explode(".", $p)[0];
$textoFinal = preg_replace("/\([^)]+\)/","", $texto);

Exemplo no Ideone:
var_dump(preg_replace("/\([^)]+\)/","", $texto));  // Ola meu nome é pseudomatica , etc

Answer: Confesso que se não fosse o exemplo de como a string deveria ficar depois de capturada e limpa teria sido quase impossível de responder.
E esses "placeholders" [....] dificultaram ainda mais.
Bom, primeiro você tem que localizar todo o texto, qualquer que seja até um ponto final:
preg_match( '/
(.*?\.).*?<\/p>/', $string, $text );

Se encontrar esse parágrafo, a variável $text terá dois índices: No primeiro tudo o que foi casado e no segundo só o que estiver dentro dos
.
Capturado, você limpa:
preg_replace( '/\s\(.*?\)/', '', $text[ 1 ] );

A limpeza é feita localizando um espaço, seguido de um abre-parêntese, com qualquer coisa dentro e um fecha-parêntese.
Localizado esse fragmento, ele é todo removido e astring resultante:
Ola meu nome é pseudomatica, etc.

O código completo:
$string = '

[........]

Ola meu nome é pseudomatica (sou normal), etc. Meu nome é assim pq sim

[........]';

if( preg_match( '/
(.*?\.).*?<\/p>/', $string, $text ) != 0 ) {

    echo preg_replace( '/\s\(.*?\)/', '', $text[ 1 ] );
}

Comment: e como posso obter uma div apartir da class que ela possui?
Comment: Isso já seria outra pergunta, mas pra não te deixar na mão, sugiro que leia [esse guia](aurelio.net/regex/guia). É simplesmente o melhor material sobre Expressões Regulares disponível em português.

Capturar e filtrar resultado


What is the limit (as a distribution) of this Fourier series, similar to that of a Dirac Delta?

Question: I know that a representation of the Dirac delta function is $\sum_{n=-\infty}^\infty e^{inx}=2 \pi \delta(x)$.
I am trying to figure out if the series with positive $n$ only $\sum_{n=0}^\infty e^{inx}$ has a simple limit as a distribution, but I cannot find any sources. The real part should be $\pi \delta(x)+\frac{1}{2}$, but what about the imaginary one?
Comment: By the way, I think your question already has an answer here https://math.stackexchange.com/a/179062/23786
Answer: I will just add a few details to the proof linked in the comment with no attempt on rigor.
As you correctly said, the real part equals
$$
\Re{ \sum_{n=0}^\infty e^{inx} } = 1+ \sum_{n=1}^\infty \cos(nx) = \pi \sum_{n=-\infty}^\infty \delta(x-2\pi n)  +\frac{1}{2}.
$$
This can be proved with the formula for the full comb.
For the imaginary part we need
$$
\sum_{n=1}^\infty \sin(nx)
$$
Using Lagrange trigonometric identities we get
$$
\sum_{n=1}^\infty \sin(nx) = \frac{1}{2} \mathrm{PV} \cot(x/2)
$$
Where the Principal Value has to be inserted to renormalize the behavior at the pole.
All in all
$$
\sum_{n=0}^\infty e^{inx} = \pi \sum_{n=-\infty}^\infty \delta(x-2\pi n) +\frac{1}{2} +i \frac{1}{2} \mathrm{PV} \cot(x/2)
$$
Answer: I'll assume you are thinking in $\mathbb R/2\pi\mathbb Z$ so that your equations are correct, and there is no need for a Dirac comb.
First off, your sum converges in the sense of distributions. Indeed, taking a (periodic) test function $\phi$, the bracket amounts to summing its positive index Fourier coefficients $\phi_n = \int_0^{2\pi}\phi(x)e^{inx}dx$. By smoothness, they decay fast, i.e. $\phi_n = O(n^{-k})$ for all non positive integer $k$ since $\phi\in\mathcal C^k$, so the sum converges.
One way of doing it is to look at the limit when $r\to1^-$ (Abel summation) of:
$$
f_r(x) = \sum_{n=0}^\infty r^ne^{inx}
$$
You recognise the geometric series:
$$
f_r(x) = \frac1{1-re^{ix}}
$$
Naively setting $r=1$ you get:
$$
f(x) = \frac1{1-e^{ix}}
$$
The issue is that it is not a well defined distribution due to the simple poles at $x=0$. You view it as the distributional limit, which is your original sum by Abel's theorem. You can explicitly calculate the limit bracket for a (periodic) test function:
$$
\langle f_r,\phi\rangle \xrightarrow{r\to1^-} 2\pi\phi(0)+\int_0^{2\pi}\frac{(\phi(x)-\phi(0))dx}{1-e^{ix}}
$$
You can also relate it to the Cauchy principal value as given in lcv's answer.
Alternatively, you can relate it to the distributional derivative of:
$$
g(x) = \sum_{n=1}^\infty \frac{e^{inx}}n = -\ln(1-e^{inx}) \\
f(x) = -ie^{-ix}g'(x)
$$
This approach agrees with the previous ones.
Hope this helps.
Comment: Nice. However one may get the impression that the real part is proportional to $2\pi\delta(x)$ (not that you ever said that). That's why I added my answer.


Gerar arquivo com JS

Question: Tenho uma consulta e monto uma string com o resultado. Até ai já tá tudo ok!
O que está me dando trabalho é encontrar uma boa forma para que quando a consulta termine e a string já esteja montada, um arquivo contendo a string seja baixado para o pc do cliente.
Comment: Talvez isso te ajude, se souber inglês no caso: https://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery
Answer: Você pode definir um elemento de âncora, , utilizando a codificação da URL para gerar seu arquivo TXT e baixá-lo. Basta você criar dinamicamente o elemento, definir o atributo href e a propriedade download com o nome do arquivo que deseja criar; após você insere no corpo da página - alguns navegadores podem bloquear o evento click se o elemento não estiver no corpo da página - e disparar o evento click do elemento, removendo-o do corpo da página ao final.
function createAndDownload(filename, text) {
  const element = document.createElement('a');

  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

Veja um exemplo:

function createAndDownload(filename, text) {
  const element = document.createElement('a');

  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}
<button onClick="createAndDownload('sopt.txt', 'Stack Overflow em Português')">Download</button>
Comment: Só pra constar display=none com click as vezes não rola (depende do navegador+dispositivo), inclusive eu propus uma solução com setTimeout e mais algumas coisas por compatibilidade e uma série de testes: https://pt.stackoverflow.com/a/217960/3635
Comment: @GuilhermeNascimento saberia dizer em qual não funciona? Lembro que quando escrevi a resposta a única *limitação* era que precisava adicionar ao DOM a âncora para poder executar o *click*.
Comment: É uma coisa que varia de versão para versão, que provavelmente hoje a maioria já se adequa bem a solução mais simples, ainda sim sempre sou sismado com devices, como mobiles (claro que iOS é o unico que não tem suporte a isso, não sei como esta no iOS12Preview), no iOS11 preciso testar com calma, hoje tem o app nativo "Files", mas não sei se ele interage com o Safari. Prometo testar com calma e lhe devolver um feedback :)

Gerar arquivo com JS


View of users having same taxonomy terms?

Question: I'm running a D7 system where every user has a skills field which is a taxonomy field.
How do I create a view to pull users where they have/share same skills (taxonomy id's) with the login user.
So for example If I've added 'photoshop' to my skills and when I login the view should provide me other user who have tagged their profiles with taxonomy term 'Photoshop'.
Note: view of users having same taxonomy term as well as login user have.
Thanks
Comment: try filter by your skill field..
Comment: @Abin you mean a contextual filter?
Comment: @Abin I cant seem to make it work .. Can you please explain which filter I need to use
Comment: sry for late rply, your view is for users right, then use the contextual filter and pass `skill value`
Comment: Another approach is try an exposed filter for **Skill Field**
Comment: you want a block or a page for that?
Comment: not too much information is presented , is it a block or page ? where is it going to be shown? you want it to load data automatically or ...
Comment: its going to be a view of users where skills (taxonomy) match with other users.
Comment: Do they all need to match?  So if I log in and am tagged with "Photoshop" and "Video Editing", do I only see other users tagged with exactly "Photoshop" and "Video Editing", or would I also see a user tagged with "Photoshop" and "Baking" because we're both tagged with "Photoshop"?
Comment: @Aaron, view should list profiles even if it has only one match. So, it should be as you said 'I also see a user tagged with "Photoshop" and "Baking" because we're both tagged with "Photoshop" '.
Answer: The right way to solve this is by writing a default argument handler.  A patch to do this was started here: https://www.drupal.org/node/721390
A "shortcut" to doing this would be to use the PHP Code default argument handler and plug it in directly.  This is not generally recommended; it would be much better to put the code in a custom default argument handler so you should Google around for how to set one of those up as that's a bit beyond the scope of this question.  But here are the steps for using the PHP Code approach and you can use the same logic for a default argument handler:

Create a view listing users
Add a contextual filter to filter on the user skills field
In the contextual filter option, for "When the filter is not in the
URL" choose "Provide a default value" and select "PHP Code" from the
list.
Assuming your field is named "field_skills", enter the following:

PHP code:
<code>global $user;
$account = user_load($user->uid);
$terms = array();
if (!empty($account->field_skills['und'])) {
  foreach ($account->field_skills['und'] as $value) {
    $terms[] = $value['tid'];
  }
}
return implode('+', $terms);
</code>

Down towards the bottom of that form there's a "more" link.  Be sure
to open that section of the form and select "Allow multiple values".

At this point, you should have the list that you want with one caveat: the currently logged-in user will show up in this list.  You probably don't want this.  To prevent that from happening add another contextual filter that excludes the current user from the list:

Add a contextual filter on the User:Uid value
Choose "Provide default value" for "When the filter is not in the
URL" and, out of that list, choose "User ID from logged in user".
Under the "more" link at the bottom, choose the "Exclude" option.
Comment: You're a life saver and it's all working. Thank you :)
Comment: is there any way I can tell how many skills are in common between two users. Like Person 'X' follow Person 'Y' as person 'y' has 2 common skills with you. thanks
Comment: I don't think PHP code or filter is needed for this to work. It can work on relationship & contextual filter.
Answer: This is so simple to create views of users having same taxonomy terms.

Add a new views of type user.
Under Filter Criteria add your term field ie skill field and select a term(photoshop) according to which you want to filter. Save the views and cheers.
Comment: thanks for your quick reply but my requirement is slightly different. I Want this view to look into 'logged in user' and match his/her skills (taxonomy) with other users therefore hard coded filter criteria wont work.
Comment: @Ozyy - You need to update your question accordingly..
Comment: @RajeevK - What I'm looking for is a view which looks looks into logged-in user and present a list of other user who share the same skills (taxonomy) as logged in user. keeping in mind that every user has as 'Term reference' field attached to their profile which they can edit. Does it make any sense?
Comment: @OzyyI got your point YES. But please edit your original question, thats what I am asking.
Comment: @RajeevK, I think my question states what I'm looking for. If you got my point than do you've a fix for my issue. Your help would be much appreciated.Thanks
Comment: @Ozyy - Frankly speaking, I don't understand your question. Contextual filter is the one you need, but you need to further explain...what do you mean by logged in users only, do you need block or page, do you have mockup for this etc?
Comment: @RajeevK, Let me take a step back and explain, I've a D7 setup where every user has a term-reference field (Users: skills_ref) attach to their profiles and very user has the ability to edit their own profile and can add 'skills'. I want a view which lists users where they have a common skill with logged in user. Hope it does make sense now
Comment: @Ozyy - Got it. Let me try to answer...though I haven't done it myself :)
Answer: This is how it should be done -

Create a views block of users.
Add a relationship for your required taxonomy vocab (in your case it's skills)
Add a contextual filter of User:uid, provide value from URL & add default argument as Userid of logged in user.
Place block on relevant page & check.

Note - I haven't done it myself or have similar exp. But logically, this should work.


Using Standard Deviation and Flipping Coins

Question: I want to create a simple project to show about ESP.
I started with the idea of guessing whether a coin would be heads or tails.
I first wanted to show some values by pure guessing.
So, using random numbers of zero (tails) or heads (one), I generated 1000 pairs of these and put them in the first two columns of a spreadsheet.  If the two values in the pair matched, I recorded it as a correct guess (a one in the third column of the spreadsheet) and if they didn't match, a zero.
I found the mean of the third column.  It was approximately 0.5.
Then I took the standard deviation of this third column also.  It's value was also close to 0.5 (about 0.49 or so).
I then took the mean plus two times the standard deviation which got me a value of about 1.5.
I did this because I was thinking this would show more than two standard deviations from the mean, which would be 95%.  My idea was if someone could guess correctly above two standard deviations from the mean, that this would suggest unusual ability better than randomly guessing.
Then I realized that, for example, if someone guessed correctly ten times, that would be an average of 1 (from 10 / 10).  But that will be less than 1.5 (the value from the mean of the random numbers plus two times their standard deviation).  It would always be impossible to guess heads/tails and get 1.5 or better.
My friend suggested that I have to take the standard deviation value divided by the square root of 1000 (the number of trials).  I don't know if this suggestion is right or not.  If I do this, double it, and add it to the mean, I get a value of about 0.55.  This suggests if a person guesses more than 55% correctly, this is above two standard deviations.  I don't know if this is the right way or not, and why.
Thanks
Answer: The whole idea about taking two or three standard deviations from the mean comes from the normal distribution and the 68–95–99.7 rule (68% of the data lies within $\pm$1 sd, 95% lies within $\pm$2 sd etc.). However the main point about such rule is not about lying some number of standard deviations from the mean, but about the probability coverage. If you want to find some the values corresponding to some given probabilities, you should look at the quantile function of binomial distribution (distribution for number of successes in $n$ trials with given probability of success $p$).
Binomial distribution does not have a closed-form quantile function, but it is often implemented in most of the popular statistical packages, e.g. in R you can calculate the 95% probability coverage region by using
qbinom(c(0.025, 0.975), 1000, 0.5)
## [1] 469 531

so if you toss a coin 1000 times, you could expect with 95% probability to see between 469 and 531 heads.
As noticed by Glen_b, since you are using quite large sample ($n=1000$), normal approximation of binomial distribution will extremely well in this case (see plot below).

It also gives you quite accurate estimates of the 95% region of the most probable number of heads in 1000 tosses:
qnorm(c(0.025, 0.975), 500, sqrt(1000*0.25))
## [1] 469.0102 530.9898
500 + c(-1, 1) * 2 * sqrt(1000*0.25) # mean -/+ 2SD
## [1] 468.3772 531.6228

However notice that this is just an approximation and in general if you don't need to use such approximations, you should rather look at the exact distribution that describes your data. It worked so well in here because the sample is large and the probability of success is not close to zero or one, but it doesn't have to be the case if those two conditions are not met.
Also notice that in real-life examples of coin tossing by different people, using different coins and experimental procedures, the results were indeed quite spread (but mostly fitted the 95% most probable region), so you should not understate the randomness -- you really should not expect to see exactly 500 heads in 1000 tosses since there is only a 0.025 probability for such event.
Answer: This simulation is a classic example of the Binomial Distribution––that is, if we assume each guess is independent and identical, then a purely random guesser would get $X$ guesses correct, where $X\sim Bin(n,p)$  with $n= 1000$ and $p = 0.5$.
According to the Binomial Distribution, we would expect this random guesser to get $np$ correct:
$$E(X) = np = 500 $$
With a variance of:
$$Var(X) = np(1-p) = 250$$
The standard deviation is just the square root of the variance:
$$StdDev(X) = \sqrt{Var(X)} \approx 15.8$$
Now if you are looking to identify if someone is not purely guessing (perhaps they have ESP?), then  you can use the 2-standard deviation threshold (as per the Normal Distribution Approximation) to determine if the guesser is not guessing at random (and be confident that we will only be wrong about 2.5% of the time).  That is, if someone is able to guess more than
$$500 + 2 * 15.8 = 531.6$$
of the coin flips ($\sim 53\%$), you can be fairly confident that they are not purely guessing (although this doesn't necessarily mean they have ESP!)
Comment: @Tim is correct. To provide evidence of sameness (within some threshold defining a minimum relevant difference), you want to **test for equivalence**.
Comment: Rejecting the null is not the same as proving the alternative hypothesis. Such experiment would show that it'd be unlikely to happen when random guessing.
Comment: I suggested this test based on the OP's original post, which seemed to be trying to do a test for statistical significance.  Of course, by design, these tests do not prove the alternative, but merely reject the null hypothesis.  Nowhere is this contradicted in my post (i.e. "you can be fairly confident that they are not purely guessing" $\equiv$ rejecting $H_0$)
Comment: David C, you are leaving implicit the assumption of an $\alpha$ error rate of 0.05%. You probably want to make that explicit.


How to restrict one exposed filter per content area?

Question: On my Drupal 8 site a have a /search view page that contains two exposed filters. I would like to expose them in different areas, for example to use search bar in the navigation, and filter by content type in the "content" block. But if I pick in 'advanced' tab 'Exposed form in block' "Yes", then both my filters appear in the navigation bar.
How can I split my exposed filters into different areas?
Answer: There is a module that seems to do exactly that: MEFIBS - More exposed forms in blocks.
Apart from that you could follow a workaround mentioned on that module project page where you clone your Views Display, don't change the Path, only change the Exposed settings. You will end up with two different blocks that can be placed in different regions, but working on the same Views page.
Comment: by "clone your display" you mean "dublicate view" or "dublicate page"? Can not find the option clone the view display in interace
Comment: Yes, sorry, it's `Duplicate` instead of `Clone` in D8. One View can have more than one Display. Display types can be `Page`, `Block`, etc. So in your case you can Duplicate the Page.


Precedence of Configuration options: Environment, Registry, Configuration file and Commandline In What Order?

Question: So this is a funny little thing I thing Stack Overflow has not discussed before. Not really a life and death question, but something I'd like to hear your input.
In short: my program is a bit over engineered in this regard: it takes configuration options from four different places:

Command line parameters
Configuration file
Environment variable
Windows Registry
(And hardcoded default values)

The question is, in what order should these be evaluated? I think it's clear that the command line options have the last say, but what about the three others? If the same option is set in both environment and ini-file, which should take precedence?
What about registry, does registry override the ini assuming I use that to change the runtime settings of the program, should I rewrite changes applied to registry into the configuration file as well? Should I set it so that registry settings can't override settings read from environment?
(If you wonder how on earth this is possible, one word: X-macro.)
Comment: Well, things have certainly happened, so I guess I should tell what I have learned in a month: I use environment variable for install time configuration, so that must override the configuration file and I use registry for runtime-configuration (with ugly MS Forms gui!), so that has the final say, unless a commandline flag is set, which overrides registry for the duration of that session. Almost acceptable, I feel I'm almost getting a hand in this "software development" thing.
Comment: Related: https://stackoverflow.com/questions/11077223/what-order-of-reading-configuration-values
Answer: Ordered by priority i would go this way: cli > envvars > registry > config > defaults

cli: it takes the options that you surely want to use when you manually start the program
envvar: generaly used to manually override configuration file options at runtime (often also used today to manage configuration options in containers environments, cf. 12factor app)
registry: specific to Microsoft Windows world, but according to what you said it have almost the same purpose that environment variables
config: defined at installation/configuration time so these are the "user wanted default options"
defaults: minimal config to run securely (for example listen on localhost only) when nothing else is provided


How to implement a custom Shader in Android

Question: I would like to draw a circle filled with blended color with gradient. However, the existing android.graphics.Shader subclasses cannot meet my need. In short, I would like to control the color of each pixel in the circle myself. Is it possible to implement a custom Shadar object by extending android.graphics.Shader?
Answer: I am not sure about subclassing android.graphics.Shader
But if you are using OpenGl ES 2.0 you can write your own Shader using GLSL which gives you very high flexibilty.
Maybe have a look at this question.


Can I block on the opponent's side?

Question: Is it legal to block the ball on the opponent's side? That it, the stricken ball reaches my hands before it reaches the net.
Answer: Yes, the blocker can reach over the net to block the ball.  However, blockers are not allowed to interfere with an opponent's play.  Essentially, this means that the blocker is not allowed to touch the ball until an opponent has made an attack hit.
The rules on blocks are found in Chapter 14 of the FIVB Official Volleyball Rules, which are the rules used in Olympic play.  Section 14.3 covers Blocking Within the Opponent's Space:

In blocking, the player may place his/her hands and arms beyond the
  net, provided that this action does not interfere with the opponent's
  play. Thus, it is not permitted to touch the ball beyond the net until an
  opponent has executed an attack hit.
Comment: Does this mean that you can make such an overreaching block only after third touch, or is for every attack hit (I am not sure that "attack hit" is actually defined)

Can I block on the opponent's side?


How should I define a MENU_LOCAL_ACTION menu item, and which is the involved page callback?

Question: Looking at user_menu() to check the answer for another question, I noticed the function contains the following definition.
  $items['admin/people/create'] = array(
    'title' => 'Add user',
    'page arguments' => array('create'),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_ACTION,
  );

The page callback is not explicitly defined.
Reading the definition of MENU_LOCAL_ACTION given in hook_menu(), I read  the following:

MENU_LOCAL_ACTION: Local actions are menu items that describe actions on the parent item such as adding a new user or block, and are rendered in the action-links list in your theme.

That doesn't explain which is the involved page callback that is called to handle that menu item.
Which is the page callback that is called to handle a MENU_LOCAL_ACTION menu item? Is there any other property that is necessary to define such menu items?
Answer: Router items can inherit properties from parent paths.
In this case, the page callback is inherited from the 'admin/people' path:
$items['admin/people'] = array(
  'title' => 'People',
  'description' => 'Manage user accounts, roles, and permissions.',
  'page callback' => 'user_admin',
  'page arguments' => array('list'),
  'access arguments' => array('administer users'),
  'position' => 'left',
  'weight' => -4,
  'file' => 'user.admin.inc',
);

The fact that the menu item is a MENU_LOCAL_ACTION doesn't actually come into it, the same is true of any type of item.
So if you define a router item like this:
$items['mymodule/path'] = array(
  'title' => 'Something',
  'page callback' => 'mymodule_page_callback',
  'access callback' => 'mymodule_access_callback',
);

And then define one like this:
$items['mymodule/path/sub-path'] = array(
  'title' => 'Something',
  'type' => MENU_LOCAL_ACTION,
  'access callback' => 'mymodule_access_callback',
);

The page callback will be inherited from the 'parent' item.
Comment: I guess I got confused from what `hook_menu()` says about access callbacks: "only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks"; that is only true for access callbacks, not for page callbacks. I seem to have mentally extended that for all the menu callbacks. `:)`
Comment: I didn't know that actually ;) I'm positive the page callback will be inherited though, I've used that as a 'feature' loads of times
Comment: @Clive thanks for very easy and important explanation.


Proposition: Let $m\in \mathbb N$ and $n\in \mathbb Z$. If $m·n\in \mathbb N$, then $n\in \mathbb N$.

Question: Proof:
$m·n\in \mathbb N$
Suppose BWOC $n\notin \mathbb N$.
Then $n=0$, or $-n\in \mathbb N$.
Case 1: $n = 0$
$m·n\in \mathbb N$ and $m·0\in \mathbb N$
$0\in \mathbb N$. This is a false statement.
Case 2: $-n\in \mathbb N$
I don't know how to prove case 2 so that there will be a false statement.
Any help is appreciated!
Comment: For any integer $x$, if $x>0$ and $y>0$, then $xy>0$ also holds- you can write $xy$ as $x+x(y-1)$- now try using induction to show that $xy$ is always $>0$ (assume $x(y-1)>0$ and show what happens if $xy<0$)
Comment: I'm sorry I haven't gotten to induction proofs yet, so my professor won't accept it. Is there another way to prove this?
Answer: Integer $n$ is natural whenever $n>0$. If $m > 0$ and $mn > 0$, then of course, $n > 0$.
Comment: I am not allowed to state this although it is obvious.
Comment: I have to use the axiom of natural numbers to prove it.
Comment: But how you define integers then? I learnt that $\mathbb Z$ are $N\times N$ divided by equivalence relation $(a, b) R (c, d) \Leftrightarrow a - c = b - d$. How are you using this definition here?
Comment: In my class, we defined integers to be members of a set equipped with binary operations addition, and multiplication.
Comment: The axiom I was given about Natural Numbers is 1) if m,n are natural numbers, then m+n is a natural number. 2) Same applies for multiplication. 3) 0 is not a natural number. 4) For every integer m, we have m is a natural number, m=0, or -m is a natural number.
Answer: I'll use two of the axioms you mentioned being given- if $x$ and $y$ are natural, then so is $xy$ & either $x$ is natural, $x$ is $0$, or $-x$ is natural (for any integer $x$).
These are enough to tackle your case $2$, for if $-n$ is natural, then (by the first axiom I wrote above), $m(-n)$ must be natural so $-(mn)$ must be natural. But, $mn$ is natural (by assumption) which contradicts the second axiom. So $-n$ can't be natural. Since you've already ruled out $n=0$, by the second axiom again $n$ is natural.
(this is assuming you've proved the consistency of the axioms)


Multiple usage of same formula in SELECT fields

Question: I have a query where I calculate value for WorkingTime as follows:
 SELECT
    SUM(CASE WHEN a.Type = 1
                THEN CAST(DATEDIFF(s,
                                ca.StartTime,
                                ca.EndTime) AS FLOAT)
                    / 60.0
                ELSE NULL
        END) AS WorkingTime ,
    AnnotherResult ...

The value of AnotherResult is also calculated with some equation, and in this equation I need to use WorkingTime.
Do I need to repeat the SUM (CASE ....) which is used to calculate WorkingTime everywhere I require it, or I can somehow refer directly to WorkingTime value in subsequent field value calculation?
Comment: You could wrap it in a subquery and then make multiple references to the computed value in the top level query.
Comment: You have to repeat it.
Comment: You could create an SQL function, passing in the parameters for the equation each time. http://msdn.microsoft.com/en-us/library/ms186755.aspx
Answer: You can use this syntax
Select ... , something/WorkingTime, something*WorkingTime, ...
From
(
Select *, CASE WHEN a.Type = 1
                THEN CAST(DATEDIFF(s,
                                ca.StartTime,
                                ca.EndTime) AS FLOAT)
                    / 60.0
                ELSE NULL
        END) AS WorkingTime
from myTable
) t

now you can use workingtime in other parts of query
Answer: You have multiple options, the most common are

Derived table
CTE

SELECT WorkingTime
    FROM (
           SELECT SUM(CASE WHEN a.Type = 1 THEN CAST(DATEDIFF(s, ca.StartTime, ca.EndTime) AS FLOAT) / 60.0
                           ELSE NULL
                      END) AS WorkingTime .....)

;WITH WT AS (SELECT SUM(CASE WHEN a.Type = 1 THEN CAST(DATEDIFF(s, ca.StartTime, ca.EndTime) AS FLOAT) / 60.0
                               ELSE NULL
                          END) AS WorkingTime .....)
SELECT WorkingTime
FROM WT
JOIN .....

Comment: Technically #1 is a derived table, not a subquery.
Comment: Corrected the terminology.
Answer: Other answers cover some of these items (derived table, common table expression), but I wanted to pull it together into a single answer with executable code, as well as providing a few additional alternatives (cross apply, CLR SQL Server Aggregate).
First, I will address the comment suggesting a user-defined function. You could certainly encapsulate the CASE statement and its calculation into a user-defined function. I would suggest an inline table-valued function, which would be fed the start time, end time, and type. It would be a pure calculation, and it would be deterministic. It would have no negative impact on performance and it would encapsulate code for re-use. This would not be an aggregate function; the aggregation would still occur on its results. See Method #4 in the code sample to see how it would be consumed.
Another user-defined function option would be to create an inline table-valued user-defined function which contained the base aggregation. You would start your query by using that function, and then its results could be used in additional calculations. See Method #5 in the code sample to see how it would be consumed. However, if you have more complex logic and avoiding code repetition is important, you will still end up using one of the other methods (CTE, derived table) in the function itself, or you will have to layer multiple user-defined functions to perform successive, stacked computations.
Other options for user-defined (native SQL) functions (scalar, multi-statement table-valued) are not recommended as they have often significant performance penalties.
Another function option is to create a CLR SQL Server Aggregate. SQL Server essentially passes the column of data out to as assembly running on the server (outside of SQL Server), which assembly performs the calculations and makes the results accessible to SQL Server for the rest of the query. Some DBAs discourage use of CLR functions because it adds some minor server management overhead and security considerations.
Pure SQL (no function creation required) methods include using derived tables or common table expressions (CTEs). CTEs are essentially derived tables which can be re-used multiple times in a statement, so they are generally more flexible than derived tables. However, they are not available prior to SQL Server 2005. Another answer provided a derived table solution but referred to it as a "subquery". Technically, a derived table is not a subquery. A subquery is generally when an entire SQL statement is used to return a single value which is used elsewhere in the statement. A derived table is a separate SELECT statement which generates a set of values and is used as a "virtual table" within the rest of the statement.
It's worth noting that the derived table (#2 below) and CTE methods (#1 below) offer a little better code reduction than the APPLY method (#3 below), because the APPLY method merely encapsulates the calculation, not the aggregation. Aggregation sort of "takes over" a query, so in order to use those aggregated results, you must encapsulate them into a CTE or derived table.
In my testing on SQL Server 2005, the first three "pure SQL" methods all generated identical query plans, so the choice of method is largely about syntactical preferences and not performance.
DECLARE @CA TABLE
(
    StartTime datetime,
    EndTime datetime,
    ActivityType int,
    Employee varchar(50)
);
INSERT INTO @CA (StartTime, EndTime, ActivityType, Employee) VALUES ('2014-04-01 1:00 PM', '2014-04-01 2:00 PM', 1, 'Jim');
INSERT INTO @CA (StartTime, EndTime, ActivityType, Employee) VALUES ('2014-04-03 1:00 PM', '2014-04-03 3:00 PM', 1, 'Jim');
INSERT INTO @CA (StartTime, EndTime, ActivityType, Employee) VALUES ('2014-04-04 9:00 AM', '2014-04-04 11:00 AM', 1, 'Jim');
INSERT INTO @CA (StartTime, EndTime, ActivityType, Employee) VALUES ('2014-04-05 10:00 AM', '2014-04-04 11:13 AM', 0, 'Jim');
INSERT INTO @CA (StartTime, EndTime, ActivityType, Employee) VALUES ('2014-04-02 10:00 AM', '2014-04-02 3:00 PM', 1, 'Sally');
INSERT INTO @CA (StartTime, EndTime, ActivityType, Employee) VALUES ('2014-04-04 1:55 PM', '2014-04-04 3:11 PM', 1, 'Sally');
INSERT INTO @CA (StartTime, EndTime, ActivityType, Employee) VALUES ('2014-03-30 1:45 PM', '2014-04-01 1:00 AM', 0, 'Sally');

-- Method #1: CTE

WITH BaseData AS
(
    SELECT
        Employee,
        SUM (
                CASE
                    WHEN ca.ActivityType = 1 THEN
                        1
                    ELSE
                        0
                END
            ) AS NumType1Entries,
        SUM (
                CASE
                    WHEN ca.ActivityType = 1 THEN
                        CAST(DATEDIFF(s, ca.StartTime, ca.EndTime) AS FLOAT) / 60.0
                    ELSE
                        NULL
                END
            ) AS TotalMinutesType1
    FROM        @CA ca
    GROUP BY    Employee
)
SELECT
    BaseData.Employee,
    BaseData.NumType1Entries,
    BaseData.TotalMinutesType1,
    CASE
        WHEN BaseData.NumType1Entries > 0 THEN
            BaseData.TotalMinutesType1 / BaseData.NumType1Entries
        ELSE
            NULL
    END AS MinutesPerType1Entry
FROM        BaseData;

-- Method #2: Derived Table

SELECT
    BaseData.Employee,
    BaseData.NumType1Entries,
    BaseData.TotalMinutesType1,
    CASE
        WHEN BaseData.NumType1Entries > 0 THEN
            BaseData.TotalMinutesType1 / BaseData.NumType1Entries
        ELSE
            NULL
    END AS MinutesPerType1Entry
FROM        (
                SELECT
                    Employee,
                    SUM (
                            CASE
                                WHEN ca.ActivityType = 1 THEN
                                    1
                                ELSE
                                    0
                            END
                        ) AS NumType1Entries,
                    SUM (
                            CASE
                                WHEN ca.ActivityType = 1 THEN
                                    CAST(DATEDIFF(s, ca.StartTime, ca.EndTime) AS FLOAT) / 60.0
                                ELSE
                                    NULL
                            END
                        ) AS TotalMinutesType1
                FROM @CA ca
                GROUP BY Employee
            ) AS BaseData;

-- Method #3 - Cross Apply

SELECT
    Employee,
    SUM (Calcs.Type1EntryCounter) AS NumType1Entries,
    SUM (Calcs.Type1EntryTotalMinutes) AS TotalMinutesType1,
    CASE
        WHEN SUM (Type1EntryCounter) > 0 THEN
            SUM (Type1EntryTotalMinutes) / SUM (Type1EntryCounter)
        ELSE
            NULL
    END AS MinutesPerType1Entry
FROM        @CA ca
CROSS APPLY (
                SELECT
                    CASE
                        WHEN ca.ActivityType = 1 THEN
                            1
                        ELSE
                            0
                    END AS Type1EntryCounter,
                    CASE
                        WHEN ca.ActivityType = 1 THEN
                            CAST(DATEDIFF(s, ca.StartTime, ca.EndTime) AS FLOAT) / 60.0
                        ELSE
                            NULL
                    END AS Type1EntryTotalMinutes
            ) AS Calcs
GROUP BY    Employee;

-- Method #4 - Inline Table-Valued User-Defined Function, Deterministic

-- Commented-out because it can't be run without creating the function first.

/*

SELECT
    Employee,
    SUM (Calcs.Type1EntryCounter) AS NumType1Entries,
    SUM (Calcs.Type1EntryTotalMinutes) AS TotalMinutesType1,
    CASE
        WHEN SUM (Type1EntryCounter) > 0 THEN
            SUM (Type1EntryTotalMinutes) / SUM (Type1EntryCounter)
        ELSE
            NULL
    END AS MinutesPerType1Entry
FROM        @CA ca
CROSS APPLY dbo.CalcType1Statistics
            (
                ca.ActivityType,
                ca.StartTime,
                ca.EndTime
            ) AS Calcs
GROUP BY    Employee;

*/

-- Method #5 - Inline Table-Valued User-Defined Function, Non-Deterministic Aggregation

-- Commented-out because it can't be run without creating the function first.
/*

SELECT
    EmpSummary.Employee,
    EmpSummary.NumType1Entries,
    EmpSummary.TotalMinutesType1,
    CASE
        WHEN EmpSummary.NumType1Entries THEN
            EmpSummary.TotalMinutesType1 / EmpSummary.NumType1Entries
        ELSE
            NULL
    END AS MinutesPerType1Entry
FROM    dbo.GetEmployeeSummary () AS EmpSummary

*/

P.S.:
An important limitation to derived tables is that you cannot refer to other fields in your statement within the definition of the derived table. They have to stand alone; when designing them in SSMS, you will need to be able to run them separately for them to be considered a true derived table. You can limit their results and reference other tables when you JOIN to them. If you need to have a set of values which is generated in relation to (i.e. correlated to) each row of the main SELECT, then you must use the APPLY operator.


A list of Android Permissions required for a certain Android API

Question: Is there any way to find the list of all permissions that must be required for a certain Android API. Is it possible to do this by parsing the Android api?
Answer: In this page you can check what API version have certain permission http://developer.android.com/reference/android/Manifest.permission.html
Comment: there are many android apis like android.content, android.bluetooth etc. I want the list of all permissions that must be required for using an API say android.bluetooth.
Answer: As far as I know, there's no full list available. But many APIs are explained in Android's API Guides. They'll also mention you that you'll need to add permission x to use the feature.
Why exactly do you want a full list of all permissions combined with the API that requires them?
Comment: For a given functionality of API xyz, I want to find similar functionality (if possible) in another APIs, that require lesser permissions or not at all.
Comment: Most of the time, you can't. You can't create a calendar event without the permission, you can't do an internet call without internet permission and so on.
Although, sometimes it is possible. For example, instead of adding the permission to make phone calls, you can simply open the Phone app with the phone number pre-entered. The user will need to press the 'call' button, but that shouldn't be that hard. Same for taking a picture(user needs to press the 'take picture' button). But, for most other permissions you can't workaround them.


Playing again by the same player after hitting the net

Question: After receiving the service the ball hits the net. It is legal to continue as long as you are within the 3 hits limit.
But can the same player continue after hitting the net? Player 1 hits the net, the ball bounces, and then the same Player 1 continues by passing to another team member?
Answer: No, this is not allowed. The official rules say:

9.1.1 CONSECUTIVE CONTACTS
A player may not hit the ball two times consecutively (except Rules 9.2.3, 14.2 and 14.4.2).

Let's have a look at these exceptions:

9.2.3 The ball may touch various parts of the body, provided that the contacts take place simultaneously.

This situation is not simultaneous, so this exception doesn't apply.

14.2 BLOCK CONTACT
Consecutive  (quick  and  continuous)  contacts  with  the  ball  may  occur  by one or more blockers, provided that the contacts are made during one action.

14.4.2 The first hit after the block may be executed by any player, including the one who has touched the ball during the block

Since this isn't about blocking, these exceptions don't apply either.


Specific range of numbers is given, trying to get another number within same range

Question: I'm trying to calculate the width of an HTML element based on the window size.
Here's what I have. These width values (first value) accurately match with the width the HTML element must be (second value). However I need to get a formula for this to be able to set the width of the HTML correctly according to any possible window size.
window width / HTML element width

1663         =  1916
1221         =  1692
1119         =  1641
1038         =  1602
630          =  1396
1500         =  ????
1400         =  ????
2000         =  ????

I've been staring at this four hours but I just can't wrap my head around it..
Any help would be appreciated.
Thanks in advance,
Roel
Comment: All of your equations are false. $1663$ is _not_ the same as $1916$", and the $=$ sign does _not_ mean "corresponds to, in some unspecified context-dependent way".
Answer: Linear regression gives: $m=0.5030755166$ $c=1078.8117490$
with $R^2=0.9999778405$. This gives the desired values as

630  1396
1500 1833
1400 1783
2000 2085
Comment: Thanks Shitikanth, glad someone knows how to do this :) .. But which formula can I use to get the element width for any window width my users may be using?? How can I implement this programmatically??? - So I mean: x (element width) =
Thanks!
Comment: y= mx+c with m and c given above (x is the window width and y is the HTML window width)
Comment: I'm sorry I'm a complete mathematics noob :P .. What does mx mean? Do i have to multiply m with x before adding it to c?  --thanks again


stateful processes (daemons?) in Tomcat?

Question: I'm not exactly sure what question to ask here since I don't know the vocabulary...
Tomcat servlets (and any server for that matter) work nicely if they are stateless and respond quickly to requests, with state stored in a database. It seems like if I have long-running operations then maybe I want to run some other service in the background, and have the Tomcat handlers communicate with it. Is there a way to run a long-running Java application in the same JVM as Tomcat and interact with it via "regular" Tomcat servlet?

Example: Let's say I want to offer a RESTful number factorization service in HTTP.
Here's a possible scenario (I hope I have the HTTP syntax right, I'm omitting most of the headers):
<code># comments start with #, > = request, < = response
#
# first we create a queue
> POST /factorizer/create-queue
> {information here}
< queue=12345B
# then we post some numbers to it
> POST /factorizer/queue/12345B
> 123
> 456
> 678
> 12345678901234567890123456789
< OK
# let's look at the status
> GET /factorizer/queue/12345B/status
< requested=4
< processed=3
# query
> GET /factorizer/queue/12345B/7
< Error: invalid index
> GET /factorizer/queue/12345B/3
< Error: not complete
> GET /factorizer/queue/12345B/0
< 123=3*41
# wait a while
> GET /factorizer/queue/12345B/status
< requested=4
< processed=4
> GET /factorizer/queue/12345B/3
< 12345678901234567890123456789=3*3*3*7*13*31*37*211*241*2161*3607*3803*2906161
</code>
I can think of how to write the servlet to handle the queries, but how could I go about implementing a daemon / independently-running service in the same JVM?
edit: In the above example, what I would like to do is to have a background application that runs autonomously, with work queues, to factor prime numbers, and has a Java interface that supports the operations that the Tomcat servlets could use to expose the service to the web. Then I don't have to worry about the web interface or HTTP in my background app, and I don't have to worry about multithreading issues or prime factorization in my servlets.
Comment: Are all the servlets in the same web application?
Comment: yes. (just curious: what would change if I said no, but they were all Tomcat servlets in the same JVM?)
Comment: If I recall correctly, Tomcat applications in the same JVM are insulated from each other.  Instead of Tomcat you would need something like JBoss that does Enterprise Java Beans.  Alternatively you can put many servlets into a single Tomcat application and they can see each other.
Answer: If you don't absolutely need to be in the same JVM (that is, if you don't need the performance of directly accessing the objects) you could write another Tomcat application and have your other apps communicate with it by HTTP to localhost.  In effect you would be writing a web service that happens to run on the same machine.  (I don't know how else multiple Tomcat applications can see each other.  This is a problem that Enterprise Java Beans solves, but that may be too heavyweight a solution for you.)
If you have only a single Tomcat application that needs to do this, create a worker thread and put it in the application context where all the requests can communicate with it.
With regard to your specific problem, it looks like you are describing something like the Asynchronous Job pattern in the O'Reilly "Restful Web Services" book.  This uses the "202 Accepted" status code to indicate that the processing is not complete.  See "Asynchronous Operations" in Chapter 8 of the book.
http://www.amazon.com/RESTful-Web-Services-Leonard-Richardson/dp/0596529260/ref=sr_1_1?ie=UTF8&s=books&qid=1255555328&sr=8-1
Comment: "application context"? is there a tutorial for this? I'm familiar enough with worker threads to know how to deal with most of the multithreading/concurrency aspects.
Comment: Your servlet extends HttpServlet.  HttpServlet.getServletContext() returns the ServletContext (or the "application scope") seen by all requests.  ServletContext.setAttribute(String name, Object value) and ServletContext.getAttribute(String name) let you put anything you want there.  A Java Server Pages tutorial probably has the most invormation about this.
Comment: oh, neat. that sounds about like what I want. Thanks!


Can't interract with a custom control onClick

Question: I can't get my custom control to call a function through the interact onClick="next()" attributes. I tried to put the "next()" function on both my screenController and my buttonController but still, no result...  I must be missing something simple here...
Here is my CustomControl definition:
<nifty-controls xmlns="http://nifty-gui.lessvoid.com/nifty-gui">
      <controlDefinition name="customImage-button" style="nifty-panel-style" controller="com.certification.renderer.jme3.gui.customControls.imagebutton.ImageButtonControl">
        <panel style="#panel" childLayout="overlay" focusable="true" width="$width" heigth="$height">
          <image id="#clicked" name="image-1" style="#select" filename="$img1" visibleToMouse="true" filter="true" >
            <interact onClickRepeat="pressedButton()" onRelease="releaseButton()" />
          </image>
          <image id="#uncliked" name="image-2" style="#select" filename="$img2" visibleToMouse="true" filter="true">
            <interact onClickRepeat="pressedButton()" onRelease="releaseButton()" />
          </image>
        </panel>
      </controlDefinition>
</nifty-controls>

Here is the screen XML:
<nifty>
    <useStyles filename="nifty-default-styles.xml" />
    <useControls filename="Interface/custom-controls.xml" />

    <screen id="loginScreen" controller="com.certification.renderer.jme3.gui.ScreenJME">
        <layer id="layer3" childLayout="center">

            <control id="numpadnumber-1" style="numpad" name="customImage-button" width="13%" height="11.75%"
                     img1="Interface/images/1_numpad_clicked.png" img2="Interface/images/1_numpad.png"
                     controller="com.certification.renderer.jme3.gui.customControls.imagebutton.ImageButtonControl"
                     visibleToMouse="true">
                <effect>
                    <onClick name="fade" start="#f" end="#0" length="15000" />
                </effect>
            </control>
        </layer>
    </screen>
</nifty>

Here is the screen controller:
public class ScreenJME extends Screen implements ScreenController {
protected String _path;
private String _key;
protected Nifty _nifty;
protected Application _app;
protected de.lessvoid.nifty.screen.Screen _screen;
private String password = "";

private final float screenHeight = 1050;

ScreenJME()
{
    //EMPTY
}

ScreenJME(String path, String key, Nifty nifty)
{
    _path = path;
    _key = key;
    _nifty = nifty;
}

@Override
public void bind(Nifty nifty, de.lessvoid.nifty.screen.Screen screen)
{
    this._nifty = nifty;
    this._screen = screen;
    System.out.println("Binding...");
}

@Override
public void onStartScreen()
{
    switch (_key)
    {
        case ("loginScreensss"):
           // populate();
            break;
        default:
            break;
    }
    System.out.println("onStartScreen..");
}

@Override
public void onEndScreen()
{
    System.out.println("..onEndScreen");
}

(...)
public void next()
{
    System.out.println("next() clicked! woohoo!");
}

}
Answer: The images in your control will consume the mouse events since they are on top of the control panel. Any interact added to the panel will not receive mouse events in that case. You'll need to remove the images or make them visibleToMouse="false". Currently you can't have both.


Proof verification: sequence $ a_n = (-1)^n $ does not converge

Question: Theorem: Show that the sequence $ a_n = (-1)^n $ for all $ n \in \mathbb{N}, $ does not converge.
Proof: Suppose that there exists a limit $L$ such that $ a_n \rightarrow L  $. Specifically, for $ \epsilon = 1 $ there exists $ n_0 $ s.t. for all $ n > n_0$ then $|(-1)^n-L|<1$, from this we can also infer that $|(-1)^{n+1}-L|<1$ for all $ n > n_0 $.
Let $ n > n_0 $ be arbitrary, then $ 2 = | (-1)^n - (-1)^{n+1} | \leq | (-1)^n - L | + | L - (-1)^{n+1} | < 1 + 1 = 2  $, so since $ n > n_0 $ was arbitrary , hence for all $ n>n_0 $ we have 2<2 which is false, hence we get a contradiction.
My question: Regarding to when I wrote " $ n>n_0 $, we have 2<2 which is false, hence we get a contradiction. "
I'm trying to understand with respect to what there is a contradiction; we get that any statement of the form $ \forall n>n_0 (P(n) )$ is false ( since we got $ \forall n>n_0 . 2<2 ) $ [ and $ P(n) $ is a statement that depends on $ n $ ], and since we already have in the proof the statement " for all $ n > n_0$ then $|(-1)^n-L|<1$ " , then we get a contradiction. Is this correct?
Note: I know there are answers on this sequence's divergence, but they didn't really help me find an answer to my question.
Comment: i think it is enough to show 2 is less than 2 for just a single big n.
Comment: Yes you are right, but I want to be sure that I can get a contradiction for any $ n > n_0 $ , i.e.  in my proof I have $ \forall n>n_0 . 2<2 $ ( which is false ) and $ \forall n>n_0 . |(-1)^{n+1}-L|<1 $  ( which is true by the assumption  that there exists a limit ) , hence I get a contradiction and thus the assumption that the limit exists is false.
Comment: The contradiction is that for all $n$ (no matter what) $1+1 < 2$ is false, so there is no $n_0$ that can assure $n > n_0\implies 2< 2$.
Answer: I say your statement $P(n)$ does not depend on $n$.
With respect to the known fact that $2=2$, you have deduced a contradiction. Hence your proof is good. (Although stop at the $2<2$ bit. You go on saying "so since $n$ was arbitrary", but that is not relevant.)
$a_n$ converges means that there is an $L$, so that for every positive epsilon, we can find a (big) index beyond which $a_n$ is epsilon-close to L.
$a_n$ does not converge means that for any $L$, there is a positive epsilon, so that for any index, we can find an even further index $t$, at which $a_t$ is not epsilon-close to L.
Maybe it will help you to see your proof from this second viewpoint.
Do you see how the "for anys" trade places with the "there exists at least one", when we contradict a complicated definition?
Try to step through your proof using the definition of "doesn't converge". It is in a way running your argument backwards.
So the task is: faced with any real $L$ candidate, to answer with a suitable epsilon.
Answer: Your statement $P(n):= 2< 2$ does not depend on $n$.
Although if $\lim (-1)^n = L$ then there would be an $n_0$ so that $n > n_0\implies 2< 2$.
But no such $n_0$ can exists because $P(n)$ is false independent of $n$.
.....
Alternatively (although this is a bit abstract for my taste) $n > n_0\implies 2< 2$ and $2< 2$ is false; implies $n > n_0$ is false and we are (in theory) claiming there is an $n_0$ that is is an upper bound for all integers.
Comment: I meant to make an analogy, just like the constant function f(x) = 2 does not depend on x, so in my case it turned out that $ P(n):= 2< 2 $ also does not depend on $ n $, but since I have let $ n > n_0  $ to be arbitrary and proceeded to show that  $ 2 = | (-1)^n - (-1)^{n+1} | $, a-priori I was showing a statement that depends on $ n $  which eventually turned out it didn't.  So $ \forall n > n_0 . P(n) $ is false in my proof ( where P(n) is some statement ), therefore it is true that $ \exists n > n_0 . \neg P(n) $
Comment: I'm not entirely sure what you are asking or what answer you want. But yes, you have a valid contradiction.  But you don't have to put it in such specific terms.  It's much more general contradiction.


Angular with Jest Unit Test: Cannot read properties of undefined (reading 'pipe')

Question: I want to unit test an Angular component with a NgRx store.
This is my component:
import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
import { select } from '@ngrx/store';
import { catchError, Observable, of } from 'rxjs';
import { View } from 'src/app/core/models/view.model';
import { selectIsAuthenticated } from 'src/app/core/store/selectors/auth.selectors';
import { BaseAuthComponent } from '../base-auth/base-auth.component';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent extends BaseAuthComponent implements OnInit {
  isAuthenticated$: Observable<boolean>;

  loginForm: FormGroup;
  formSubmitted = false;
  loginError = false;

  ngOnInit(): void {
    this.isAuthenticated$ = this.store.pipe(select(selectIsAuthenticated));

    this.loginForm = this.formBuilder.group({
      email: ['firstname.lastname@example.com', [Validators.required, Validators.email]],
      password: ['wfojewfioerjferergER$§T', [Validators.required]],
      rememberMe: [false],
    });
  }

  login(): void {
    this.formSubmitted = true;

    if(this.loginForm.valid) {
      this.authService.login(this.loginForm.value).pipe(
        catchError(() => {
          this.formSubmitted = false;
          this.loginError = true;

          return of(false);
        })
      )
      .subscribe(data => {
        data ? this.onSuccess.emit() : {};
      });
    }
  }

  changeView(): void {
    this.onViewChange.emit(View.REGISTER);
  }
}

My test file looks like this:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideMockStore } from '@ngrx/store/testing';
import { selectIsAuthenticated } from 'src/app/core/store/selectors/auth.selectors';
import { LoginComponent } from './login.component';
const spyOn = jest.spyOn;

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  const initialState = {
    auth: {
      authenticated: false
    }
  };

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [],
      declarations: [ LoginComponent ],
      providers: [
        provideMockStore({
          initialState,
          selectors: [
            { selector: selectIsAuthenticated, value: true }
          ]
        })
      ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

The login component extends from this component:
import { Component, EventEmitter, Output } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Store } from '@ngrx/store';
import { View } from 'src/app/core/models/view.model';
import { AuthService } from 'src/app/core/services/auth/auth.service';
import { FormService } from 'src/app/core/services/form.service';
import { AppState } from 'src/app/core/store/reducers';

@Component({
  template: ''
})
export abstract class BaseAuthComponent {
  @Output() onSuccess = new EventEmitter();
  @Output() onViewChange = new EventEmitter<View>();

  constructor(
    protected formBuilder: FormBuilder,
    protected authService: AuthService,
    protected store: Store<AppState>,
    public formService: FormService
  ) { }
}

If I try to run this test I get the following error:
 FAIL  src/app/modules/auth/login/login.component.spec.ts
  LoginComponent
    × should create (187 ms)

  ● LoginComponent › should create

    TypeError: Cannot read properties of undefined (reading 'pipe')

      20 |
      21 |   ngOnInit(): void {
    > 22 |     this.isAuthenticated$ = this.store.pipe(select(selectIsAuthenticated));
         |                                        ^
      23 |
      24 |     this.loginForm = this.formBuilder.group({
      25 |       email: ['email@example.com', [Validators.required, Validators.email]],

      at LoginComponent.ngOnInit (src/app/modules/auth/login/login.component.ts:22:40)
      at callHook (node_modules/@angular/core/fesm2015/core.mjs:2526:22)
      at callHooks (node_modules/@angular/core/fesm2015/core.mjs:2495:17)
      at executeInitAndCheckHooks (node_modules/@angular/core/fesm2015/core.mjs:2446:9)
      at refreshView (node_modules/@angular/core/fesm2015/core.mjs:9479:21)
      at renderComponentOrTemplate (node_modules/@angular/core/fesm2015/core.mjs:9578:9)
      at tickRootContext (node_modules/@angular/core/fesm2015/core.mjs:10809:9)
      at detectChangesInRootView (node_modules/@angular/core/fesm2015/core.mjs:10834:5)
      at RootViewRef.detectChanges (node_modules/@angular/core/fesm2015/core.mjs:21757:9)
      at ComponentFixture._tick (node_modules/@angular/core/fesm2015/testing.mjs:141:32)
      at node_modules/@angular/core/fesm2015/testing.mjs:154:22
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:407:30)
      at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:3765:43)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:406:56)
      at Object.onInvoke (node_modules/@angular/core/fesm2015/core.mjs:25826:33)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:406:56)
      at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:167:47)
      at NgZone.run (node_modules/@angular/core/fesm2015/core.mjs:25680:28)
      at ComponentFixture.detectChanges (node_modules/@angular/core/fesm2015/testing.mjs:153:25)
      at src/app/modules/auth/login/login.component.spec.ts:36:13
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:407:30)
      at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:3765:43)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:406:56)
      at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:167:47)
      at Object.wrappedFunc (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:4250:34)

I already tried to import StoreModule.forRoot(reducers), but if I rerun the test I get another error:
Unexpected value 'StoreRootModule' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.

I tried:
providers: [
        {
          provide: Store,
          useValue: {
            pipe: of({})
          }
        }
]

and
providers: [
        {
          provide: Store,
          useClass: MockStore
        }
]

I also followed the guide on the NgRx website on how to mock a store NgRx Testing.
Neither worked.
My Angular project is running version 13.0.0 and Jest is running version 27.4.3.
If someone could help me with this, I would really appreciate that.
Answer: I copy pasted your code and adapted the lines I didn't have access to but my tests failed with another error
NullInjectorError: StaticInjectorError(DynamicTestModule)[LoginComponent -> FormBuilder]:
  StaticInjectorError(Platform: core)[LoginComponent -> FormBuilder]:
    NullInjectorError: No provider for FormBuilder!

Adding ReactiveFormsModule to the import section of the testfile solved this and the test passed
imports: [ReactiveFormsModule],

I don't think it's supposed to make a difference but you could also try this shorter syntax:
this.isAuthenticated$ = this.store.select(selectIsAuthenticated);


How to get the survival duration prediction for each individual in the data by using the Kaplan-Meier method?

Question: I am trying to learn how to use the Kaplan-Meier survival estimator model in the lifelines package. The documentation says that the KaplanMeierFitter.fit function returns "a modified self, with new properties like 'survival_function_'." I checked what the survival_function_'s contents are - it seems to contain the average survival probability for all the players in the dataset at each time time interval. For example, in my dataset, there are 66 months and about 250,000 players (i.e., individuals whose death event we are trying to predict - 75% of them have had their deaths and the rest 25% is censored data, i.e., their deaths have not been observed), so the survival_function_ contains the following:
>>> kmf.survival_function_

        KM_estimate
timeline
-1.0    1.000000
0.0     0.995473
1.0     0.779609
2.0     0.621312
3.0     0.508698
4.0     0.424205
5.0     0.366714
6.0     0.324090
7.0     0.289432
8.0     0.259339
9.0     0.234256
10.0    0.212542
11.0    0.192735
12.0    0.172880
13.0    0.157821
14.0    0.144604
15.0    0.132614
16.0    0.121743
17.0    0.112202
18.0    0.103710
19.0    0.095829
20.0    0.088811
21.0    0.082302
22.0    0.076773
23.0    0.071249
24.0    0.065752
25.0    0.060534
26.0    0.056082
27.0    0.051978
28.0    0.048073
...     ...
37.0    0.023696
38.0    0.020562
39.0    0.017846
40.0    0.015783
41.0    0.013817
42.0    0.012253
43.0    0.010645
44.0    0.009354
45.0    0.008186
46.0    0.007195
47.0    0.006274
48.0    0.005486
49.0    0.004656
50.0    0.003948
51.0    0.003391
52.0    0.002823
53.0    0.002352
54.0    0.002004
55.0    0.001655
56.0    0.001388
57.0    0.001114
58.0    0.000932
59.0    0.000707
60.0    0.000536
61.0    0.000343
62.0    0.000193
63.0    0.000080
64.0    0.000038
65.0    0.000016
66.0    0.000000

68 rows × 1 columns

It tells us the average survival probability of the entire population at each time period, taking both dead as well as censored players. It does not tell us the survival probability for each individual censored player, which is what I am interested in. How do I find that? It can be as detailed as, giving the survival probability for each individual player for each of the 66 months. Or, if that's not possible, I'm ok with having having the survival probabilities of each individual player at a fixed time in the future, say 3 months, or anything else (which is 1 of the 66 time periods).
In other words, instead of the output being a 66x1 vector of average survival probabilities, can I get an output matrix of dimensions txn, where t is the number of time periods and n is the number of censored players in the dataset, and the entry (i,j) is the survival probability of player i at time period j?
If this is not possible with the KM method, please feel free to suggest other methods where its possible to get the survival estimate for each individual. Thank you.
EDIT: I tried Cam Davidson Pilon's suggested way, and the prediction matrix gives the same exact predictions for each individual for a given time period:

This is not what I wanted; I expected a prediction matrix where the (i,j)'th entry (the survival probability for person j at time i) would be mostly unique. Whereas this just takes the survival_function_ values and copies them for each individual.
Answer: Hi author of lifelines here. So what you asking is possible. The Kaplan-Meier curve gives you is a distribution of possible durations, where duration is the time between birth and death. However, given a player has existed for $N$ months, you can condition the survival function on $T > N$ to get a better estimate.
Let $S(t) = P(T \ge t)$ be the survival function. We are curious about $S(t | T \ge N)$.
$$
S(t | T\ge N) = \frac{P(T \ge t \text{ and } T \ge N)}{P(T \ge N)} = \frac{P(T \ge t)}{S(N)} = \frac{S(t)}{S(N)},\;\; t \ge N
$$
So we simply need to divide the survival function by itself evaluated at the duration seen thus far.
In your use case, you could do something like:
predictions = pd.DataFrame(index=kmf.survival_function_.index)

for ix, row in alive_individuals.iterrows():
    T = row['T']
    predictions[ix] = kmf.survival_function_/kmf.survival_function_.loc[T]

# can't have probabilities great than 1.
predictions[predictions > 1.0] = 1.

This gives you the new survival function. However, in lifelines, there is another utility you can use. kmf.conditional_time_to_event_ computes these conditional survival functions and then takes the median time remaining. Output using some fake data I have:
          KM_estimate - Conditional time remaining to event
timeline
0.0                                                    56.0
6.0                                                    50.0
7.0                                                    49.0
9.0                                                    47.0
13.0                                                   43.0
15.0                                                   41.0
17.0                                                   39.0
19.0                                                   37.0
22.0                                                   34.0
26.0                                                   32.0
29.0                                                   29.0
32.0                                                   26.0
33.0                                                   27.0
36.0                                                   24.0
38.0                                                   22.0
41.0                                                   19.0
43.0                                                   17.0
45.0                                                   15.0
47.0                                                   13.0
48.0                                                   13.0
51.0                                                   10.0
53.0                                                    8.0
54.0                                                    7.0
56.0                                                    7.0
58.0                                                    5.0
60.0                                                    8.0
61.0                                                    7.0
62.0                                                    6.0
63.0                                                    6.0
66.0                                                    3.0
68.0                                                    1.0
69.0                                                    6.0
75.0                                                    0.0

So if a player lives until age 62, we expect 6 more months left (6 months being the median time to death, given the player lived to 62). That may help as well.
Comment: Thanks for the prompt reply, Cam! About the line `predictions[predictions > 1.0] = 1.0`, wouldn't it be better to divide the predictions matrix by the max value in it? Something like, `predictions /= max(map(max, predictions))`. I say this because, I'm no statistician, but I feel the procedure by which we calculate probabilities should *inherently* have an upper bound of 1, isn't it? And if it somehow doesn't, maybe "normalizing" it by dividing it by the max value would make more sense than just truncating the decimal digits in the probabilities greater than 1, isn't it?
Comment: This way, at least we preserve the relative magnitudes among the numbers. What I mean is, if there was a number in predictions that was big, say around 10. Then by simply making it 1 and not changing the other numbers, we lose this info. Whereas, if we divide all the numbers for that player by 10, we know that something funny is happening at that time duration for this player. What do you say?
Comment: Also, how do I check the prediction accuracy? How do I validate the prediction?
Comment: dividing by the max doesn't make sense in this context. Note I chose 1.0 because _that's what we observed_! For a given individual who lived to atleast month N, their probability of dieing prior to month N was 0.0, so the survival curve should be 1.0 at those points. Note that the `predictions` dataframe has the same index as the survival function too.
Comment: Hi Cam. I tried your suggested method, and I've edited the question details in the end to include the results. I did not get what I expected, which was (mostly) ***unique*** probabilities for each individual for each time period. Instead what I got is the ***exact same*** survival probabilities for each individual at each time period. Please advice. In other words, this just takes the `survival_function_` values and copies them for each individual.
Comment: hm, something must be wrong - you should get unique probabilities _unless_ the censorship time for all these users is the same (I assume it's not). Can you confirm that `T = row['T']` is different per user?
Comment: Yeah, the censorship times are different for different individuals.
Comment: hm, maybe it's the `-1` in your data... I wonder if that is breaking some part of the code I posted / breaking some assumption.
Comment: I tried by removing the `-1`s, still the same result.  Anyway, I'm moving on to cox regression; seems like that's the better method for this kind of goal. I'm just not clear on one thing though, and it'd be great if you could shed some light on it. How do I divide my dataset into training and testing data? If I do a "traditional" split using sklearn's `train_test_split`, the training data will have some censored data points (whose survival probabilities I want to predict). If I train on all the dead individuals and predict for the alive ones, I feel the result would be skewed. Please advice.
Comment: If you randomly partition the dataset into train test splits, then the chance you only train on dead individuals is close to 0, no?
Comment: Yes, that's true. I guess what I don't understand is, when I'm training the model, shouldn't I be training on only dead people, since I want to predict for the alive people? I also don't get how to validate the training results if I include the alive people - I'll have the predicted survival probabilities (for a given duration) for the dead people and can compare this with how long they actually lived from the dataset; but what do I compare with for the alive people? That's what's confusing for me.
Answer: One condition of use K-M method to estimate the survival probability is that all subjects follow the ONE survival curve. Your situation is: When you use K-M method, you agree with one survival curve assumption, but after that you want to get the individual level survival curve. In fact, it is impossible.
If you think it is necessary to fit the survival curves for different groups of subjects, for example, male vs female, you need to run K-M multiple times.
Especially, in survival analysis, we assume that censoring has no relation with survival probability after censoring. For example, at time 25, 2000 were censored, and 20000 were still followed. If you believe (based on your knowledge/experience) that 2000 censored subjects would survival longer (or shorter) than the 20000 followuped subjects, then even K-M methods is invalid.
Comment: Well, about your last statement `"If you believe (based on your knowledge/experience) that 2000 censored subjects would survival longer (or shorter) than the 20000 followuped subjects, then even K-M methods is invalid."`, I thought we use survival analysis for these tasks exactly for the reason that it can handle the case that the survived population can live much longer, potentially, than the dead population. Isn't that correct? Otherwise, why not simply use linear regression to predict the survival duration?
Comment: censored at time 25 means the subjects are still alive at time 25, but after time 25, their disappeared, and you do not know when they die. For all of survival analysis, the common assumption is: Given the subjects are alive at time t, and some of them censored (disappeared), and some of them still are under the follow-up, the survival probabilities after time t are the same between two groups.


remove a code line begining with username in Visual Studio Code

Question: I would like to create a regex to select all lines begining with 'username'=> and remove them.
I began my regex, but I'm a little bit stuck :
This code selects any lines begining with username :
(?<='username'=>)

but I wondering how can I select the end of the line too and remove it ?
This is an example :
'username'=> 'CRPV',

I'm working with Visual Studio Code.
Thank you in advance for your help.
Comment: Add a piece of the file you use. Does `'username'` start at the beginning of the line or is there white space?
Answer: Find:
Enable button .* in Find dialog
^'username'.*\n?

Replace: with nothing.
The ? at the end is if the last line without a newline character is also a username line
Comment: Hi, thank you for your reply.  Weird, it seems that it does not work.  I have no result...
Comment: @laravelnoobie Do you enable the regex Find? Enable button `.*` in Find dialog
Comment: yes, this is the liink to show you https://www.dropbox.com/s/pbo4upcuqx3eudi/Capture%20d%27%C3%A9cran%202020-07-16%2010.03.20.png?dl=0


How can I find the matrix of affine transformations?

Question: I know the points of a triangle: x1 = (0,2), x2 = (-2,-2) and x3 = (2,-2) and the triangle has been scaled, translated and rotated, how can I find the scaling, translation and rotation matrices (assuming homogenous coordinates) if I know one of the transformed points y3 = ((9-√3)/2,(5-√3)/2) which corresponds to the transformation of x3.
I tried multiplying the matrices S, T, and R (STR) * x3 and I got

But not sure what to do from there.
Comment: I am assuming y3 corresponds to x3
Comment: Translation isn't represented by matrix multiplication, just vector addition.
Comment: Well assuming the use of homogenous coordinates, can't it be done with matrix multiplication?
Comment: You transform has 4 parameters, but if you know the image of only 1 point it gives you only 2 equations. E.g., you can apply arbitrary scaling and rotation, and then use translation to get from x3 to y3.
Answer: First of all, it is not clear why you wish to use homogeneous coordinates, which would mean embedding the Euclidean plane into the projective plane. That can certainly be done and yields very intersting results on what happens to mid-points, perpendicularity and so on in terms of the projective concepts of cross-ratio and harmonic conjugate but your question seems to me one that is more appropriately handled by staying in the Euclidean plane. An affine transformation is one of the form $(x,y) \mapsto (x^{\prime},y^{\prime})$ where $$\begin{bmatrix}x^{\prime}\\y^{\prime} \end{bmatrix}=A\begin{bmatrix}x\\y \end{bmatrix}+\begin{bmatrix}e\\f \end{bmatrix}$$ where $A$ is a 2 $\times$ 2 matrix. Thus you have 6 unknowns, viz. $e,f$ and the 4 entries of $A$. If you only know what hapens to one point, you have just two equations, so you have a lof freedom in choosing $A$ and $e,f$. Once you have made such a choice let $k=\sqrt{\vert \det A \vert \space}$. Then  $kI$ is a scaling matrix and $A=(kI)B$ where either $\det B$ =-1 and $B$ corresponds to reflection about a line throuth origin or $\det B$ =1 and $B$ corresponds to a rotation about the origin. Note that if you choose $A$ such that $\det A>0$, then $\det B=1.$


memsql-deploy leaf node consistently failed

Question: On the same host as master to memsql-deploy leaf node always failed with same error. Switching the operation to new machines has the same failure.
Here is the steps to deploy master role:
# memsql-ops memsql-deploy -a Af53bfb  -r master -P 3306 --community-edition
2017-03-24 16:15:54: Je5725b [INFO] Deploying MemSQL to 172.17.0.3:3306
2017-03-24 16:15:59: Je5725b [INFO] Installing MemSQL
2017-03-24 16:16:02: Je5725b [INFO] Finishing MemSQL Install
Waiting for MemSQL to start...
MemSQL successfully started

Here is the immediate steps to add leaf node after deploying master:
# memsql-ops memsql-deploy -a Af53bfb  -r leaf -P 3308
2017-03-24 16:16:43: J32c71f [INFO] Deploying MemSQL to 172.17.0.3:3308
2017-03-24 16:16:43: J32c71f [INFO] Installing MemSQL
2017-03-24 16:16:46: J32c71f [INFO] Finishing MemSQL Install
Waiting for MemSQL to start...
MemSQL failed to start: Failed to start MemSQL:

        set_mempolicy: Operation not permitted
setting membind: Operation not permitted

What can be the possible reasons behind the error messages and what way that I can follow to find out the root cause or fix?
Comment: Further dig in to `job-logs` and find a related error message happened during the start of leaf node:  `J2f44c7 [WARNING] Could not read tracelog for MemSQL node 636F0213D6DA91A67D67DD3F4554E20B5CC3FAF1 because it doesn't exist`
Answer: After one day search on Google, I believe I finally locate the root cause of this error. I feel strange why no one asked before because it should be happened more often than just me.
The real cause for this issue is I installed numactl package per MemSQL's best practice suggestion on a non-NUMA machine. This would effectively  let the memsql node other than the first one try to run numactl sub-command set_mempolicy to bind individual MemSQL nodes to CPUs but this command would eventually fails. And the start of the node by sub-commands memsql-start or memsql-deploy from memsql-ops will all fail.
The workaround to this is very simple, just remove the package numactl. Then everything will be fine. This workaround particularly applies to some virtualization based memsql deployments like Docker.
Answer: Can you try on the master:
memsql-ops start
memsql-ops memsql-deploy --role master -P 3306 --community-edition

On the agent:
memsql-ops start
memsql-ops follow -h <host of primary agent> -P <port of primary agent if configured to use one>
memsql-ops memsql-deploy --role leaf -P 3308 --community-edition

Comment: Both `master` and `leaf` are on the same host. Do I still need to run `follow` prior `memsql-deploy` ?
Comment: @robert I believe so
Comment: though I doubted but I did give it a try. Turned out agent can not follow itself when I do this on `primary` agent box which is also the `master` of memsql. I believe we can only have one memsql agent per host, but we may have one or more nodes per memsql host. There should be other causes to my problem. Thanks.