Use Play() method to start dynamically loaded HTML 5 Video in IOS Safari / Chrome Mobile

Question: I'm using a jQuery onclick function to dynamically load in an HTML5 video player, which I'm then trying to call play() on to make it play as soon as it appears.
This works fine on desktop chrome / safari, but not on their mobile counterparts. I'm aware that mobile browsers (Safari in particular) are understandably funny about the play() method, but I was under the impression that calling it from a user interaction event (such as a click) was ok?
Perhaps it is the fact the the video is being dynamically loaded in the same interaction function? Has anyone else experienced this / can suggest a workaround or let me know that I'm doing something wrong.
The jQuery function goes something like this:
$(document.body).on('click', '#vidloader', function( event ){

    $.ajax({
        type: "GET",
        url: '/get_video.html?id=123',
        cache: false,
        success: function(data) {

            $("#dynamicVideoHolder").append('
' + data + '
');

            construct_video_player( 'dynVidViewer' );

            var newvideo = document.getElementById("newvid");
            newvideo.play();

        }
    });

    return false;

});

get_video.html loads a pre-constructed <video> (id='newvid') element and supporting UI, construct_video_player creates supporting interaction around the UI. All works fine, just won't play as soon as it's loaded!
Comment: try with audiomuted see https://webkit.org/blog/6784/new-video-policies-for-ios/
Answer: The problem here is that you are calling play() in the callback of the ajax call, so the context is lost, and it doesn't count as a user interaction anymore.
Try to log what is happening with:
newvideo.play()
  .then(() => console.log('success :)'))
  .catch(err => console.log('error :( ', err));

If my guess is correct, the execution should go to the catch, and you should see something like NotAllowedError.
So... you are going to need to move that play() out of the ajax callback.
A workaround would be to let the play() call as it is (since works on desktop browsers), and just show a play button if the initial play() call fails (that would be the case of some mobile devices), then you will need another "click" event on that play button, that will play again the video, now without any ajax call involved. There is an example of this in another answer I gave here.
I hope it helps!
Comment: Ah ok - I totally hadn't considered the context side of things... I tried your code and it caught the error "DOMException: play() can only be initiated by a user gesture.". I think I may have come up with a way around it though based on what you said - I set a global 'videoIsLoaded' variable to false, which I set to true in the callback function of the ajax call. Then I use setInterval to create a function to watch when that turns true which then calls the play() method. Not as clean as i'd like, but hey seems to work :) Many thanks for your help, I wouldn't have worked it out otherwise.
Comment: Sweet! Great to read that it worked!
 I was a bit surprised it worked, though, since you have the `play()` inside the function of the setInterval, so I thought the context would be lost as well.
BUT... I found out that a user gesture is forwarded on `setTimeout` and `setInterval`. (You learn something new every day!), with some restrictions, like  "if a setTimeout handler invokes setTimeout again, the user gesture won't be forwarded twice, and if the timeout is >1s it won't be forwarded either."
How much is your timeout? Less than 1s, right?
Comment: These couple of links helped me to understand it:
- https://github.com/WICG/interventions/issues/12
- https://bugs.chromium.org/p/chromium/issues/detail?id=354217
Comment: Great finds on those links, it's a lot clearer now. Yeah it was more a trial and error than a deep understanding of context that got me there, but now it all makes a lot more sense. Yep I set the timeout at 100ms which ticks the box for the gesture forwarding and also makes it run quicker :) Thanks again!


how to use settimeofday(2)?

Question: What am I doing wrong here? I expect settimeofday() to change the system time, not return EINVAL.
$ uname -a
Linux io 4.3.5-300.fc23.x86_64 #1 SMP Mon Feb 1 03:18:41 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
$ cat settimeofday.c
#include <sys/time.h>
#include <stdio.h>

int main()
{
    struct timeval tv = {0, 0};
    if (settimeofday(&tv, 0) == -1)
        perror("settimeofday");
}
$ gcc settimeofday.c
$ sudo ./a.out
settimeofday: Invalid argument

The error is coming from a Thinkpad T450 running Fedora 23. The same code runs fine on OS X.
EDIT
To clarify, the command is being executed as root:
# whoami
root
# sudo ./a.out
settimeofday: Invalid argument

As expected, I get EPERM not EINVAL if I run the program as a regular user:
$ ./a.out
settimeofday: Operation not permitted

Comment: Note that you need permission to `settimeofday`, not that it should return an `EINVAL` error if you're not running as root.
Comment: See the "sudo" in "sudo ./a.out". The command is being run as root.
Comment: you should be sudo user or root user, by default its not allowed for normal user to change the time
Comment: with same code  for me it worked perfectly fine
Comment: On some systems, under certain security settings, even the superuser can not set the time backwards with `settimeofday()` -- is this something Fedora does?
Comment: No. The call fails with EINVAL no matter what the timeval is set to, even if would cause time to jump forward. Anyways, if this was a security issue then I would expect EPERM.
Comment: You don't have a Linux Security Module installed that hooks into the settime syscall do you?
Comment: So I was wrong when I commented earlier and said that the call fails no matter what the timeval is set to. See my answer for details.
Answer: Commit e1d7ba was introduced to the Linux kernel in mid-2015 and restricts the value of the tv_sec field. The restriction is influenced by system uptime -- see the commit message and related LKML discussion for details.
That's what was causing the settimeofday call to return EINVAL and explains why the code runs on OS X and older Linux machines.
Answer: As shown in the manpage of settimeofday().

