The sum of three positive integers is $20$. Find the probability that they form the sides of a triangle.

Question:
The sum of three positive integers is $20$. Find the probability that they form the sides of a triangle.

Let $a,b,c$ be there positive integers. So, $a+b+c=20$
Total number of solutions would be $^{19}C_2=171$
For $a,b,c$ to form a triangle $0\lt a,b,c\le9$
So, number of such solutions= coefficient of $x^{20}$ in $(x+x^2+x^3+...+x^9)^3=$ coefficient of $x^{17}$ in $(1+x+x^2+...+x^8)^3=$ coefficient of $x^{17}$ in $(1-x^9)^3(1-x)^{-3}=1\times^{19}C_2-3\times^{10}C_2=36$
So, the required probability is $\frac{36}{171}$ but the answer given is $\frac8{33}$
In the hint, they have written total combinations of $a,b,c=\frac{144}{6}+\frac{27}{3}=33$, and favorable combinations of $a,b,c=\frac{12}{3}+\frac{24}{6}=8$
I think they have split $171$ as $144+27$ and $36$ as $24+12$ but why? and why to divide them with $6$ or $3$?
Comment: Yes, I overlooked that !
Comment: What about the sum of any two sides being greater than the third side ?
Comment: @true blue anil, isn't that covered when we take $0\lt a, b, c\le9$?
Answer: It is a bad question as they have not described how the sides have been chosen, but their answer almost reveals what they intended:

There are $171$ compositions of $20$ into three positive integer parts (any order).  Of these,

$144$ compositions have the three parts distinct
$27$ compositions have two of the parts equal and the third distinct
$0$ compositions have all three parts equal ($20$ is not divisible by $3$)

So removing duplicates which are the same but in a different order, there are

$\frac{144}{3!}=24$ partitions which have the three parts distinct
$\frac{27}{3}=9$ partitions which have two of the parts equal and the third distinct
$0$ partitions have all three parts equal ($20$ is not divisible by $3$)
making $24+9+0=33$ for the number of partitions of $20$ into three positive integer parts

The $36 \to 8$ is the same but where the two smaller numbers add up to more than the largest number
Comment: Thanks, how did the number $144$ come about?
Comment: @aarbee - I do not know how they did it, but the easiest numbers to find here are $171,9,0$ and you can say $171- 3\times 9 -1\times 0=144$, easily extended to other cases.  Before you ask, $9$ comes from counting $1+1+18, 2+2+16,\ldots, 9+9+2$ and spotting these is no triplet
Comment: Thanks. Now I am trying to see why they split $36=12+24$. Of course, we can't use $1+1+18$, etc here. If I assume the two values were same, then the third would have $9$ options? I guess not.
Comment: @aarbee perhaps say the third has to leave a positive even number so must on of $2,4,\ldots,18$ so $9$ and $3\times 9$ possibilities.  Of these, $6,7,8,9$ would make a triangle so $4$ and $3 \times 4=12$ possibilities
Comment: That's quite a reasonable explanation, thanks.
Answer: Because in the case of a triangle's sides, order has no meaning. The set $\{7,8,5\}$, representing $a,b$ and $c$ forms the same triangle as $\{8,5,7\}$ and likewise. So, if $a,b,c$ are distinct, the $6$ possible ordered pairs give only $1$ combination, hence division by $6$. If two of $a,b,c$ are equal, then $3$ different ordered pairs are possible, which give only one combination, hence division by $3$.
Comment: There are $144$ distinct combinations. I feel the easiest way to get this would be to take the other case, the one where two of the three are equal. Say $a=b\neq c$. Then, we have the cases of $a=b=1$, $a=b=2$,...$a=b=9$ that is $9$ cases. We would similarly have $9$ cases each for $b=c\neq a$ and $a=c\neq b$. That makes $27$. Hence the distinct case would have $171-27=144$ solutions. Note that there is never any case of an equilateral triangle.
Comment: This is certainly what the person who wrote the answer was thinking, but I'm not so sure it's clear from the question, which I think is badly posed.  The question should specify whether the probability space is sets of $3$ positive integers or ordered triples of $3$ positive integers.
Comment: Thanks and how to decide the split? $171=144+27$. Why so?


Laurent series for $1/(e^z-1)$

Question: Trying to compute the first five coefficients of the Laurent series for $$\frac{1}{e^z-1}$$ centered at the point $0$. I'm not seeing a way to use the geometric series due to the exponential. Any ideas?
Comment: The Laurent series with respect to which point?
Comment: I assume you're interested in the series that converges on the punctured disc of radius $2\pi$, and not one of the ones that converges on an annulus (whose inner and outer radii are both multiples of $2\pi$)?
Comment: Centered at the point $0$.
Comment: Yes, the first one.
Answer: You can do this formally. Since $\frac{1}{e^z-1}$ has a simple pole at $0$, it must have a Laurent series with no coefficient of $z^k$ for $k<-1$. If the coefficient of $z^k$ is $a_k$, we must then have
$$\left(\frac{a_{-1}}{z}+a_0+a_1z+a_2 z^{2} + a_3z^3+ O(z^4)\right)\left(z+\frac{z^2}{2!}+\frac{z^3}{3!}+\frac{z^4}{4!}+\frac{z^5}{5!}+O(z^6)\right)=1$$
and you can multiply this out and equate coefficients to find the values of the $a_i$. For example, equating order-zero coefficients immediately gives $a_{-1}=1$. Equating order-one coefficients gives $\frac{a_{-1}}{2}+a_0=0$, so $a_0=-\frac{1}{2}$. Equating order-two coefficients gives $\frac{a_{-1}}{6}+\frac{a_0}{2}+a_1=0$, and so $a_1=-\frac{1}{6}+\frac{1}{4}=\frac{1}{12}$; and so on.
Comment: This is the answer I would have given, too, but I would have given a different method of finding the coefficients. You set up a long division problem à la high-school math, but run the terms in the opposite direction, that is, increasing degrees as you go left to right. You're dividing the standard series for $e^x-1$ into $1$, and do your thing. Of course it gets messy after a while, but there are no undetermined coefficients.
Comment: I believe that this method is closest to what is looked for in an intro to complex variables class.
Answer: Consider that $e^z-1$ has a simple zero in $z=0$, since:
$$\lim_{z\to 0}\frac{e^z-1}{z}=1.$$
This gives that $z=0$ is a simple pole for $f(z)=\frac{1}{e^z-1}$ with residue $1$, hence
$$ g(z)=\frac{1}{e^z-1}-\frac{1}{z}$$
is a holomorphic function in a neighbourhood of zero.
The coefficients of the Taylor series of $g(z)$ depend on the Bernoulli numbers, since we have:
$$\frac{z}{e^z-1}=\sum_{n\geq 0}\frac{B_n}{n!}z^n,$$
giving:

$$\frac{1}{e^z-1}=\frac{1}{z}+\sum_{n=0}^{+\infty}\frac{B_{n+1}}{(n+1)!}z^n.$$

Laurent series for $1/(e^z-1)$


CSS column layout hide empty columns

Question: I've done a few things with css columns and I really like them, but today I stumbled into a problem for which I just won't find a solution:
I have a page with multiple lists. These lists have dynamic contents and open up in small popups. The old behaviour was, that the list contents have been shown in a single column (normal HTML
). The new behaviour should be that they are displayed in up to 4 columns. So I have extended my CSS with ul { column-count: 4; }. This works pretty nice for lists with many entries.
Now to my problem: sometimes there are lists with less then 4 entries. If that's the case, the popups for the lists still span 4 columns, with only 2 columns filled. So the popup for the less-filled list is still as wide as a popup with a full-filled list. For example:

ul {
  background-color: lime;
  list-style: none;
  column-count: 4;
}

entry 1

entry 2

entry 3

entry 4

entry 5

entry 6

entry 7

entry 8

entry 9

entry 10

entry 11

entry 12

entry 1

entry 2

My question now is: How do I hide those empty columns? I want a popup with a less filled list (no. of entries < 4) to be less wide then a popup with a full-filled list. I'd like to find a CSS-only solution, as I didn't intend to count the entries and add extra classes to decrease the column-count.
The order in which the elements are displayed is important: top-down and then left-right.
I've tried using flexbox, but there I have to set a fixed width for the container, which just results in the popups being too wide as well.
Edit for clarification:

The dotted line should be the right border for the second popup.
The diagonal lines mark the empty space I need to be gone.
Edit further approaches:
Another approach posted by user 'Gobbin' as answer, is to use flex. But as I mentioned, I'd have to set some fixed width. Here it is a max-width for the list itself, so that wrapping works and a fixed width for the list elements. I don't want to have either. Also this approach lists the items from left to right and then from top to bottom, which is also not what I need:

ul {
  list-style: none;
  display: inline-flex;
  flex-wrap: wrap;
  max-width: 16em;
  float: left;
  clear: both;
}

li {
  background-color: lime;
  width: 4em;
}

entry 1

entry 2

entry 3

entry 4

entry 5

entry 6

entry 7

entry 8

entry 9

entry 10

entry 11

entry 12

entry 1

entry 2

Comment: Highly suggest looking into CSS Grid and CSS Flexbox. They are, quite literally made for this sort of thing
Comment: @TheCrzyMan isn't CSS grid pretty much fixed for column counts and overall widths? And I already mentioned, that with flexbox I have to set a fixed width for the container, so that the items will be in columns.
Comment: Hmm.. Guess I need to read better. Also, why do you need to not display the empty columns? Can you just give the `li` elements the background color?
Comment: @TheCrzyMan these lists are shown in popups, which can be distinguished from the normal background. The background-color in the code snippet here is for visualization only.
Comment: Do you need to have the column count? can you just get rid of it?
Comment: @TheCrzyMan When I use `column-width` I have to set a fixed width for the popups. Then again, when less then 4 entries, the popup is too wide. I've updated my question for clarification.
Answer: Maybe this is an option for you, although the columns are spread across the available width.

var maxColumns = 4;
$("ul").each(function() {
  var numColumns = $(this).find("li").length;
  $(this).css("column-count", numColumns);
  $(this).css("width", 25*numColumns + "%");
});
ul {
  background-color: lime;
  list-style: none;
}

entry 1

entry 2

entry 3

entry 4

entry 1

entry 2

Comment: And the spreading of the content for the complete width is problematic. :/
Comment: Adjusted taking into account 4 columns is the maximum.
Comment: This is getting an interesting approach. Unfortunately this is no pure CSS solution as requested. But I will look further into this if nothing else pops up!
Answer: I think this is your desired layout. Edited my answer as the list items still had margins.

ul {
  list-style: none;
    display: inline-flex;
    float: left;
    clear: both;
}
li{
   background-color: lime;
   width: 100%;
   display: inline;
}

entry 1

entry 2

entry 3

entry 4

entry 1

entry 2

Comment: Sorry, not what I need. I updated my question for clarification.

CSS column layout hide empty columns


Filtered html with class attribute not being stripped?

