Bloquear célula após preenchimento

Question: Estou tentando melhorar a planilha de controle da empresa que trabalho, mas estou tendo problema.
Temos que registrar a ligação de um cliente, já consegui fazer para a planilha preencher a Data e Hora automaticamente após preencher o campo Nome. O que quero agora é proteger os campos Data e Hora nesse momento, para que não possa ser alterado. O que está acontecendo é que em algumas linhas o excel bloqueou a linha inteira. Alguém pode me ajudar?
Esse é o código que fiz até aqui.
Private Sub Worksheet_Change(ByVal Alvo As Range)

     Dim limite_maximo As Integer

  limite_maximo = 4000 ' limite ultima linha

  If Alvo.Cells.Count > 1 Or IsEmpty(Alvo) Then Exit Sub

    ' faz nada se mais de uma célula modificada ou se deu delete

  If Alvo.Column = 5 And Alvo.Row >= 4 And Alvo.Row <= limite_maximo Then

    ' o if acima seta onde vai iniciar e o range e = 5 (coluna), row (linha = 4)

    ' desliga captura do evento change

  Application.EnableEvents = False

    ' muda a célula E da linha correspondente

  ' Desprotege

  ActiveSheet.Unprotect

  Alvo.Offset(0, -1).Value = Time() ' Registra a hora (A = 0, D = 3)
  Alvo.Offset(0, -2).Value = Date   ' Registra a data (A = 0, E = 4)

  Linha = Alvo.Row

  Range("C" & Linha).Locked = True
  Range("e" & Linha).Locked = True

  ' Protege
  ActiveSheet.Protect

  ' religa a captura de eventos
  Application.EnableEvents = True
  End If
End Sub

Essa é a planilha
Answer: Primeiro você deve inserir Locked = False em todas as células da planilha somente uma vez, com o seguinte código:
Sub Destravar_Tudo()
    ActiveSheet.Unprotect
    ActiveSheet.Cells.Locked = False
End Sub

Pois por padrão em .Protect, todas as células estão com .locked = True
Depois, ao travar cada célula, a planilha é protegida com ActiveSheet.Protect Contents:=True, DrawingObjects:=False, como pode ser visto no código abaixo:
Private Sub Worksheet_Change(ByVal Alvo As Range)
    Dim limite_maximo As Long, linha As Long
    'Tratar Erros
    On Error GoTo sair

    limite_maximo = 4000                         ' limite ultima linha

    If Alvo.Cells.Count > 1 Or IsEmpty(Alvo) Then Exit Sub

    ' faz nada se mais de uma célula modificada ou se deu delete
    If Alvo.Column = 5 And Alvo.Row >= 4 And Alvo.Row <= limite_maximo Then
        ' o if acima seta onde vai iniciar e o range e = 5 (coluna), row (linha = 4)
        ' desliga captura do evento change
        Application.EnableEvents = False

        ' muda a célula E da linha correspondente
        ' Desprotege

        ActiveSheet.Unprotect

        Alvo.Offset(0, -1).Value = Time()        ' Registra a hora (A = 0, D = 3)
        Alvo.Offset(0, -2).Value = Date          ' Registra a data (A = 0, E = 4)

        linha = Alvo.Row

        Range("C" & linha & ":E" & linha).Cells.Locked = True

        ' Protege
        ActiveSheet.Protect Contents:=True, DrawingObjects:=False
    End If
sair:
    ' religa a captura de eventos
    Application.EnableEvents = True
End Sub

Ou para travar manualmente cada linha:
Sub manual_linha()
    Dim linha As Long
    linha = 4
    ActiveSheet.Unprotect
    Range("C" & linha & ":E" & linha).Cells.Locked = True
    ActiveSheet.Protect Contents:=True, DrawingObjects:=False
End Sub

No exemplo, a linha 4 está sendo utilizada, portanto, o intervalo de C4:E4
Comment: Daniel, obrigado pela ajuda.

Fiz como disse, mas houve um problema. Ele acabou travando também outras linhas, como na imagem ele travou da E7 até a H7... não entendo porque ele trava outras células que eu não indiquei.

indiquei apenas dessas colunas Range("C" & linha & ":E" & linha).Cells.Locked = True

Sabe porque isso ocorre?
Comment: Estranho. Num teste que fiz não trava as outras
Comment: Ele não travou todas, só travou algumas que não estavam na seleção do vba. Pode me mandar o arquivo que você fez para eu ver se tem algum erro no meu?

Bloquear célula após preenchimento


How to load static files from view HTML in web2py?

Question: Given a view with layout, how can I load static files (CSS and JS, essentially) into the  from the view file?
layout.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>{{=response.title or request.application}}</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

        {{include 'web2py_ajax.html'}}

        {{include}}

myview.html
{{extend 'layout.html'}}
{{response.files.append(URL(r=request,c='static',f='myview.css'))}}

Some header

    some content

In the above example, the "myview.css" file is either ignored by web2py or stripped out by the browser.
So what is the best way to load page-specific files like this CSS file?  I'd rather not stuff all my static files into my layout.
Answer: In myview.html reverse the first two lines
{{response.files.append(URL(r=request,c='static',f='myview.css'))}}
{{extend 'layout.html'}}

Mind that 1.78.1 and 1.78.2 had a bug did not allow this to work. It was fixed in 1.78.3 on the same day. The response.file.append(...) can also be moved in the controller action that needs it. You are not supposed to put logic before extend but you define variables to be passed to the extended view.


Copying a set of records with constraints, with common ancestor

Question: I have a set of tables that's actually a stubby tree.  At the top, there's a Customer, and below that Invoices, and Invoice Detail records.  (In actuality, there's about two dozen of these tables all referring to the Customer but the principle should apply with just three tables.)
What I'd like to do is to copy the Customer and all of the records belonging to that Customer without having to enumerate every single field in every record.  Everything is foreign-key constrained to the thing above it, and most of the tables have auto-increment identity fields.
Below is a T-SQL script to set up a database.  Yes it's messy, but it's complete.
CREATE TABLE [dbo].[Customer](
    [custID] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED ( [custID] ASC)
 WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Invoice](
    [invoiceNum] [int] IDENTITY(1,1) NOT NULL,
    [custID] [int] NOT NULL,
    [Description] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Invoice] PRIMARY KEY CLUSTERED ( [invoiceNum] ASC )
 WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ) ON [PRIMARY]
GO
CREATE TABLE [dbo].[InvoiceDetail](
    [invoiceNum] [int] NOT NULL,
    [sequence] [smallint] NOT NULL,
    [description] [varchar](50) NOT NULL,
    [price] [decimal](10, 2) NOT NULL CONSTRAINT [DF_InvoiceDetail_price]  DEFAULT ((0.0)),
 CONSTRAINT [PK_InvoiceDetail] PRIMARY KEY CLUSTERED ( [invoiceNum] ASC, [sequence] ASC )
 WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Invoice]  WITH CHECK ADD  CONSTRAINT [FK_Invoice_Customer]
    FOREIGN KEY([custID])
    REFERENCES [dbo].[Customer] ([custID])
GO
ALTER TABLE [dbo].[Invoice] CHECK CONSTRAINT [FK_Invoice_Customer]
GO
ALTER TABLE [dbo].[InvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_InvoiceDetail_Invoice]
    FOREIGN KEY([invoiceNum])
    REFERENCES [dbo].[Invoice] ([invoiceNum])
GO
ALTER TABLE [dbo].[InvoiceDetail] CHECK CONSTRAINT [FK_InvoiceDetail_Invoice]

declare @id int;
declare @custid int;
insert into Customer values ('Bob');
set @custid = @@IDENTITY;
insert into Invoice values ( @custid, 'Little Purchase');
set @id = @@IDENTITY;
insert into InvoiceDetail values (@id, 1, 'Small Stuff', 1.98);
insert into InvoiceDetail values (@id, 2, 'More Small Stuff', 0.25);
insert into Invoice values ( @custid, 'Medium Purchase');
set @id = @@IDENTITY;
insert into InvoiceDetail values (@id, 1, 'Stuff', 11.95);
insert into InvoiceDetail values (@id, 2, 'More Stuff', 10.66);
insert into Customer values ('Sally');
set @custid = @@IDENTITY;
insert into Invoice values ( @custid, 'Big Purchase');
set @id = @@IDENTITY;
insert into InvoiceDetail values (@id, 1, 'BIG Stuff', 100.00);
insert into InvoiceDetail values (@id, 2, 'Larger Stuff', 99.95);