If either tv or tz is NULL, the corresponding structure is not set or returned.
Comment: And a few lines further down it says:  `The  use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.`
Comment: The consequence of set tv to {0, 0}: http://www.wired.com/2016/02/dont-set-your-iphone-back-to-1970-no-matter-what/
Comment: @John Hascall, After fully read the manpage of setimeofday(), it seems that the tz_dsttime fied of timezone will not be supported in linux, but the tz_minuteswest filed is still needed to be set. I am not sure I read correctly.
Comment: Numerous reputable examples (such as Robert Love's Linux System Programming) show settimeofday() used with the second argument set to NULL. Furthermore, I tried passing in a non-NULL timezone struct and it made no difference.
Comment: It seems you are prohibited to set tv to {0, 0}, the start of Epoch time. as mentioned in [this page](http://www.gnu.org/software/libc/manual/html_node/High_002dResolution-Calendar.html), _Use adjtime (below) to make a smooth transition_ @JoshuaJohnson

how to use settimeofday(2)?


xmlGregorianCalendar convert to GregorianCalendar reducing the date by a day

Question: I am trying to convert the xmlGregorianCalendar to Date. But the output is reducing the date by a day.
The below is the code I use - xmlGregorianCalendar is passed as 2019-04-02Z ,
But when the below line is executed its returns the date as - Mon Apr 01 19:00:00 CDT 2019
private Date formatDate(XMLGregorianCalendar xmlGregorianCalendar) {

    if(null != xmlGregorianCalendar ) {
        return xmlGregorianCalendar.toGregorianCalendar().getTime();
    }
    return null;
}

Not sure what am I doing wrong.
Comment: I would suggest you start using `java.time.LocalDate` for date-only values, instead of the outdated `java.util.Date` class. See [Convert between LocalDate and XMLGregorianCalendar](https://stackoverflow.com/q/29767084/5221149) for how to convert correctly.
Comment: @Andreas - used localDate to get desired result. Thanks
Comment: The value is being skewed by time zone. You need to account for time zone.
Comment: `04/02/2019` is not a valid XML date string. Did you mean that XML value is `2019-04-02`?
Comment: @Andreas Updated the Question - date is passed as 2019-04-02Z but converted as - Mon Apr 01 19:00:00 CDT 2019
Comment: As I said, the `2019-04-02Z` value (in UTC time zone) is being converted to 4/1/2019 at 7:00 PM in Central Time Zone, which is correct. To get correct date value, *you* must specify time zone of UTC when formatting the date value for display.
Comment: Oh, the trouble with the good old, no, bad old `Date` class again. No one should be using that anymore. Glad that the modern `LocalDate` helped you out.
Answer: Try to use this:
return xmlGregorianCalendar
    .toGregorianCalendar(TimeZone.getTimeZone("Coordinated Universal Time"), null, null)
    .getTime();

Comment: No  - Its still the same returned as - Mon Apr 01 19:00:00 CDT 2019


What's the difference between the associative law and the commutative law?

Question: Both laws say that for some operations the order in which the calculation happens does not affect the result. Where is the difference exactly?
Comment: $x\circ y = xy+1$ is commutative but not associative.
Comment: Pairwise averaging, $x\circ y:=(x+y)/2$, is also commutative but not associative. And matrix multiplication is associative but not commutative.
Comment: One says the order of the parantheses doesn't matter, the other that the order of the terms doesn't matter. You can have associative non commutative laws but also commutative non associative laws.
Comment: Does anyone know a nice minimal example for a commutative non-associative operation?
Answer: The commutative law says that $X \circ Y = Y \circ X$ where $\circ$ is the operation under consideration (addition, multiplication, what have you). In words, you can swap the order of the two inputs of the operation and it won't matter.
The associative law says that $(X \circ Y) \circ Z = X \circ (Y \circ Z)$, where the parentheses tell you what you should be doing first. As you can tell, it's quite different: this is no longer about changing the order of the "things" you operate on, but rather the order of the operations themselves.
Suppose the "things" are permutations of 3 objects (so that "swap 1 and 2" and "move 1 to 2, 2 to 3 and 3 to 1" are legitimate "things"), and the "operation" is "do the first and then the other". You can see for yourself that the commutative law is not satisfied (try swapping 1 2 and then 2 and 3 vs doing it in the opposite order), but the associative law is.
Answer: These are really hard for me to keep straight. I like Alon's answer but I also like something really simple I can reference:

Associative: order of operations
Commutative: order of operands

The other trouble I have beyond this is coming up with a simple literal example versus an abstract. If I think of one, I'll add it here.


jQuery or vanilla JavaScript: Replace or escape all < and >

Question: I have a div like this

ASDF IS AWESOME

Just another Headline

Hey

and need a jQuery or vanilla JavaScript function, method to convert the whole stuff into this
<div id="asdf"
  <div>
    <p>ASDF IS AWESOME</p>
  </div>
  <h1>Just another Headline</h1>
  <nav>
    <ul>
      <li class="listitem"Hey</li>
    </ul>
  </nav>
</div>

so I just want to escape the < and >
I tried .replace and .text()
Comment: Duplicate of : https://stackoverflow.com/questions/784586/convert-special-characters-to-html-in-javascript
Comment: You can check my answer below using only one function.
Answer: Try that

var html = $('#asdf').html();
var escaped=$('
').text(html).html();
console.log(escaped);

ASDF IS AWESOME

Just another Headline

Hey

Comment: `$("#asdf").prop("outerHTML")` would be a better idea - since `#asdf` should be also included
Answer: Try this: Using only 1 function, then you can use it wherever you want

$(document).ready(function(){
  $selector = $('#asdf');
  console.log(htmlEntities($selector));
  function htmlEntities(str) {
    str = str.html();
    return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
  }
});

ASDF IS AWESOME

Just another Headline

Hey

You can reference this: https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/


Life table probabilities

Question: I am using 2007's Social Security Life Table: http://www.ssa.gov/oact/STATS/table4c6.html
I would like to use the table to generate a number for each scenario I ran. This number represents the remaining life (in years) scenario n will live. The way I plan to do this is to first input an age 'x' let say age 60. I get the corresponding number on column 'Number of Lives' which is 85,227. (This simply reveals that out of 100K people, 85,227 survived) Next, I randomly select one integer from 1:100K and if it is less than 85,227, then this scenario will continue on to next year else this case will die off. I repeat this process, at each age get the corresponding number from column 'Number of Lives' and so on ...
I want to know if such method is sound from a probability perspective. Does it violate any axioms. Do I still preserve the underlying population distribution of the table? Any better ways of doing it?
Comment: most life table comes with a column that tells you the expected life at that age.
Comment: What you're describing, in essence, is an [accept reject algorithm](http://en.wikipedia.org/wiki/Rejection_sampling).
Answer: I don't want to say that there is anything wrong with the approach but I do not understand why you need to simulate.  The life table is a discrete form of survival analysis where instead of looking at survival data in continuous time you group by a time interval like years.  The method is often referred to as the Cutler-Ederer method due to a famous paper by those authors. It is essentially an interval form of Kaplan-Meier (at least there is an analogy that can be made).
If age is a covariate that you want to use in constructing tables, you could do a survival model that uses regression (it could be through a parametric survival model as in the SAS lifereg procedure or a semiparametric survival model, e.g. the Cox proportional hazard model).  Given data that enable you to fit such a model, I think you could construct your lifetables from such a model.
Answer: Yeah if you choose a radix of $100,000$, then $l_{x+t}/l_x$ is the probability of somebody aged $x$ living at least $t$ more years.

Life table probabilities


multiple UIAlertView issue

Question: I have an issue with my code, I have two blocks of code of UIAlertViews one with cancel and ok button, and the other to make a UIImagePicker
-(IBAction)publicaPeticion
 {
    if([txtPeticion hasText] )
    {

        UIAlertView *alerta = [[UIAlertView alloc]
                              initWithTitle:@"Confirmación de Compra"
                              message:@"Deseas comprar la petición por $12.00"
                              delegate:self
                              cancelButtonTitle:@"Cancelar"
                              otherButtonTitles:@"Aceptar", nil];
        [alerta show];
    }

}

The issue is between publicaPeticion and cargaImagen
-(IBAction)cargaImagen
{

    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Subir una imagen"
                          message:@"¿De donde deseas subir una imagen?"
                          delegate:self
                          cancelButtonTitle:@"Cancelar"
                          otherButtonTitles:@"Desde el equipo",@"Tomar con camara", nil];
    [alert show];

}

and also my method to get the source of the image, from the photo stream or from the camera
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker animated:YES];

    }
    if(buttonIndex ==2)
    {
        picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentModalViewController:picker animated:YES];
    }
}

the question is, that when i press "Aceptar" button (OK), it takes me to the upload picture from the photo library...
maybe is a little bit silly the question but how can I differentiate it?
Answer: A couple ways.
1)
See how the delegate method is called?
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

From the alertView parameter, you can tell which alert did the calling (if you set cargaImagen and publicaPeticion's alertviews to separate instance variables).
2)
Another (and probably easier) thing you could do is to set a tag property on your alertView.
In your 'cargaImagen' method and right after you create the UIAlert, set the tag to 1 via alert.tag = 1;.
Then, in your alertView:clickedButtonAtIndex: delegate method, when alertView.tag == 1, you'll know it comes from cargaImagen and if it's 2 (or zero), you know it comes from publicaPeticion.

multiple UIAlertView issue


What's the point of Software Assurance on a MS Volume License?

Question: I'm currently trying to buy a whole bunch of Windows 7 licenses to upgrade XP and Vista Home Premium to Windows 7 Professional.
It seems like a good time to start on an Open License agreement.  Every time I talk to a vendor, or go through Microsoft's Licensing website, I see references to Software Assurance.
Apparently it offers some level of updates.. I'm confused though.  I thought updates were already free for anyone with a genuine copy of windows.

Do you have a license with Software Assurance enabled?
What do you use the "Assurance" for?
Is it worth the extra £90ish?
Answer: Software Assurance provides access to the new major versions of the software; for instance, a Windows Vista Software Assurance customer got automatic access to Windows 7 when it came out, for no additional cost above the Software Assurance.
Basically, it's buying the software on subscription instead of paying the upgrade costs all at once when moving to a new version.
Answer: Another benefit is for example getting Extended Hotfix Support for older versions (for non-security hotfixes).


ASP .NET MVC 5 - DropDownList com ModelState?

Question: Estou desenvolvendo um sistema de cadastro utilizando MVC5 com DAO, porém vieram algumas dúvidas que não consegui solucionar.
Tenho uma tabela onde cadastro Projetos e uma outra onde ficam os tipos de Projetos:
Tabela: Projetos
Campos:

ProjProjetoId
ProjNome
ProjTipoId

Tabela: ProjetoTipo
Campos:

ProjTipoId
ProjTipoNome

Preciso mostrar na minha view um DropDownList com todos os projetos para o usuário selecionar (no cadastro). E também preciso trazer esses Tipos de Projetos na página de Editar Projeto, de modo que o valor cadastrado anteriormente venha selecionado.
Após algumas pesquisas consegui fazer funcionar, porém não do jeito que eu gostaria que atualmente o código se encontra assim:
(ProjetoController)
//Controller GET: Projeto/Edit/5
public ActionResult Editar(int id)
{
    //Pesquisar projeto selecionado
    ProjetoDAO proj_dao = new ProjetoDAO();
    Projeto proj = proj_dao.listById(id);

    //Pesquisar todos os TIPOS de projetos
    ProjetoTipoDAO proj_tipo_dao = new ProjetoTipoDAO();
    List<ProjetoTipo> lista_projetotipo = proj_tipo_dao.ListAll();

    //Lista de SelectListItem
    List<SelectListItem> lista_ddl = new List<SelectListItem>();

    //Percorrer lista de Tipos de Projetos e adicionar na lista de SelectListItem
    bool selected = false;
    foreach (var item in lista_projetotipo)
    {
        //Checar se é o ID selecionado
        selected = (proj.ProjTipoId.ToString().Equals(item.ProjTipoId.ToString()));

        //Adicionar item na lista
        lista_ddl.Add(
            new SelectListItem()
            {
                Text = item.ProjTipoNome,
                Value = item.ProjTipoId,
                Selected = selected
            });
    }

    //Enviando a lista de Tipos de Projetos para a view através de ViewBag
    ViewBag.ListaTiposProjeto = lista_ddl;
}

(Editar.cshtml)

            @Html.LabelFor(model => model.ProjTipo,
                 new { @class = "control-label" })

            @Html.DropDownList("ListaTiposProjeto", null,
              "Selecione um item", new { @class = "form-control" })

Dessa forma, consigo exibir os dados no DropDownList e também trazê-lo selecionado na página de editar, porém não consigo utilizar o ModelState para validar o formulário.