Question: How to extend "filtered html" by ability of using class attribute? I can't let user have full html, but classes seem to be useful.
Answer: I found way of implementing of filtering system:
http://definitivedrupal.org/node/90
but I still hope there's easier way like just a checkbox [x] don't filter class attribute.
Answer: I use the Wysiwyg filter module in combination with the wysiwyg module for this. The module allows you to define exactly what properties to allow, what elements, classes etc. It takes a little time to set up, but the added control is well worth it imo.
Comment: telling by the screenshot(http://drupal.org/files/issues/wysiwyg_filter_settings.png) it looks it might do the job. thank you


SMTP server on debian 6.0 linux

Question: I have some questions: I am using a SMTP service for sending monthly newsletter for my website (~3000 email addresses).
I was thinking: I already own a virtual server configured as a web server and secured, why not using it to send email and save 7€/month ??
Is this a reasonable idea or am I a fool?
Does anybody knows a good (and up-to-date) guide for debian squeeze linux? I have read the official documentation, but i've understood a little...
And again: what I'm talking about is the so-called "smtp-relay"?
Comment: How little is your time worth?  At 7 euros/month, it'll be a long time before the savings pay for the investment of your time to learn all this stuff.
Comment: possible duplicate of [Should I run my own MTA?](http://serverfault.com/questions/337678/should-i-run-my-own-mta)
Comment: uhmm... considering the time for learn how to setup a smtp server, i guess 7€/month it's a reasonable price. This topic (mail server) is really huge
Answer: Assuming your list of email addresses are all opted in and the recipients do want your emails (i.e. they don't think it is spam) then it makes perfect sense to send these yourself. Especially considering it's just 3000 addresses give or take. Any low power set up could handle that. The reason you want to be sure your recipients don't think it is spam is that you don't want to have your IP get a bad reputation and be listed everywhere.
I would advice to use mailman to manage the email list in addition to your Debian setup. Debian comes with exim4 by default, but you can switch to postfix if you prefer.
With regards to how to configure and set it all up I think you will have to ask separate more specific questions.
Comment: Yes, all addresses are opted in; thanks for the hint about mailman.
I need to study postfix/exim/mailman/etc... before asking anything.

So this wasn't a bad idea at all.
Comment: +1 and postfix is the way to go.
Comment: Well, "postfix vs. exim" is probably a holy war the same way "vi vs. emacs" is. :-) I like both, they share a few very important characteristics, stability, and licensed under gpl.
Answer: Setting up a mailserver on Debian can be quite annoying. I hope you have a few days/weeks. I suggest starting with something easier.
If you want a decent guide about how to setup a mailserver, I learned it with this one: http://workaround.org/ispmail/squeeze
Which is a very comprehensive guide explaining everything step by step. I you want mailinglists you can set these up with either of these:

mailman
sympa (bad documented though)
mlmmj

SMTP server on debian 6.0 linux


Sonata Admin Bundle: How to add a "Delete" button in form, to the entities on the nested entities list?

Question: In the parent entity I can do something like that:
protected function configureFormFields(FormMapper $formMapper)
{

    $formMapper->add('units', 'sonata_type_collection', [
        'required' => true,
        'by_reference' => false,
        'label' => 'Units',
        'type_options' => [
            'delete' => true,
        ],
        'btn_add' => 'Add unit',
    ], [
        'edit' => 'inline',
        'inline' => 'table',
        'sortable' => 'position',
        'multiple' => true,
    ]);
}

This will display a delete checkbox. What is a proper way of having a simple "Delete" button next to every unit allowing for deleting it from the list? Is it possible to have something like this with minimal configuration?
Comment: Did you found out, how to make this. I'm very interested also in the maximum configuration ;) thanks
Comment: I believe this is not supported, but a very good idea!
Answer: I guess with minimal config is not possible. You should override a template or make your own


CTools modal with webform unable to close

Question: I'm using the CTools modal with a webform, the form comes in via ajax. When a user is logged in, all works normally. If an anonymous user clicks on the link for the modal, I'm seeing the following behavior:

CTools modal close button does not work. No js errors.
The 2nd time the link to display the modal is clicked, the page links directly to the form page (no ajax, no modal).

For logged in users, the close button works and the button to trigger the overlay behaves properly on repeat clicks.
Any tips greatly appreciated.
Answer: We figured it out - this was being caused by the ThemeKey module. The base page was one theme, and the ajax call was requesting default theme, trigging a reload of all the javascript.
The solution is to enable  'Bypass a request forgery protection in theme selection for Ajax responses.' and select the safe themes.


ImageJ export list of histogram data

Question: I'm trying to record a macro on ImageJ. I found this post
http://imagej.1557.x6.nabble.com/Saving-histogram-list-to-Excel-file-td3682144.html
which is similar to what I want to do but it refers to RGB channel. How can i export the histogram of gray levels and not of single RGB channels?
Comment: I suggest asking this kind of question directly on the [ImageJ forum](http://forum.imagej.net/).
Answer: You can record all actions in the ImageJ macro recorder to get the right commands:
https://imagej.nih.gov/ij/docs/guide/146-31.html#sub:Record...
http://imagej.net/Introduction_into_Macro_Programming
Here an recorded Windows histogram example how to save the results of a histogram (change the file path and execute this code as an ImageJ macro!):
<code>run("Blobs (25K)");
run("Histogram");
saveAs("Results", "C:\\Users\\xxx\\Histogram of blobs.csv");
</code>

ImageJ export list of histogram data


Salvar Campo Automatico

Question: Tenho a seguinte situação.
No Banco, tenho as tabelas Estado, Cidade, com os dados devidamente cadastrados e vinculados.
Na View gostaria de colocar somente um DropDown com a lista de Cidades, mas gostaria de gravar automático o id do Estado no banco.
namespace CadastroMVC.Models
{
    public class Class1
    {
        public int CidadeId { get; set; }
        public int EstadoId { get; set; }
        public string NomeCidade { get; set; }
    }
}

Comment: Traga o estado num campo tipo `hidden`.
Comment: Gravar aonde? Tem isso ai pra colocar na pergunta.
Comment: Gostaria de gravar o id do Estado na tabela Cidades, automaticamente, sem precisar selecionar o estado uma vez, que as tabelas ja estão relacionadas no banco.
Comment: Para gravar o estado em um tabela de cidades, tem que selecionar a estado para que o cadastro saiba, isso não se faz automático...!
Answer: Você precisar selecionar o Estado novamente ao salvar:
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Criar(Class1 class1)
    {
        if (ModelState.IsValid)
        {
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var estado = contexto.Cidades
                                     .Include(c => c.Estado)
                                     .FirstOrDefault(c => c.CidadeId == class1.CidadeId);

                // Verificar aqui se o estado existe, para evitar erros de referência nula.

                class1.EstadoId = estado.EstadoId; // Não é muito correto fazer isso, mas se você faz questão de salvar o EstadoId, tudo bem.
                context.Class1.Add(class1);
                await context.SaveChangesAsync();
                scope.Complete();
            }

            return RedirectToAction("Indice");
        }

        // ViewBags aqui
        return View(class1);
    }

Answer: Pelo que entendi você quer manter o Id do Estado fixo na sua aplicação.
Pensando nisso, basta no seu método Create preencher o EstadoId com o valor desejado.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Criar(Cidade cidade)
        {
            if (ModelState.IsValid)
            {
                //setando o estado
                cidade.EstadoId = 1;
                context.Cidades.Add(cidade);
                await context.SaveChangesAsync();

                return RedirectToAction("Indice");
            }

            await ViewBags();
            return View(cidade);
        }

Salvar Campo Automatico


Levenshtein distance in T-SQL

Question: I am interested in algorithm in T-SQL calculating Levenshtein distance.
Answer: I implemented the Levenshtein edit distance function in TSQL with several optimizations that improves the speed over the other versions I'm aware of. In cases where the two strings have characters in common at their start (shared prefix), characters in common at their end (shared suffix), and when the strings are large and a max edit distance is provided, the improvement in speed is significant. For example, when the inputs are two very similar 4000 character strings, and a max edit distance of 2 is specified, this is almost three orders of magnitude faster than the edit_distance_within function in the accepted answer, returning the answer in 0.073 seconds (73 milliseconds) vs 55 seconds. It's also memory efficient, using space equal to the larger of the two input strings plus some constant space. It uses a single nvarchar "array" representing a column, and does all computations in-place in that, plus some helper int variables.
Optimizations:

skips processing of shared prefix and/or suffix
early return if larger string starts or ends with entire smaller string
early return if difference in sizes guarantees max distance will be exceeded
uses only a single array representing a column in the matrix (implemented as nvarchar)
when a max distance is given, time complexity goes from (len1*len2) to (min(len1,len2)) i.e. linear
when a max distance is given, early return as soon as max distance bound is known not to be achievable

Here is the code (updated 1/20/2014 to speed it up a bit more):
-- =============================================
-- Computes and returns the Levenshtein edit distance between two strings, i.e. the
-- number of insertion, deletion, and sustitution edits required to transform one
-- string to the other, or NULL if @max is exceeded. Comparisons use the case-
-- sensitivity configured in SQL Server (case-insensitive by default).
--
-- Based on Sten Hjelmqvist's "Fast, memory efficient" algorithm, described
-- at http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm,
-- with some additional optimizations.
-- =============================================
CREATE FUNCTION [dbo].[Levenshtein](
    @s nvarchar(4000)
  , @t nvarchar(4000)
  , @max int
)
RETURNS int
WITH SCHEMABINDING
AS
BEGIN
    DECLARE @distance int = 0 -- return variable
          , @v0 nvarchar(4000)-- running scratchpad for storing computed distances
          , @start int = 1      -- index (1 based) of first non-matching character between the two string
          , @i int, @j int      -- loop counters: i for s string and j for t string
          , @diag int          -- distance in cell diagonally above and left if we were using an m by n matrix
          , @left int          -- distance in cell to the left if we were using an m by n matrix
          , @sChar nchar      -- character at index i from s string
          , @thisJ int          -- temporary storage of @j to allow SELECT combining
          , @jOffset int      -- offset used to calculate starting value for j loop
          , @jEnd int          -- ending value for j loop (stopping point for processing a column)
          -- get input string lengths including any trailing spaces (which SQL Server would otherwise ignore)
          , @sLen int = datalength(@s) / datalength(left(left(@s, 1) + '.', 1))    -- length of smaller string
          , @tLen int = datalength(@t) / datalength(left(left(@t, 1) + '.', 1))    -- length of larger string
          , @lenDiff int      -- difference in length between the two strings
    -- if strings of different lengths, ensure shorter string is in s. This can result in a little
    -- faster speed by spending more time spinning just the inner loop during the main processing.
    IF (@sLen > @tLen) BEGIN
        SELECT @v0 = @s, @i = @sLen -- temporarily use v0 for swap
        SELECT @s = @t, @sLen = @tLen
        SELECT @t = @v0, @tLen = @i
    END
    SELECT @max = ISNULL(@max, @tLen)
         , @lenDiff = @tLen - @sLen
    IF @lenDiff > @max RETURN NULL

    -- suffix common to both strings can be ignored
    WHILE(@sLen > 0 AND SUBSTRING(@s, @sLen, 1) = SUBSTRING(@t, @tLen, 1))
        SELECT @sLen = @sLen - 1, @tLen = @tLen - 1

    IF (@sLen = 0) RETURN @tLen

    -- prefix common to both strings can be ignored
    WHILE (@start < @sLen AND SUBSTRING(@s, @start, 1) = SUBSTRING(@t, @start, 1))
        SELECT @start = @start + 1
    IF (@start > 1) BEGIN
        SELECT @sLen = @sLen - (@start - 1)
             , @tLen = @tLen - (@start - 1)

        -- if all of shorter string matches prefix and/or suffix of longer string, then
        -- edit distance is just the delete of additional characters present in longer string
        IF (@sLen <= 0) RETURN @tLen

        SELECT @s = SUBSTRING(@s, @start, @sLen)
             , @t = SUBSTRING(@t, @start, @tLen)
    END

    -- initialize v0 array of distances
    SELECT @v0 = '', @j = 1
    WHILE (@j <= @tLen) BEGIN
        SELECT @v0 = @v0 + NCHAR(CASE WHEN @j > @max THEN @max ELSE @j END)
        SELECT @j = @j + 1
    END

    SELECT @jOffset = @max - @lenDiff
         , @i = 1
    WHILE (@i <= @sLen) BEGIN
        SELECT @distance = @i
             , @diag = @i - 1
             , @sChar = SUBSTRING(@s, @i, 1)
             -- no need to look beyond window of upper left diagonal (@i) + @max cells
             -- and the lower right diagonal (@i - @lenDiff) - @max cells
             , @j = CASE WHEN @i <= @jOffset THEN 1 ELSE @i - @jOffset END
             , @jEnd = CASE WHEN @i + @max >= @tLen THEN @tLen ELSE @i + @max END
        WHILE (@j <= @jEnd) BEGIN
            -- at this point, @distance holds the previous value (the cell above if we were using an m by n matrix)
            SELECT @left = UNICODE(SUBSTRING(@v0, @j, 1))
                 , @thisJ = @j
            SELECT @distance =
                CASE WHEN (@sChar = SUBSTRING(@t, @j, 1)) THEN @diag                    --match, no change
                     ELSE 1 + CASE WHEN @diag < @left AND @diag < @distance THEN @diag    --substitution
                                   WHEN @left < @distance THEN @left                    -- insertion
                                   ELSE @distance                                        -- deletion
                                END    END
            SELECT @v0 = STUFF(@v0, @thisJ, 1, NCHAR(@distance))
                 , @diag = @left
                 , @j = case when (@distance > @max) AND (@thisJ = @i + @lenDiff) then @jEnd + 2 else @thisJ + 1 end
        END
        SELECT @i = CASE WHEN @j > @jEnd + 1 THEN @sLen + 1 ELSE @i + 1 END
    END
    RETURN CASE WHEN @distance <= @max THEN @distance ELSE NULL END
END

As mentioned in the comments of this function, the case sensitivity of the character comparisons will follow the collation that's in effect. By default, SQL Server's collation is one that will result in case insensitive comparisons.
One way to modify this function to always be case sensitive would be to add a specific collation to the two places where strings are compared. However, I have not thoroughly tested this, especially for side effects when the database is using a non-default collation.
These are how the two lines would be changed to force case sensitive comparisons:
    -- prefix common to both strings can be ignored
    WHILE (@start < @sLen AND SUBSTRING(@s, @start, 1) = SUBSTRING(@t, @start, 1) COLLATE SQL_Latin1_General_Cp1_CS_AS)

and
            SELECT @distance =
                CASE WHEN (@sChar = SUBSTRING(@t, @j, 1) COLLATE SQL_Latin1_General_Cp1_CS_AS) THEN @diag                    --match, no change

Comment: How can we use this to look up top 5 closest strings in a table? I mean let's say I have street names table with 10m rows. I enter search a street name but 1 character is incorrectly written. How can I look up top 5 closest matches with maximum performance?
Comment: Other than brute force (comparing all addresses), you can't. Levenshtein is not something that can easily take advantage of indexes. If you can narrow the candidates to a smaller subset via something that can be indexed, such as a zip code for address, or a phonetic code for names, for example, then straight Levenshtein like that in the answers here can feasibly be applied to the subset. To apply to an entire set that is large, you would need to go to something like Levenshtein Automata, but implementing that in SQL is way beyond the scope of the SO question being answered here.
Comment: @DaveCousineau - As mentioned in the function comments, string comparisons use the case sensitivity for the SQL Server collation in effect. By default, this typically means case insensitive. See the edit to my post I just added. The Fribble implementation in another answer behaves similarly regarding collation.
Comment: @MonsterMMORPG in theory you could do the reverse and calculate all possible permutations for a given Levenshtein-distance. Or you could try and see if the words in your addresses make up a list short enough to be useful (probably ignoring words which only rarely appear).
Comment: @MonsterMMORPG - this is late, but I thought I'd add a better answer. If you know the minimum number of edits you will allow, you can use the Symmetric Delete method like has been done in the symspell project on github. You can store a small subset of permutations of just deletes, and then search for any in the small set of delete permutations of the search string. On the returned set (which would be small if you only allow 1 or 2 max edit distance), you then do the full levenshtein calc. But that should be much, much less than doing it on all strings.
Comment: this does not seem to give completely correct results. at first I thought it was just off by 1, but the greater the distance, the greater the error becomes. you should probably unit test your algorithm with various known distances.
Comment: @DaveCousineau -  can you give an example? I did test it, and just ran a test again to double check. I compare 1000 unique words against those same 1000 words (1,000,000 compares) where the words are a mix of from 1 to 14 characters in length. I compare the results against a c# implementation I wrote, and also against the Fribble implementation that's one of the answers in this question. All three implementations give the same results for all those compares.
Comment: @hatchet the strings `1234 52 Ab CD` and `261 Eafghci Jai CD` should have a distance of 13. I get 13 from my C# implementation, and from online calculators, but executing this function gives me 12.
Answer: Arnold Fribble had two proposals on sqlteam.com/forums

one from june 2005 and
another updated one from may 2006

This is the younger one from 2006:
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE FUNCTION edit_distance_within(@s nvarchar(4000), @t nvarchar(4000), @d int)
RETURNS int
AS
BEGIN
  DECLARE @sl int, @tl int, @i int, @j int, @sc nchar, @c int, @c1 int,
    @cv0 nvarchar(4000), @cv1 nvarchar(4000), @cmin int
  SELECT @sl = LEN(@s), @tl = LEN(@t), @cv1 = '', @j = 1, @i = 1, @c = 0
  WHILE @j <= @tl
    SELECT @cv1 = @cv1 + NCHAR(@j), @j = @j + 1
  WHILE @i <= @sl
  BEGIN
    SELECT @sc = SUBSTRING(@s, @i, 1), @c1 = @i, @c = @i, @cv0 = '', @j = 1, @cmin = 4000
    WHILE @j <= @tl
    BEGIN
      SET @c = @c + 1
      SET @c1 = @c1 - CASE WHEN @sc = SUBSTRING(@t, @j, 1) THEN 1 ELSE 0 END
      IF @c > @c1 SET @c = @c1
      SET @c1 = UNICODE(SUBSTRING(@cv1, @j, 1)) + 1
      IF @c > @c1 SET @c = @c1
      IF @c < @cmin SET @cmin = @c
      SELECT @cv0 = @cv0 + NCHAR(@c), @j = @j + 1
    END
    IF @cmin > @d BREAK
    SELECT @cv1 = @cv0, @i = @i + 1
  END
  RETURN CASE WHEN @cmin <= @d AND @c <= @d THEN @c ELSE -1 END
END
GO

Comment: @Lieven: It isn't my implementation, the author is Arnold Fribble. @d parameter is a maximal allowed difference between strings after reaching which they are considered too diverse and function returns -1. It's added because the algorithm in T-SQL works too slowly.
Comment: @Alexander, it seems to work but I would change your variable names to something more meaningfull. Also, I'd get rid of @d, you know the length of the two strings in your input.
Comment: You should check out the algorithm psuedo code over at: http://en.wikipedia.org/wiki/Levenshtein_distance it isn't a whole lot improved.
Answer: IIRC, with SQL Server 2005 and later you can write stored procedures in any .NET language: Using CLR Integration in SQL Server 2005. With that it shouldn't be hard to write a procedure for calculating Levenstein distance.
A simple Hello, World! extracted from the help:
using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;

public class HelloWorldProc
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void HelloWorld(out string text)
    {
        SqlContext.Pipe.Send("Hello world!" + Environment.NewLine);
        text = "Hello world!";
    }
}

Then in your SQL Server run the following:
CREATE ASSEMBLY helloworld from 'c:\helloworld.dll' WITH PERMISSION_SET = SAFE

CREATE PROCEDURE hello
@i nchar(25) OUTPUT
AS
EXTERNAL NAME helloworld.HelloWorldProc.HelloWorld

And now you can test run it:
DECLARE @J nchar(25)
EXEC hello @J out
PRINT @J

Hope this helps.
Answer: You can use Levenshtein Distance Algorithm for comparing strings
Here you can find a T-SQL example at http://www.kodyaz.com/articles/fuzzy-string-matching-using-levenshtein-distance-sql-server.aspx
CREATE FUNCTION edit_distance(@s1 nvarchar(3999), @s2 nvarchar(3999))
RETURNS int
AS
BEGIN
 DECLARE @s1_len int, @s2_len int
 DECLARE @i int, @j int, @s1_char nchar, @c int, @c_temp int
 DECLARE @cv0 varbinary(8000), @cv1 varbinary(8000)

 SELECT
  @s1_len = LEN(@s1),
  @s2_len = LEN(@s2),
  @cv1 = 0x0000,
  @j = 1, @i = 1, @c = 0

 WHILE @j <= @s2_len
  SELECT @cv1 = @cv1 + CAST(@j AS binary(2)), @j = @j + 1

 WHILE @i <= @s1_len
 BEGIN
  SELECT
   @s1_char = SUBSTRING(@s1, @i, 1),
   @c = @i,
   @cv0 = CAST(@i AS binary(2)),
   @j = 1

  WHILE @j <= @s2_len
  BEGIN
   SET @c = @c + 1
   SET @c_temp = CAST(SUBSTRING(@cv1, @j+@j-1, 2) AS int) +
    CASE WHEN @s1_char = SUBSTRING(@s2, @j, 1) THEN 0 ELSE 1 END
   IF @c > @c_temp SET @c = @c_temp
   SET @c_temp = CAST(SUBSTRING(@cv1, @j+@j+1, 2) AS int)+1
   IF @c > @c_temp SET @c = @c_temp
   SELECT @cv0 = @cv0 + CAST(@c AS binary(2)), @j = @j + 1
 END

 SELECT @cv1 = @cv0, @i = @i + 1
 END

 RETURN @c
END

(Function developped by Joseph Gama)
Usage :
select
 dbo.edit_distance('Fuzzy String Match','fuzzy string match'),
 dbo.edit_distance('fuzzy','fuzy'),
 dbo.edit_distance('Fuzzy String Match','fuzy string match'),
 dbo.edit_distance('levenshtein distance sql','levenshtein sql server'),
 dbo.edit_distance('distance','server')

The algorithm simply returns the stpe count to change one string into other by replacing a different character at one step
Comment: This unfortunately does not cover the case where a string is blank
Answer: I was looking for a code example for the Levenshtein algorithm, too,  and was happy to find it here. Of course I wanted to understand how the algorithm is working and I was playing around a little bit with one of the above examples I was playing around a little bit that was posted by Veve. In order to get a better understanding of the code I created an EXCEL with the Matrix.
distance for FUZZY compared with FUZY
Images say more than 1000 words.
With this EXCEL I found that there was potential for additional performance optimization. All values in the upper right red area do not need to be calculated. The value of each red cell results in the value of the left cell plus 1. This is because, the second string will be always longer in that area than the first one, what increases the distance by the value of 1 for each character.
You can reflect that by using the statement IF @j <= @i and increasing the value of @i Prior to this statement.
CREATE FUNCTION [dbo].[f_LevenshteinDistance](@s1 nvarchar(3999), @s2 nvarchar(3999))
    RETURNS int
    AS
    BEGIN
       DECLARE @s1_len  int;
       DECLARE @s2_len  int;
       DECLARE @i       int;
       DECLARE @j       int;
       DECLARE @s1_char nchar;
       DECLARE @c       int;
       DECLARE @c_temp  int;
       DECLARE @cv0     varbinary(8000);
       DECLARE @cv1     varbinary(8000);

       SELECT
          @s1_len = LEN(@s1),
          @s2_len = LEN(@s2),
          @cv1    = 0x0000  ,
          @j      = 1       ,
          @i      = 1       ,
          @c      = 0

       WHILE @j <= @s2_len
          SELECT @cv1 = @cv1 + CAST(@j AS binary(2)), @j = @j + 1;

          WHILE @i <= @s1_len
             BEGIN
                SELECT
                   @s1_char = SUBSTRING(@s1, @i, 1),
                   @c       = @i                   ,
                   @cv0     = CAST(@i AS binary(2)),
                   @j       = 1;

                SET @i = @i + 1;

                WHILE @j <= @s2_len
                   BEGIN
                      SET @c = @c + 1;

                      IF @j <= @i
                         BEGIN
                            SET @c_temp = CAST(SUBSTRING(@cv1, @j + @j - 1, 2) AS int) + CASE WHEN @s1_char = SUBSTRING(@s2, @j, 1) THEN 0 ELSE 1 END;
                            IF @c > @c_temp SET @c = @c_temp
                            SET @c_temp = CAST(SUBSTRING(@cv1, @j + @j + 1, 2) AS int) + 1;
                            IF @c > @c_temp SET @c = @c_temp;
                         END;
                      SELECT @cv0 = @cv0 + CAST(@c AS binary(2)), @j = @j + 1;
                   END;
                SET @cv1 = @cv0;
          END;
       RETURN @c;
    END;

Comment: As written, this will not always give the correct results. For example, the inputs `('jane', 'jeanne')` will return a distance of 3, when the distance should be 2. To correct this additional code should be added that swaps `@s1` and `@s2` if `@s1` has a shorter length than `@s2`.
Answer: In TSQL the best and fastest way to compare two items are SELECT statements that join tables on indexed columns. Therefore this is how I suggest to implement the editing distance if you want to benefit from the advantages of a RDBMS engine. TSQL Loops will work too, but Levenstein distance calculations will be faster in other languages than in TSQL for large volume comparisons.
I have implemented the editing distance in several systems using series of Joins against temporary tables designed for that purpose only. It requires some heavy pre-processing steps - the preparation of the temporary tables - but it works very well with large number of comparisons.
In a few words: the pre-processing consists of creating, populating and indexing temp tables. The first one contains reference ids, a one-letter column and a charindex column. This table is populated by running a series of insert queries that split every word into letters (using SELECT SUBSTRING) to create as many rows as word in the source list have letters (I know, that's a lot of rows but SQL server can handle billions of rows). Then make a second table with a 2-letter column, another table with a 3-letter column, etc. The end results is a series of tables which contain reference ids and substrings of each the words, as well a the reference of their position in the word.
Once this is done, the whole game is about duplicating these tables and joining them against their duplicate in a GROUP BY select query which counts the number of matches. This creates a series of measures for every possible pair of words, which are then re-aggregated into a single Levenstein distance per pair of words.
Technically this is very different than most other implementations of the Levenstein distance (or its variants) so you need to deeply understand how the Levenstein distance works and why it was designed as it is. Investigate the alternatives as well because with that method you end up with a series of underlying metrics which can help calculate many variants of the editing distance at the same time, providing you with interesting machine learning potential improvements.
Another point already mentioned by previous answers in this page: try to pre process as much as possible to eliminate the pairs that do not require distance measurement. For example a pair of two words that have not a single letter in common should be excluded, because the editing distance can be obtained from the length of the strings. Or do not measure the distance between two copies of the same word, since it is 0 by nature. Or remove duplicates before doing the measurement, if your list of words comes from a long text it is likely that the same words will appear more than once, so measuring the distance only once will save processing time, etc.
Answer: My mods for Azure Synapse (changed to use SET instead of SELECT):
-- =============================================
-- Computes and returns the Levenshtein edit distance between two strings, i.e. the
-- number of insertion, deletion, and sustitution edits required to transform one
-- string to the other, or NULL if @max is exceeded. Comparisons use the case-
-- sensitivity configured in SQL Server (case-insensitive by default).
--
-- Based on Sten Hjelmqvist's "Fast, memory efficient" algorithm, described
-- at http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm,
-- with some additional optimizations.
-- =============================================
CREATE FUNCTION [db0].[Levenshtein](
    @s nvarchar(4000)
  , @t nvarchar(4000)
  , @max int
)
RETURNS int
WITH SCHEMABINDING
AS
BEGIN
    DECLARE @distance int = 0 -- return variable
          , @v0 nvarchar(4000)-- running scratchpad for storing computed distances
          , @start int = 1      -- index (1 based) of first non-matching character between the two string
          , @i int, @j int      -- loop counters: i for s string and j for t string
          , @diag int          -- distance in cell diagonally above and left if we were using an m by n matrix
          , @left int          -- distance in cell to the left if we were using an m by n matrix
          , @sChar nchar      -- character at index i from s string
          , @thisJ int          -- temporary storage of @j to allow SELECT combining
          , @jOffset int      -- offset used to calculate starting value for j loop
          , @jEnd int          -- ending value for j loop (stopping point for processing a column)
          -- get input string lengths including any trailing spaces (which SQL Server would otherwise ignore)
          , @sLen int = datalength(@s) / datalength(left(left(@s, 1) + '.', 1))    -- length of smaller string
          , @tLen int = datalength(@t) / datalength(left(left(@t, 1) + '.', 1))    -- length of larger string
          , @lenDiff int      -- difference in length between the two strings
    -- if strings of different lengths, ensure shorter string is in s. This can result in a little
    -- faster speed by spending more time spinning just the inner loop during the main processing.
    IF (@sLen > @tLen) BEGIN
        SET @v0 = @s
        SET @i = @sLen -- temporarily use v0 for swap
        SET @s = @t
        SET @sLen = @tLen
        SET @t = @v0
        SET @tLen = @i
    END
    SET @max = ISNULL(@max, @tLen)
    SET @lenDiff = @tLen - @sLen

    IF @lenDiff > @max RETURN NULL

    -- suffix common to both strings can be ignored
    WHILE(@sLen > 0 AND SUBSTRING(@s, @sLen, 1) = SUBSTRING(@t, @tLen, 1))
        SET @sLen = @sLen - 1
        SET @tLen = @tLen - 1

    IF (@sLen = 0) RETURN @tLen

    -- prefix common to both strings can be ignored
    WHILE (@start < @sLen AND SUBSTRING(@s, @start, 1) = SUBSTRING(@t, @start, 1))
        SET @start = @start + 1
    IF (@start > 1) BEGIN
        SET @sLen = @sLen - (@start - 1)
        SET @tLen = @tLen - (@start - 1)

        -- if all of shorter string matches prefix and/or suffix of longer string, then
        -- edit distance is just the delete of additional characters present in longer string
        IF (@sLen <= 0) RETURN @tLen

        SET @s = SUBSTRING(@s, @start, @sLen)
        SET @t = SUBSTRING(@t, @start, @tLen)
    END

    -- initialize v0 array of distances
    SET @v0 = ''
    SET @j = 1

    WHILE (@j <= @tLen) BEGIN
        SET @v0 = @v0 + NCHAR(CASE WHEN @j > @max THEN @max ELSE @j END)
        SET @j = @j + 1
    END

    SET @jOffset = @max - @lenDiff
    SET @i = 1

    WHILE (@i <= @sLen) BEGIN
        SET @distance = @i
        SET @diag = @i - 1
        SET @sChar = SUBSTRING(@s, @i, 1)
             -- no need to look beyond window of upper left diagonal (@i) + @max cells
             -- and the lower right diagonal (@i - @lenDiff) - @max cells
        SET @j = CASE WHEN @i <= @jOffset THEN 1 ELSE @i - @jOffset END
        SET @jEnd = CASE WHEN @i + @max >= @tLen THEN @tLen ELSE @i + @max END

        WHILE (@j <= @jEnd) BEGIN
            -- at this point, @distance holds the previous value (the cell above if we were using an m by n matrix)
            SET @left = UNICODE(SUBSTRING(@v0, @j, 1))
            SET @thisJ = @j

            SET @distance =
                CASE WHEN (@sChar = SUBSTRING(@t, @j, 1)) THEN @diag                    --match, no change
                     ELSE 1 + CASE WHEN @diag < @left AND @diag < @distance THEN @diag    --substitution
                                   WHEN @left < @distance THEN @left                    -- insertion
                                   ELSE @distance                                        -- deletion
                                   END
                     END
            SET @v0 = STUFF(@v0, @thisJ, 1, NCHAR(@distance))
            SET @diag = @left
            SET @j = case when (@distance > @max) AND (@thisJ = @i + @lenDiff)
                then @jEnd + 2
                else @thisJ + 1 end
        END
        SET @i = CASE WHEN @j > @jEnd + 1 THEN @sLen + 1 ELSE @i + 1 END
    END
    RETURN CASE WHEN @distance <= @max THEN @distance ELSE NULL END
END

Comment: You can at least give credit to the person you got the code from .........

Levenshtein distance in T-SQL


Store slice of 3D Numpy Array as a variable

Question: I've got various 3D arrays that I'm viewing 2D slices of, along either the X, Y or Z axis.
To simplify my code, I would like to have one location of declaring the slice such as
# X View
my_view = [10, :, :]
# Y View
# my_view = [:, 4, :]
# Z View
# my_view = [:, :, 7]

and choose which view to run in my script.
Then the rest of my code can apply the myview slice when visualizing,
plt.plot(my_data[myview])
plt.plot(more_data[myview])

There's no way to "store" the ':' portion of the slice. How would I accomplish this in Python/Numpy?
Comment: `myview=(4, slice(None), slice(None))` etc
Answer: np.s_ is a handy tool for making an indexing tuple:
In [21]: np.s_[10,:,:]
Out[21]: (10, slice(None, None, None), slice(None, None, None))

but you can create that directly:
In [22]: (10,slice(None),slice(None))
Out[22]: (10, slice(None, None, None), slice(None, None, None))

arr[i,j] is the same as arr[(i,j)], the comma creates a tuple.
In [23]: 10,slice(None),slice(None)
Out[23]: (10, slice(None, None, None), slice(None, None, None))

You can create a more general indexing tuple this way.
Answer: Why not make my_view a function?
def my_view(arr):
    """Returns a certain 2d slice of a 3d NumPy array."""
    # X View
    return arr[10, :, :]
    # Y View
    # return arr[:, 4, :]
    # Z View
    # return arr[:, :, 7]

Application:
plt.plot(my_view(my_data))
plt.plot(my_view(more_data))


Prob. 10 (d), Sec. 19 in Munkres' TOPOLOGY, 2nd ed: How to show that this map is open?

Question: Here's Prob. 10, Sec. 19 in the book Topology by James R. Munkres, 2nd edition:

Let $A$ be a set; let $\{X_\alpha \}_{\alpha \in J}$ be an indexed family of spaces; and let $\{ f_\alpha \}_{\alpha \in J}$ be an indexed family of functions $f_\alpha \colon A \to X_\alpha$.
(a) Show there is a unique coarsest topology $\mathscr{T}$ on $A$ relative to which each of the functions $f_\alpha$ is continuous.
(b) Let $$\mathcal{S}_\beta = \left\{ \ f_\beta^{-1}(U_\beta) \ \colon \ U_\beta \mbox{ is open in } \ X_\beta \ \right\},$$ and let $\mathcal{S} = \bigcup \mathcal{S}_\beta$. Show that $\mathcal{S}$ is a subbasis for $\mathscr{T}$.
(c) Show that a map $g \colon Y \to A$ is continuous relative to $\mathscr{T}$ if and only if each map $f_\alpha \circ g$ is continuous.
(d) Let $f \colon A \to \prod X_\alpha$ be defined by the equation
$$ f(a) = \left( f_\alpha(a) \right)_{\alpha \in J};$$
let $Z$ denote the subspace $f(A)$ of the product space $\prod X_\alpha$. Show that the image under $f$ of each element of $\mathscr{T}$ is an open set of $Z$.

Now parts (a), (b), and (c) are clear to me.
How to show part (d)?
Let $V$ be an open set in $A$, let $x \in f(V)$, and let $a \in V$ such that $x = f(a)$. Since $a \in V$, there is some basis element $\cap_{i=1}^n f_{\alpha_i}^{-1}(U_{\alpha_i})$ (i.e. a finite intersection of element of $\mathcal{S}$) such that $$a \in \cap_{i=1}^n f_{\alpha_i}^{-1}(U_{\alpha_i}) \subset V.$$ Here $\alpha_1, \ldots, \alpha_n$ are distinct indices and $U_{\alpha_i}$ is open in $X_{\alpha_i}$ for each $i$. Let's take $U_\alpha = X_\alpha$ for all other indices $\alpha \in J$. Thus,
$$a \in \cap_{\alpha \in J} \ f_\alpha^{-1}(U_\alpha) \subset V.$$
So $$x= f(a) \in \prod_{\alpha \in J}  U_\alpha,$$ which is open in the product space $\prod X_\alpha$. So $$x \in f(V) \cap \left( \prod_{\alpha \in J}  U_\alpha \right) \subset Z \cap \left( \prod_{\alpha \in J}  U_\alpha \right) . $$
Is my reasoning correct so far? If so, then what next?
Comment: (b) is false as stated, you only have a subbase. You need to add finite intersections of those sets to get a base.
Comment: Show $f \left[\cap_{i=1}^n f_{\alpha_i}^{-1}[U_{\alpha_i}] \right]$ is exactly the product set (with the other $U_\alpha = X_\alpha$) intersected with $Z$. Then $f$ is open in base elements and so open for all, as images preserve unions.
Comment: @HennoBrandsma I've edited the post. Could you please elaborate the second comment of yours.
Answer: Your reasoning is correct so far. The crucial observation is that the last set in your post is just the image of the basis element of $A$ under $f$, so
$$
\textstyle
f(a)\in Z\cap\prod_{\alpha\in J}U_\alpha = f\left(\bigcap_{\alpha\in J}f_\alpha^{-1}(U_\alpha)\right) \subseteq f(V)$$ That means $f(V)$ is open in the relative topology of $Z$.


Htaccess Redirect with Regular Expressions

Question: I have a question regarding htaccess configuration win a PHP Project
I have this code to use redirection
DirectoryIndex src/client/index.php

Redirect /app/about http://localhost/app/?p=about
Redirect /app/contact http://localhost/app/?p=contact

Inside src/client/index.php I check the GET[p] to include the page requested.
It works... but I dont want to modify the htaccess file each time I add a new page.
I would like to implement something like this but it doesnt work, Im pretty sure I have syntax errors
Redirect ^/app/(.*) http://localhost/app/?p=$1

Thanks for your time :)
Answer: You just need to use RedirectMatch:
RedirectMatch ^/app/(.*) http://localhost/app/?p=$1


Send an email to a group of users after new content has been created

Question: In Drupal 9, I need to notify all users belonging to a role by sending them an email about the new created content.
Everything's fine, but I don't know how to put together the email addresses of these users in the Send to data selector of the Rules module.
Answer: In Rules there's a "Send email to all users of a role" action you can use for this purpose. There is no "Send to" input for this action because all you need to do is specify the role, not the email addresses.
Comment: What exactly should i insert into the "Send to" text box? the machine name of the user role? Or its full name? If i insert `administrator` there, i get an error on the new node creation"
`Error: Call to a member function id() on string ve funkci Drupal\rules\Plugin\RulesAction\SystemEmailToUsersOfRole->Drupal\rules\Plugin\RulesAction\{closure}() (řádek 125 souboru /mnt/data/accounts/b/buffaloo/data/www/nohec.tingz.cz/modules/contrib/rules/src/Plugin/RulesAction/SystemEmailToUsersOfRole.php) `
Answer: As anonymous indicated, use the "Send email to all users of role." I believe roles are identified by number. If you go to /admin/people/permissions/roles, and hover over 'edit permission,' the number at the end of the url should indicate the id for the role.
Comment: Roles are identified by the machine ID of the role, which is usually a string in Drupal 8 and 9. For example, then "Authenticated" user role has a machine ID of "authenticated". This input will be replaced with a select box in then near future, where you may simply select from the site's existing roles rather than having to type in a machine ID.


New Line Added in file write when inserting text

Question: I've tried several ways to append a string to a line being written to a file when reading from another file (as well as in place using fileinput). I'm definitely missing something but trying different approaches for a few hours has not fixed the problem.
The latest approach is below, which still results in the imagelist being on a new line after the datarow where the goal is to output them to a single line.
for datarow in oldfile:
    rowcols     = datarow.split('|')
    imagelist   = []
    image_seed  = rowcols[headers.index('Group ID')]+'_'+rowcols[headers.index('Case ID')]+'_'+rowcols[headers.index('Contact ID')]

    if isfirstrow:
        newfile.write(headerrow)
        isfirstrow = False
    else:
        for imagename in imagefiles:
            if image_seed in imagename:
                imagelist.append(os.path.basename(imagename))
        if len(imagelist) > 0:
            imagelist.insert(0, datarow)
            newfile.write('|'.join(imagelist)+'\n')
        else: newfile.write(datarow)

Thanks in advance for you input!
Answer: You probably have some reminent '\n' either in front of your 1st item of your imagelist or after datarow. Unfortunately you dont show how you read oldfile.
Soluttion, clean '\n' from it:
imagelist.insert(0, datarow.rstrip('\n'))                      # rstrip for clean on end
newfile.write('|'.join(x.strip('\n') for x in imagelist)+'\n') # strip: clean both ends

Maybe you should give this a read:    How to debug small programs (#5)
You might also need to clean up
 else: newfile.write(datarow.rstrip('\n')+'\n')          # make it consistently have a \n

Comment: Thanks, imagelist.insert(0, datarow.rstrip('\n'))  did the trick.


Get the SQL for a Rails 3 Association

Question: I really like how in Rails 3 you can ask a scope for its SQL like this:
User.admins.to_sql

Is there any way to do the same thing with a has_many relation?:
User.first.jobs.to_sql

I've tried User.first.jobs.public_methods.grep /sql/ and other tricks, but I haven't turned up anything.
Answer: User.first.jobs.scoped.to_sql

Get the SQL for a Rails 3 Association


Qual a diferença de namedtuple e NamedTuple?

Question: A documentação do módulo typing afirma que os dois trechos de código abaixo são equivalentes.
Utilizando typing.NamedTuple:
from typing import NamedTuple

class Employee(NamedTuple):
    name: str
    id: int

Utilizando collections.namedtuple:
from collections import namedtuple

Employee = namedtuple('Employee', ['name', 'id'])

São exatamente a mesma coisa, ou se não, quais as diferenças entre eles?
Answer: Para todos os fins práticos, são a mesma coisa.
Na verdade, a própria implementação de typing.NamedTuple utiliza internamente a estrutura collections.namedtuple para toda a lógica da tupla, adicionando alguns campos ao objeto.
class NamedTuple(metaclass=NamedTupleMeta):
    _root = True

    def __new__(self, typename, fields=None, **kwargs):
        if kwargs and not _PY36:
            raise TypeError("Keyword syntax for NamedTuple is only supported in Python 3.6+")
        if fields is None:
            fields = kwargs.items()
        elif kwargs:
            raise TypeError("Either list of fields or keywords can be provided to NamedTuple, not both")
        return _make_nmtuple(typename, fields)

Trecho de código tirado do arquivo fonte no repositório oficial, linhas 2170 a 2207
Perceba que o retorno do construtor da classe é o retorno da função _make_nmtuple. Tal função foi definida linhas acima:
def _make_nmtuple(name, types):
    msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
    types = [(n, _type_check(t, msg)) for n, t in types]
    nm_tpl = collections.namedtuple(name, [n for n, t in types])
    # Prior to PEP 526, only _field_types attribute was assigned.
    # Now, both __annotations__ and _field_types are used to maintain compatibility.
    nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
    try:
        nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
    except (AttributeError, ValueError):
        pass
    return nm_tpl

O retorno da função será nm_tpl, que foi definido utilizando collections.namedtuple, adicionando os campos __annotations__ e _field_types. Não obstante, na classe NamedTupleMeta, qual a NamedTuple utiliza como metaclasse, existe o seguinte trecho:
nm_tpl = _make_nmtuple(typename, types.items())
defaults = []
defaults_dict = {}
for field_name in types:
    if field_name in ns:
        default_value = ns[field_name]
        defaults.append(default_value)
        defaults_dict[field_name] = default_value
    elif defaults:
        raise TypeError("Non-default namedtuple field {field_name} cannot "
                        "follow default field(s) {default_names}"
                        .format(field_name=field_name,
                                default_names=', '.join(defaults_dict.keys())))
nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
nm_tpl.__new__.__defaults__ = tuple(defaults)
nm_tpl._field_defaults = defaults_dict

O que são metaclasses?
Onde fica claro a adição dos três campos sobre a estrutura padrão namedtuple: __annotations__, __defaults__ e _field_defaults.
Mas no que isso tudo implica para mim, como desenvolvedor?
Utilizando as versões mais recentes do Python, 3.6+, prefira utilizar a estrutura typing.NamedTuple, por seu muito mais simples de escrever e mais legível.

A definição de typing.NamedTuple é mais simples;
Os dois trechos de código abaixo são, na prática, equivalentes, mas veja a diferença nas suas definições.
class Employee(typing.NamedTuple):
    name: str
    id: int

Employee = collections.namedtuple('Employee', ['name', 'id'])

# Python <= 3.5
Employee = collections.namedtuple('Employee', [('name', str), ('id', int)])

Além disso, utilizando typing.NamedTuple você pode facilmente definir valores padrões para os campos:
class Employee(typing.NamedTuple):
    name: str = 'Guido'
    id: int = 1

Em comparação com collections.namedtuple:
Employee = collections.namedtuple('Employee', ['name', 'id'])
Employee.__new__.__defaults__ = ('Guido', 1)

É muito mais fácil adicionar uma docstring na typing.NamedTuple;
Para adicionar uma docstring no objeto criado, basta adiciona-la normalmente à classe que criou.
class Employee(typing.NamedTuple):
    """ Documentação da classe Employee """
    name: str
    id: int

Enquanto para collections.namedtuple precisa fazer a atribuição manualmente.
Employee = collections.namedtuple('Employee', ['name', 'id'])
Employee.__doc__ = "Documentação da classe Employee"

Não é necessário repetir o nome da classe. Para collections.namedtuple, na própria definição do objeto será necessário informar o nome duas vezes, mais uma para cada personalização do objeto que fizer. Com typing.NamedTuple, o nome é indicado apenas uma vez como nome da classe.
Com typing.NamedTuple é possível adicionar facilmente métodos ao objeto.
class Employee(NamedTuple):
    """Represents an employee."""
    name: str
    id: int = 3

    def __repr__(self) -> str:
        return f'<Employee {self.name}, id={self.id}>'

Mas atenção, mesmo que você defina Employee como herdando de typing.NamedTuple, ele não será um sub-tipo deste.
isinstance(Employee('Guido', 1), typing.NamedTuple)  # False

Answer: Com typing.NamedTuple é possível colocar tipo nos atributos, enquanto com namedtuple não. Outra diferença é que com typing.NamedTuple é possível ter valores padrão para alguns dos atributos.
Para guardar essas informações, a nova classe criada tem 2 atributos extras: _field_types e _field_defaults.
Também é possível adicionar docstrings nas classes derivadas de typing.NamedTuple e adicionar métodos.


SSRS 2008 Multiple X-Axis Categories - Remove Brackets

Question: I am trying to add multiple X-axis categories to an SSRS 2008 line chart, but by default it is adding these brackets to each additional category.  Is there a way to remove these brackets?  I am trying to display about 50 data points and it the brackets are causing the data in the categories to be cut off/squished/un-readable.  Or if there is a better way of displaying multiple x-axis data.  Any help is greatly appreciated!  Thanks.
Brackets in question:
http://i44.photobucket.com/albums/f39/sethmo38/SSRSLineChart3_zps348f76b8.jpg
Answer: You should be able to just click on the axis X or Y till you see a selected block outline and then click 'delete' on your keyboard and it is removed.  If you want to perform operations outside the norm but keep some of the options click properties instead.
The default is pane is Axis Options and you can change 'Category' to 'Scalar' if you want numbers.  You set expressions instead of the auto here if you want.  If you don't want that but want a custom labeling go to the pane 'Labels' instead.  You can hide the labels all together or choose an expression to determine when they are hidden.  You may wish to mess with the major and minor tick marks as well.  When you want to highly customize an axis you may wish to mess with hiding some of the major marks and potentially turn off the 'Category' axis type and set everything manually.  Sorry I can't see your picture at work to be more understanding of your situation so forgive me if I missed something.


Alterar cor do texto e do background ToolTip

Question: Como posso alterar a cor de background e do texto de um ToolTip? Já fiz uma pesquisa e encontrei aqui um trecho de código mas não consigo alterar. As cores mantêm-se sempre as padrão do NetBeans. Alguma sugestão?
Coloquei o seguinte código no construtor da minha classe:
     UIManager.put("ToolTip.foreground", Color.BLACK);
     UIManager.put("ToolTip.background", Color.GREEN);
     ToolTipManager.sharedInstance().setInitialDelay(0);
     ToolTipManager.sharedInstance().setDismissDelay(1500);
     jFormattedNIPC.setToolTipText("teste");

Atualização:
Utilizar HTML nas propriedades do campo na secção toolTipText. A cor consegui mudar bem, mas o background fica assim:

A cor de background não preenche o 'balão' por completo.
Cógido utilizado:
teste

Comment: Alguns elementos do swing aceitam HTML no texto. Por exemplo numa Label você pode colocar algo assim no texto: `"Palavra em negrito."`. Tentou colocar isso no teu tooltip?
Comment: Não usei qualquer tipo de HTML no meu código. vou tentar esse. Mas a nível de cores qual seria o código? É que não estou muito por dentro de HTML. Desde já obrigado! FUNCIONA O NEGRITO !! :) preciso das cores para background e texto :)
Comment: Mudar a cor do texto já consegui, falta-me para o background do tooltip.
Answer: Solução 1
Alguns elementos do swing aceitam HTML no texto. Por exemplo numa label você pode colocar algo assim no texto: "Palavra em negrito.".
No seu caso podes fazer assim:
"
TESTETETESTE";