So what I want to do is make a copy of "Bob" in this database, and call it "Bob2" without all of the hassle of specifying each column for every table.  I could, but in the Real World that's a LOT of columns.
The other problem being that I'd have to write an explicit loop to get each of the invoices.  I need the identity from the previous Invoice insert in order to write the Invoice Detail.
I've got a working C# "copy" program, but I'd like to do this all in the database.  The naive implementation is a transact sql stored procedure with loops and cursors everywhere.
Is there a clever way of avoiding one (if not both) of these issues?
Answer: I had similar problem with much more tables involved. We can indeed avoid making cursor for each rows to be copied. The only cursor is for looping the list of the table names involved. We are also going to need dynamic SQL for this. The whole operation is extremely fast, compared to the traditional cursor loop solution.
The trick is to insert the relevant rows into the same tables; and then  update its FK column to its parent. How we can collect the mass @@identity is by making use of 'output' keyword during the insertion, and save them into a temporary table #refTrack. Later we join #refTrack with the tables involved for updating the their FKs.
We know that:

create table #refTrack
(
    tbl sysname,
    id int,
    refId int
)

insert InvoiceDetail (refId, invoiceNum, sequence, description, price)
output 'InvoiceDetail', inserted.id, inserted.refId into #refTrack
select invoiceNum, invoiceNum, sequence, description, price from InvoiceDetail
where custID = 808 -- denormalized original Bob^s custID

will populate temporary #refTrack table with a list of newly created auto running numbers. Our job is just to make this insert query as dynamic.
The only drawback of this method is that we need consistencies, on each table we must have:

Primary key of its own by the name of 'id'. In this case we need to rename: Customer.custID to become Customer.id; Invoice.invoiceNum to become Invoice.id; and a new column 'id int identity(1, 1) primary key' in InvoiceDetail.
A denormalized 'custID' column. For tables listed with 'depth' > 1, the table will require the current front end application to populate this new helper column. An 'insert trigger' will make our work a bit more complicated.
A column called 'refId', defined as: int null. This column is for making the relationship of rows belong to 'Bob2' as a copy of 'Bob'.

Steps taken:
A. List all table names into @tList table variable

declare @tList table
(
     tbl sysname primary key,
     fkTbl sysname,
     fkCol sysname,
     depth int
)
insert @tList select 'Customer', null, null, 0
insert @tList select 'Invoice', 'Customer', 'custID', 1
insert @tList select 'InvoiceDetail', 'Invoice', 'invoiceNum', 2

I'd love to go abstract as to just populating 'tbl' column during insertion above; and dynamically populate the rest of the columns by updating them with the result of recursive CTE of information_schema's views. However that could be beside the point. Let's assume we have a table with the list of table names involved, ordered by the way it should be populated.
B. Loop the @tList table in a cursor.

declare
    @depth int,
    @tbl sysname,
    @fkTbl sysname,
    @fkCol sysname,
    @exec nvarchar(max),
    @insCols nvarchar(max),
    @selCols nvarchar(max),
    @where nvarchar(max),
    @newId int,
    @mainTbl sysname,
    @custId int

select @custId = 808 -- original Bob^s custID to copy from

select @mainTbl = tbl from @tList where fkTbl is null

declare dbCursor cursor local forward_only read_only for
    select tbl, fkTbl, fkCol, depth from @tlist order by depth