Como eu faria a mesma coisa usando o @Html.DropDownListFor<>?
Esse seria mesmo o caminho?, pois segui alguns tutoriais e não deram certo!
Answer: Você pode criar um ViewBag com as informações do TipoProjeto, seria mais ou menos assim:
  public ActionResult Editar(int id)
    {
        //Pesquisar projeto selecionado
        ProjetoDAO proj_dao = new ProjetoDAO();
        Projeto proj = proj_dao.listById(id);

        //Pesquisar todos os TIPOS de projetos
        ProjetoTipoDAO proj_tipo_dao = new ProjetoTipoDAO();
        List<ProjetoTipo> lista_projetotipo = proj_tipo_dao.ListAll();

        SelectList dropDown = new SelectList(lista_projetotipo, "ProjTipoId", "ProjTipoNome");

        ViewBag.ListaTiposProjeto = dropDown;

        return View(proj);
    }

View:

                        @Html.LabelFor(model => model.ProjTipo, new { @class = "control-label" })

                        @Html.DropDownListFor(model => model.ProjTipo, (SelectList)ViewBag.ListaTiposProjeto, "Selecione um item", new { @class = "form-control" })

é necessário que na sua classe Projeto tenha o ID de Tipo de projeto e que na recuperação do objeto esse ID tenha valor
Comment: Obrigado, funcionou da forma como eu precisava.
Answer: Na sua viewmodel, crie o seguinte atributo:
public SelectList TiposProjeto { get; set; }

aí, onde você prepara a sua tela (controller ou alguma outra camada), você populará:
model.TiposProjeto = new SelectList(proj_tipo_dao.ListAll(), "ProjTipoId", "ProjTipoNome");

no seu arquivo cshtml:
@Html.DropDownListFor(model => model.ProjTipoId, Model.TiposProjeto, "Selecione...", new { @class = "form-control" })

dessa maneira, caso já tenha valor dentro de ProjTipoId, ele já virá selecionado.


How do I hide the submission button basing on some conditions?

Question: I have a webform with a mandatory Yes/No button. I want to hide the submission button if No is selected.
How can I set up the logical condition for achieving this?
Answer: I just figured out that there is the 'Submit' element at the end of the webform elements under webform build tab and I can apply the conditions on that 'Submit' element.
Answer: If I were you I'd make it easier for myself and leave it as is.
Because if the answer is no and you don't want him to submit at all so bother to make him do it from the first place!
But: if you need this to happen it is possible to have a little JavaScript doing that for you, see this Example


Parsing and removing text with cmd or powershell

Question: I've checked quite a few other questions here but was unable to find what I need. I am currently trying to automate the process of finding out what VMs are in what Hyper V servers. Here is my current script.
@echo off
set /P dc= "Which DC do you want? "
dsquery computer -name %DC%VUT* > dsquery.txt
type dsquery.txt | findstr /v IMAGINGOU | findstr /v OTHEROU > dsquery2.txt
powershell -command Get-Content dsquery2.txt | ForEach-Object { $_ -replace '"CN=', "" } | Set-Content dsquery3.txt
powershell -command Get-Content dsquery3.txt | ForEach-Object { $_ -replace ',OU=CAM,OU=Exchange,OU=Server,DC=RED001,DC=local"', "" } | Set-Content serverlist.txt
powershell -command .\Get-HyperVMod.ps1 -file output.csv

The problem I have hit is the servers that I can do dsquery from (Win2k3) can't do the ForEach-Object because they have an older version of Powershell and the Win2k8 servers that can do the ForEach-Object can't do a dsquery.
Here is a sample of the dsquery output that I am trying to parse and remove all but the server name.
"CN=SERVER001,OU=VUT,OU=Infastructure,OU=Server,DC=dcname,DC=local"
"CN=SERVER008,OU=ImagingWDS,DC=red002,DC=local"

Output should be
SERVER001
SERVER008

Any suggestions on either doing this with another method or just my small problem of removing the extra text from the file.
Answer: run this against your dsquery.txt, it will parse what you need.
@echo off
setlocal enabledelayedexpansion
::Echos your Computer Name only.
for /F "tokens=1,2 delims==," %%G IN (dsquery.txt) DO echo %%H
pause
endlocal

basically what it does is uses two different delimeters: "=" and "," which immediately surround your server names. and looks only for that second token. It works based on the strings you provided above.
Answer: The ForEach-Object cmdlet was introduced in PowerShell V1 so you'll have it there.
Jon's regex here shows you how you can pull the common name from a LDAP string.
This will apply the regex to each line in a text file and return the result.
Get-Content file.txt | % { $_ -replace '(CN=)(.*?),.*', '$2' }

Update
Here's how your batch script would translate into PowerShell:
$dc = Read-Host "Which DC do you want?"
& dsquery computer -name "${dc}VUT*" | % {
    # Do your processing here...
    $_ -replace '(CN=)(.*?),.*', '$2'
}

Comment: That works but only if I enclose it in quotes which leaves the output with quotes. I assume it have to do because I am calling a powershell command from a batch file

`powershell -command "Get-Content dsquery2.txt | % { $_ -replace '(CN=)(.*?),.*', '$2' }"`
Comment: @Edwin Why don't you just go all PowerShell instead of mixing the two? Life would be much easier :-)
Comment: I honestly don't know anything about powershell. Just trying to do the best I can as quickly as I can with what I know. I'll try and make the whole thing in Powershell then since I can't seem to get it to work with the two.
Comment: @Edwin I updated my answer to show you how you can translate your batch script into a pure PowerShell script. If you show me what your original text file looks like and describe the result you want I can add an example to do that.


What's this (flamenco?) rhythm called? (Tres Lagrimas)

Question: This song by Guitarra Azul has a very distinctive rhythm that I have also heard in other songs. How is it called? Is it one of the classical flamenco rhythms?
Comment: This is a tango. There are a couple variations of the rhythm but the one heard here is the most common, wih the upright bass playing a bassline with the rhythmic pattern (**1!** + 2 **+! 3!** + **4!**)
Comment: according to [this answer](https://music.stackexchange.com/a/5263/32406) and what I was taught in highschool, the tango is characterised by having four beats in a bar and having an emphasis on the "and" of beat two. I would also like to add that the video of the man playing on the link you gave also uses this rhythm
Comment: @Aric: You could combine your comments into a nice answer :)
Comment: At 3:18, you can also see that guy playing a 3:2 son clave rhythm on the wood clave
Comment: @Aric thanks. According to this [link](https://flamencobites.com/main/flamenco-rhythm-tangos.html), typical tango is 8 beats, accented as 1 **2 3 4** 5 **6 7 8**. But this song seems more like 1 2 **3** 4 5 6 **7** 8.
Comment: If you were to count at double speed and put 8 notes in a bar, the rhythm would be (**1** 2 3 **4 5** 6 **7** 8)
Answer: agreed this is a Typical Bolero with a 3:2 then 2:3 Clave Pattern - I wrote this song in 2005 for my Group Guitarra Azul on our first Album! I hope you Like it!
Comment: Welcome, Stefano!
Comment: Thanks for your comment Steve! I really enjoy the music of Guitarra Azul.
Answer: Thanks to guidot for reminding me about this question.

This is a tango. There are a couple different tango rhythms. The most common one (and the one used in this video, played clearly on the upright bass) is tango rhythm 1 in the diagram below:

As seen in the diagram and according to this answer, tango rhythms are characterised by having four beats in a bar and having an emphasis on the "and" of beat two. Both of the rhythms above fit these criteria.
Another point of interest is the 3:2 son clave rhythm being played on the wood claves at 3:18 in the video. The 3:2 and 2:3 rhythms are as follows (2:3 is just 3:2 but the other way round)


O que são os arquivos .pyi do Python e para que servem?

Question: Reparei que na hora de criar um arquivo Python no PyCharm é oferecida uma opção "Python stub". Isso cria um arquivo .pyi. O que são esses arquivos e para que servem?
Answer: pyi significa "Python interface". Interface, nesse sentido, é uma descrição dos tipos das funções, variáveis, classes etc. de um módulo, mas sem nenhuma implementação. Os stub files foram propostos na PEP 484, lançada pelo próprio criador do Python, que versa sobre inferência de tipos na linguagem.
Os arquivos .pyi são usados apenas pelo ambiente de desenvolvimento, eles não servem para ser executados (embora possam). As IDEs devem oferecer compatibilidade para esse recurso.
Seja test.py um módulo próprio ou de terceiros. Ao criar um arquivo test.pyi (a localização dele não importa, basta que a IDE esteja configurada para encontrá-lo), ele passará a oferecer inferência de tipos para o módulo de implementação. Por exemplo:
# test.py, o arquivo de implementação
def area_retangulo(base, altura):
    return base * altura

Só com essa sintaxe, não há indicação alguma de tipos. base, altura e o retorno da função são todos desconhecidos. No entanto, se tivermos um arquivo de interface:
# test.pyi, o arquivo de interface
def area_retangulo(base: float, altura: int) -> float: ...

A IDE automaticamente infere o tipo dos parâmetros e do retorno da função area_retangulo no módulo test.py. Repare que o arquivo .pyi não tem uma sintaxe especial, esta é meramente uma declaração de função que poderia ser feita num arquivo .py tradicional.
Segundo a própria especificação dos stub files, é recomendado que se use o operador Elipsis, que é as "reticências" (...), para não fornecer as implementações. Também é possível fornecer o tipo de variáveis (usando simplesmente variavel: tipo) e de métodos de classe.
Bem, os stub files não oferecem nenhuma funcionalidade a mais em relação ao que já é possível de se fazer sem eles. A proposta deles é melhorar a organização do código, visto que inferência de tipos pode tomar um espaço muito grande nos módulos. Além disso, eles também são usados para permitir a retrocompatibilidade do Python 3 para com o Python 2 sem que se perca a tipagem forte. Também é possível especificar a interface de uma biblioteca de terceiros que não a ofereça ainda.
Quem quiser usar os stub files no seu projeto deveria ler a seção dele (link no primeiro parágrafo), que contém diversos detalhes bem específicos de como usá-los.


Docker, UFW and IP Tables

Question: first of all, i kind of new to docker / linux / ufw and stuff!
What i´m doing:
I´m creating a docker container which exposes a port. in this case its 8080.
 The container behaves as expected.
Secondly i want to close down the server. Therefore i activate UFW and only allow 22, 80, 443.
I would have expected that i cannot access the myserver:8080, since the port is closed!
I understand that docker uses the iptables todo 'stuff' regarding routing to it. As of now its sadly just 'stuff' to me.
So i created the json file /etc/docker/daemon.json with this content:
{
        "iptables": true
}

with the intent to make sure that all my ports stay closed and UFW works as expected.
At first everything seemed to be working just fine until i noticed that my container cannot reach out anymore. It seems that it cannot resolve the dns.
So i get that i´m playing with stuff i dont fully understand currently.
What i´m trying todo!
I basicly want containers running, with closed ports. But the containers should be able to reach http/https api´s on the outside. How can i accomplish that?
Any help and support for my learning process is greatly appreciated :)
Thanks in advance.
Regards,
Hannes
Answer: The standard port used by DNS is UDP 53, so you have to allow the output port 53 in udf
sudo udf allow out 53