Porém, como apontado pelo autor da pergunta, esta solução não resolve perfeitamente o problema. Ele não deixa o fundo completamente preenchido com a cor.
Solução 2
Você pode criar um ToolTip customizado para o componente:
class MyCustomToolTip extends JToolTip {
    public MyCustomToolTip(JComponent component) {
       super();
       setComponent(component);
       setBackground(Color.black);
       setForeground(Color.red);
    }
}

Então na hora de inicializar um componente, neste exemplo um jTextField, faça assim:
jTextField1 = new JTextField("teste"){
    @Override
    public JToolTip createToolTip() {
        return (new MyCustomToolTip(this));
    }
};

Obs.: se você usa NetBeans podes mudar o tooltip de um componente da seguinte forma:

Coloque a classe MyCustomToolTip depois do método initComponents();

Clique com o botão direito no componente;

Vá em Propriedades;

Clique na aba Código;

Na propriedade Código de Criação Personalizado clique nos ... e digite o código de criação (no caso um JTextField):

new JTextField("teste"){ // Pode ser new JLabel, depende do tipo do componente
    @Override
    public JToolTip createToolTip() {
        return (new MyCustomToolTip(this));
    }
};

Ok.
Comment: Dessa forma não funciona. Tem de ser colocado o código HTML nas propriedades do campo na parte to tooltip.
Comment: O seu texto ficará vermelho..  esse código põe a cor do texto vermelha.