open dbCursor
fetch next from dbCursor into @tbl, @fkTbl, @fkCol, @depth
while @@fetch_status = 0
begin
    set @where = case when @depth = 0 then 'Id' else 'custId' end + ' = ' +
        cast(@custId as nvarchar(20))
    set @insCols = dbo.FnGetColumns(@tbl)
    set @selCols = replace
    (
        @insCols,
        'refId',
        'Id'
    )
    set @exec = 'insert ' + @tbl + ' (' + @insCols + ') ' +
        'output ''' + @tbl + ''', inserted.id, inserted.refId into #refTrack ' +
        'select ' + @selCols + ' from ' + @tbl + ' where ' + @where

    print @exec
    exec(@exec)

    -- remap parent
    if isnull(@fkTbl, @mainTbl) != @mainTbl -- third level onwards
    begin
        set @exec = 'update ' + @tbl + ' set ' + @tbl + '.' + @fkCol + ' = rf.Id from ' +
            @tbl + ' join #refTrack as rf on ' + @tbl + '.' + @fkCol + ' = rf.refId and rf.tbl = ''' +
            @fkTbl + ''' where ' + @tbl + '.custId = ' + cast(@newId as nvarchar(20))

        print @exec
        exec(@exec)
    end

    if @depth = 0 select @newId = Id from #refTrack
    fetch next from dbCursor into @tbl, @fkTbl, @fkCol, @depth
end

close dbCursor
deallocate dbCursor

select * from @tList order by depth
select * from #refTrack

drop table #refTrack

C. The content of FnGetColumns():

create function FnGetColumns(@tableName sysname)
returns nvarchar(max)
as
begin
    declare @cols nvarchar(max)
    set @cols = ''
    select @cols = @cols + ', ' + column_name
        from information_schema.columns
        where table_name = @tableName
            and column_name <> 'id' -- non PK
    return substring(@cols, 3, len(@cols))
end

I am sure we can further improve these scripts to be far more dynamic. But for the sake of solving the problem, this would be the minimum requirement.
Cheers,
Ari.
Answer: "most of the tables have auto-increment identity fields"
There's part of the problem. Using IDENTITY as a PK makes these kind of operations both difficult and costly (from a computing standpoint). Even if you didn't use IDENTITY though, you're still going to need to generate new invoice numbers for the "new" customer, which means that you're going to need to either cycle through one at a time or come up with a set-based method of assigning new invoice numbers which can then be used to create the invoice detail rows.
I'm going to assume that you understand what you're getting into from a business perspective, but I still have to point out that you're also now creating data that isn't exactly "real". If you copy one of these customers, including all of their invoices and then you report on your sales for the year you're going to be double-counting sales.
With more information on the business problem that you're trying to solve, maybe another solution could be found.
Comment: There aren't really "Customers" and "Invoices".  It'd be improper to post actual schema in a public forum.  They do mimic a real database though.


Online Convex Optimization: meaning of different loss function each time $t$

Question: In the survey of Shai Shalev-Shwartz (see 1), the online convex optimization is presented as:

where one can see that the loss function is chosen. All proofs for regret bounds use (more or less) the loss difference $f_{t}(w_t) - f_{t+1}(w_t)$ and also $f_{t+1}(w_t) - f_{t+1}(w_{t+1})$.
Concretelly,

as part of the proof, the author stets:

I can understand that $f_t(w_t)$ denotes the 'chosen' loss function at time $t$, where the solution vector $w_t$ was given. Yet, what does $f_{t+1}(w_t)$ mean? how can the loss function be chosen one step ahead and use the previous solution vector to the optimization? how can I compute the loss differences $f_t(w_t) - f_t(w_{t+1})$?
Answer: What does $f_{t+1}(w_t)$ mean? It means $f_{t+1}$ is evaluated at the argument value $w_t$.
As an illustrative example, let $t = 1, f_1(x) = x^2, w_1 = 1, w_2 = 2$. Then $f_t(w_t) - f_t(w_{t+1}) = 1 - 4 = -3$.  At the time of the evaluation (at t+1), $f_t$ is still known, therefore it can be evaluated.
Anyhow, the point of the bounds is not that they would necessarily be computed during algorithm execution, but that they provide a guarantee as to progress, and therefore can facilitate such things as convergence proofs.


Can I multiply *into* limits?

Question: I learned a lot yesterday and it requires me to overhaul the way I think about derivatives.  So I have something worked out but it relies on the answer to this question.
EDIT: Basically I need a simple proof that says $b \cdot [\lim_{h \to a} g(h)] = \lim_{h \to a} [b\cdot g(h)]$
Comment: My view is that it is important to master individual examples before worrying about general rules.  I do not see how to assign a clear meaning to parts of the post, including at least the last two paragraphs.
Comment: For the edited problem, if the limit on the left exists, so does the limit on the right, and your expressions are equal. If $b\ne 0$, and the limit on the right exists, then so does the limit on the left, and the expressions are equal. These facts are very reasonable from the intuitive content of limit. But any proof must use $\epsilon$-$\delta$ methods. If you have uncertainties about details, I can write out a solution.
Answer: In the expression
$$\color{red}{h} \lim_{\color{green}{h} \to 0} \frac{a}{\color{green}{h}}$$
$\color{red}{h}$ and $\color{green}{h}$ are different variables. You could bring $\color{red}{h}$ inside the limit, but if you did, you can't cancel it with $\color{green}{h}$. This limit is either 0 (if $a=0$) or it doesn't exist.
In the expression
$$\color{red}{h} \lim_{\color{green}{h} \to 0} \frac{a}{\color{red}{h}}$$
you could bring $\color{red}{h}$ into the limit, but there isn't really any problem, because you already know
$$\lim_{\color{green}{h} \to 0} \frac{a}{\color{red}{h}} = \frac{a}{\color{red}{h}}$$
This expression, however, is nonsense:
$$\color{green}{h} \lim_{\color{green}{h} \to 0} \frac{a}{\color{green}{h}}$$
The variable $\color{green}{h}$ introduced in the limit expression only "exists" inside the limit expression. It's simply not allowed to appear outside of the limit expression on the left like that.
Of course, you usually don't have the colors to help distinguish variables.* If a variable $h$ already has meaning in your work, it is very confusing to introduce a new variable called $h$, e.g. by writing a limit $\lim_{h \to 0} f(h)$, because it's easy to forget which $h$ is which. Use a different letter instead -- e.g. the synonym $\lim_{k \to 0} f(k)$ -- or do something else to distinguish the two versions, such as color, case, font, decorations, et cetera. -- e.g. $\lim_{\mathbf{\hat{h}} \to 0} f(\mathbf{\hat{h}})$.
Comment: I like this answer.  There are some ideas here I can use.  For example, I can understand that the two h's are different, and the difference is the h inside the limit is undergoing a process.  That makes it different to an h on the outside.  I don't know how to express this formally but that's how I understand it.
Comment: Using this idea, I can say that $\lim_{h \to 0} \frac{h}{h}=1$, because if $f$ and $g$ are two functions and if $f=g$ then $\lim_{h \to 0} f = \lim_{h \to 0} g$. If $f(x)=\frac{h}{h}$ then $g(x)=1$.  I said that kind of backwards but hopefully you understand what I'm trying to say.
Comment: If you know any computer programming, it's helpful to think about for-loops. You can't reference the index variable outside of the loop; here $h$ is the index variable. The analogy can be very helpful when you have multiple variables and limits floating around.
Comment: @Korgan: What you write is not really correct: $f(x)=\frac{h}{h}$ should be $f(h)$; and if you take $f(h)=\frac{h}{h}$, and $g(h)=1$, then $f$ and $g$ are not equal: $f$ is undefined at $h=0$, whereas $g$ *is* defined (remember: two functions are equal if and only if they have the exact same domain, and at every point of the domain they have the same value). Instead, you are using the following theorem about limits: "if $f(x)$ and $g(x)$ are two functions such that $f(c)=g(c)$ for every $c$ in a neighborhood of $a$, except perhaps at $x=a$, then $\lim_{x\to a}f(x)=\lim_{x\to a}g(x)$".
Answer:
Any algebraic manipulation going on inside the brackets of the limit is fine

Mathematically, the content of this statement is that if $f(h) = g(h)$ then $\lim_{h \to a} f(h) = \lim_{h \to a} g(h)$.

can I multiply what is inside the brackets with something outside the brackets

It is a theorem that $k \lim_{h \to a} f(h) = \lim_{h \to a} [k f(h)]$. In fact, this is a simple consequence of a more general theorem:
$$[\lim_{h \to a} f(h)] \cdot [\lim_{h \to a} g(h)] = \lim_{h \to a} [f(h)g(h)].$$
See here for a proof of a very closely related theorem.. whose proof can be very easily adapted to prove this.
Comment: I guess that the theory you have mentioned is valid if the limit for both f and g exists. So limit ((x)(1/x)) as x approaches infinity can't be distributed because the limit for (x) as x approaches infinity is not defined.
Comment: @EmmadKareem, that's right.
Comment: @QED.  Thanks, I will need to spend time on that proof as I'm not very familiar with set theory notation.  Proving $[\lim_{h \to a} f(h)] \cdot [\lim_{h \to a} g(h)] = \lim_{h \to a} [f(h)g(h)]$ is exactly what I need.
Comment: @KorganRivera, note there is no mention or use of sets in any of this.
Comment: $\forall \varepsilon_1 > 0, \exists \delta_1 > 0, \forall x, 0 < |x - a| < \delta_1 \implies |f(x) - f(a)| < \varepsilon_1$ ...that's what I'm talking about.
Answer: If $A$ is equal to $B$ then $B$ is equal to $A$.
It folows that if
$$
\lim_{h\to a} (b g(h)) = b \lim_{h\to a} g(h)
$$
then
$$
b\lim_{h\to a} g(h) = \lim_{h\to a} (b g(h)).
$$

Can I multiply *into* limits?


Altiris Deployment Console and PXE booting over multiple vlans

Question: I am rebuilding a 2008 server with sql 2008 and altiris Deployment console 6.9 sp2. It is working now however I am trying to get the clients to be able to pxe boot and load an image from altiris no matter which vlan they are on.  We have about 8 vlans each with its own DHCP scope and using hp procurve switches for the acls and the core switch does all the layer 3 work. Has anybody acheived this?
Answer: I don't have any experience with Altiris, but normally you would configure the Layer 3 device to forward BOOTP/DHCP/PXE requests to an IP address (in this case you DHCP server and deployment server).
On a Cisco switch this is configured using IP HELPER ADDRESS.
Comment: Yep thanks this worked, the command is the same for hp procurve switches.  The only problem I face is that some of the other vlans are already using the ip helper command on them and they are for a different dhcp server so I am going to integrate both answers have two nics on 2 subnets that should cover all angles. Thanks guys
Answer: I've not done this, so this is just my musings.
Give the 2008 server multiple static ip addresses and assign mutiple VLANS to the port that it plugs into.
Make sure the 2008 server doesn't try to bridge any traffic.
Comment: To add to this, If you add option 60 to your DHCP server wih PXEClient as the value.
You can do this by the netsh command line.
Then on all the vlans set the helper address as listed above and done.


Ratio of difference and sum of i.i.d. exponential random variables

Question: I just noticed that for two i.i.d. exponential random variables $X$ and $Y$, the combination $\frac{X-Y}{X+Y}$ appears to be distributed uniformly on $[-1, 1]$ (ignoring the case $X=0, Y=0$ for the moment):
<code>x <- rexp(1000000)
y <- rexp(1000000)
hist((x-y)/(x+y))
</code>

Is this a known fact? I was unable to find a reference to this, and would appreciate one if it does exist. Furthermore, I'd be interested if there are any known results about the dependent case.
Comment: I'm sure it is known, note that it is equal to $1 - 2Y/(X+Y)$ and that $Y/(X+Y)$ is known to be Uniform on (0,1) from the generic relationship between and Gamma and Beta distributions.
Comment: Perfect justification from @guy. Note that the case $X=Y=0$ is irrelevant, being of measure zero.
Comment: Yes, good catch, @guy! I would accept this as the answer if you could post it as such (to increase your rep score ;-) )
Answer: We can assume $X, Y$ are iid $\mathcal{E}(1)$, as the scale parametyer is irrelevant for the distribution of the ratio. Using theshale-scale parametrization of the Gamma distribution, then, this is the same as the gamma distribution $\mathcal{Gamma}(1,1)$. The sum $X+y$ is then $\mathcal{Gamma}(2,1)$ and the ratio $\frac{X}{X+Y}$ is $\mathcal{Beta}(1,1)$, that is, uniform.
Noting that
$$ \frac{X-Y}{X+Y}=\frac{X+Y-2Y}{X+Y}=1-2\frac{Y}{X+Y}$$
so is 1-twice a random variable having the standard uniform distribution. So is uniform on $(-1,1)$.
(all standard results used contained in above wiki link).


RFC2822 non compliance, something about Date or From in PHP header?

Question: I'm trying to have a form submit to an email and it's ultimately ending up at a gmail address.  However, I'm getting return errors saying:

Our_system_has_detected_that_this_message_is/550-5.7.1_not_RFC_2822_compliant._To_reduce_the_amount_of_spam_sent_to_Gmail,/550-5.7.1_this_message_has_been_blocked._Please_review/550_5.7.1_RFC_2822_specifications_for_more_information.w10si875474obo.147-_gsmtp/

Code below, am I doing something wrong or is there bad code/syntax I'm missing somewhere?:
<?php

    if($_POST) {

        if($_POST["token"]==true){

            $email = $_POST['email'];

            $from_name = 'Whoever';
            $from = 'email@example.com';

            $to = 'firstname.lastname@example.com';
            $subject = 'Connect Form';
            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
            $headers = "Date: ". date("r") ."\r\n". "From: ".$from .  "\r\nFrom: ".$from_name." <".$from.">\r\n";
            $headers .= "MIME-Version: 1.0\n" .
                "Content-Type: multipart/mixed;\n" .
                " boundary=\"{$mime_boundary}\"";
            $message_top = "This is a multi-part message in MIME format.\n" .
                "--{$mime_boundary}\n" .
                "Content-Type:text/html; charset=\"iso-8859-1\"\n" .
                "Content-Transfer-Encoding: 7bit\n";

                if(sizeof($_POST['contact_via'])>0)
                    $contact_via=implode(", ", $_POST['contact_via']);
                else
                    $contact_via="";

                $email_message = "\n".'

Contact Name : 	'.$_POST['contact_name'].'

';

            $email_message = stripslashes($email_message);
            $email_message = str_replace("\n","\n",$email_message);
            $email_message = $message_top . $email_message;

            mail($to, $subject, $email_message, $headers);
            echo '';
          exit;

        }else{
            echo '';
            exit;
        }

    }
?>

Comment: Did you read RFC 2822?
Comment: Not the whole thing, just what's pertinent; in this case the date and header bits
Comment: http://webapps.stackexchange.com/questions/42771/emails-sent-to-gmail-domain-suddenly-not-rfc-2822-compliant-possible-to-bypass
Answer: Using mail() directly is a recipe for frustration. There are lots of things to get wrong and you have to hand-code stuff like attachments, HTML e-mail support, etc.
Using a sane wrapper for mailing like SwiftMailer allows you to worry a lot less about getting the esoteric details of mail addressed and focus on more useful things.
In this particular case, it appears you're setting duplicate From: headers (and having a hard time deciding between \r\n and \n).

$headers = "Date: ".date("r")."\r\n" . "From: ".$from .  "\nFrom: ".$from_name." <".$from.">\n";
Comment: The duplicate From: has been addressed, as well as the uniformity of \r\n.  However, still getting the compliance error from Gmail.
Comment: @Jordan Again, you're likely to get much better results using SwiftMailer. It's an easy transition and your future mailing life will be much happier.
Answer: The RFC2822 dictates that Date: and From: are mandatory header fields on the email.
You have this, but incorrectly.
Try this header line:
$headers = "Date: ". date("r") ."\r\n". "From: $from_name <$from>\r\n";

Comment: I have corrected the header.  Additionally, i have uniformed everything with \r\n.

I successfully am able to send to other accounts (like our Company's on the Exchange Server), but am still getting the compliance error when trying to send to Gmail.
Comment: @Jordan did you ever solve this problem?


fragment container not keeping the addBackStack android

Question: I have implemented a fragment container to change fragments inside my tabs. (see: android, dynamically change a fragment inside a tab)
I'm using a fragment tab host, and a framelayout (that its on a separate activity) to load my fragments into it. I have a button in my fragment that is changing into another Fragment. I've implemented that method, and I resolve the overlapping fragment problem. the thing is, that now, every time I press the back button my app exits (no matter where my fragment is).
I have checked that I a have the tx.addToBackStack(curFrag.getClass().getSimpleName()) even tried with tx.addBackStack(null) before the commits, but still doesnt do anything. Could anyone help me? thank you.
Edited:
I'm already adding a tag to my tabhost.
this is my FragmentTabMenu.java
setContentView(R.layout.activity_fragment_tab_menu);
        Resources res = getResources();

        mtabHost = (FragmentTabHost) findViewById(android.R.id.tabhost); //id from the activity that hosts the tabwidget
           mtabHost.setup(this, getSupportFragmentManager(), R.id.FrameLayout1); //id from the other activity that only hosts the framelayout

           //passing the class that my container will execute on the onResume method

           Bundle args1=new Bundle();
           args1.putSerializable(PARAM_CONTENT_FRAGMENT,RegistoUtilizador.class);

           //creating the tab
           mtabHost.addTab(
                    mtabHost.newTabSpec("RegistoUti").setIndicator("Tab 1",
                            res.getDrawable(R.drawable.tab_icon_rui)),
                    ContentorFragRegistoUti.class, args1);

And this is my container class
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

   return inflater.inflate(R.layout.frag_container, null);
}

public void replaceContent(Class<? extends Fragment> clz, Bundle args) {
    FragmentTransaction tx = getChildFragmentManager().beginTransaction();

    tx.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

    // save
    Fragment curFrag = getChildFragmentManager().findFragmentById(R.id.FrameLayout1);
    tx.addToBackStack(curFrag.getClass().getSimpleName());

    // change
    try {

        Fragment newFragment = clz.newInstance();
        newFragment.setArguments(args);
        tx.replace(R.id.FrameLayout1, newFragment, clz.getClass().getSimpleName());

        tx.commit();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

@Override
public void onResume() {
    super.onResume();
    Fragment f = getChildFragmentManager().findFragmentById(R.id.FrameLayout1);
    if (f == null) {
        Class<? extends Fragment> claz = (Class<? extends Fragment>) getArguments().getSerializable(
                PARAM_CONTENT_FRAGMENT);

      FragmentTransaction tx = getChildFragmentManager().beginTransaction();
        try {
            f = claz.newInstance();
            f.setTargetFragment(this, 0);
            tx.add(R.id.FrameLayout1, f);
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
}

Maybe i missunderstood what Framelayout id, i should be calling on my methods?
Answer: Let me give you the hint what to do :
Suppose 3 tabs in Whole App :
One Main Activity = TabActivity
Add three Tabs in this Activity
like :
Tab 1 = FragmentActivity
Tab 2 = FragmentActivity
Tab 3 = FragmentActivity
Tab 1 -> different Fragments
Tab 2 -> different Fragments
Tab 3 -> different Fragments
and So On :
save your preference at each Fragment
Then when On second launch of app you know which tab was selected before so trigger the intent for that FragmentActivity , now you are in that Tab then trigger the respected fragment in that activity..
Note : Seriously if you are thinking to recover the old backstack then its not gonna happen because the OS it self handle the backstack for FragmentActivity..
Comment: thank you for your answer, ive edited my post to make it more clear to understand my problem. (i hope) :)
Comment: i narrowed my problem to the following: it seems the backstack doesn't take into account any nested Fragments, only Fragments added to the FragmentActivity. Therefor i need a workarround. I think its better if i save the state of my entire fragmenttabhost and restoring it when the app iniciate onCreate if instance available. Any ideias or suggestions? :)
Comment: Yes ! can you please clearify what you really want to develop so i can give you any suggestion..
Comment: I want to keep the user's selected fragment everytime the back button is pressed (since it sends my app to the background destroying the fragments and the activity).When returning to the app, it loads the last fragment used by the user. my problem is also how to send that fragment to the my fragmenttabhost in order for it to load the proper fragment. i can save the name of the fragment where the user last pressed the back button, but how can i inicialise my tabhost with it!? Suppose the user was in the 3 tab, second fragment. I need to him to return to that postion when app launches. Thanks
Comment: ok good explainantion got some thing to share:
Lets start from the begin :
are you able to save preference at the back button pressed before app i closed ??
Comment: actually i only have 1 fragmentActivity. I have created one container for each tab (extended from fragment)  that in turn will replace the fragments i want in(being those its childrenfragment). i can get the name of the container and the fragment that is showing when i press the back button (im using  onBackPressed() method). since i can only save strings in shared preferences (cant save bundles or argss) i retrieve my container and my fragment string to store in it. now how do make for a fragmenttabhost to load that container and fragment. im using the code showned, but can update it. thanks
Comment: Regarding to the backstack i decided to implement exit buttons (that will replace the nested fragments by the previous fragment) seemed a better solution, if i manage to save the state of my app. :)
Answer: ok, first part is done. im calling the container and loading it using: mtabHost.setCurrentTabByTag("Activecontainer");
Activecontainer is my string that i get from sharedpreferences is has been tagged with the fragment name.
Now i only need to set the fragment. Any suggestion?
thank you.


How to get the latest released tag name in github actions?

Question: I want to try to implement that whenever I make a new release in github, actions will automatically publish the corresponding release to pypi for me, but this requires me to get the latest release number.
I've tracked some of stackoverflow's related question, but embarrassingly none of them work for me. For example in #16241
My error message is:
Set output
Run echo ::set-output name=tag::${GITHUB_REF#refs/*/}
::set-output
name=tag::

Test
Run echo $RELEASE_VERSION
Write-Output: D:\a\_temp\7fa75053-482a-4be6-bec1-6b0f60cdf855.ps1:3
Line |
   3 |  echo
     |  ~~~~
     | Cannot process command because of one or more missing mandatory parameters: InputObject.

Error: Process completed with exit code 1.

I'm running on a windows vm, is there something wrong with my code? Thanks.
Answer: Here is the answer on How to get Tag Name in GitHub Actions
on:
  push:
    tags:
      - '*'
jobs:
  github-example-tags:
    steps:
     - name: GitHub Tag Name example
       run: |
         echo "Tag name from GITHUB_REF_NAME: $GITHUB_REF_NAME"
         echo "Tag name from github.ref_name: ${{  github.ref_name }}"

See
https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables
Answer: You can get this by setting your publish workflow to run on the following event:
on:
  push:
    # Sequence of patterns matched against refs/tags
    tags:
      - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10

Then you'll be able to get the tag itself with the github.ref context in your job.


Fire scheduled lambda function after cloudformation stack creation

Question: This schedules my cloudformation lambda to run once per day but I'd like it to fire upon creation one time.
Transform: AWS::Serverless-2016-10-31
...
EventListFunction:
  Type: 'AWS::Serverless::Function'
  Properties:
    ...
    Events:
      Schedule1:
        Type: Schedule
        Properties:
          Schedule: rate(1 day)

Answer: Here are a few options:

Manually create an SNS Topic. Add an AWS::SNS::Subscription to your stack with the lambda function as the Endpoint and the SNS topic as the TopicArn. On stack creation/update, configure Stack Event Notifications to be sent to this SNS topic.
Add a Custom Resource referencing the newly-created function, which will call the function on creation. In order for the Custom Resource creation to complete and not cause a rollback in your stack, you will need to adapt your Lambda function to support the CloudFormation request/response format (see Custom Resource Reference). Also note that the function will also be called again on stack deletion, and this will also need to be handled.
Add the Lambda function to the Stack Outputs, then write a simple script that performs both the stack update and invokes the Lambda function after completion.
Answer: Look at  AWS:: CloudFormation::CustomResource to call it


Pegar ID em sequencia baseado no último inserido

Question: Estou com um problema que está me dando problemas.
Tenho o seguinte código:
$sql = $pdo->prepare ("SELECT cpf,idUser FROM `tblContacts` where cpf = '".$cpf."' limit 1");
$sql->execute();
$row = $sql->fetch();

if($row != null)
  {
    //  echo "SQL 01 ". $sql;
    $randomicId = $row->idUser;
  }
  else
  {
    switch ($horaAtual) {
      case ($horaAtual > $hora1 && $horaAtual < $hora2): $periodo = 'manha'; break;
      case ($horaAtual > $hora2 && $horaAtual < $hora3): $periodo = 'tarde'; break;
      default: $periodo =  'manha';
    }

    $sql2 = "SELECT * FROM `tblUser` where grupo = 'vendas' and ativo = 1 and periodo = '".$periodo."' ORDER BY RAND() LIMIT 1";
    $stmt = $pdo->query($sql2);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if($row['idUser'] != null)
    {
      //echo "SQL 02 ". $sql2;
      $randomicId = $row['idUser'];
    }
  }

O código tem 2 partes:
Quando um cliente faz um cadastro, eu pego o ID de um usuário e atribuo a este cadastro:
id   nome_cliente  ......  idUsuario

1    fulano                   2

Se o cliente fulano fizer um outro cadastro futuramente, o sistema verifica se tem algum cadastro igual no banco, se tiver, ele usuário o mesmo ID do usuário.
Se não tem nenhum cadastro no banco, o sistema passar por um processo de verificar para pegar o ID de algum usuário:
O sistema pega a hora atual:

se for antes das 15h, ele fará um consulta no banco e selecionará os usuários do período da manhã.
se for depois das 15h, ele fará um consulta no banco e selecionará os usuários do período da tarde.

Tabela usuários:
id   nome      periodo  ...
1    siclano    tarde

O sistema, após verificar o período, pega um ID aleatório com o RAND() limit 1 .
Assim, o código está funcionando.
Mas, pegando o ID aleatório, está acontecendo o seguinte problema: está ainda mais cadastros para 1 usuário do que para outro.
Então, eu queria, invés de pegar aleatório, atribuir um ID em sequencia.
Verifica o horário, a insere o ID em sequencia (obs: Os ID variam).
IdUsuario : 2,34,45

cadastro 1  - idUsuario : 2
cadastro 2  - idUsuario : 34
cadastro 3  - idUsuario : 45
cadastro 4  - idUsuario : 2
....

Alguém pode ajudar a fazer dessa forma?
Answer: Pra fazer esse controle você precisa ter um campo onde controle qual foi o último usuário utilizado. Sugiro fazer uma normalização no teu banco, alterando o campo periodo passando os dados pra uma tabela e armazenando apenas o ID desses registros na tabela de usuários, e armazene nessa tabela qual foi o último usuário utilizado, assim terás uma fila para cada turno. Segue um exemplo.
Modelagem básica:
Turnos
CREATE TABLE `turnos`(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  nome VARCHAR(45),
  lastfunc INT
);

INSERT INTO turnos (nome) VALUES ('manhã'), ('tarde');

 _________________________
| id | nome  | lastfunc   |
|____|_______|____________|
| 1  | manhã |            |
|____|_______|____________|
| 2  | tarde |            |
|____|_______|____________|
2 registros

A coluna lastfunc será usada para controlar a sequência de usuários/funcionarios.
Funcionários
CREATE TABLE `funcionarios`(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  nome VARCHAR(45),
  turno_id INT NOT NULL,
  FOREIGN KEY (turno_id) REFERENCES turnos(id)
);

INSERT INTO funcionarios (nome, turno_id)  VALUES
('João', 1), ('Maria', 1), ('José', 2), ('Joana', 2);

 __________________________
| id | nome     | turno_id |
|____|__________|__________|
| 1  | João     | 1        |  ---
|____|__________|__________|    |-- Turno da Manhã
| 2  | Maria    | 1        |  ---
|____|__________|__________|
| 3  | José     | 2        |  ---
|____|__________|__________|    |-- Turno da Tarde
| 4  | Joana    | 2        |  ---
|____|__________|__________|
4 registros

Clientes
CREATE TABLE `clientes`(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  nome VARCHAR(45),
  funcionario_id INT,
  FOREIGN KEY (funcionario_id) REFERENCES funcionarios(id)
);

 ____________________________
| id | nome | funcionario_id |
|____|______|________________|
0 registro

Código e Lógica.
A lógica consiste em que cada vez que cadastrarmos um cliente, buscamos um funcionário para associa-lo ao seu cadastro, a regra de
busca do funcionário é a seguinte:

Se cliente cadastrado busca existente no cadastro
Senão Se existe próximo da fila busca com base no horário
Se não existe próximo, busca o primeiro da fila

Com base nessa regra, construi o seguinte código: (Detalhamento nos comentários)
// Altere CPF e Variável $turno para testes
$novoCliente = Array(
   'cpf' => '66666666668',
   'nome' => 'Fulano Pereira Pinto',
   'funcionario_id' => null
);

$turno = 2; // 1 - Manhã | 2 - Tarde

// Define variável para armazenar funcionário
$funcId = null;

// Consulta se o cliente tem cadastro com base no CPF e pega o funcionário associado
$stmt = $con->prepare("SELECT funcionario_id FROM clientes WHERE cpf = :cpf");
// Executa a query
$stmt->execute( Array(':cpf' => $novoCliente['cpf']) );

// Verifica se teve resultado, se sim armazena ID do funcionário
if ($stmt->rowCount() > 0)
   $funcId = $stmt->fetch(PDO::FETCH_ASSOC)['funcionario_id'];

// Se não tem cadastro
if (is_null($funcId)){

   // Pega o próximo funcionario da sequencia com base no turno
   // A query busca o funcionario que tem um ID MAIOR do que o ID que estiver
   // na tabela de turno no campo `lastfunc`, ou seja o próximo
   $sql  = "SELECT fu.id as id
            FROM funcionarios as fu
               INNER JOIN turnos as tu ON tu.id = fu.turno_id
            WHERE
               fu.id > tu.lastfunc AND
               fu.turno_id = :turno
            ORDER BY fu.id ASC LIMIT 1";
   $stmt = $con->prepare($sql);
   $stmt->execute( [':turno' => $turno] ); // Executa a query

   // Se teve resultado armazena o ID do funcionário
   if ($stmt->rowCount() > 0)
      $funcId = $stmt->fetch(PDO::FETCH_ASSOC)['id'];
}

// Se a regra anterior não teve resultado é porque
// chegou no último da fila e não tem próximo
// ou porque não tem nenhum id no campo `lastfunc` da tabela `turno`
// Então executa a regra seguinte
if (is_null($funcId)){

   // Seleciona o primeiro funcionario
   $sql  = "SELECT id FROM funcionarios ORDER BY id ASC LIMIT 1";
   $stmt = $con->prepare($sql);
   $stmt->execute(); // Executa a query

   // Se teve resultado armazena o ID do funcionário
   if ($stmt->rowCount() > 0)
      $funcId = $stmt->fetch(PDO::FETCH_ASSOC)['id'];

  // Se não houver funcionar é porque não existe funcionário cadastrado
}

if (is_null($funcId)){
   // Se não pegou nenhum funcionário interrompe a execução do código
   exit('Erro: Nenhum funcionário pode ser associado ao cliente. Cadastro interrompido.');
} else {
   // Se encontrou algum funcionário atualiza os dados do cliente
   $novoCliente['funcionario_id'] = $funcId;
}

// Insere o funcionário no banco com os dados
$stmt = $con->prepare("INSERT INTO clientes (cpf, nome, funcionario_id) VALUES (:cpf, :nome, :funcionario)");
// Executa a query
$res = $stmt->execute(
   Array(
      ':cpf' => $novoCliente['cpf'],
      ':nome' => $novoCliente['nome'],
      ':funcionario' => $novoCliente['funcionario_id']
   )
);

if ($res){
   // Essa parte é muito IMPORTANTE
   // Tens que armazenar o ID do funcionário utilizado no turno dele,
   // para que a fila ande, pois é com base nesse campo que verificamos a
   // posição da fila e então pegamos o próximo.
   $stmt = $con->prepare("UPDATE turnos SET lastfunc = :lfunc WHERE id = :turno");
   $res = $stmt->execute(
      Array(
         ':lfunc' => $funcId,
         ':turno' => $turno
      )
   );
}

echo $res ? 'Sucesso' : 'Erro';

Resultado

Obs.: O primeiro registro saiu sem id de funcionário porque eu esqueci de atualizar a variável $novoCliente['funcionario_id'] antes do INSERT do cliente.
Comment: Boa tarde KaduAmaral , muito obrigado pela resposta , nao sabia como poderia fazer. Quanto ao código , se possivel , poderia comenta-lo ? Pelo menos a parte MySql , por que nao entendo muito ainda. Do mais, saindo do serviço ja testo o código. Grato
Comment: Opa @HenriqueFelix, eu to no trampo agora também, assim que chegar em casa eu tiro um tempo pra detalhar mais a resposta. ;)
Comment: Comentado @HenriqueFelix
Comment: Boa tarde @KaduAmaral , deu certinho,muito obrigado !


Why is Non-local means non parametric?

Question: I am working on NL means for denoising and other segmentation based results. I am confused as to why it is called non parametric. It does have parameters which are definite with regards to patch size, window size and few other factors but the parameters are finite and remain the same. Why exactly is it called non-parametric?
Comment: Maybe they mean that it does not make assumptions about any specific parametric statistical distribution. I.e. they are talking about the assumptions of the nature of the noise and not the nature of the algorithm.
Answer: NL means is called non-parametric in the sense that it does not estimate any parameter of an assumed model for an input image.
More precisely,  the term - non-parametric comes from the inherent nature of the NL means which is non-parametric regression on the input image.
The patch-size, window-size, etc. that you are thinking of as parameters are somehow optimally guessed through a rigorous study of the nature of an ensemble of a particular type of images (e.g. for natural images, an optimal value of the patch-size is $7\times7$). These factors are not estimated from or for a particular input image.
References:

Buades, A., B. Coll, and J-M. Morel. "A non-local algorithm for image denoising." 2005 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'05). Vol. 2. IEEE, 2005.
Milanfar, Peyman. "A tour of modern image filtering: New insights and methods, both practical and theoretical." IEEE Signal Processing Magazine 30.1 (2013): 106-128.
Haque, S. M., G. P. Pai, and V. M. Govindu. "Symmetric smoothing filters from global consistency constraints." IEEE Transactions on Image Processing 24.5 (2015): 1536-1548.

Why is Non-local means non parametric?


Unique Complete Reducibility of Finite Groups

Question: Maschke's Theorem states that every complex representation $(\rho,V)$ of a finite group $G$ can be written as a direct sum of irreducible representations that form subsets of V, such that $V = V_1\oplus V_2 \oplus...\oplus V_N$, where $V_i$ are irreducible representations of $G$. This seems like a silly question, but I would like to check - do the irreducible representations of$G$ direct-summed over have to be sub-representations of $G$ in V under the map $\rho$ as well, or could some of them be sub-representations under a different map? Is this "decomposition" of V into a direct sum of irreducible representations unique? If so, how should I prove this fact? Does this "decomposition" of V include all irreducible representations in V under the map $\rho$?
Comment: I don't understand your terminology, and I am not sure what you are asking. I have never head of a *sub-representation*. A representation (such as $\rho$) is a homomorphism. $V$ is usually called a module, and the $V_i$ are submodules. But what exactly do you mean by "a subrepresentation of $G$ in $V$ under the map $\rho$"?
Answer: I'll assume that you are working over $\mathbb{C}$.
First, given any representation, it is not true that every irreducible representation is a direct summand.  Consider a group with $2$ irreducible representations, and then take one of them.
Second, the decomposition of any representation into irreducible components is unique, up to order, and isomorphism (see Derek's comment below).  This can be proved using Schur's lemma.
Your last question is sort of similar to your first, in that not all irreducible representations are sub-representations of any representation.  There is a special representation though, called the regular representation (G acting on itself by left multiplication) which does have every irreducible representation in its decomposition.  What's more, the number of times each irreducible representation appears is equal to its dimension.
Comment: The submodules $V_i$ in a decomposition are unique up to isomorphism, but they are not necessarily unique in an absolute sense. For example, if $G$ is the trivial group and $V$ has dimension two, then $V = V_1 \oplus V_2$ with the $V_i$ of dimension one, but there are infinitely many different choices of $V_1$ and $V_2$.
Comment: Thank you for your answer. I'm sorry I did not phrase my first question well. I meant whether the theorem only allowed you to "decompose" V into sub-representations formed using the map $\rho$, or whether it also allowed you to include some irreducible sub-representations formed using a different map, $\pi$, as summands as well.


Geometric interpretation of the Kronecker product?

Question: Is there any geometric interpretation of the Kronecker product of two $2\times 2$ matrices?
Comment: Related: http://math.stackexchange.com/questions/18881/motivation-for-tensor-product Also, there is a nice quantum mechanical interpretation in terms of a system of two qubits.
Answer: It pays to notice that the Kronecker product is really the tensor product acting on operators: if $f: A \to B$ and $g: X \to Y$ are linear mappings, then $f \otimes g: A \otimes X \to B \otimes Y$ is given by the Kronecker product in any bases of the form $a_i \otimes x_j$, $b_k \otimes y_l$, where $\{x_i\}$ is the basis of $X$ etc.
Now consider a pure vector $a \otimes x \in A \otimes X$. By definition we have $(f \otimes g)(a \otimes x) = f(a) \otimes g(x)$. E.g. if $B = Y$ and $g = 1$, we have $(f \otimes 1)(a \otimes x) = f(a) \otimes x$, so the "$X$ part" is untouched.
Thus, at least when both $f$ and $g$ are endomorphisms you can picture $f \otimes g = (f \otimes 1) \circ (1 \otimes g) = (1 \otimes g) \circ (f \otimes 1)$ as acting independently on factors of its domain by $f$ and $g$ respectively. This is obviously a corollary of $(f \otimes g)(a \otimes x) = f(a) \otimes g(x)$, which remains true in general.


Can the home team win an extra-inning baseball game by more than 1 run?

Question: In baseball, I'm wondering how home teams are awarded winning runs. If the visiting team in, say, Inning 10, plates 5 runs, then the home team has the bottom of that inning to match or exceed this number.
But what if this scenario occurs: game is tied in the 10th with the home team up to bat. 1 runner is on base, and the batter launches a home run over the fence. The game is clearly over via a "walk-off" at this point, but since the home team doesn't "need" 2 runs to win (remember, it's tied), are they only awarded the 1 run from the on-base runner? Or are they given a 2-run win? If it's the former, is the batter then only awarded a single RBI for his stats, thus "robbing" him of the extra RBI (in this case, himself)?
TL;DR: can the home team in an extra-inning baseball game ever win said game by more than 1 run?
Answer: According to Baseball Almanac prior to 1920 this was not possible.  In fact, if a runner was on base, the batter would not be given credit for a home run.
However, this is now explicitly allowed in the rules.
While 7.01(g)(3) states that

... the game ends immediately when the winning run is scored.

it also lists the exception for home runs:

EXCEPTION: If the last batter in a game hits a home run out of the
  playing field, the batter-runner and all runners on base are permitted
  to score...

So with runners on base, a home team can win in the bottom of the ninth or later by up to 4 runs.
Answer: Yes, the home team certainly can win by more than one run.
For an example, see Royals vs Tigers on 2019-05-05: the score was tied at 2 after nine innings, the Royals didn't score in the top of the tenth, but then in the bottom of the 9th Brandon Dixon hit a three-run home to win the game 5-2.


Android - Trying to sanitize user input on a preference

Question: I am trying to sanitize some user input on my app that will be sent server side. Based on the server settings, the data entered by the user may be used when creating or accessing files and folders. Obviously, sanitation will be also handled on the server but I will not and the app will not be able to control this due to the nature of the app. Therefore I feel it is my responsibility to have end to end sanitation where I or my app have control.
The preference I am trying to sanitize is for a photo album name that will be passed to the server.
According to the Log.d output this is working correctly. However, when I click the preference field to edit it, it shows the unsanitized input and when the preference is passed to the server it is also showing the unsanitized input.
FileUtil.sanitize(stringValue) is a simple method that trims leading and trailing spaces and removes ../ and ..\ from the string, for now atleast. I know there are others that I need to watch, just not 100% what they are yet.
So, the obvious question is, what am I missing? Is there an event that fires after this is complete that overwrites the changes that I am making here? I have a feeling that something is overwriting my changes because when I get the value immediately after the change, it shows the correct, sanitized data.
    /**
     * A preference value change listener that updates the preference's summary
     * to reflect its new value.
     */
    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
        String stringValue = value.toString();

        if (preference instanceof ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list.
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);

            // Set the summary to reflect the new value.
            preference.setSummary(
                index >= 0
                    ? listPreference.getEntries()[index]
                    : null);

        } else if (preference.getKey().equals("text_default_album")) {
            Log.d(TAG, "default pref: "+preference.getKey()+" value: "+stringValue);
            stringValue = FileUtil.sanitize(stringValue);
            Log.d(TAG, "default pref: "+preference.getKey()+" value: "+stringValue);
            preference.setSummary(stringValue);

            SharedPreferences prefs = preference.getSharedPreferences();
            String def = prefs.getString("text_default_album", "");
            Boolean updated = prefs.edit().putString("text_default_album", stringValue).commit();
            String def2 = prefs.getString("text_default_album", "");
            Log.d(TAG, "def: "+def);
            Log.d(TAG, "def2: "+def2);
            Log.d(TAG, "updated: "+updated);
        } else {
            // For all other preferences, set the summary to the value's
            // simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
        }
    };

Comment: In the `else if` branch, try using `preference.getSharedPreferences()` instead of `getSharedPreferences(Context)`.
Comment: so this instead: `SharedPreferences prefs = preference.getSharedPreferences();` ?
Comment: I've made the change, didn't make a difference to the behavior I'm experiencing but it sure looks better.
Answer: I've resolved my issue by extending the EditTextPrefence class and overriding setText and getText
this is based on the answer I found here
package com.example.overrides;

import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;

public class SanitizedEditTextPreference extends EditTextPreference {
    public SanitizedEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SanitizedEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SanitizedEditTextPreference(Context context) {
        super(context);
    }

    @Override
    public String getText() {
        String value = super.getText();
        return StringUtil.sanitize(value);
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        super.setText(restoreValue ? getPersistedString(null) : (String) defaultValue);
    }

    @Override
    public void setText(String text) {
        if (StringUtil.isStringBlank(text)) {
            super.setText(null);
            return;
        }
        super.setText(StringUtil.sanitize(text));
    }
}

I simplified my previous code to:
/**
 * A preference value change listener that updates the preference's summary
 * to reflect its new value.
 */
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
    String stringValue = value.toString();

    if (preference instanceof ListPreference) {
        // For list preferences, look up the correct display value in
        // the preference's 'entries' list.
        ListPreference listPreference = (ListPreference) preference;
        int index = listPreference.findIndexOfValue(stringValue);

        // Set the summary to reflect the new value.
        preference.setSummary(
            index >= 0
                ? listPreference.getEntries()[index]
                : null);

    } else if (preference.getKey().equals("text_default_album")) {
        stringValue = StringUtil.sanitize(stringValue);
        preference.setSummary(stringValue);
    } else {
        // For all other preferences, set the summary to the value's
        // simple string representation.
        preference.setSummary(stringValue);
    }
    return true;
    }
};

and in the pref.xml file it is used like:
<com.example.overrides.SanitizedEditTextPreference
            android:key="text_default_album"
            android:title="@string/pref_title_default_album"
            android:defaultValue="@string/pref_default_album"
            android:selectAllOnFocus="true"
            android:inputType="text"
            android:capitalize="none"
            android:singleLine="true"
            android:maxLines="1" />


Fazer toast desaparecer ao correr comando root

Question: Viva,
Tenho o telemóvel ligado ao computador e quando corro comandos root pelo adb, aparece sempre uma toast no êcra, existe alguma forma de fazer estas toats desaparecerem? Relembro que elas não estão a ser criadas pelo meu código.
Já tentei correr este comando no ínicio, mas não deu em nada :S
<code>su appops set android TOAST_WINDOW deny //adb shell
</code>
Comment: Vai nas configurações, marca para garantir sempre a permissão e tem uma configuração lá para não mostrar mais o alerta de quando garantir
Comment: você tem alguma aplicação de superuser instalada no smartphone ?
Comment: @AndersonCanteiro sim, o superSU
Comment: @AndersonCanteiro it worked, if you want to anwser that bellow i give you the correct anwser, thanks ;)
Comment: glad to help, i've put as answer
Answer: Vai nas configurações, marca para garantir sempre a permissão e tem uma configuração lá para não mostrar mais o alerta de quando garantir.


How to make HTTP Get request in Github for example Get Issues using R?

Question: So I want to gather some information about an Institute where students upload projects and stuff in Github.
So I want to gather all that an analyse it. But in order to do that I have to request it from git hub. I want to do that using R. Or secondary using Python.
But i dont quite understand how could I use that in R as a get Request.
So if anyone could show me an example I would appreciate that.
Thanx!
Answer: Requests is a HTTP library for python that is very robust and easy to use. JSON and XML responses can be parsed easily.
Use it as below
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

Use Github credentials'user' and 'pass' for authentication.
To get a list of reporsitories by a user or oranisation you can use Github's REST APIs.
Github has a REST API documentation. An HTTP GET request as below can fetch repositories for the specified org.
GET /orgs/:org/repos

find it here https://developer.github.com/v3/repos/#list-organization-repositories


Why I can't run this on jsfiddle

Question: I'm keep getting error why ? I tried everything, have removed every label and name tag. I know that there is similar questions being asked but non of them is useful to me. One of the answers for this particular error was to remove }) but I don't have any of those extra brackets. Thanks.

{"error": "Shell form does not validate{'html_initial_name':
  u'initial-js_lib', 'form': , 'html_name': 'js_lib', 'html_initial_id':
  u'initial-id_js_lib', 'label': u'Js lib', 'field':
  ,
  'help_text': '', 'name': 'js_lib'}{'html_initial_name':
  u'initial-js_wrap', 'form': , 'html_name': 'js_wrap', 'html_initial_id':
  u'initial-id_js_wrap', 'label': u'Js wrap', 'field':
  ,
  'help_text': '', 'name': 'js_wrap'}"}

And how to print my username and password ??
<form id='submit_leave_email' method = 'post'>
<input id='username' type='text' value='username'/>
<input id='password' type='password' value='password'/>
<button type='submit' class='input_button' value='submit'>Insert </button>
</form>

 Text, please stay here

    $('#submit_leave_email').submit(function() {

    var username = $('#username').attr('value');
    var password = $('#password').attr('value');

    });

Comment: You cannot always assume that whoever comments on your posts will downvote or upvote.
Comment: There is nothing here that would indicate an error. Can you share the fiddle with us?
Comment: Why -1 ? I shared everything the error and my code. http://jsfiddle.net/QQGfc/385/  @JayBlanchard
Comment: What is that error coming from?
Comment: Why are you asking me about -1? I have no idea where that came from.
Comment: My apologies to You, I thought You gave it to me. @JayBlanchard
Answer: The form submit is trying to hit a server when clicked it seems? If you prevent the default action it should work, fiddle here: https://jsfiddle.net/uL0ut0xk/
 $('#submit_leave_email').submit(function(e) {
     var username = $('#username').val();
     var password = $('#password').val();
     console.log(username);
     console.log(password);
     e.preventDefault();
 });

Comment: If you want to submit the form to your server using the form data you would remove that -- that's just for the jsfiddle.
Comment: @StefanJovanic depends on what you will be doing. If you are parsing the data with JS instead of posting it to something like a php page, then you will need the ` e.preventDefault();`.
Comment: Ok this helped with the jsfiddle but do I have to put e.preventdefault in real code or it is just the jsfiddle issue ? @brettkc
Comment: Thanks I will post whole question because this helped me with jsfiddle but I cant find the answer I'm looking for. Thanks for your answer @hopkins-matt
Answer: The error is generated because the form does not have the action attribute defined which tells where to post the data. Also, jsFiddle does not allow you to post data.
Comment: If I don't put method = 'post' then I get {"error": "Please use POST request"} @dxcorzo
Comment: if form does not have the `action` attribute, it will usually send back to the page itself
Answer: Javascript code must be inside script tag, or add the javascript code to the javascript section

Answer: This is because jsfiddle does not offer a web server to handle your form submit. But if you just want to print the username & password you can use the button type="button" rather than button type="submit". So it this way you can also avoid using event.preventDefault(),which infact prevent the default behaviour of the a HTML element.
HTML
<form id='submit_leave_email' method = 'post' >
<input id='username' type='text' value='username'/>
<input id='password' type='password' value='password'/>
<button type='button' class='input_button' value='submit'>Insert </button>
</form>

 Text, please stay here

JS
$('.input_button').on('click',function(event) {
    var username = $('#username').attr('value');
    var password = $('#password').attr('value');
   console.log(username , password)
 });

WORKING DEMO
Note: If your not using $(document).ready(function(){..} you have to wrap this js snippet inside body tag.
Also if you really need to submit the form then in real application you dont need to use event.preventDefault().Also printing & consoling will take place actual form submit.
Here is a  DEMO.
Note:I just used action  tab and used action = "www.google.com". You can check in console that before processing it is consoling the username & password

Why I can't run this on jsfiddle


Como disparar múltiplas exceções?

Question: foreach (Foo el in arr) {
    // ...
    Validate(el);
    // ...
}

No código de exemplo, quando o foreach é executado, uma exceção pode ser disparada da função Validate que será tratada em quem chamou o método que contém o loop.
As exceções disparadas pelo Validate tem que ser tratadas pelo usuário. O mais conveniente seria o usuário saber todas os erros que foram jogados para que corrigisse-os antes de reexecutar a função que contem o loop.
Para isso, eu teria que fazer algo do tipo:
List<Exception> errors = new List<Exception>();

foreach (Foo el in arr) {
    // ...

    try {
        Validate(el);
    } catch(Exception e) {
        errors.Add(e);
    }

    // ...
}

if(erros.Any()) {
    throw errors; // somente objetos do tipo Exception podem ser disparados com throw.
}

Como eu disparo múltiplas exceções?
Comment: Não sei se entendi a explicação do problema. A conclusão do que teria que fazer para resolvê-lo e talvez por isso a pergunta em si não parece fazer sentido e a resposta seria "não dá". Talvez por não entender o problema não consiga ver a motivação pra tentar fazer isto.
Comment: Exceções devem ser utilizadas para controle de fluxo? (https://pt.stackoverflow.com/a/48458/41056)
Answer: Isso me parece um erro conceitual no código.
Aparentemente você está usando exceções para tratar validações e isso não só é errado como é muito ruim, é um extremo mal uso do mecanismo de exceções.
Deixando isto de lado a resposta curta para sua pergunta é: Não é possível.
Exceções são para, como o próprio nome diz, casos excepcionais e não para validação de dados ou tarefas similares.
Supondo que você não queira consertar o código e deixar de usar estas exceções, o máximo que poderá fazer é passar essa lista de exceções até a camada de interface gráfica e lá fazer algo para mostrar as mensagens de deseja (ou fazer o que bem entende).
Mas, desta forma, não é possível capturá-las usando um bloco catch.
Ainda é possível disparar uma AggregateException com base na lista de exceções e capturá-la. Algo como:
Para disparar:
if(erros.Any()) {
    throw new AggegateException("Mensagem", errors);
}

Para capturar:
catch (AggregateException ae)
{
    ae.Handle((x) =>
    {
        // Todas as exceções dentro de 'ae' passarão por este bloco
        return true; // Isso impede a parada do código
    });
}

Talvez seja interessante ler estas publicações:

Melhor maneira de lidar com Exceptions
Devo usar um "try-catch" para identificar se uma senha está errada?
Exceções devem ser usadas para controle de fluxo?
Exceções consomem muito processamento. Verdade ou lenda? (essa não tá relacionada diretamente, mas acho bom ver)

Código funcional do exemplo com AggregateException. Veja funcionando no .NET Fiddle.
using System;
using static System.Console;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        try
        {
            FazerAlgo();
        }
        catch (AggregateException ae)
        {
            ae.Handle((ex) =>
                      {
                          WriteLine(ex.Message);
                          return true;
                      });
        }
    }

    static void FazerAlgo()
    {
        throw new AggregateException("", new List<Exception>
                                     {
                                         new Exception("Erro 1"),
                                         new Exception("Erro 2")
                                     });
    }
}

Comment: @vnbrs Você precisa desenvolver com isso em mente. Existem muitas técnicas. Por exemplo, no ASP.NET MVC, são feitas validações no controller, com base em anotações (`attributes`) que são definidas nas classes. Existe o fluent validation e por aí vai indo. Sobre este dois método estarem na mesma classe: não posso dizer que isto é errado e nem que não vai funcionar, mas a validação deveria mais perto da UI e menos perto do funcionamento. Se você começar as separar as responsabilidades e distribuí-las entre as "camadas" da aplicação vai notar que fica mais fácil fazer este tipo de validação.
Comment: Legal. Pode falar mais um pouco sobre não lidar com exceções para validação? Por exemplo, meu método `Gravar`, da classe, chama o método `Validar`, da classe também, como minha view ficaria sabendo do erro que ocorreu para interromper o fluxo e mostrar o erro de validação?
Answer: Caso realmente queira lançar várias exceções de uma vez para o chamador do código, use a classe AggregateException, ela recebe uma lista de Exception.
Adaptei seu código como exemplo:
List<Exception> errors = new List<Exception>();

foreach (Foo el in arr) {
    // ...

    try {
        Validate(el);
    } catch(Exception e) {
        errors.Add(e);
    }

    // ...
}

if(erros.Any()) {
    throw new AggregateException(
        "Vários erros ocorreram durante a execução do método.",
        errors)
}

Comment: Eu votei na resposta porque me parece que responde a pergunta, só quero dizer que acho isto muito raro de ser útil, quase sempre tem gambiarra nisto.

Como disparar múltiplas exceções?


Static content with Jetty and Spring

Question: My webapp doesn't  show any static content.

Spring MVC
Twitter Bootstrap
Jetty 7

Build project:
mvn clean install with Jetty included
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Some company</display-name>
    <welcome-file-list>
        <welcome-file>list.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

spring-servlet.xml
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:annotation-config />

    <mvc:annotation-driven />
    <mvc:default-servlet-handler />
    <tx:annotation-driven transaction-manager="transactionManager" />
    <jdbc:embedded-database id="dataSource" type="H2" />

    <context:component-scan base-package="com.company.config" />
    <context:component-scan base-package="com.company.market.dao" />
    <context:component-scan base-package="com.company.service.app" />
    <context:component-scan base-package="com.company.controller" />

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
    <bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
                    <property name="viewClass"
                        value="org.springframework.web.servlet.view.JstlView" />
                    <property name="prefix" value="/WEB-INF/jsp/" />
                    <property name="suffix" value=".jsp" />
                </bean>
            </list>
        </property>
    </bean>
</beans>

hero.jsp Added .jsp libary otherwise twitter bootstrap example but deleted some content
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Bootstrap, from Twitter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="../resources/assets/bootstrap/css/bootstrap.css" rel="stylesheet">

    <link href="../resources/assets/bootstrap/css/bootstrap-responsive.css" rel="stylesheet">

    <link rel="shortcut icon" href="../resources/assets/bootstrap/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../resources/assets/bootstrap/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../resources/assets/bootstrap/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../resources/assets/bootstrap/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="../resources/assets/bootstrap/ico/apple-touch-icon-57-precomposed.png">

          Project name

Home

About

Contact

Hello, world!

This is a template for a simple marketing or informational website. It includes a large callout called the hero unit and three supporting pieces of content. Use it as a starting point to create something more unique.

Learn more »

Folder structure is maven like.
src
- main
    - webapp
        - WEB-INF
            -jsp
            -resources
                - assets
                    -bootstrap
                        - css
                        - ico
                        - img
                        - js
        - spring-servlet.xml
        - web.xml

When I open the the hero.jsp as hero.html and view it in my browser I see that twitter bootstrap is working but when I deploy it nothing works...
I played around with
<mvc:resources mapping="/resources/**" location="/public-resources/"/>

but it didn't worked...
If I looked in the source of the html file when it is deployed the link e.g. for .css points to
http://localhost:8080/resources/assets/bootstrap/css/bootstrap.css

Comment: try moving resources to webapp directory. thanks
Comment: THX!! I had also to change the location from ../resources... to ../../resources
Answer: Try moving resources to webapp directory was the right tip.

Static content with Jetty and Spring