Answer: if you want to expose the port 8080 and want to bind the same port on host for the container, then you need to open 8080 port on host Iptables. / ufw.
docker run -d --name container_name -p 8080:8080 Image_name:tag

Docker, UFW and IP Tables


Can't get CKEditor to work on Drupal 7.8

Question: I've tried both the CKEditor module, as well as the WYSIWYG module (with CKEditor library installed). I've configured it all correctly and it should work, but it doesnt. I've also tried changing the CSS options but still nothing.
I'm getting "r is undefined" in the console, but only if I change the text format option underneath where the editor should be.
I'm currently working off localhost - might that be an issue?
Comment: Working from your localhost won't be an issue. What exactly do you mean by not working though? Are you able to enable the module and just not see the editor appear on fields? Are you able to edit content with the WYSIWYG editor but it doesn't actually format the content appropriately?
Comment: I am able to see the module, and select CKEditor, however when it comes to editing content there's nothing but white space.
Comment: You probably didn't configure it correctly. Maybe some files are missing from /site/all/libraries/ckeditor. Make sure you use CKEditor through WYSIWYG.
Comment: It is all configured properly, including the CKEditor library, as I said.
Comment: It's eider you have js disabled in your browser or it's installed or configured the wrong way. Can't be anything else.
Comment: Lol well it was something else, read my answer.
Comment: it is not, like i wrote you installed or configured it the wrong way, i also suggest to use ckeditor through wysiwyg module
Answer: Well I finally got it working...
I installed CKEditor module, CKEditor library, and then had to hack the CKEditor library folder by creating new subdirectories with the appropriate files (it was looking for the skin and language files in the wrong directory within the CKEditor library folder)...
I'm using the latest version of everything - why is this happening? I would have thought since this happened to me its happening to everyone else as well!
If anyone else has this problem, ensure you have these files in your /modules/ckeditor/ckeditor/ folder:
"lang/en-gb.js"
"skins/kama/images/sprites.png"
"skins/kama/editor.css"
"skins/kama/icons.png"
All these files are just in the root folder by default for some reason.


Is it possibleto Start a Flash video with jquery?

Question: I'm using html5 as a video player but as it doesn't work in ie8 and we have to support ie8 im using a fallback to flash.  I need the videos to swap from one to another on click which i have got to work for both the html5 video player using .load and the flash player by replacing the html in a div but I need the video to start to play.
In html5 it works as follows:
<code>                    $(".featureLogoText").on("click", function (event) {

                        $oVideo[0].pause();
                        $oPause.hide();
                        $oPlay.hide();
                        $oPlay.css('display', 'block');

                        var media = $(this).attr('media');
                        var mediamp4 = media + "mp4";
                        var mediawebm = media + "webm";
                        var mediaogv = media + "ogv";
                        var newPoster = $(this).attr('data-poster');
                        $('.scrPoster').attr('poster', newPoster);
                        $('.scrVideomp4').attr('src', mediamp4);
                        $('.scrVideowebm').attr('src', mediawebm);
                        $('.scrVideogg').attr('src', mediaogv);
                        $(".scrPoster").load();

                        var html = ' <param name=\"movie\" value=\"http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf\" type=\"application/x-shockwave-flash\"allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"352\" height=\"198\" flashvars=\"src=' + mediamp4 + '&poster=' + newPoster + '\"></embed>';

                        $("#objFlash").html("");
                        $("#objFlash").append(html);

                        var number = $(this).attr('data-number');
                        alert(number);

                        $oVideo[0].play();
                        $oPlay.hide();
                        $oPlayBig.hide();
                        $oPause.css('display', 'block');
                    });
</code>
How can i do the same thing with flash? is it possible? Or is there a better way to show video across browser incl ie8 - i've looked at videojs but it says that doesn t support ie8.
Thanks
Answer: This is strictly dependent on the type of flash player you choose to use.
some have an API that allow to programatically play the video.
In example. the common player FlowPlayer has such a command:
<code>// get a handle to the first player on the page and start the clip
$f(0).play();

// get a handle to the first player and stop it
$f().stop();
</code>
Short answer: Yes.
Comment: I think i ll need to look into flowplayer i m currrently using http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf i'm afraid i dont  kow a hige amount about fladsh


Underline entre duas variáveis

Question: Tenho o seguinte código num arquivo .sh:
echo "$pasta/Dados/$MA/$ano\_$mes/$tabela"

Com todas as variáveis setadas corretamente. Porém, ai rodar o script, o echo resulta em
data-integration/Dados/MA1/2015\_11/HT_MA1_ESS_SEG

Enquanto eu gostaria que o resultado fosse
data-integration/Dados/MA1/2015_11/HT_MA1_ESS_SEG

Existe alguma outra sintaxe para essa situação?
Obrigado.
Answer: Uma possibilidade é você colocar o nome das variáveis entre chaves {}:
#!/bin/sh

pasta="data-integration"
MA="MA1"
ano="2015"
mes="11"
tabela="HT_MA1_ESS_SEG"

echo "$pasta/Dados/$MA/${ano}_${mes}/$tabela"

Executando o programa acima, a saída é:
data-integration/Dados/MA1/2015_11/HT_MA1_ESS_SEG
testado com GNU bash, version 4.3.42
Comment: Funcionou perfeitamente! Obrigado!

Underline entre duas variáveis


Why doesn't $query->hasTag() work with this view?

Question: Below I have a View. I have the following hook. I'm hoping to modify the WHERE clause of the view, but the following code seems not to be called.
function jch_utilities_query_alter(QueryAlterableInterface $the_query) {
  if ($the_query->hasTag('jch')) {
    dsm('Found it!');
    dsm($the_query);
  }
}