O seu código deve ter algum erro ou então não funciona :S
Comment: Exato. Depois do style tem que por um `=`. Eu tinha posto um `:`.
Comment: tenta assim  `"TESTETETESTE";`   (só para ajudar, nao sei se é a mesma coisa @Earendul)
Comment: Eu não percebo nada de html. @jsantos1991 o seu código não funcionou :S Earendul esse funciona mas tem um pequeno problema. Vou editar a pergunta e mostrar o que acontece.
Comment: @HugoMachado eu também não pesco lá muito, mas esse código funciona para mim ;) mas ainda bem que o código do Earendul funciona
Comment: Ok, já vou editar a resposta com mais uma solução...
Comment: Editei a resposta. Testei aqui e a solução 2 funcionou melhor que a primeira.
Comment: Tenho sempre um problema com isso que deve ser básico mas não consigo resolver :S Já tentei esse código ontem mas não consegui. Em vez de tar a criar um new JTextField eu quero utilizar num campo que já tenho no meu design. Como faço?
Comment: Você usa NetBeans?
Comment: Sim estou com netbeans. Se a solução do @jsantos1991 funcionou aos dois talvez eu não esteja a por o código bem. Pode colocar a linha de código nas Soluções tambem ?
Comment: @HugoMachado alterei a resposta com o código do jsantos1991. Também coloquei os passos para mudar no NetBeans.
Comment: Não me está a funcionar. Pode Colocar a linha de código do @jsantos1991 nessas soluções? e tudo numa linha só para ver se eu ponho em HTML ? :) EDIT: Já está lá !