I wanted to use hook_views_query_alter() but I read that it doesn't work with indexed content. So I was trying this. I also couldn't get Views PHP to work (bug with $row).
I just want a way to modify $query->where and I keep getting blocked at every turn. Any suggestions?
$view = new view();
$view->name = 'collection_products';
$view->description = '';
$view->tag = 'jch';
$view->base_table = 'search_api_index_product_display';
$view->human_name = 'Collection products';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = '%1';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['class'] = 'products-per-collection';
$handler->display->display_options['row_plugin'] = 'fields';
/* Header: Global: View area */
$handler->display->display_options['header']['view']['id'] = 'view';
$handler->display->display_options['header']['view']['table'] = 'views';
$handler->display->display_options['header']['view']['field'] = 'view';
$handler->display->display_options['header']['view']['view_to_insert'] = 'collection_products:block_1';
$handler->display->display_options['header']['view']['inherit_arguments'] = TRUE;
/* Relationship: Category */
$handler->display->display_options['relationships']['field_category']['id'] = 'field_category';
$handler->display->display_options['relationships']['field_category']['table'] = 'search_api_index_product_display';
$handler->display->display_options['relationships']['field_category']['field'] = 'field_category';
$handler->display->display_options['relationships']['field_category']['ui_name'] = 'Category';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_entity'] = 0;
/* Field: Content: Rendered Content */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_node';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['label'] = '';
$handler->display->display_options['fields']['rendered_entity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['display'] = 'view';
$handler->display->display_options['fields']['rendered_entity']['view_mode'] = 'product_list';
/* Sort criterion: Category: Search Rank (indexed) */
$handler->display->display_options['sorts']['field_category_field_search_rank']['id'] = 'field_category_field_search_rank';
$handler->display->display_options['sorts']['field_category_field_search_rank']['table'] = 'search_api_index_product_display';
$handler->display->display_options['sorts']['field_category_field_search_rank']['field'] = 'field_category_field_search_rank';
/* Contextual filter: Indexed Content: Collection */
$handler->display->display_options['arguments']['field_collection']['id'] = 'field_collection';
$handler->display->display_options['arguments']['field_collection']['table'] = 'search_api_index_product_display';
$handler->display->display_options['arguments']['field_collection']['field'] = 'field_collection';
$handler->display->display_options['arguments']['field_collection']['default_action'] = 'not found';
$handler->display->display_options['arguments']['field_collection']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_collection']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_collection']['summary_options']['grouping'] = array(
  0 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['arguments']['field_collection']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['field_collection']['validate']['type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['field_collection']['validate_options']['vocabularies'] = array(
  'collection' => 'collection',
);
$handler->display->display_options['arguments']['field_collection']['break_phrase'] = 0;
/* Filter criterion: Indexed Content: Status */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'search_api_index_product_display';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = array(
  1 => '1',
);
$handler->display->display_options['filters']['status']['group'] = 1;
/* Filter criterion: Indexed Content: Content type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'search_api_index_product_display';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'bags_cases' => 'bags_cases',
  'basic_products' => 'basic_products',
);
$handler->display->display_options['filters']['type']['group'] = 1;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = '%1';
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
$handler->display->display_options['fields']['name_1']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name_1']['label'] = '';
$handler->display->display_options['fields']['name_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['name_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name_1']['link_to_entity'] = 0;
$handler->display->display_options['fields']['name_1']['replace_spaces'] = TRUE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['text'] = '
[name]
';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_entity'] = 0;
/* Field: Content: Rendered Content */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_node';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['label'] = '';
$handler->display->display_options['fields']['rendered_entity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 0;
$handler->display->display_options['fields']['rendered_entity']['display'] = 'view';
$handler->display->display_options['fields']['rendered_entity']['view_mode'] = 'product_list';
/* Field: Collection: Description (indexed) */
$handler->display->display_options['fields']['field_collection_description']['id'] = 'field_collection_description';
$handler->display->display_options['fields']['field_collection_description']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_collection_description']['field'] = 'field_collection_description';
$handler->display->display_options['fields']['field_collection_description']['label'] = '';
$handler->display->display_options['fields']['field_collection_description']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_collection_description']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_collection_description']['link_to_entity'] = 0;
/* Field: Category: Search Rank (indexed) */
$handler->display->display_options['fields']['field_category_field_search_rank']['id'] = 'field_category_field_search_rank';
$handler->display->display_options['fields']['field_category_field_search_rank']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_category_field_search_rank']['field'] = 'field_category_field_search_rank';
$handler->display->display_options['fields']['field_category_field_search_rank']['label'] = '';
$handler->display->display_options['fields']['field_category_field_search_rank']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_category_field_search_rank']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_category_field_search_rank']['settings'] = array(
  'thousand_separator' => ' ',
  'prefix_suffix' => 1,
);
/* Field: Indexed Content: Collection */
$handler->display->display_options['fields']['field_collection']['id'] = 'field_collection';
$handler->display->display_options['fields']['field_collection']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_collection']['field'] = 'field_collection';
$handler->display->display_options['fields']['field_collection']['label'] = '';
$handler->display->display_options['fields']['field_collection']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_collection']['link_to_entity'] = 0;
$handler->display->display_options['fields']['field_collection']['display'] = 'id';
$handler->display->display_options['fields']['field_collection']['view_mode'] = 'full';
$handler->display->display_options['fields']['field_collection']['bypass_access'] = 0;
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Indexed Content: Status */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'search_api_index_product_display';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = array(
  1 => '1',
);
$handler->display->display_options['filters']['status']['group'] = 1;
/* Filter criterion: Indexed Content: Content type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'search_api_index_product_display';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'bags_cases' => 'bags_cases',
  'basic_products' => 'basic_products',
);
$handler->display->display_options['filters']['type']['group'] = 1;
$handler->display->display_options['path'] = 'collection/%';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['defaults']['css_class'] = FALSE;
$handler->display->display_options['css_class'] = 'collection-terms';
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'name_1',
    'rendered' => 0,
    'rendered_strip' => 1,
  ),
);
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['style_options']['class'] = 'head-test';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['header'] = FALSE;
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = '
On This Page
';
$handler->display->display_options['header']['area']['format'] = 'full_html';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_entity'] = 0;
$handler->display->display_options['fields']['name']['replace_spaces'] = TRUE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
$handler->display->display_options['fields']['name_1']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name_1']['label'] = '';
$handler->display->display_options['fields']['name_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['name_1']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['name_1']['alter']['text'] = '[name_1]';
$handler->display->display_options['fields']['name_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name_1']['link_to_entity'] = 0;
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = '';
$handler->display->display_options['fields']['nothing']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['nothing']['hide_empty'] = TRUE;
/* Field: Collection: Description (indexed) */
$handler->display->display_options['fields']['field_collection_description']['id'] = 'field_collection_description';
$handler->display->display_options['fields']['field_collection_description']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_collection_description']['field'] = 'field_collection_description';
$handler->display->display_options['fields']['field_collection_description']['label'] = '';
$handler->display->display_options['fields']['field_collection_description']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_collection_description']['link_to_entity'] = 0;
/* Field: Category: Search Rank (indexed) */
$handler->display->display_options['fields']['field_category_field_search_rank']['id'] = 'field_category_field_search_rank';
$handler->display->display_options['fields']['field_category_field_search_rank']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_category_field_search_rank']['field'] = 'field_category_field_search_rank';
$handler->display->display_options['fields']['field_category_field_search_rank']['label'] = '';
$handler->display->display_options['fields']['field_category_field_search_rank']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_category_field_search_rank']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_category_field_search_rank']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
);
$translatables['collection_products'] = array(
  t('Master'),
  t('%1'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Category'),
  t('All'),
  t('Page'),
  t('
[name]
'),
  t('Block'),
  t('
On This Page
'),
  t('[name_1]'),
);

Answer: I've never used tag but it should work, name works and that's usually where I change mine.
/**
 * Implements hook_views_query_alter().
 */
function MODULENAME_views_query_alter(&$view, &$query) {
  // Alter query for 'OR'.
  if ($view->name === 'VIEW_NAME') {
    $query->where[0]['type'] = 'OR';
  }
}

For reference: hook_views_query_alter()
edit
I guess I should have read closer, the view is integrated with search API. So you have to use hook_search_api_query_alter() I believe.
function hook_search_api_query_alter(SearchApiQueryInterface $query) {
  $info = entity_get_info($index->item_type);
  $query->condition($info['entity keys']['id'], 0, '!=');
}

More info
Comment: Unfortunately, this view does not get fired with hook_views_query_alter(). Apparently that is the case for views which use Indexed content as I wrote above. Are you using Commerce and the Search API? collection_products?
Comment: Have you tried this alter? http://drupalcontrib.org/api/drupal/contributions!search_api!search_api.api.php/function/hook_search_api_query_alter/7
Comment: Here's another link: https://www.drupal.org/node/2179003
Comment: Thanks, I'll give it a shot. Some days... I truly -hate- Drupal. Or rather... the absolutely crap documentation.
Comment: PS... What's weird: hook_views_pre_render() DOES work with this View. Why oh -why- would that work and hook_views_query_alter -not- work? That's the kind of thing that drives me NUTS.
Comment: Yea I feel that somedays, the search api alter wasn't present until sometime in 2013, probably didn't make it into stable until late 2013-early 2014. Usually if you look in the module code on decent modules there will be API documentation (usually named MODULENAME.api.php) about what hooks are available. As for the other comment pre render would work due to the fact the view is already in the render array I believe, it's a theme type hook the other hook runs in the DB layer so I get why the normal query alter wouldn't work in this case.


Largest audience for a sport match?

Question: It was said than one of the last Real Madrid vs Barcelona was watched by 600 millions persons. Audience Real Madrid vs Barcelona FC
Is this the largest audience for a sport match or are there F1 or other sport matches which has a larger audience?
Answer: According to FIFA, seems that more than 715 million people watched the 2014 World Cup Final source.
So I believe that this events has a large audience than that match
Answer: There is a new record, the 2018 world cup final was viewed by 1.12 billion viewers.
Record audience world cup

Largest audience for a sport match?


Custom block: How to know you're in an admin context?

Question: I've developed a custom block which relies on a taxonomy term ID being present in the URL, otherwise it throws a 404.
I've placed this block in a panel page (ctools pages), but now when I try to edit the panel page, I get a 404 response, but only on the "Content" tab of the panel page variant.
What's the proper method for knowing you're on an admin page, or in the context of a panel edit, so that I can skip throwing a 404?
Answer: Looks like I just need to call path_is_admin
if (!path_is_admin(current_path())) {
  drupal_not_found();
  drupal_exit(); // This is needed if we call drupal_not_found() from hook_block_view()
}


How to improve writing transitions between ideas?

Question: I seem to have the absolute worst time writing transitions. Any musical project that I start that has even a semblance of requiring a transition ends up taking months, trying dozens of combinations of fragments to glue 2 ideas together. Usually what ends up happening is the piece is abandoned.
I try many different types of transitions - silence, introducing material slowly, modulation, voice leading, crescendos, 1 bar fills, 2 bar fills, 4 bar fills, exposition, transient material. But it all just sounds like crap, it sticks out in my ears like a sore thumb, and ruins the musical flow.
I've tried distancing myself, coming back weeks, or months later with fresh eyes and ears, but 20 minutes later and I'm back exactly where I started.
I feel like I've exhausted all my possibilities and I'm not getting any better. Even when analyzing other composers transitions in score, I can clearly see some of the inner workings of how they did this, but when I try to take these ideas for myself, the execution is poor, and the music is at a standstill because of a really jarring piece of material.
Is there anything else I can explore (reading, examples, etc) that will help me improve? I feel as though I have no intuition in this black art, and this is the biggest thing holding me back from completing any music.
Comment: Take a piece by a respected composer. Observe how they transition between themes. Does it sound good? Can you find any recurring patterns? What if you try something similar? Does it stick in your ears like a sore thumb? What's different between your application of the method and the master's? Can you find patters? Rinse and repeat.
Comment: @Kilian Foth - Looks like the OP has already "[tried] something similar" and it still "[sticks] in [his/her] ears like a sore thumb". See "Even when analyzing other composers transitions in score, I can clearly see some of the inner workings of how they did this, but when I try to take these ideas for myself, the execution is poor, and the music is at a standstill because of a really jarring piece of material." Emphasize "What's different between your application of the method and the master's?", although it's possible that the OP cannot find any.
Comment: That's my problem, on the surface it looks like I did exactly as they did, but on playback it sounds horrible. It's almost as if you need a human to make it come alive, because a human has intuitions on how to slow up/down and crescendo in a way that makes it seem whole. If I try to play what I want, it doesn't follow what I've written, so I don't know how to express it.
Answer: Kilian's comment is right on the money, but I thought I'd share some more specific ideas:

Experiment between what we call depending and independent transitions. A dependent transition uses prior material to create the transition (i.e., it depends on prior material), whereas an independent transition uses only new material. Try writing with both types to get some ideas of what works best for you, or of what you need to work on in the future.
As you're writing dependent transitions, experiment with what material you're bringing back. Try it with something large, like a two-measure melodic/motivic snippet that you can transform. But also try it with something impossibly small, like an E/G harmonic dyad. Experiment with how much you can flesh out of this tiniest of dependent material.
Try what my old composition professor always said: just write out a string of 12 random pitches, using each pitch exactly once. Play it through a couple times, find your favorite part of the string, and then use that little segment as a kernel of an idea that you'll then develop.

Lastly, make sure you're not over-thinking this. It's possible that, in your own mind, you listen to your work and think "well, here comes the transition, I really suck at writing these" and then you hate the transition. Maybe play some music for others (or share it in our chat!) to see what others think. It's always possible that you are your own worst critic and are overlooking the positive qualities of the transitions you've written.
Comment: Important also to remember to start with the most basic question: Do I even need a transition? Separate thought: transitions aren't meant to be listened to.
Answer: Not drawing from experience, but from Sting/Gordon Sumner. Sorry, I can't remember where I read/heard it first. Let someone else play it! Sting mentioned that he doesn't feel like his music is real, unless he hears it being played by someone else.
Drawing from my own experience, it helps me to record the ideas and listen later to it -- sometimes very much later (think: years, up to decades). Sometimes ideas stick and you have the urge to come back to them, sometimes they are just lost. And I often permute ideas when I write songs. I write some text and then develop a musical idea, which then seems to fit much better to some other text, which might lead to something else... etc.
And apart from that, just relax. Unless you have some deadlines or some other outside pressure, there is no external quality meter.
What worked for me: when I really stopped worrying about writing, I started to write for real. (Please note: I don't care if it will never be heard or played by anybody.)


Where is the line between countable an uncountable ordinals?

Question: for the difference between N and R there is a discrete operation, R is the powerset of N, or anything equivalent you like. There is some kind of discontinuity (and thus, I guess, cardinality). But when we use ordinals, it is not clear to me what operation or property makes countable ordinals before $\omega_1$ to become uncountable at $\omega_1$. I cannot see any obvious "change" or operation that makes this possible. Am I asking some stupid question? (Yes, I know)
Comment: Your question is getting upvotes, so I'm guessing it's not stupid ;-)
Answer: The only change is that $\omega_1$ has uncountably many predecessors, while each $\alpha<\omega_1$ has only countably many predecessors. In character it's the same kind of change that occurs at $\omega$: $\omega$ has infinitely many predecessors, while each $n<\omega$ has only finitely many predecessors.
Comment: you have no idea how great is to have your wisdom available from anywhere in the world! (and for free)
Comment: I promise not to ask questions about ordinals for a long time!
Comment: @julian: :-) (And yes, MSE is a wonderful resource.)
Answer: Perhaps another way to see Brian's answer is the following:

Consider $\omega$.  This is what we get when we gather all of the finite ordinals together, and well-order them in the natural way.  This well-ordering cannot have finite order-type, since otherwise it would be the largest finite ordinals, and every proper initial segment of this order is finite, so it is the first infinite ordinal.  Thus we have the least  infinite ordinals.
Similarly, $\omega_1$ is what we obtain when we gather all of the countable ordinals together and well-order them in the natural way.  Again, the order-type of this well-ordering cannot be countable, since otherwise it would be the largest countable ordinal, and all proper initial segments of this ordering are countable.  Thus we have the least uncountable ordinal.
Comment: @ Arthur: so, the set of countable limit ordinals between any arbitrarliy high countable limit ordinal and $\omega_1$ is uncountable, right? because the set before it is countable, and the union of two countable sets is countable?
Comment: @Julian: That's correct.


Real Analysis and infinity

Question: What is the nature of order relations between infinity?Is
$\infty$ = $\infty$ and hence
$\infty$ $\leq$ $\infty$
or is it simply undefined?
Comment: You've tagged this as real analysis, so I'm going to assume you're working in the [extended real numbers](https://en.wikipedia.org/wiki/Extended_real_number_line). In that case, you can make perfect sense of these things.
Comment: How do you define $\infty$? It's not a real number...
Answer: You must be careful to define symbols before you use them, especially if it is not obvious which meaning you are using. For instance there are so many different kinds of infinity in mathematics, including the infinite ordinals, infinite cardinals, real projective infinity, complex infinity and finally the two endpoints $\infty,-\infty$ of the affinely extended reals. Hence the answer to your question is that your "$\infty$" is undefined (precisely because you didn't define it) and your comparison operations on your "$\infty$" are naturally also undefined. However, if you want to ask specifically about the affinely extended reals, then yes in that context $\infty$ is the largest extended real number and whole extended real line is the interval $[-\infty,\infty]$.
Answer: There are various ways to "compactify" the set ${\mathbb R}$ of real numbers. In analysis one usually considers the set $\bar {\mathbb R}:={\mathbb R}\cup\{-\infty,\infty\}$. This enlarged structure $\bar{\mathbb R}$ is not meant to be a field, but certainly is a totally ordered set, insofar as one stipulates $-\infty<x<\infty$ for all $x\in{\mathbb R}$. Furthermore $\bar R$ is a compact topological space, homeomorphic to a finite closed interval, as $[{-1},1]$. A neighborhood base for $\infty$ is the set of all extended intervals ${\mathbb R}_{>a}\cup\{\infty\}$, $\>a\in{\mathbb R}$, and similarly for $-\infty$.

Real Analysis and infinity


The register function does not show up after admin.site in my PyCharm Django Development

Question: I am supposed to use admin.site.register to register a model to my website, but register function does not show up after admin.site. There is a register function showing up after admin though. Should I use admin.register instead of admin.site.register?
from django.contrib import admin

from .models import Question

admin.site. # register does not show up

Comment: By show up you mean it doesn't autocomplete it ? You should type `admin.site.register()` anyway.
Comment: Are you sure that you chosen the right Python Interpreter? Did you install django on that interpreter ?
Comment: What exactly does you mean by "Does not show up"? Doesn't it "suggest" register or is there an error when you run with "admin.site.register()"?
Comment: If it just doesn't suggest it, try just running your program anyways, even if it is saying that admin.site.register is not found.
Answer: Sometimes, if you program in an IDE (For example PyCharm), the IDE can sometimes lose track of all the functions and modules that are loaded. And that can lead to some weird errors while programming, where you for example can't see a specific function that you know should be there, or it just shows errors weird places where there shouldn't be any. The solution to this is to restart your IDE or to just run your program anyways after you've typed in what you think should be right;
in this case: admin.site.register(<Model Name>)


Does there always exist a unique point with minimal average distance to any curve?

Question: Given any curve $\gamma:[0,1]\to\mathbb{R}^2$, we can consider the average distance from any point $x\in\mathbb{R}^2$ to the curve, $\int_0^1d(x,\gamma(t))dt$. I am interested in the points $x\in\mathbb{R}^2$ which minimize this distance. It is easy to prove that such points exist by a compactness argument, but are they always unique?
This problem can be expressed much more generally: given a compactly supported probability measure $m$ on $\mathbb{R}^2$, is there always a unique point $x$ that minimizes $\int_{\mathbb{R}^2}d(x,y)dm(y)$? In this case the general answer is no, for example, we can consider a measure where the points $(0,0)$ and $(0,1)$ each have probability $\frac{1}{2}$: then any point between them minimizes the average distance. But are there some simple sufficient conditions that eliminate "trivial" counterexamples like that one? (e.g. the measure not being supported in two points or something more restrictive if necessary).
The case of the first paragraph with a curve $\gamma$ can be seen as a concrete case of a compactly supported probability measure, just by defining a measure $m$ in $\mathbb{R}^2$ by $m(A)=\mu(\gamma^{-1}(A))$, where $\mu$ is the usual Lebesgue measure in $[0,1]$.
If the uniqueness part is true, it would have some cool consequences: for example, if the curve is a regular polygon parametrized by arc length, then the unique point at minimal average distance has to be the center of the polygon. The same would apply to other curves whose isometry group (that is, the group of isometries $\phi:\mathbb{R}^2\to\mathbb{R}^2$ such that $\phi\circ\gamma=\gamma$) fixes just $1$ point.
Comment: Ok, that's fair. Very interesting question, by the way.
Comment: The quantity $\int_0^1 d(x,\gamma(t))\;dt$ is probably not what you have in mind, since it depends on the parametrization of the curve. So different parametrizations **of the same curve** will give you different averages, which is not what you described with words.
Comment: @jjagmath Yes, it's what I have in mind. If I want the average to be taken "proportionally to length" then I should parametrize the curve by length. But that's just a concrete case of the problem, the question does not require the curve to be parametrized by length. In fact I am more interested in the more general statement of the problem given in the second paragraph. The case you mention is the original motivation of the problem though, so just solving that case would be great
Comment: But then you say "if the curve is a regular polygon, then the unique point at minimal average distance has to be the center of the polygon", but that wouldn't be true if the polygon parametrization is not proportional to the parametrization by length, so you ARE thinking in that kind of parametrizations.
Comment: I thought it was understandable by context, but I will add "parametrized by arc length" to be more precise. But yeah the question asks for any parametrizations (or compactly supported measures), not only arc length ones
Answer: Okay, so I got the result I wanted:
For any curve $\gamma:[0,1]\to\mathbb{R}^2$, only one point achieves the minimal average distance to $\gamma$.
This will be deduced from the following result:
Proposition: If a compactly supported probability measure $m$ in $\mathbb{R}^2$ is not supported in a line, then the set $A$ of points at minimal average distance from $m$ contains just one point.
After proving the result I adress separately the case where the image of $\gamma$ is contained in some line.
Proof of the general result:
Note that for any point $x$, the function $z\to d(x,z)$ is convex: concretely, we have $\forall x,y,z\in\mathbb{R}^2$ and $\lambda\in(0,1)$ that
$d(\lambda x+(1-\lambda)y,z)=|z-(\lambda x+(1-\lambda)y)|=|\lambda(z-x)+(1-\lambda)(z-y)|$
$\leq \lambda|z-x|+(1-\lambda)|z-y|=\lambda d(x,z)+(1-\lambda)d(y,z).$
If $x\neq y$ and $\lambda\in(0,1)$, then equality is reached only when $|\lambda(z-x)+(1-\lambda)(z-y)|=\lambda|z-x|+(1-\lambda)|z-y|$, and this only happens when $z-x$ and $z-y$ are linearly dependent and they don't have opposite directions. So, when $z$ is in the line formed by $x$ and $y$ and not inside the "open" segment $xy$.
Now let $F(x):=\int_{\mathbb{R}^2}d(x,z)dm(z)$ be the average distance of a point $x\in\mathbb{R}^2$ to the measure $m$, and suppose there are two distinct points $x,y\in A$ where $F$ reaches its minimum value $k$ (it is not difficult to show by a compactness argument that this value is reached). Then for any $\lambda\in[0,1]$ we have
$$F(\lambda x+(1-\lambda)y)=\int_{\mathbb{R}^2}d(\lambda x+(1-\lambda)y,z)dm(z)\leq \int_{\mathbb{R}^2}\lambda d(x,z)+(1-\lambda)d(y,z)dm(z)=\int_{\mathbb{R}^2}\lambda d(x,z)+\int_{\mathbb{R}^2}(1-\lambda)d(y,z)dm(z)=\lambda k+(1-\lambda)k=k,$$
so $F(\lambda x+(1-\lambda)y)\leq k$. But as $k$ is the minimum value of $F$, we necessarily have $F(\lambda x+(1-\lambda)y)=k$. This implies that the inequalities above are all equalities, so if we let $G(z)=d(\lambda x+(1-\lambda)y,z)$ and $H(z)=\lambda d(x,z)+(1-\lambda)d(y,z)$, then we have
$$\int_{\mathbb{R}^2}G(z)dm(z)=\int_{\mathbb{R}^2}H(z)dm(z).$$
However we already know that $G(z)\leq H(z)$ $\forall z$. So for the integrals to be equal, we need to have $G(z)= H(z)$ for $m$-almost every $z$. That is, almost every $z$ has to be in the line containing $x$ and $y$ and outside the open segment $xy$. So the measure $m$ is supported in the line formed by $x$ and $y$.$\square$
Some comments:

This also works for compactly supported measures in $\mathbb{R}^n$ for any $n$, or more generally in any Hilbert space $H$ (where $|x|+|y|=|x+y|$ implies that $x,y$ are linearly dependent). Also, for this to work we don't need the probability measure $m$ to be compactly supported, we just need the functions $z\mapsto d(x,z)$ to be in $L^1$, or equivalently, we need $\int_H|z|dm(z)<\infty$.

If the measure $m$ is supported in a line $l$, then it is clear that no point outside of $m$ is in $A$ (its projection onto $l$ has less average distance). Moreover, $A$ is a closed segment, and as we have seen, for any $x,y\in A$ the measure is supported outside the open segment $xy$. So we have two cases:

Case 1: $A$ is just one point.
Case 2: $A$ will be a closed segment with "interior" $A_0$ such that the
measure is supported in $l\setminus A_0$. Moreover, it is easy to
check that if $l^+$ and $l^-$ are the two components of $l\setminus
   A_0$, then $m(l^+)$ and $m(l^-)$ are both $\frac{1}{2}$: if not, the
average distance from the points of $A$ to $m$ would not be constant.

If our measure is induced by a curve $\gamma:[0,1]\to\mathbb{R}^2$ contained in a line $l$, then we cannot have case 2 from above: if we had a segment $A_0$ such that $m(l^+)$ and $m(l^-)$ are both $\frac{1}{2}$, then the image of the curve would intersect both $l^+$ and $l^-$, so it would intersect $A_0$. Moreover $\gamma^{-1}(A_0)$ is open in $[0,1]$, so $A_0$ would have positive measure, contradicting $m(l^+)=m(l^-)=\frac{1}{2}$.


Display field in views-view-field--field_title.html.twig

Question: If I have view with fields:
field title [hidden]
field text [hidden]
field image [hidden]
field display

and I make rewrite in "display" field with "title" and "text" field added, how can I print content of field "image" (url of this image) with views-view-field--field_display.html.twig? I need wrapper with image url from this field. I see all available variables (view, field, row, output) in template and suggestion to fetch output with construct:
data = row[field.field_alias]

but when I try to write twig code with my field_image alias it's not showing me anything. Field with image is set up to display just url to image. I translated few code lines from drupal 7 to twig, but I am unable to see anything in kint, just dump show me some key strings. Views create block and I am placing this block on my page.
What I am doing wrong?
Comment: you want to print the image url? is that your question?
Comment: Yes. It will be for field wrapper. Field are set up to display with HTML list, each field in list is  content with title and text and I want to wrapp each slide with image
 {{ output -}}
Answer: URL FORMATTER module

This module add a url formatter for image field. Then you can output image url directly.

Enable the module, then in views, click on your image field, and change the Formatter to Image url.
{{ fields.field_image.content }}  // will display url instead of picture

Comment: @Jack how did it go?
Comment: I've figured out that I have already installed that module, turned on and this field is set up to display url. I think I put wrong twig to print that field. What I am doing now is trying to display my field in
views-view-fields--myview.html.twig
not in
views-view-field--myfield.html.twig

but not success yet.
Comment: `I want to wrapp each slide` is each slide is a row? and what is `{{ output }}` ?
Comment: NOW IT WORKS!  I tried to overwrite a wrong template file, in the template for all rows for fields it working just perfect! Now it's time to twig it  in my complicated way! Thank you again for support!


How to determine probabilities according to a position on a list

Question: I'm working on a SQL system in which i have to retrieve a "winning" user from a users list. The winner is determined randomly, but the users should have more chances if their coeficient number is lower. This coeficient number is an auto-incremental number asigned to each of the users.
So, this said, this is an example of what i have:
User. | Coeficient.
user1 | 1
user2 | 2
user3 | 3
user4 | 4
I would like to the users to have more chances in an inverse proportional way to its coeficient number. Something like User1 40%, user2 30%, user3 20% and user4 10%, no need to exactly be that proportion though. Please note that only one user wins for each draw that is made and the amount of users can vary.
I've been trying to figure out a mathematical ecuation or process to achieve this or similar but couldn't.
If you know a way to achieve this or a technique that serves as guide it would help me a lot.
Thanks and sorry for the bad english!
Comment: The phrase "users should have more chances if their [coefficient] number is higher" seems ambiguous or even contrary to how you then proposed to assign probabilities (higher meaning *lower*?).  However it is possible to map those integers unequally to an interval where you assign a uniform probability.
Comment: The probability figures you've assigned are not actually in "inverse proportion" to the ranking of the users ("coefficient"), though they do *vary inversely* in a linear (straight-line) fashion.
Comment: "higher meaning lower?" yes, that's right, typo error, sorry! Providing that the users ranking is lower their probabilities should increment
Answer: Since the probability grows linearly, the cumulative distribution function grows quadratically. You can draw from any distribution by applying the inverse of its cumulative distribution function to a value $u$ uniformly drawn from $[0,1]$. Thus you might want to give the prize to user $n-\lfloor n\sqrt u\rfloor$ (where $n$ is the number of users).


Poisson Model Interrupted Time Series Analysis

Question: I've run an Interrupted Time Series Analysis on count data, fitting a Poisson Model as below:
glm(`Subject Total` ~ Quarter + int2 + time_since_intervention2 , df, family = "poisson")

This is intended to show the change in number of application received and needs to be interpretable as such. The plot shows a diminishing trend in the [longer] pre-intervention period with a level change and potentially slight trend change.
The output summary from the model is:
Call:
glm(formula = `Subject Total` ~ Quarter + int2 + time_since_intervention2,
    family = "poisson", data = df)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-1.72350  -0.67721   0.06528   0.68167   1.35607

Coefficients:
                          Estimate Std. Error z value Pr(>|z|)
(Intercept)               3.681163   0.088844  41.434   <2e-16 ***
Quarter                  -0.028692   0.009733  -2.948   0.0032 **
int2                     -0.164817   0.202510  -0.814   0.4157
time_since_intervention2 -0.024379   0.038969  -0.626   0.5316

I can't really present the ITS outcomes as above as I need to make such more interpretable and intended to do so by just using exp() on the coefficients. However, whilst exp(Intercept) does reflect the plotted value - the others do not. I am sure this is due to my lack of understanding of the Poisson model, but could do with some advice/help as to how to derive a more usable figure??

For example int2 equates to the level change in the post-intervention period.
Under the summary output it is -0.164817. Exp(int2) = 0.8480492.
However, the "real difference" between the fitted value and relevant counterfactual = -4.2 applications.
Whilst I can report said level change in an interpratble way the trend is much more problemtaic.
Anyone have any ideas/is it just me not really understanding the Poisson model.
Thanks
Answer: I think that your problem is in the interpretation of the coefficients. This type of display shows coefficients that represents differences from the intercept associated with differences of predictors from their reference values.
In a Poisson model with a log link, the intercept and coefficients are in units of log of mean expected counts. You need to add/subtract the contributions from the predictor coefficients to the intercept in that scale before you exponentiate.
For example, $\exp(3.681163) \approx 39.7$ counts for the intercept at reference values of other predictors. For the difference associated with int2 with other predictors at reference values, you calculate $\exp(3.681163-0.164817) \approx 33.7$ counts, a difference of 6 counts.
This type of work can be simplified by specifying a set of predictor values of interest to post-modeling analysis software like the emmeans package in R. That can provide estimates in the original count units along with confidence intervals and tests of significance between scenarios.
Reporting model coefficients
Reporting coefficients in the way displayed in the question, with coefficients representing changes in logs of counts associated with the predictors, is standard for Poisson models. If you exponentiate the coefficients as you propose, what you get are multiplicative factors acting on the number of counts.
The model that you show fits:
$$\log(\bar T) = \beta_0  + \beta_1 Q + \beta_2 \text{int2} + \beta_3 \text{tsi2}$$
Where $\bar T$ is the mean "Subject total", $Q$ is "Quarter," and $\text{tsi2}$ is "time_since_intervention2." As noted above, you need to add up all the terms on the right side before you exponentiate to get the estimate of mean "Subject total" $\bar T$. If you do that, you get the following product:
$$\bar T = \exp(\beta_0)  \exp(\beta_1 Q) \exp( \beta_2 \text{int2}) \exp (\beta_3 \text{tsi2})$$
Thus the coefficient $\beta_2$ is the multiplicative factor for "Subject total" counts associated with $\text{int2}$, other things being equal. The coefficient is not itself on a count scale. It's not clear that exponentiating the coefficients will make them any more interpretable.
For a Poisson model, I thus don't see any advantage to going beyond the log-scale coefficients. If you nevertheless want to report exponentiated coefficients, you need to make it clear that the exponentiated coefficients represent represent multiplicative associations with counts. You also need to report corresponding confidence intervals. For 95% confidence intervals of a coefficient with value $\beta$, you report $\exp(\beta \pm 1.96 \text{SE}_{\beta})$, where $\text{SE}_{\beta}$ is the standard error in the original scale. Those will be asymmetric about $\exp(\beta)$.
Comment: have had to come back to this and realise that I still can't figure out how to exponentiate my change outcomes for the purpose of reporting. Ideally I need to be able to report each outcome as an exponentiated individual figure (e.g. "int2"), but am still not sure of how to do so.......
Comment: @j.rahilly I added to the answer to address what it means to exponentiate the coefficients of a Poisson model. It's not clear that really makes them more interpretable, as they still don't correspond to values of counts, but I show how to proceed if you want to do that anyway.
Comment: Thanks for the answer EdM. Do you have an example of use of the emmeans package for conversion of coeffeicients? Also wondered why I get 6 as the difference based upon the above when the fitted values suggest  difference of 4.2? Sorry for stupid question....just still a little confused.
Comment: @j.rahilly my simple example didn't take the number of quarters into account. If there were 13 quarters at the time of `int2` then you would compare `exp(3.681163-13* 0.028692)=27.33` against `exp(3.681163-0.164817-13* 0.028692)=23.18`, for a difference of 4.15 counts. There are many vignettes explaining how to use the [`emmeans` package](https://cran.r-project.org/package=emmeans). You define a "reference grid" of combinations of predictor values of interest, over which to get estimates from the model. If you ask for results on the "response" scale you will get counts in this case.
Comment: @j.rahilly one more thought: although the log link is the default, canonical link for a Poisson model, that enforces multiplicative rather than additive contributions from predictors. For example, it's fitting an exponential decay with respect to `Quarter` in your model. Depending on your understanding of the subject matter, you might consider an identity link instead, which would fit a linear trend with respect to `Quarter` and additive rather than multiplicative contributions from `int2` and `time_since_intervention2`.


Why Sum in database query giving NULL

Question: Suppose I have a table named "Expense" and it has some month-wise expense which may contain some "NULL", now I want to check the yearly expenses in total with this below query:-

Select Sum(January) + Sum (February) ..... (I skipped the rest 10 months)
from Expense

This gives result as "NULL"
How can I avoid this situation? I think there are more convenient way to check the yearly sum
Comment: `SUM(IIF(Col IS NULL, 0, Col))`
Answer: All arithmetic or logical operations involving NULL yield NULL. For example:
SELECT 1 + NULL -- NULL

You must convert NULL to zeros before you can + them:
SELECT
    COALESCE(SUM(January), 0) +
    COALESCE(SUM(February) , 0) +
    ...

It is also possible to add the columns first and then calculate the sum:
SELECT SUM(
    COALESCE(January, 0) +
    COALESCE(February, 0) +
)

Be advised that (i) SUM skips NULL values (ii) returns NULL instead of 0 if all values are NULL:
SELECT SUM(a) FROM (VALUES
    (1),
    (2),
    (NULL)
) AS v(a) -- returns 3 instead of NULL

It will return NULL if all values encountered were NULL:
SELECT SUM(a) FROM (VALUES
    (CAST(NULL AS INT)),
    (NULL),
    (NULL)
) AS v(a) -- returns NULL instead of 0

Answer: use coalesce function to convert null to 0 then use sum
Select Sum(coalesce(January,0)) + Sum (coalesce(February,0)) ..... (I skipped the rest 10 months)
from Expense

Answer: Just use coalesce [ with 0 as the second argument ] to replace nulls for all month columns, otherwise you can not get true results from aggregation of numeric values :
select sum(coalesce(January,0)+coalesce(February,0) ... )
  from Expense

Answer: Because null + value is always null and in your sample some months sums are null, you can avoid this by adding ISNULL
Select isnull(Sum(January),0) +
    isnull(Sum(February),0)
--..... (I skipped the rest 10 months)
from Expense

Alternatively you can use below way:
Select Sum(
    isnull(January,0) +
    isnull(February,0)
    )
--..... (I skipped the rest 10 months)
from Expense

Answer: You can use ISNULL(SUM(January),0).
Answer: That because you have NULL values, you can use Case, Coalesce or IIF:
Select SUM(IIF(Col IS NULL, 0, Col))

Select SUM(CASE WHEN Col IS NULL THEN 0 ELSE Col END)

Select COALESCE(Sum(Col), 0)

Answer: Any arithmetic function will return null if there is at least one null value in the given column. That's why you should use functions like coalesce or isNull (MSSQL), NVL (Oracle).

Why Sum in database query giving NULL


How to get flag count for any time period

Question: I have View which displays a list of nodes with counters (flags), but the counters for all the time. How to display a list of nodes with counters (flags), for example, over the last week or last month?
Answer: Did you try to use the filter criteria : Flagged Time and eventually expose it to users?
Then you can define :
- the operator: is equal to / is less than / ...
- a specific date or offset
Is that what you are looking for?
Comment: I've tried it. I get the nodes which are marked in a given period of time, but the counter flags these nodes for all time.