Só uma questão, as aspas e o ';' entram no código HTML ?
Comment: @HugoMachado - coloquei lá o código do jsantos1991. No caso da solução 2 lembrou de colocar a classe `MyCustomToolTip` junto ao código? Pode colocar depois do método `initComponents()`.
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/18648/discussion-between-earendul-and-hugo-machado).
Comment: Sim coloquei a classe depois no initComponents e pus o código que me disse no Custom Code nas propriedades e não me funciona :(


Factor significant within model but non significant after drop?

Question: This may be quite a basic question but I was running a simple linear model and dropping non significant terms until I got to a minimal model. When this was reached, I was obtaining the significance for the explanatory variables that remained also by dropping them one at a time. Now, what I am getting is that one of those variables in my minimal model becomes non-significant after I drop it and I am not quite understanding what is going on. If someone could give me an hint, that would be great (code is below).
So my minimal model was:
m1<-lm(log10(para.ml) ~ treat + prop.r + log(od))

Analysis of Variance Table

Response: log10(para.ml)
                 Df Sum Sq Mean Sq F value    Pr(>F)
treat             3 4.2925 1.43083  30.113 9.181e-09 ***
prop.r            1 1.5419 1.54190  32.451 4.723e-06 ***
log(od)           1 0.5698 0.56981  11.992  0.001796 **
Residuals        27 1.2829 0.04751

So here treat is a factor with 4 levels and both prop.r and log(od) are continuous variables. As you can see, all effects look significant and if I drop prop.r or log(od), model m1 is still preferred. Though the same does not happen if I drop treat:
m2<-update(m1,~.-treat)
anova(m2,m1)

Analysis of Variance Table

Model 1: log10(para.ml) ~ prop.r + log(od)
Model 2: log10(para.ml) ~ treat + prop.r + log(od)
  Res.Df    RSS Df Sum of Sq      F  Pr(>F)
1     30 1.6202
2     27 1.2829  3   0.33728 2.3662 0.09308 .

now, if I get the anova table for this last model, I obtain this:
anova(m2)

Analysis of Variance Table

Response: log10(para.ml)
                 Df Sum Sq Mean Sq F value    Pr(>F)
prop.r            1 4.8607  4.8607  90.003 1.537e-10 ***
log(od)           1 1.2062  1.2062  22.335 5.045e-05 ***
Residuals        30 1.6202  0.0540

So, comparing anova(m2) and anova(m1) it looks like most of the variation that was being explained by treat is now explained by prop.r or by log(od). Thus is it just the case that when I have treat in my model it just explains a lot of the variation that could just be explained by the other variables?
Any help appreciated!
Comment: A related phenomenon is discussed at http://stats.stackexchange.com/questions/14500/. You seem to be performing an *ad hoc* version of "stepwise regression," which has been [extensively discussed](http://stats.stackexchange.com/search?q=%2Bstepwise+%2Bregression) on this site.  There is practically a consensus that this method is best avoided (or used with care by experts in particular situations); there are better model-building techniques available.
Answer: In the first code block you do not show how you produced the analysis of variance table.  It looks likely that you used anova(m1).  If that is the case then the table produced is the sequential table, which means that the first line shows the effect of 'treat' by itself (not adjusting for the other terms), then the 'prop.r' row is the effect of 'prop.r' adjusting for 'treat' but not the other variable, etc.
In that case with some relationship between the predictor variables it is possible that 'treat' is related by itself, but is redundant given the other variables.  This is what is looks like is happening.  The second time you use anova you get different results because the adjusting is different.
Answer: It could be related to the type of sums of squares that R uses for lm. I can't find the documentation, but lm() might be using Type 1 sums of squares. For Type 1 sums of squares, the order of the variables in the model matters (see here for a summary).
treat might be correlated with the other variables in the model. If so, by having it first, it may explain much of the variance that could be explained by the other variables. Once you remove it, the other variables might explain that variance, meaning that it is no longer significant. Try rearranging the order in your minimal model to have treat last and see if it is still significant.
Comment: I realized that this answer practically duplicates @Greg's. I've added this to his answer to provide a more complete response.
Answer: The variables you choose for your model can be correlated with each other.  This may mean that there is no "best" subset.  The significance of a variable thus depends on what the other variables in the model are.  Their importance really comes in as to how well they work together to fit the data.  So when included with certain other variables a particular variable might appear to add significantly to the model by being added whereas with another set of variables in the model it might not. As an oversimplified example suppose X1 can be expressed as a linear comination of X2, X3 and X4.  Theb if X2, X3 and X4 are already in the model X1 has no significant effect to add to the model.  But if at least one of the variables X2, X3 and X4 is not in the model when X1 is being evaluated, X1 could turn out to significantly improve the model fit.
Comment: Hi Michael,

thank you very much for your reply. That does make sense to me. But in my case what I am getting is that my X1 (to use your notation) seems significant in the presence of my X2 and X3, but isn't when I drop it from the model. I guess what I don't understand well is why in the first model some of the variation is being explained by my X1 (treat) and not by the other variables, since that is what happens when I simplify the model.
Comment: @ricardo That sounds simple to explain.  Suppose Z is a linear function of X1, X2, and X3 and Z is a useful predictor of the model response.  Then in combination X1, X2, and X3 are significant in explaining y but none of them by themselves would be.


(Absolute) convergence of $\sum_{k=0}^\infty (-1)^k \frac{1+k}{k^2-2k-\pi}$

Question: We want to find out if the following series converges (absolutely).
$$\sum_{k=0}^\infty (-1)^k \frac{1+k}{k^2-2k-\pi}$$
Since we have $(-1)^k$, we can use the Leibniz criterion.
We have to prove that $a_n$ is a null sequence and that it is monotonically decreasing.
$$\lim_{k \to \infty} \frac{1+k}{k^2-2k-\pi} \\
= \lim_{k \to \infty} \frac{k^2 \cdot (\frac{1}{k^2} + \frac{1}{k})}{k^2 \cdot (1 - \frac{2}{k} - \frac{\pi}{k^2})} \\
= \lim_{k \to \infty} \frac{0}{1} = 0$$
To prove that it is monotonous decreasing, we have to show $a_n \geq a_{n+1}$
$$a_n \geq a_{n+1}
\\ \Leftrightarrow \frac{1+k}{k^2-2k-\pi} \geq \frac{2+k}{(k+1)^2-2(k+1)-\pi}
\\ \Leftrightarrow \frac{1+k}{k^2-2k-\pi} \geq \frac{2+k}{k^2+2k+2-2k-2-\pi}
\\ \Leftrightarrow \frac{1+k}{k^2-2k-\pi} \geq \frac{2+k}{k^2-\pi}$$
But how do we continue from here?
Comment: You can avoid verifying the monotonicity property of $(1+k)/(k^2-2k-\pi).$ See my answer.
Answer: If you want to test if it is absolutely convergent, then you need to test the following:
$$S=\sum_{k=1}^\infty \frac{1+k}{k^2-2k-\pi}>\sum_{k=1}^\infty \frac{k}{k^2}=\sum_{k=1}^\infty\frac{1}{k} \rightarrow\infty $$
So it is not absolutely convergent.
Comment: numerator: $k+1>k$ , denominator: $k^2-2k-\pi\frac{1}{k^2}$ hence get the desired form @user1234567890
Comment: Thanks, but how do you get to $\frac{k}{k^2}$?
Answer: The Leibniz criteria only gives us conditional convergence. The series is not absolutely convergence, try the comparison criteria with $\frac{1}{k}$
Answer: There is a general rule if $\sum a_n,$ $\sum b_n$ are convergent, and $$\sum|a_n|=\infty,\qquad \sum|b_n|<\infty$$ then $$\sum (a_n+b_n) \ {\rm is \ convergent,} \quad\sum |a_n+b_n|=\infty$$ In your case $$a_n={(-1)^n\over n}\qquad b_n=(-1)^n{1+n\over n^2-2n-\pi}-{(-1)^n\over n}$$
and $|b_n|\approx {3\over n^2}.$
Observe that we avoid verifying the monotonicity property of ${1+n\over n^2-2n-\pi}$.
In this way we decide about convergence and absolute convergence simultaneously.


What does the term "gaussian models" mean?

Question: In the R documentation for the cv.glmnet function, type.measure parameter is described as:

loss to use for cross-validation. Currently five options, not all available for all models. The default is type.measure="deviance", which uses squared-error for gaussian models (a.k.a type.measure="mse" there), deviance for logistic and poisson regression,...

Could someone help me with the exact definition of the term gaussian models? Does it refer to all regression models?
Comment: errors are Gaussian
Comment: pardon me, but is there a more layman explanation for what are Gaussian errors and what is non-Gaussian errors? I find it hard to grasp the meaning of the term...
Comment: Are you familiar with normal distribution ?
Answer: Gaussian models are models that use the Gaussian distribution (also known as the normal distribution).  The reference usually refers to an assumption that the "error terms" in the model are assumed to be normally distributed.  Maximum likelihood estimation for this distribution can be shown to be equivalent to minimising the Mean-Squared-Error (MSE).
Comment: Theoretically yes, you can, If you assume that the errors are Gaussian, roughly speaking it's mean that errors are predictable.  you may check prof Anderw Ng lecture notes page 11. (probabilistic interpretation).https://see.stanford.edu/materials/aimlcs229/cs229-notes1.pdf
Comment: But when would the gaussian assumption for 'error terms' be reasonable? For example can we assume all linear regression models have gaussian error terms? Thank you!


Components won't auto-resizing when using JFXDecorator, how to fix that?

Question: I want to use JFXDecorator to fancy a look of a Window of my application. But using it brokes an auto-resize of components. This is what my code looks like

 @Override
 public void start(Stage stage) throws Exception {

    FXMLLoader loader = new FXMLLoader(getClass().getResource("ApplicationView.fxml"));
    Parent root = loader.load();

    JFXDecorator decorator = new JFXDecorator(stage, root);
    decorator.setCustomMaximize(true);

    stage.setTitle("Weather API");
    stage.setScene(new Scene(decorator));

    String cssURI = getClass().getResource("stylesheet/style.css").toExternalForm();
    decorator.getStylesheets().add(cssURI);

    stage.show();
}

And this is the effect, look at the split-pane.

Without JFXDecorator works normally with code like below.
@Override
public void start(Stage stage) throws Exception {

    FXMLLoader loader = new FXMLLoader(getClass().getResource("ApplicationView.fxml"));
    Parent root = loader.load();

    stage.setTitle("Weather API");
    stage.setScene(new Scene(root));

    String cssURI = getClass().getResource("stylesheet/style.css").toExternalForm();

    stage.show();
}

I tried to set AncorPane properties of main pane similar to childs so maybe it will resising but it failed. My FXML looks like that
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="480.0" prefWidth="640.0" stylesheets="@stylesheet/style.css" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.161">
   <children>
     <SplitPane dividerPositions="0.29797979797979796" layoutX="220.0" layoutY="129.0" prefHeight="480.0" prefWidth="640.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
      <items>
        <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
        <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
      </items>
    </SplitPane>
   </children>
</AnchorPane>

How can I fix it? Thank You.
Comment: Show minimal-complete `FXML` with fault.
Comment: I attached full FXML by now
Comment: This `FXML` seems to the be the one that is working the way you want it to work.
Comment: Okay, yea looks like a problem.
Comment: It does not make sense, but when I made the `SplitPane` the root `FXML` node it worked.
Answer: Get rid of the AnchorPane and make the SplitPane the root node.
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.layout.AnchorPane?>

<SplitPane dividerPositions="0.29797979797979796" prefHeight="480.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
   <items>
      <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
      <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
   </items>
</SplitPane>


Criar um Android App Bundle com Xamarin Forms

Question: Quando tento publicar publicar um app Xamarin.Android no console do desenvolvedor Android recebo a seguinte mensagem de aviso que não me deixa publicar o app:

Neste caso como eu poderia criar um APK otimizado, ou seja, como poderia criar um Android App Bundle de um app desenvolvido em Xamarin Forms?
Answer: Nas propriedades do projecto Android -> Avançadas -> em Supported ABIS, seleccionar
armeabi e armeabi-v7a
Comment: Bruno Caceiro essas opções que você mencionou são do Android Studio ou do Xamarin Forms? Porque no meu caso eu estou desenvolvendo usando Xamarin Forms..
Comment: São no Visual Studio, tanto para Mac como para Windows, e sim, usando XamarinForms
Answer: Estava com o mesmo problema hoje e infelizmente não achei uma solução para este aviso. Alterei os ABIS suportados, tentei criar um package para cada ABI e subir separadamente, mas o aviso continuou em todos os casos.
Conforme a seguinte postagem no forum do xamarin https://forums.xamarin.com/discussion/138216/android-app-bundle-dynamic-delivery, foi comentado que a solução estava no github do xamarin forms, porém não achei nada referente a isto.
No final das contas isto é apenas um aviso e pode ser ignorado. O problema é que nem todos os itens obrigatórios estão preenchidos. Verifica do lado esquerdo quais itens não estão com o check verde. No meu caso era o App Content

Após preencher os dados e o check ficar verde vai conseguir fazer a publicação da versão normalmente.
Answer: Passos para gerar o arquivo .aab no Visual Studio 2019 para desenvolvimento com Xamarin.Forms:

Clique com o botão direito em seu projeto e selecione Propriedades.
Navegue até as opções do Android.
Altere sua configuração para Release.
Altere o formato do pacote Android para bundle.

Depois de concluir essas etapas, você pode gerar um pacote de aplicativos clicando com o botão direito do mouse em seu projeto e selecionando Arquivar (Archive) para gerar o arquivo bundle (.aab)

Trecho extraído da fonte:
https://devblogs.microsoft.com/xamarin/android-app-bundle/
Comment: A pessoa que negativou a minha resposta acima, provavelmente foi uma das que deram a resposta errada. Não existe como criar arquivo .aab apenas mudando o tipo de suporte ao processador. Além do mais, já é definição da própria Google Play que APKs só serão aceitos até agosto de 2021. Após essa data deve-se fazer o procedimento que eu citei acima para criação correta do arquivo para upload no Google Play.
Answer: Tem um jeito fácil para resolver isto.

No projeto do Android, clique com o botão direito e selecione a opção: "Descarregar Projeto";
Em seguida, o Visual studio vai abrir o arquivo .csproj;
Pesquise pela palavra: "AndroidPackageFormat"... Quando você localizar, você troca a opção apk por aab, ficando desta forma:

<code><AndroidPackageFormat>aab</AndroidPackageFormat>
</code>
Feito isto, salve o arquivo e clique novamente com o botão direito no projeto do android, e selecione a opção "Recarregar Projeto"... Pronto!
Agora você pode arquivar novamente o projeto e o arquivo .aab será gerado.


How to set type of generic Java class at runtime?

Question: I'm currently running into a problem with Java generics, where the type of the parameter T has to be determined at runtime.
Here's the class having a type parameter T:
public class Something<T> {
    T value;

    public Something(T value) {
          this.value = value;
    }

    ... //some other methods
}

And here's a method in another class, where an instance of Something should be created, but where the type of T depends on the dynamic type of the given object:
public void create(Object o) {

    //this is not working, since there is no getType() method
    Something<o.getType()> s = new Something();
}

Is there a way to determine the dynamic type of o and pass it as type parameter to the Something-class? It is no option to make use of an if-cascade using instanceof, since there are many possibilities what o might be.
Comment: Generics provide compile-time checking so that's why it's not possible to do it like you want to.
Comment: What do you mean by dynamic type here? Do you mean the actual object being referenced?
Comment: Do you need the actual class of the instance or the type you pass as a parameter? Ie, if you pass a `A` but ultimately the argument is a `B` where `B` extends `A`, what should happen?
Comment: The way you've suggested it's not possible; however, maybe if you tell us *why* you want to do this...
Comment: Can you explain why would you want to do that?
Comment: I am currently working on a code generation project consisting of two sub projects. The first subproject contains the `Something`-class and does the  actual code generation part. The other project delivers input for the code generation and contains the `create`-method. since the code generation should work for arbitrary objects, I don't know at compile time which objects might be passed to this method.
Answer: You can parametrize the create() method by K (just to avoid the confusion with T)
public <K> void create(K o) {
    Something<K> s = new Something<K>();
}

Then, when you invoke the create() method several times, here's what will happen:
create(Object o)  -> will parametrize Something by Object

create(Integer i) -> will instantiate Something by Integer

Comment: This won't be the runtime type of `K` right? What if you pass an `Object` reference holding a `String` object to this method. `K` will be inferred as `Object`. So, no this won't work.
Comment: Erasure means it doesn't matter: there's no differnece between a `Something` and a `Something`.  This is fine.
Comment: Whoever invokes the create method will provide the actual type argument here.
Comment: I don't think this works, because you actually need to implement 'create' for every type K that you might create. Plus the fact that at runtime all the Somethings are exactly the same anyway.
Comment: @DJClayworth, I don't think there's a need of implementing `create` for "every type K". Actually, `K` is considered here as "some type with alias K", which means the method is eligible for every type. @Rohit Jain is correct that there's no way to know the runtime type of the object at compile time, though
Comment: You don't even need the parameter `o`. It is not used.
Comment: @kocko When you write this method, it has to be inside a parameterized class Factory. Then the argument of the method is the concrete parameterized type.
Answer: No you can't do that. Type information of generics are erased at compile time. The type that you use as type arguments, must be known to the compiler. Any expression that gives you the runtime type of a reference, will be evaluated at runtime only, when it's too late to set the type argument.
Comment: @ErstwhileIII Tell me how using `instanceof` operator you can set the type argument?
Comment: Well ... consider using the instanceof operator .. the problem is only unsolvable if the class of "runtime usages" is completely unknown.
Comment: See my alternate answer below, please.
Answer: At run-time all generic parameters are erased and everything is Object.
At compile-time, the compiler checks if the methods used on an instance are those of the generic type of that instance.
ArrayList<o.getType()> s is meaningless because at compile-time javac needs to know if it should make an error or not, of the following:
s.get(0).intValue()
What if o is Integer and what if it's String ?
Answer: If you need to create the right generic type for an explicit small number of classes, you could use the instanceof operator ... something like
  if (o instanceof T) { x = new Something<T>();}
  else if (o instanceof String) {x = new Something<String>();}
  else if ....

Comment: `o instanceof T` won't even compile.


Salvar a opção selecionada do radioButton para consulta futura

Question: Gostaria de saber se tem como salvar em um DataTable (ou algo do tipo, para ser consultado mais tarde) a informação que um radioButton foi clicado. Eu estou fazendo um programa simples para um cliente informar três informações em três textbox isso é salvo em uma DataTable e é mostrado em uma DataGrid. Além disso, gostaria de mostrar qual radioButton (se o radiobutton de pessoa fisica for selecionado, então o txt_registro vai receber um numero de cpf)foi clicado no cadastro que o usuário está visualizando na DataGrid (o usuario pode consultar as informações de cadastro depois só clicando em cima da linha da dataGridView.
Pensei que talvez isso devesse ser feito dentro da classe, em um método, mas não sei ao certo pois ainda tenho que fazer uma opção para editar o cadastro selecionado (para o usuário poder editar o que ele havia escrito em um cadastro antigo por meio da text box e salvar no mesmo lugar do cadastro antigo.
public int con;

DataSet ds = new DataSet();
DataTable dt = new DataTable("Cadastro");

public Form1()
{
    InitializeComponent();

    dt.Columns.Add("Nome", Type.GetType("System.String"));
    dt.Columns.Add("Email", Type.GetType("System.String"));
    dt.Columns.Add("Registro", Type.GetType("System.String"));

    dataGridView1.DataSource = dt;
}

private void bt_salvar_Click_1(object sender, EventArgs e)
{

    DataRow dr = dt.NewRow();

    if (con == 1)
    {
        Fisica dadosfisica = new Fisica(txt_nome.Text, txt_email, txt_registro.Text);
        dr["Registro"] = "CPF: " + dadosfisica.CPF;
        dr["Nome"] = dadosfisica.Nome;
        dr["Endereco"] = dadosfisica.Email;

    }

    if (con == 2)
    {
        Juridica dadosjuridica = new Juridica(txt_nome.Text, txt_email,txt_registro.Text);
        dr["Registro"] = "CNPJ: " + dadosjuridica.CNPJ;
        dr["Nome"] = dadosjuridica.Nome;
        dr["Endereco"] = dadosjuridica.Email;

    }

    dt.Rows.Add(dr);
    dataGridView1.DataSource = dt;

}>

                 <public class Dados
            {

            private string _nome;
            private string _email;

            //construtor para iniciar os dados privados - recebe parametros
            public Dados(string nome, string email)
            {
             this._nome = nome;

             this._email = email;
            }

            public string Nome
            {
             get
             {
                 return _nome;
             }
             set
             {
                 _nome = value;
             }
            }

            public string Email
            {
             get
             {
                 return _email;
             }
             set
             {
                 _email = value;
             }
            }
            }>

              <//Classe Juridica herdada da classe Dados
            public class Juridica : Dados
            {

                private string nCNPJ;

                public Juridica(string nome, string email, string nCNPJ)
                    : base(nome, email) //chama o construtor da classe base
                {
                    this.nCNPJ = nCNPJ;
                }

                public string CNPJ
                {
                    get{return nCNPJ;}

                    set{nCNPJ = value;}
                }

            }>

              </Classe Fisica herdada da classe Dados
            public class Fisica : Dados
            {
                private string nCPF;

                public Fisica(string nome, string email, string nCPF)
                    : base(nome, email) //chama o construtor da classe base
                {
                    this.nCPF = nCPF;
                }

                public string CPF
                {
                    get{return nCPF;}

                    set{nCPF = value;}
                }

            }>

//Seleção do RadioButton
private void bt_pfisica_CheckedChanged_1(object sender, EventArgs e)
{
    if (bt_pfisica.Checked)
    {
        txt_registro.Enabled = true;
        txt_registro.Mask = "000,000,000-00";
        con = 1;
    }
}

private void bt_pjuridica_CheckedChanged_1(object sender, EventArgs e)
{
    if (bt_pjuridica.Checked)
    {
        txt_registro.Enabled = true;
        txt_registro.Mask = "00,000,000/0000-00";
        con = 2;
    }
}

Answer: Você pode salvar um valor simbólico na DataTable, indicando se ele foi clicado ou não, exemplo:
dr["Registro"] = "CPF: " + dadosfisica.CPF;
dr["Nome"] = dadosfisica.Nome;
dr["Endereco"] = dadosfisica.Email;
//Crie uma coluna para salvar o dado pretendido. No caso, usarei o valor '1' para 'clicado' e '0' para não clicado
dr["PessoaFisica"] = dadosfisica.Juridica ? "1" : "0";

E então, você pode criar um atributo booleano na sua classe para salvar essa informação:
private bool bJuridica;
public bool PessoaJuridica
{
      get{return bJuridica;}

      set{bJuridica = value;}
}

, Assim sendo, podes definir o valor no atributo assim:
dados.Juridica = bt_pjuridica.Checked;

Espero ter entendido corretamente sua dúvida
Comment: Na verdade a ideia não é mostrar em coluna, e sim mostrar o radioButton "checked" quando eu selecionar a linha do cadastro na dataGridView.
Comment: O dr["PessoaJuridica"] = dados.Juridica ? "1" : "0" está dando problemas para encontrar o local de Juridica.
Comment: Sim, você tem que adicionar a coluna na `DataTable` e o atributo na Classe.

Para definir o radiobutton como "checked", você fazer: `bt_pjuridica.Checked = true;`, caso encontre a condição necessária
Comment: Tem como não adicionar a coluna? Pois eu só quero ver a radioButton selecionada quando eu clicar em uma linha da dataGrid (que tem um cadastro) e o valor do registro já vai estar em uma coluna.
Comment: Se você não precisar guardar a informação em algum lugar, não precisa adicionar a coluna na DataTable.
Comment: Eu só preciso guardar a informação de qual radioButton foi clicado em cada cadastro.
Comment: Então, da maneira que você parece estar desenvolvendo, recomendo guardar qual RadioButton foi clicado na DataTable, juntamente aos outros dados.
Comment: Mas daí eu vou precisar mostrar na coluna, não?
Comment: Você pode colocar a coluna do DataGridView como `.Visible = false;`, assim ela não será visível ao usuário
Comment: Ah, eu não sabia dessa função! Obrigado, vou usar!!
Comment: Por nada :). Vale lembrar que os dados continuarão ali, apenas invisíveis para o usuário
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/55080/discussion-between-bellon-and-artur-trapp).


Lua socket irc twitch bot not getting pinged?

Question: <code>local Bot = {
   Channel = "#*twitch_channel*",
   Name = "smmchrisbot",
   Pass = "oauth:*code*",
   Server = "irc.chat.twitch.tv",
   Port = 6667
}

local socket = require("socket")

local client,err = socket.tcp()
if not client then
   error(err)
end

Bot.Client = client

function Bot.Pingpong(self)
   print("Fire") --Does print
   local msg = Bot.Client:receive("*l") --Doesn't get anthing?
   print(msg)
   if msg == "PING :tmi.twitch.tv" then
      Bot.Client:send("PONG :tmi.twitch.tv")
   end
end

--function Bot.Chat(self,msg)
--Bot.Client:send("PRIVMSG "..Channel.." :"..msg.."\r\n\r\n")
--end

Bot.Client:settimeout(1)

Bot.Client:connect(Bot.Server, Bot.Port)

Bot:Pingpong()
Bot.Client:send("PASS "..Bot.Pass)
Bot:Pingpong()
Bot.Client:send("NICK "..Bot.Name)
Bot:Pingpong()
Bot.Client:send("JOIN "..Bot.Channel)

while true do
   Bot:Pingpong()
   sleep(1)
   --Bot:Chat(io.read())
end
</code>
It print "Fire" and then nil, over and over again. Anybody know why?
Comment: I have no idea what's wrong...
Answer: The answer was actually easy! I just needed to concatenate "\r\n" at the end of my password and stuff!


VBA Error Message - Method 'Range' of Object _Global' failed

Question: I have a code where I'm receiving a "'Range' of Object _Global' failed" error and I'm hoping someone can help as to why. I've looked online and everything seems to advise that I need to specific which sheet the code is referring to, which i've done using With and End With. Please see my code below;
With ThisWorkbook.Worksheets("Tables")
Range(StartingPoint, EndPoint).Copy
End With

However, it doesn't seem to be working. The variables specified above this code are as follows;
Dim ws7 As Worksheet
Set ws7 = ActiveSheet

Dim StartingPoint As Range
Dim EndPoint As Range
Set StartingPoint = Sheets("Tables").Range("C58:R58").Find(ws7.Range("C3"))
If Not StartingPoint Is Nothing Then
Set EndPoint = StartingPoint.Offset(10, 0)
End If

Any help and / or useful reading material would be much appreciated.
Thanks.
Comment: Where does the erroring part come in the code, do you check startpoint and endpoint before using?
Comment: It's the Range within the With / End With piece on the first set of code where's it falling over.
Comment: Just a quick comment: Besides from the full stop @Rory suggested in his answer, are you sure that StartingPoint is getting set to anything, because if it is not, then EndPoint will never get set, therefore failing.
Comment: I've ran the StartingPoint code entirely on its own, adding a copy request in, and it's doing exactly what it should be which indicates it's something to do with the EndPoint?
Answer: Your With statement is not currently doing anything as you haven't qualified the Range call - it needs to be:
With ThisWorkbook.Worksheets("Tables")
.Range(StartingPoint, EndPoint).Copy
End With

Note the full stop in .Range
Also, this assumes those two ranges are on the Tables sheet, or the code will fail.
Comment: Thanks @Rory. I've done that, and am now getting an error saying "Application-defined or Object-defined error". Aren't StartingPoint / EndPoint being defined using the Dim / Set coding though?
Comment: Are those two ranges on the Tables sheet?
Comment: Yes, the first range determines parameter 1, but it is also called on to determine parameter 2, the idea being that both together provide the range. So yes, both ranges are on the Tables sheet.
Comment: Are you certain of that? What does `Msgbox StartingPoint.Parent.Name` display?
Comment: I was, not so much now though. But if I change it to specify the Tables sheets through `Set StartingPoint = Sheets("Tables").Range("C58:R58").Find(ws7.Range("C3"))` that should suffice shouldn't it?
Comment: Yes that ought to do it.


Auto Post to Google + from RSS Feed Content

Question: I am using Drupal 7. I used Feeds module for content from the RSS. So i can get the content from RSS Feeds. Now Feed Content types automatically saved with RSS Feeds content. So now I want to auto Post the Feeds content to the twitter,linkedin and facebook.I am using Twitter module.
So i can Auto post the content using rules module to Facebook.
Same Time I Can Auto Post the content using rules module to twitter..
Now I want to auto post the content to Google + also.I am using Google plus for Google+ connect to my drupal site. After saving my new node display the google+ icon and sharing option also. Same time I want to Auto post the the new node to Google+ Page.
Comment: Please frame the question clearly, what is the issue and what is happening?
Answer: Edit: google+ does have an api, but this module is old, and doesn't implement it.
You can't post using this module.
This link night give you some more information: https://stackoverflow.com/questions/7570327/how-to-post-in-google-plus-wall