Shrink parent element to eliminate gaps left after wrapping line-level children

Question: I have a centered box containing a number of elements to be displayed side-by-side, possibly wrapping onto several lines. On resize, I'd like the box to shrink. The elements should remain the same size, wrapping onto additional lines as necessary.
I can think of a few ways of handling this (e.g., setting children to display: inline-block or float: left, or setting parent to display: flex; flex-flow: row wrap;).
In every scenario, resizing causes the elements to wrap. However, this leaves a gap between the last element on the line and the edge of the parent. This behavior is entirely reasonable in most contexts, but here it pulls the elements visually out-of-center.
I'd love it if I could apply some CSS magic to have the parent box "shrink" to the width actually occupied by child elements, ignoring end-of-line space. I was hoping display: table would come to my rescue here, but no such luck.
I recognize that a workaround would be to use a flex box, specifying justify-content: space-between (or without a flex box, just text-align: justify). This would eliminate the gap by distributing unused space between the elements - but I don't really want to have spaces between the items.
Here are some images depicting the issue: before resize / after resize
See below for snippet (I believe you'll need to run it full-page to have it respond to resize).

body {
  padding: 50px;
  background: pink;
}

.outer {
  display: flex;
  flex-flow: row wrap;
  max-width: 600px;
  margin: 0 auto;
  padding: 10px;
  background: yellow;
}

.item {
  width: 100px;
  height: 100px;
}

.a {
  background: green;
}

.b {
  background: blue;
}

Comment: possible duplicate: [Make container shrink-to-fit child elements as they wrap](http://stackoverflow.com/q/37406353/3597276)
Comment: possible duplicate: [How to center a flex container but left-align flex items](http://stackoverflow.com/q/32802202/3597276)
Comment: Thank you @Michael_B, I will check these out. Not sure how I didn't find these earlier!
Answer: I did a bit more research, using Michael_D's comments as a starting point.
Concluding that it's difficult to get a container to shrink this way using pure CSS.
From another post:

The browser renders the container on the initial cascade. It doesn't
  reflow the document when a child wraps.

When the container contents have a single known width, perhaps the most straightforward workaround would be to use media queries to set the container width. Breakpoints would occur at multiples of the base content width up to the maximum number of columns. This described and demonstrated here.


Adding a slideshow dynamically by proving json data

Question: Actually i have a json file(images.json)
 {
       "images":  [
        {"title": "Image One", "url": "image1.jpg", "rating": "3.5"},
        {"title": "Image Two", "url": "image2.jpg", "rating": "1"},
        {"title": "Image Three", "url": "image3.jpg", "rating": "5"}
      ]
    }

I need to create a slideshow by using this json data
And i have tried this by searching your site but i couldn't get the result expected

Can you please mention any style sheets or scripting files need to be imported
Comment: How are u displaying the images?You are just appending the texts not the tags to display them.
Answer: there were no element with id slideshow and jquery library was missing. hope it will work now. the is below -

Comment: It's displaying images how to display it as slideshow as i'm new to the concept can you help  me need any css or script files to be imported?
Comment: I have tried some plugins and one of them i have tried is http://reallysimpleworks.com/slideshow/      And the code i have written is

This is the first slide
Comment: I'm having problem with output it's just displaying the image in slide which is written in  tag but not displaying images that are dynamically added
Comment: You cant expect all the code here. try to figure it out the problem on ur own.


Duvida Python com consulta em banco Firebird

Question: Ola estou com um problema na consulta com o banco de dados firebird.
Faço a conexão com o banco e passo esta consulta, mas o problema esta no retorno, ele retorna o nome do produto normal só que o retorno do preco_venda vem com o "tipo decimal" descrito na frente do dado, mas sendo que o tipo do dado que esta cadastrado no banco é numeric.
cursor = conector.cursor()
cursor.execute("select e.descricao, e.preco_venda from estoque e where  '7853849020424' = e.barras")
lista = cursor.fetchall()

print(lista)

cursor.close()
conector.close()

Muito obrigado
Answer: Esse Decimal não é tipo Decimal do Firebird esse é tipo Decimal do Python
O módulo decimal foi projetado para suportar aritmética decimal não arredondada exata(aritmética de ponto fixo) e aritmética arredondada de ponto flutuante.
Para iniciar o uso do tipo decimal primeiro deve-se ajustar seu Contexto de operação.
Contextos são ambientes para operações aritméticas. Eles governam a precisão, estabelecem regras para arredondamento, determinam quais sinais são tratados como exceções e limitam o alcance dos expoentes.
O método decimal.getcontext() retorna o Contexto para o thread ativo.
>>> from decimal import *
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

Esse Contexto retornado é o contexto na falta. Seus valores são prec= 28, rounding= ROUND_HALF_EVEN, e traps para Overflow, InvalidOperation, e DivisionByZero.
Para ajustar uma das propriedades do contexto:
>>> getcontext().prec = 7

Para definir um novo contexto use o método decimal.setcontext() e passe como argumento um dos Contextos predefinidos decimal.Defaultcontext, decimal.BasicContext e decimal.ExtendedContext, ou crie seu próprio contexto com o construtor decimal.Context().
Instâncias decimais podem ser construídas a partir de números inteiros, strings, ponto flutuantes ou tuplas:
>>> Decimal(3) / Decimal(4)
Decimal('0.75')
>>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
>>> max(data)
Decimal('9.25')
>>> min(data)
Decimal('0.03')
>>> sorted(data)
[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
>>> sum(data)
Decimal('19.29')
>>> a,b,c = data[:3]
>>> str(a)
'1.34'
>>> float(a)
1.34
>>> round(a, 1)
Decimal('1.3')
>>> int(a)
1
>>> a * 5
Decimal('6.70')
>>> a * b
Decimal('2.5058')
>>> c % a
Decimal('0.77')

As operações entre decimais são fechadas entre si.
Se quiser a representação textual de um decimal o converta para string:
>>> str(Decimal(1) / Decimal(7))
'0.1428571'
>>> f'{Decimal(Decimal(2) * Decimal("0.34")):g}'
'0.68'

Ou no seu caso:
cursor = conector.cursor()
cursor.execute("select e.descricao, e.preco_venda from estoque e where  '7853849020424' = e.barras")
for row in cur.fetchall():
  print(f'Item: {row[0]}, Valor: {row[1]:g}')

cursor.close()
conector.close()

Answer: Consegui "contornar" ou exibir as informações assim:
        cursor.execute("select e.descricao, e.preco_venda from estoque e where  '"+barras+"' = e.barras")
        retorno = cursor.fetchall()

        print(retorno[0][0])
        print(retorno[0][1],"RS")

Pois as informações estavam em uma tupla, desta maneira consegui exibir o conteúdo da posição.


Unable to set response header "Connection" in ASP.NET Core 6

Question: I have an ASP.NET Core 6 Web API and the requirement to set a Connection: Close header in certain situations to put some legacy terminals (client) in a maintenance mode.
I can set the headers in general, but the Connection: Close header gets removed and is not part of the response.
Here is my controller:
[ApiController]
[Route("[controller]")]
public class HeaderTestController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        Response.Headers.Add("Foo", "Bar");           // part of the response
        Response.Headers.Add("Connection", "close");  // NOT part of the response

        return NoContent();
    }
}

This is how my Program.cs looks like:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

When I invoke the API method, it returns the foo header but omits the Connection header:

Any idea which component is removing the Connection header and how I can bypass it?
Comment: check this method `CreateResponseHeaders` in [HttpProtocol.cs](https://github.com/dotnet/aspnetcore/blob/72ee5732f00289191a7f89ce8000854e52de808c/src/Servers/Kestrel/Core/src/Internal/Http/HttpProtocol.cs). it is removing this header here. and i don't think any ways to bypass it.
Comment: one more thing. this is only removed if client is making http/2 or http/3 request. if your legacy client is still using http/1.1 then it won't be removed.
Comment: @CodingMytra This is the information I was looking for and the answer to my question. I was able to retrieve the `Connection: Close` header with a http/1.1 request. Also, when I try the same request with http/2 or http/3, I don't get the Connection header. Can you add this as an answer so I can gladly accept it?. Thanks a ton.
Comment: What's your frontend server? Kestrel only? Iis?
Comment: @DanielA.White Right now I use just Kestrel but I will deploy it to an Azure Web App in the future
Comment: as you mentioned, i converted this to ans. see below
Answer: Check method CreateResponseHeaders in HttpProtocol.cs. it is removing this header here. and I don't think any ways to bypass it.
and also this is only removed if client is making http/2 or http/3 request. if your legacy client is still using http/1.1 then it won't be removed.
Hope this helps.
Answer: Try this and add code to Program.cs:
builder.Services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
    builder.WithExposedHeaders(new string[] { "Connection"});
}));

and also add this line too:
app.UseCors("MyPolicy");

I have similar problem and solved
Comment: Please do not put screenshot as ans. and also this will be not solve the problem.
Comment: Thanks for your help mohsen mashhadi. Unfortunately, this doesn't solve the problem - I tried it.
Comment: I edited my answer and hope that solves your problem.


How do I include quotation marks in a print statement if I am using a variable

Question: word = input("Enter a word: ")
word_length = len(word)

print("The length of", word,"is ", word_length)

If word is 'back', the output will be:
The length of back is 4

I want the output to be:
The length of 'back' is 4

Comment: `'The length of "{}" is {}'.fomrat(word, word_length)`
Answer: The Good way:
The best way is to use format
print("The length of '{}' is {}".format(word, word_length))

The Bad way:
Using C-like statement, note that this is de-emphasised, (but not officially deprecated yet)
print("The length of '%s' is %s" % (word, word_length))

The Ugly way:
One way is to have your string add with a ' and using sep attribute
print("The length of '", word,"' is ", word_length, sep = '')

Comment: While the Python documentation recommends using the newer `format` method, the older `printf`-style formatting has never been deprecated.
Answer: You can use repr of a word to include the Python quotation marks (as they appear in e.g. the interactive interpreter); this has the added benefit of working reasonably when quotes are already in the string:
print("The length of", repr(word), "is", word_length)


Lasso on squared parameter

Question: Assume a linear regression problem where I want to force sparsity of some parameters. However, due to some physics, I know that one of my parameters is always positive. For instance, I have that
$$ y=\sum \beta_ix_i+\epsilon $$ where $\beta_5\geq0$
Is it safe to find the parameter estimates through maximizing the penalized likelihood below while just adding the constraint $\beta_5\geq0$
$$l_p=l(\boldsymbol\beta)+\lambda \sum |\beta_i|$$
By safe I mean, can we still interpret the sparsity results the same way we do in the lasso and if yes why, is there another way to do it using an $l_1$ norm, or does this minimization retain the lasso properties at the MLE.
Comment: What are the "lasso properties at the MLE"?
Comment: @AdamO consistency in estimation and selection, under some regularity conditions first introduced by Tibshirani and then expanded by Hui Zou in 2006.
Comment: @RichardHardy yes I did, it was put on hold as it was unclear.
Comment: Wis, There was a related question recently, but I cannot find it anymore. Did you delete it?
Answer: The MLE estimate that you get for your parameters will not include the prior you have of B5 being positive. However unless your model has a hard time fitting and you end up having negative estimates for B5, it's unlikely that not introducing that prior will change your interpretation in any meaningful way - it might just mean that your confidence intervals would have been slightly different if the prior had been there.
Comment: Could you please clarify this answer so that I can accept it.
Comment: What do you mean by "clarify" ?

Lasso on squared parameter


Spring MVC - Set an actionURL parameter with Javascript

Question: Is it possible to dynamically set a Spring MVC portlet:actionURL portlet:param using javascript?  I have tried with the following code, but the id value always comes across as null to the controller. I have verified that setting the portlet:param manually passes the value correctly:
<portlet:param name="id" value="2" />

I have also verified the value in the javascript is being set correctly and is not null.
(Note: I've changed the variable names, etc. from the original code to simplify it and obfuscate it since it is my employer's code.)
JSP:
<portlet:actionURL var="modifyURL">
    <portlet:param name="do" value="modify" />
    <portlet:param name="id" value="${model.id}" />
</portlet:actionURL>

...

<form:form action="${modifyURL}" id="modifyForm" modelAttribute="model">
    <form:hidden path="id" id="id" />
</form:form>

Javascript called when the update URL is clicked:
function update() {
    document.forms[0]["id"].value = selectedId;
    document.forms[0].submit();
}

Controller:
@RequestMapping(params = {"do=modify"})
public void modify(@ModelAttribute("model") Model model,
    @RequestParam(value = "id", required=true) Long id,
    ActionRequest request, ActionResponse response,
    SessionStatus sessionStatus, ModelMap modelMap)  {
....

Answer: A co-worker figured it out.  It looks like you just have to add the parameter to the action within the javascript and not include it in the actionURL or form.
JSP:
<portlet:actionURL var="modifyURL">
    <portlet:param name="do" value="modify" />
</portlet:actionURL>

...

<form:form action="${modifyURL}" id="modifyForm" modelAttribute="model" method="POST">
</form:form>

Javascript called when the update URL is clicked:
function update() {
    $("modifyForm").action = '${modifyURL}&id='+selectedId;
    $("modifyForm").submit();
}

Answer: I came across this almost 3 years later, still i found it easier to add  a hidden form field and when the action is clicked than to set this value to the hidden field
something like
 <input type="submit" id="btn_terminate_cmpn"
                value="Terminar campaña" onclick="setAction('terminate');">

and the javascript code
function setAction(action){
    $("#actionToDo").val(action);

}

Answer: The URL generated by the portlet tag is on the server side.  Javascript doesn't see the portlet tag.  It only sees the actual URL. What your coworker is suggesting would work but it's not a good approach.  Here he's just adding the dynamic parameter as a query string parameter which makes it visible to all the portlets on your target portal page.  A better solution is to keep a hidden element (text box or something) and set the dynamic value to this hidden element in your onSubmit Javascript hander function.


How to display git "tag" in lightline?

Question: I work on git tags on a daily basis & switch between 'em. I have my lightline configured where it does display git branch in status bar of lightline. But I am trying to display git tag as well. gitbranch component from lightline does display the commit id when I checkout / switch to a tag but those commit ids are pretty much unusable.
Here is my lightline block in neovim config:
let g:lightline = {
        \ 'colorscheme': 'powerline',
        \ 'active': {
        \   'left': [['statuslinetabs', 'lineinfo'], ['gitbranch',  'gittag', 'readonly', 'modified']],
        \   'right': [['mode'], ['paste'], ['absolutepath']],
        \ },
        \ 'inactive': {
        \   'left': [[], ['line', 'relativepath', 'readonly', 'modified']],
        \   'right': [[], [], ['gitbranch']],
        \ },
        \ 'component_expand': {
        \   'statuslinetabs': 'LightlineStatuslineTabs',
        \ },
        \ 'component_function': {
        \   'gitbranch': 'MyFugitiveHead'
        \ },
        \  'component': {
        \    'clock': '%{strftime("%a %d %b %I:%M%p")}'
        \  },
        \ }

In help of fugitive's AUTOCOMMANDS section it does say -
    AUTOCOMMANDS                                    fugitive-autocommands

A handful of User autocommands are provided to allow extending and
overriding Fugitive behaviors.  Example usage:

        autocmd User FugitiveBlob,FugitiveStageBlob call s:BlobOverrides()

                                                User_FugitiveTag
FugitiveTag             After loading a tag object.

But I am unable to figure how to utilize that as neither component or component_fuction.
Please advice!
Thanks.
Comment: Another way I thought of doing it - having the output of ":G describe --tags" added somehow to a lightline section - but not sure how that's possible either as it displays the command and doesn't process the command for an output before displaying.
Answer: You have set gittag in the active list:
\ 'active': {
        \   'left': [['statuslinetabs', 'lineinfo'], ['gitbranch',  'gittag', 'readonly', 'modified']],
        \   'right': [['mode'], ['paste'], ['absolutepath']],
        \ },

Then you should add:
...
'component_function': {
        \   'gitbranch': 'MyFugitiveHead'
         \   'gittag': 'FugitiveTag'
        \ },
...

Comment: Thanks Rico. But it doesn't work that way in my configuration - it simply doesn't display anything. Did it work in yours?
Comment: I just realized you have `MyFugitiveHead` instead `FugitiveHead`. This might be the problem. Also check what happens when you type the command `:FugitiveTag`, whether it displays the tag or not.
Comment: Thanks for your response again Rico. MyFugitiveHead is a custom function as:
function MyFugitiveHead()
  let head = FugitiveHead()
  if head != ""
    let head = "\uf126 " .. head
  endif
  return head
endfunction
So its not related. I am not able to get anything after typing :FugitiveTag command.
Comment: I see. It does not work because FugitiveTag is not a command but a kind of event. Try `:Git describe --tags --abbrev=0` instead of `FugitiveTag`.
Answer: Found a solution, not the vim-fugitive but native git way - via system calls. Just declared below as a component (not function) and since I work with multiple tags sometimes, used xargs to show all tags pointing to head. Includes non-git files scenario command output sending to /dev/null.
        \  'component': {
        \    'gittag': '%{substitute(system("git tag --points-at HEAD 2>/dev/null | xargs"), "\n", "|", "g")}',
        \  },

How to display git "tag" in lightline?


Can't commit and push to github repository

Question: Screenshot
Hi,
I'm trying to commit and push my work onto github. However, I can't.
Seems like it's saying some of the files i'm trying to push are too large.
But that's why I specified the .csv and .pt files in .gitignore.
I am not sure why .gitignore is not working as it should.
Any help will be very much appreciated.
Bye.
Comment: Don't abuse tags. Why `python` tag?
Answer: You need to first commit and push your .gitignore file before it is considered by Git.
Comment: yes, checkout all your changes, commit a previous .gitignore, then use git add instead of git -a to commit useful files only
Answer: Try this
git rm -rf --cached

then
git add

this should remove all the files from ur commit cache and then add them back but using the ignore


Which tag or code invokes AngularJS for very first time

Question: Which tag or code invokes AngularJS for very first time. Or what is the entry point of AngularJS.
Let's take the below example.

Angular application

ng-app specify it is an angular block. This means AngularJS is already running in the document that is why it is able to identify the directive.
Comment: when you use ng-app , it invokes AngularJs for the first time
Comment: But how my document know ng-app is a angular directive ?
Answer: It's the ng-app but you can bootrap it yourselves as well , then you have the control to initialize
 angular.bootstrap(document, ['demo']);

I think you need to look in to how angular works , here are the basic concepts
Answer:


${3^n\choose k}$ is divisible by $3$?

Question: How can I prove that ${3^n\choose k}$ is divisible by $3$ for all positive integer values of $n$? (where $k$ is any positive integer smaller than $3^n$) Can you use induction? Thanks.
Comment: This follows from [Lucas's theorem](https://en.wikipedia.org/wiki/Lucas%27s_theorem)
Comment: Slight update to your question: for $k=3^n$ it's trivially wrong, what you have in mind must be $0<k<3^n$.
Comment: Might be related: If $p$ is a prime and $0<t<p$ then $p$ divides $\binom{p}{t}$.
Comment: @saisaandeep $3$ is prime, so his/her comment could be relevant.
Comment: If $k= 3^n$ C($3^n$,k)=1 which is not divisible by 3
Comment: Yanko sir. Here p is not a prime number.
Comment: Yeah k should be less than 3^n thanks guys.
Answer: I just want to demonstrate the relevance of if $p$ is prime and $0<t<p$ then $p$ divides $\displaystyle \binom p t$
Consider $$\begin{split}(x+y)^p
& =\sum_{k=0}^p \binom p k x^{p-l} y^{k} \\
& =x^p+\binom p 1x^{p-1}y+\binom p 2x^{p-2}y^2+\cdots+\binom{p}{p-1}xy^{p-1}+y^p\\
& = x^p + y^p \mod p
\end{split}$$
Hence
$$\begin{split}
(x+y)^{p^n} &= \left((x+y)^p\right)^{p^{n-1}} \\
&= \left(x^p+y^p \mod p\right)^{p^{n-1}}\\
&= (\left(x^p+y^p \mod p\right)^p)^{p^{n-2}}\\
&= \left(x^{p^2}+y^{p^2} \mod p\right)^{p^{n-2}}\\
& \vdots\\
& = x^{p^n}+y^{p^n} \mod p
\end{split}$$
But also
$$\begin{split}
(x+y)^{p^n}
& =\sum_{k=0}^{p^n} \binom{p^n}{k} x^{p^n-l} y^{k} \\
& =x^{p^n}+\binom{p^n}{1}x^{p^n-1}y+\binom{p^n}{2}x^{p^n-2}y^2+\cdots+\binom{p^n}{p^n-1}xy^{p^n-1}+y^{p^n}\\
& = x^{p^n}+y^{p^n} \mod p
\end{split}$$
Therefore $p$ divides $\displaystyle\binom{p^n}{k}$ for all $k$ with $0<k<p^n$
Comment: Is there supposed to be a way to get from $$\sum_{k=1}^{p^n - 1} {p^n \choose k}x^{p^n - k} y^k \equiv 0 \pmod p$$ to $${p^n \choose k} \equiv 0 \pmod p$$ ?
Comment: @DanielV First note that the $x$ and $y$ variables don't have any common terms in that range of said sum. Then note taking a polynomial modulo $p$ means exactly taking the modulo $p$ of every coefficient. Combined with modulo $p$ those terms are zero means that since no common powers of $x$ and $y$ can cancel that each coefficient must be $0$ modulo p.
Answer: This is a consequence of Lucas's Theorem:
$${a \choose b} \equiv \prod {a_j \choose b_j} \pmod p$$
for prime $p$, where $a = \sum_{j = 0}^n a_j ~p^j$ and $b = \sum_{k = 0}^n b_j~ p^j$.
The original question is thus equivalent to showing (for $a=3^n$) that $\exists j.{a_j \choose k_j} \equiv 0 \pmod p$.
So just to show that there is a pair such that $k_j > a_j$ which is observable from the ternary representation of $3^n$ and $k$.
Answer: Hint: Notice that $$\binom{3^n}{k}=\sum_{a+b+c=k}\binom{3^{n-1}}{a}\binom{3^{n-1}}{b}\binom{3^{n-1}}{c}$$summing over all valid ordered triples $(a,b,c)$ of non-negative integers.
Answer: Looking at the fractional expansion of the binomial coefficient, you can cancel out factors of 3 in the $(3n+1)^\text{th}$ value in the numerator with the $(3n)^\text{th}$ value in the denominator, for example:
$${3^3 \choose k} = \begin{array} {c}
27 & 26 & 25 & \color{red}{24} & 23 & 22 & \color{blue}{21} & 20 & 19 & \color{green}{18} & 17 & 16 & \color{orange}{15} & \dots & 27 - (k - 1)  \\ \hline
1 & 2 & \color{red}{3} & 4 & 5 & \color{blue}{6} & 7 & 8 & \color{green}{9} & 10 & 11 & \color{orange}{12} & 13 & \dots & k
\end{array}$$
So you get $\pi_3(\text{Numerator}) - \pi_3(\text{Denominator}) = \pi_3(3^n) - \pi_3(k) > 0$.
Comment: and, e.g., the 27 takes care of left over 3's when $k=3^nm$, with $3 \nmid m.$

${3^n\choose k}$ is divisible by $3$?


Finding the probability space of the given experiment.

Question: Specify the probability space completely for the following experiment: tossing a fair coin till we see the first heads. Here is what I have done so far:
The sample space is simply  $T^n H$ where $n$ can go from $0$ to infinity i.e. $\{T,TH,TTH,TTTH,\ldots\}$
Essentially the sample space is infinite.
Let event $E_n$ be that head shows up after $n$ tails
then $P(E_n)$ will be $(1/2)^{n+1}$ since we require $n$ tails and then a heads must show up.
How do I denote the sigma algebra since the sample space is infinite.
Also, I am under the impression that the sigma algebra will always be the power set of sample space. Is it correct? If so, then why use a special name sigma algebra and not simply call it the power set?
Thanks!
Answer: You have the right sample space, and you are right that if the $\sigma$-algebra were always the power set of the sample space, then there wouldn't be a point in having such a concept.
This is a discrete sample space.  "Discrete" means the sum of the probabilities assigned to subsets of the sample space having just one member is $1$.  In other words, all of the probability is accounted for by point masses.  This particular discrete sample space also has no points with probability $0$.  In discrete sample spaces with no points having probability $0$, the $\sigma$-algebra will always be the power set of the sample space.
Contrast this with the uniform distribution on the interval $[0,1]$.  If $0\le a \le b\le 1$, then the probability assigned to the interval $[a,b]$ is the length $b-a$ of the interval.  That means every subset with just one member has probability $0$.  In this case the $\sigma$-algebra is the set of all Borel sets that are subsets of $[0,1]$.  Borel sets are sets that can be reached by starting with intervals and closing under the operations of complementation and countable union.
Comment: Thanks for the brilliant answer! :)
Answer: The way I'd do it is as the $\sigma$-algebra generated by the sets of the form $\Delta(a_{1}, \ldots, a_{n}) = \{ (s_{k})_{k \in \mathbb{N}} \in \{T, H\}^{\mathbb{N}} : s_{k} = a_{k}, k = 1, \ldots, n\}$, that is, the set of sequences of tails and heads for which the first $n$ flips will agree with some prescribed sequence of $n$ outcomes, i.e. $\Delta(THHT)$ is the set of sequences beginning $THHT$, though what happens after is irrelevant. These are called cylinder sets, or cylinders, of rank $n$, and they generate a $\sigma$-algebra.
Your event is the disjoint union of the cylinders $\Delta(T^{k}H)$, each of measure $2^{-(k + 1)}$.


Number of parameters in Multivariate Gaussian for different covariance matrices

Question: In the following links : Full Covariance Gaussians, Diagonal Covariance Gaussians, Spherical Covariance Gaussians, the number of parameters is specified as $D + \frac{D(D+1)}{2}$, $2D$, $D+1$ respectively, where $D$ = # dimensions.
How do you arrive at those formulas for the number of parameters?
Thank you!
Comment: links not working anymore
Answer: For a $p$ dimensional random vector, the mean vector is of length $p$ and the covariance matrix is $p \times p$

Full covariance: If every parameter is free, then there are $p(p+1)/2$ parameters; one way of seeing this is that there's a covariance for each pair, of which there are $$\binom{p}{2} = \frac{p!}{(p-2)! \times 2} = \frac{p(p-1)}{2}$$
then add the diagonal entries, of which there are $p$:

$$ p + \binom{p}{2} = p + \frac{p(p-1)}{2} = \frac{2p + p^2 - p}{2}
= \frac{p^2 + p}{2} = \frac{p(p+1)}{2}$$

Diagonal: this means all of the off-diagonal entries are zero, so the only free parameters are on the diagonal; there are $p$ of those.
Spherical: this means all of the off diagonal entries are 0 and the diagonal entries are all equal, so there's $1$ free parameter.

If you add in the mean parameters to be estimated, you add $p$ to each of those totals and you get $p + p(p+1)/2$, $2p$, and $p+1$, respectively.
Answer: Full: # of means = D, # of variance = D, # of covariance = (D-1)D/2: Total = D+D(D+1)/2
Diag: # of means = D, # of variance = D, covariance = 0: Total = 2D
Spherical: # of means = D, Assume the variance are the same so # of variance = 1, covariance = 0: Total = D+1


Use rules on custom content fields

Question: I am trying to apply a rule to a certain content type with a taxonomy term selected from a list, this term is from a select list that selects the terms from a certain vocabulary that lists the terms from the vocabulary. I want the rule to only apply when international is selected......I have been at if now for four days, nothing doing. Tried a search but the results I found were not helping. I would really appreciate the help.
Answer: Your can probably add a rule of this kind :
The event is : Before saving content
Restrict by type : your content type
Then add a condition : Text comparaison then select your field with the Data selection like this node:field-example:0:name and match the International value. The rules will fire if all theses conditions passes

Use rules on custom content fields


Make divs inside table cells the same height without javascript

Question: I would like to make two divs contained in table cells in a shared row both have the height of the taller div. I would like to do this without JS. Here is a fiddle with a simplified example:
http://jsfiddle.net/Lem53dn7/1/
Here is the code from the fiddle:
HTML

small content

this is some longer content that will wrap.
                 I want the other div to be the same height as this one.

CSS
table{
    width: 200px;
    table-layout: fixed;
}
div {
    border: 1px solid black;
}

Comment: Can I ask why you need the equal height, to set up the borders?
Comment: @sdcr exactly, I want the borders to mark out equally sized and proportioned boxes with different content from one another
Comment: Why don't you set up the borders on the TD instead of DIV?
Comment: take out the div css and add these lines of code: table td{

    border: 1px solid black

}
Answer: Add the following properties to your div rule:
height: 100%;
display: inline-block;

Updated fiddle.
Comment: Thank you for the answer! Unfortunately I want the divs to be the same width as well and `display: inlinle-block;` messes that up. Here is an updated fiddle demonstrating this problem http://jsfiddle.net/Lem53dn7/6/ . Suggestions?
Comment: My only suggestion is to use [flex-box](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) instead of tables. :) If you're alright with [the browser support](http://caniuse.com/#feat=flexbox), it's definitely the way to go for layout.
Answer: You can add a height to the TD elements and then make the DIVs height 100%:
table{
    width: 200px;
    table-layout: fixed;
    height: 100%;
}

table td {
    height: 100%;
}

div {
    border: 1px solid black;
    height: 100%;
}

http://jsfiddle.net/Lem53dn7/7/
Comment: Updated my answer. Seems to work fine in every browser (didn't check IE). @kat
Comment: the problem with this is that I don't know the desired height of the cells. This doesn't work for dynamic content


Generate .jar from scala

Question: I'm developing an application on Eclipse with Scala and a would like to create a .jar. I have found tuto to do that, but it use the package scala.tools.nsc and I don't know where I can found this thing.
I have tried too, to generate the .class and then with the command jar cmf .... to generate the .jar but when I launch the .jar an error occur. (NoClassFound)
With sbt I have tried too, but when I compile my project that work with eclipse a lot of error appear.
Somebody can me explain how I can simply create a .jar with Eclipse or another tools.
Comment: I corrected 'java cmf' to 'jar cmf', please review if this is ok. And look out at faq and meta and sidebar, how to edit your post. Layout and so on. In general, when asking because of an error: What did you exactly? Command? Cut'n'paste it, to avoid transfer errors. Copy and paste the exact error message. In which directory did you start the command, what is your file structure, what project name did you choose, did the file hierarchy correspond to the directories? Did you use `jar` before, for example with `Java` and with how much success? Thanks.
Answer: Eclipse has a build-in option to generate runnable jars, but it is well hidden. Also it does not recognize Scala's main() signatures, so you will have to create a Java class with a main() method.

Create a Java class with a main() method which simply forwards the call to your Scala code.
Then right click on your newly created Java class and select: Run As -> Java Application.
This will create a runnable configuration which will later be used as a part of your runnable jar.
Now you are ready to dig out the runnable jar option from the Eclipse's menu:
File -> Export -> Java -> Runnable JAR file
In the presented dialog select the Launch Configuration you have created earlier (in step2), name your jar (myapp.jar), select your dependency export options and click finish.
The jar will be created in the Eclipse's workspace by default.
Run the jar using the line: scala myapp.jar

Your question about missing images: Eclipse requires a manual refresh when files are added or removed. Right click on your project and select Refresh.
This concludes the tutorial on the highly intuitive Eclipse interface.
Note: Instructions for Eclipse version 3.6.2.
Comment: Thanks, but it doesn't work.... I have created a java class with a main(). Then created the .jar and when I want to launch the jar the name of my app appears on the menu and on the terminal I have this error : "lang.ClassNotFoundException: scala.ScalaObject" and  "java.lang.reflect.InvocationTargetException" and when I want to launch with the line : scala myapp.jar I have this error "Permission denied"
Comment: I have installed a new version on Scala, it's for that that I have the error "Permission denied" but now I have with the line : scala myapp.jar this error : error: IO error while decoding /Users/danymorard/Documents/workspace/myAppl1.jar with UTF-8
Comment: Launching jars using "scala myapp.jar" is supported since Scala 2.9.0. Looks like you have an older version installed which tries to load the jar as a script file.
Try launching the jar with "java -cp $SCALA_HOME/lib/scala-library.jar:myapp.jar mypackage.Mymain"
Answer: Jars
When you create a jar out of your classes, possibly the dependencies are not included in that jar. When running that jar, you need to put the jars containing the dependencies on the classpath (with the -cp switch to java). Most important dependency is the scala-library jar. Of course knowing what is not found by NoClassDefFound would help.
Sbt
When building with sbt, maybe it is missing dependencies that you have manually added to the Eclipse project? (Note: I did not use sbt).
Maven
I found the clearest and most painless way is to go with maven alone, or possibly maven + Intellij Idea (community edition is free) + Scala Plugin. Works very smooth.
For maven, you need to adapt the available scala archetype a bit since the libraries it refers to are not the most recent version, but apart from that it is very fine.
Here is a pom.xml I'm using: https://gist.github.com/1096870
Use the standard maven folder structure (source root is src/main/scala) and then mvn package creates the jar fine.
Comment: @Snoopy: Don't say 'Thanks', but upvote helpful answers. That, which solves your problem best (if any) should be marked as accepted answer.
Answer: Use the below steps for time being .But this is not the full time solution.Better to go for sbt build jar for Spark-Scala combination.
Temporary solution using java class ,calling the scala main class.
MainClass.java
public class MainClass {
    public static void main(String[] args) {
        SampleApp app=new SampleApp();
        app.main(args); }
}

SampleApp.scala
class SampleApp {
   def main(args: Array[String]) {
     println("First Scala SampleApp")}
}

Export it as  a jar by using normal java jar export by choosing the MainClass main method.
name the jar file as Sample.jar
Run it in the Cluster using below command.

/spark/bin/spark-submit --class com.scala.MainClass SampleScala.jar

The output you can get as:
First Scala SampleApp
Comment: This did it for me. Super-annoying that Eclipse doesn't recognise Scala main files!
Comment: Also note that I created a new Java project and added the Scala libs, as recommended here: http://stackoverflow.com/questions/11413888/exporting-scala-project-as-jar-from-eclipse
Answer: % cat a.scala
package foo

object Whee {
  def main(args: Array[String]): Unit = {
    println("I'm in a jar")
  }
}
% scalac29 -d whee.jar a.scala
% scala29 -cp whee.jar foo.Whee
I'm in a jar
%

Comment: Tanks for the answer, but I understand nothing what you are doing
Comment: This does not make a runable jar for you. It only compresses your code inside of a jar file. To make it runable, you need to at a manifest, where you define the main-class.
Answer: To build off of what @Kumar Basapuram wrote:
Make a java class called "Wrapper.java".
package animals;
public class Wrapper {
    public static void main(String[] args) {
        SampleApp app=new SampleApp();
        app.main(args);
    }
}

Link this main method to the main method in the "SampleApp.scala" class.
package animals
class SampleApp {
  def main(args: Array[String]){
     var c = new Cow("Bessie", 100)
     println(c.speak)
     var h = new Horse("CJ", 50)
     println(h.speak)
     var s = new Sheep("Little Lamb", 25)
     println(s.speak)

     println(s.weigh)
     println(h.weigh)
     println(c.weigh)
  }
}

Project with Java and Scala Classes Picture
Right Click on the Project ScalaPracticeCreation.
Click Export...
Click Runnable JAR file under the Java folder
Exporting Scala Class into a jar Executable Picture
Click Next >
Select Wrapper - ScalaPracticeCreations
Select Export destination to a place on your computer
Select "Extract required libraries into generated JAR" under the "Library
handling:" option
Click Finish
Run the file through the Eclipse IDE and it works.
Run it through the Command Prompt and it does not work.
Command Prompt Picture
To fix this remove the println methods from the "SampleApp.scala".
package animals
class SampleApp {
  def main(args: Array[String]) {
    var c = new Cow("Bessie", 100)
    var h = new Horse("CJ", 50)
    var s = new Sheep("Little Lamb", 25)
    c.weigh().toString()
  }
}

add "System.out.println(app.main(args));" to replace "app.main(args);" in the Wrapper.java class
package animals;
public class Wrapper {
    public static void main(String[] args) {
        SampleApp app=new SampleApp();
        System.out.println(app.main(args));
    }
}

Now reexport the program after running it.
success in the command prompt Picture
Now it works.
Here are the extra filler .scala classes. Note that the Demo.scala class is irrelevant.
Weight.scala:
package animals
abstract class Weight(size: Int) {
  def weigh = "My size is " + size
}

Animal.scala:
package animals
abstract class Animal(name: String, weight: Int) extends Weight(weight){
  def speak = name + " says " + sound
  def sound: String
  override def weigh() = "My name is " + name + " and I weigh: " + weight
}

Cow.scala:
package animals
class Cow (name: String, weight: Int) extends Animal(name,weight){
  override def sound() = "mooooo"
}

Horse.scala:
package animals
class Horse (name: String, weight: Int) extends Animal(name,weight){
  override def sound() = "neigh"
}

Sheep.scala:
package animals
class Sheep (name: String, weight: Int) extends Animal(name,weight) {
  override def sound() = "baaaa"
}

Note that this may not be the best solution although it is a functional solution. Scala sbt may be a better solution: Scala sbt or this Scala sbt-assembly.

Generate .jar from scala


Why is my bass eating up 9 volt batteries like candy?

Question: My Ibanez Soundgear SG6 is eating through brand-new 9v batteries in a matter of days... I've been testing it for a couple weeks now. I'll replace the battery (right out of the package,) and after 2 to 3 days, it's completely dead and needs to be replaced again.
History: About 7 or 8 years ago, I took it in because I was getting no sound... I was advised to replace the input jack. No issues since then. About 2 years ago, a friend borrowed this bass and cleaned out the pots after noticing a slight scratching in one of the knobs. No issues since then either.
Here are some pics (I just now removed the electrical tape from where the wires of the battery connector are spliced):
Answer: On the assumption you're taking the jack out after playing (You are, aren't you..?) then I'd go for the jack socket itself, which is switched, so as to activate the circuitry when a jack is inserted. Could be the switch isn't clearing when the jack's taken out. Might just need a bit of judicous poking around with a small screwdriver. With a multimeter, it's quite easy to check there's voltage at the socket.
Comment: @TimBurnett-Bassist you won't get a reading at the jack because it's switching the negative / ground line. Put the positive of the multimeter on the red wire where the battery is spliced and put the negative to the green followed by the black wires on the jack, if you get a reading on both with it unplugged the circuit will be getting power all the time because the internal switch is stuck.
Comment: Yes lol, I'm removing the instrument cable from the jack after I am finished playing. Thanks for that suggestion... I'll get back to you
Comment: So with another new battery, I'm not getting a reading at the socket... I do get a reading where the wires are spliced on the battery connector
Comment: if you have a multimeter, just measure the current the battery is supplying to the circuit with the cable in and out. And then see what happens when you take the cover off and physically remove the battery (to check if the issue is what I suggest below).
Comment: @PeterJ - I just did what you suggested and I was getting a reading  on both the green and black wires on the jack. However, I noticed that the green wire and its terminal were touching the pot that is just behind it... I twisted the wire and terminal away from the pot and now I get a reading from only the green wire, not the black
Answer: Are those bare wires soldered together that have no sleeving or insulation on them? that's just asking for trouble. They can short to just about anything intermittently. Get some heatshrink, cut the joints down a bit and insulate them.
They seem to be the wires that go to the battery connector. If they short to each other for a few seconds, there goes a big chunk of battery life right there. Or they can short to some random node in the circuit and cause it to screw up and possibly die. Whoever did that - you need to have a word with them.
EDIT : also, how is the battery physically secured when fitted? Are you sure the body isn't shorting things out, or the terminals shorting to something?
Comment: TBF, the poster said he'd removed the insulating tape from those splices before taking the photos.
Comment: OK, I didn't see that. But I wouldn't trust tape - it unwinds over time and it's just messy. Do it properly to be sure.
Comment: The battery sits in the clip that is in the top left of the first two photos (in the middle, under the wiring in the last photo.) No reading comes off of that whether the battery is physically in it or not...
Comment: what do you mean by "no reading comes off that" exactly?
Answer: As a follow up to this (in case anyone searching here ever experiences the same issue,) the culprit was indeed the input jack, as suggested by Tim. However, the issue wasn't with the switch clearing after taking out my instrument cable...
After a bit more prodding as suggested by PeterJ in the comments:

@TimBurnett-Bassist you won't get a reading at the jack because it's
  switching the negative / ground line. Put the positive of the
  multimeter on the red wire where the battery is spliced and put the
  negative to the green followed by the black wires on the jack, if you
  get a reading on both with it unplugged the circuit will be getting
  power all the time because the internal switch is stuck. – PeterJ Nov
  4 at 10:39

I noticed that part of the jack was actually touching the bottom of the pot just behind it, thereby creating the short:

@PeterJ - I just did what you suggested and I was getting a reading on
  both the green and black wires on the jack. However, I noticed that
  the green wire and its terminal were touching the pot that is just
  behind it... I twisted the wire and terminal away from the pot and now
  I get a reading from only the green wire, not the black – Tim Burnett
  - Bassist Nov 4 at 16:51

Since I've pulled the jack away from the pot so it's no longer touching, I have had no issues whatsoever with the battery draining incessantly. Thanks for all the help, folks!


index.php file for custom module

Question: i have custom software and wanna write an api for drupal (custom software -> drupal). The thing is the custom software will call api calls to index.php (you cant change that). So how can i write something like an index.php for my module, like (http://drupal.install/myhookmenulink/index.php) so the software can reach that link and send infos to my module. anyone know ?
greetings
Answer: Drupal allows calls to .php files out of the box. Take a look at the .htaccess file and you will see that .php files will be handled just like any php application.
So... just create your .php file and make sure you are including it at the appropriate path.
That all said, in D8 (or in D7 + elbow grease) you get some pretty powerful autoloader capabilities out of the box so ideally you could take advantage of that in your module.
Comment: Small caveat (I'm sure you know this but for others that may not): Drupal doesn't supersede the web server, and it's not uncommon to lock external requests for .php files down to the known 'safe' ones (/index.php, /cron.php, etc), so there's a chance some server config will be needed too. It'll be more relevant if using nginx, for example, where it's considered good practice to lock the fpm proxy down to specific files rather than *.php
Comment: So i should create a index.php file in my module folder and include the bootstrap there ? Then i could make a call to my .module functions.
Comment: It wasn't clear that's what you're trying to do from the original question, but you don't need to bootstrap anything. Just implement `hook_menu()` with a path of "path/to/index.php" and you'll have a fully bootstrapped Drupal in the callback as normal. Going out of Drupal and back in again would be a wasted step here, `hook_menu` routes can have extensions in them
Comment: oh ok i understand, thx a lot :)

index.php file for custom module


Does Drupal 7 support connecting to DB using MySQLi?

Question: I have tried to connect to Mysql DB using Mysqli by declaring 'driver' => 'mysqli' inside DB array in settings.php but I get the following error:
<code>Warning: require_once(/srv/http/my-domain/includes/database/mysqli/database.inc): failed to open stream: No such file or directory in /http/www/my-domain/includes/database/database.inc on line 1688
</code>
Thanks.
Comment: Uses PDO, better than MySQL driver and similar to mysqli
Comment: No, the file does not exist.
Answer: No. Drupal 7 does not come with Mysqli support. It only comes with PDO based drivers for MySQL, pgSQL and SQLite.
https://www.drupal.org/node/310070
https://www.drupal.org/requirements/pdo
See the files :

INSTALL.mysql.txt
INSTALL.pgsql.txt
INSTALL.sqlite.txt

to find out more about how to install using each option.
There are also many community provided solutions for connecting to other databases including MsSQL, Mongo and Oracle.
Have a look at the Drupal modules page for more information on database drivers
The core advantage of PDO over MySQLi is in its database driver support. PDO supports 10+ different drivers, opposed to MySQLi, which supports MySQL only.
If you are interested in the comparison between PDO and Mysqli there are many articles around including this one.


Tab. timing inaccuracies

Question: In a lot of tab. (for guitar/bass) there is no indication referring to timing. The numbers will obviously refer to string/fret for each note to be played, but when each note is played is somewhat vague. True, the longer notes have a wider gap between them and the next, but how long?
It's as vague as when the words of a song are written out, with chords above - no knowing whether a chord is half a bar, a bar, two bars - unless one knows the song. When arguably one doesn't need the chords - or tab., maybe.
The better tabs have an accompanying 'proper' music stave underneath, with the timing, and some do have stems and flags, so it's not all.
What about when using the little dashes, they (and the numbers) represent say 16 semis in a bar? That way, the timing could be counted with fair accuracy.
Comment: I'm not sure what your actual question is, but in my opinion anything too complicated should be notated in standard notation anyway.
Comment: Why is "tab" in all caps every time it appears in here? Also, it's not clear to me what your question is.
Comment: @ToddWilcox - 'cos it's usually in caps when it's printed! Is that a problem? We all understand, don't we? The question is in the final paragraph - 'What about'- with a question mark. Semis refers to semi-quavers - 1/16 notes. Hence the idea of using 16 in a bar. Or is there a better, more accurate way? As it all seems quite random - to me.
Comment: Why do you write "tab" in all caps?
Comment: The way this is worded, I read it as a suggestion, not a question: "What about when using the little dashes, they (and the numbers) represent say 16 semis in a bar?" Can you clarify what kind of answer you're looking for? Are you asking if that would be helpful? Seems subjective. Are you asking if that would be technically feasible? Seems trivially true. If you're asking something else, can you elaborate?
Comment: What is the question?
Comment: "Dashes", d'you mean like [ASCII tab](https://en.wikipedia.org/wiki/ASCII_tab)?
Comment: @ElementsinSpace - I mean 3----- 5-- 2---. Never used ASCII tab, knowingly!
Comment: @phoog - I explained the reason to Todd. O.k. I give in. Now ask me why there's a full stop after..!
Comment: Sorry, I read the question but not the comments before posting my comment.  It just seems as though TAB is either a trademark for an artificially sweetened cola or an acronym for something (totally awesome b...; b...; b...?  I can't think of anything!) rather than the first syllable of _tablature._
Answer: There are several problems I can think of off the top my my head with using dashes for 16th note counts like you say:
Longer notes will have too many dashes to be able to identify clearly without pausing to count, a bit painstakingly I might add.
Rests are not taken into consideration
If the subdivision changes in a piece, for example quarter or eighth note triplets that system will not work.
Tab has lines. Dashes between the lines would look confusing.
Tab should have rhythmic notation. There is no reason not to use traditional rhythmic symbols such as stems, flags and rests for rhythms in tab (TAB? I've often seen it in all caps too). You have seen it. I also have seen it many times as in the example below, which also includes traditional music notation:

I have a theory as to why this is not done in many instances.
One reason is the person creating the tab has no knowledge of how to notate rhythms.
Another reason is laziness.
CAUTION: POSSIBLE SOAPBOX MOMENT AHEAD: Another one is that I believe sometimes the use of tab has a certain element of resistance to learning music in terms of notes, keys, rhythms, etc. That is not necessarily a bad thing. I believe there is a benefit to learning how to play by ear and instinct and not being glued to a page. However, using tab exclusively is the musical equivalent of "paint by numbers".
Comment: I have a positive view of tab not always containing rhythm. To me, there are two main weaknesses to the Western European notation system, which are how pitch and rhythm are regimented and communicated. As pitch in western instruments is more or less fixed as part of their designs, the rhythmic system of Western European notation is its greater fault, IMHO. Tab without rhythm communicates pitch only, and leaves the rhythms to be learned as part of an aural/oral tradition. The advantage being that the tab learner gains understanding of subtleties of rhythm that are not easily notated.
Comment: @Tim I see using dashes as being even more problematic in those 100% typed tabs. Dashes already represent the strings, then what, more dashes for rhythms?  I don't recall where but I have seen x's for muted notes in tabs before
Comment: Regarding muted notes, every tab I've read that has muted notes, whether ascii or engraved, has used x to indicate a muted note. Here's an example: https://www.songsterr.com/a/wsa/led-zeppelin-stairway-to-heaven-tab-s27
Comment: Tab doesn't always have lines - the ones I refer to have these dashes. Dashes with no numbers in a bar would mean no note - (like what we see anyhow), and it would be easy to use x or some other note (x = muted, so not a good example!) for those rests. Just a thought. Although thinking, don't know how muted notes are portrayed.
Comment: @ToddWilcox - that's a slightly different tab, where the dots are actually shown, as are rests, which make good sense - the note duration is clear. Not what I'm concerned with.
Comment: @Tim I was just using that as a reference for x as muted string. Not for any other part of your question.
Answer: While the other answer explains how timing information can be and is included tabs, I'd like to add a different point of view. Often the tabs are not used as the only source, but instead as an aid to learn to play a song that is already been recorded. In that case the learner can listen to the original recording to get the exact timing and writing everything in the tab is not necessary. Especially ASCII art tabs tend to become difficult to read if every detail is written down.
It should be noted that the timing information in sheet music notation is inaccurate too. It describes an abstract version of the music but omits details like pushing and pulling, slight tempo changes, swing that is not exactly triplets or dotted notes, slight tempo changes, etc.
Edit: If you're interested about much more about the kind of detail I meant, one source is https://helda.helsinki.fi/items/918be3c5-987a-4a6b-b717-ecf6996a6a80 starting from page 83 (in-paper page numbers, page 95 in PDF navigation), and the sources it refers.
Comment: Could you give examples of these annotations? Suggesting that 1/16th is the smallest unit of notation doesn't sound very nuanced to me?
Comment: @Tim so did you read and understand the part about why the "proper dots" are inaccurate?
Comment: You have it backwards. Rhythmic notation provides a concrete representation of music where as the pushing, pulling, etc are the abstract concepts. On top of that, the pushing, pulling, etc is generally better understood by people who have a foundation of knowledge as opposed to people who are learning and know little to nothing about it, with the possible exception of some individuals who are savants.
Comment: @JohnBelzaguy Since the notation isn't the actual music in the air and the push-pull and audible rhythm in the air is the music that we actually hear, considering the actual music to be "more concrete" and the inaudible marks on a page to be the "abstract representation" makes a lot of sense to me. My experience contradicts your second assertion also - both my experience as a musician who is certainly not a savant and my experience with other musicians who are also certainly not savants (no offense to them!)
Comment: @ToddWilcox I appreciate your point of view but you and a few others here seem to be approaching this discussion from the point of view of people who already have a certain (and fairly advanced) level of knowledge and skill. Most people that are learning that are beginners or low level intermediate players and those concepts are over their heads and lost on them. They are working hard just trying to play notes with the correct timing and order to get the music out to think about push and pull and note durations of swing, etc. That is the point I'm trying to make.
Comment: @JohnBelzaguy Errr. Well I learned guitar from tab, and most of it had no rhythm information and the tab that had the rhythm I ignored the rhythm because it's much harder to read than the numbers. But **hearing** the rhythm and timing is much easier and now that I'm excellent at reading and writing scores I'm frustrated that it's not really possible to write the important but subtle timing that I hear in my head. You can learn to play funk by listening a **lot** easier than by reading, at least in my experience. You can easily start with the swing if you aren't aware of the "grid".
Comment: @JohnBelzaguy Another thing I've experienced is teaching beginners their first day of guitar and showing them a blues shuffle before they can read tab or notation and they can imitate the shuffle and improvise with rhythm before they can read. Timing isn't "over their heads" because it's not a head thing. It's a heart and fingers and feeling thing.
Comment: @ToddWilcox All I can say about your two comments is in my experience some can and some cannot.
Comment: @JohnBelzaguy (and Tim) I had a thought I didn't add yesterday that this answer hints toward: All systems of representing music leave out details, often intentionally, to make them more useable. At the extreme, MIDI data (or, lol, an actual waveform) communicate extreme detail about *exactly* what happens, but they would be very impractical as performance instructions. At the other end is a page that says "A, B, bridge, B," and all the rest is in the performer's head. Tab, staff notation, solfege symbols, drummers' rhythm shorthands, etc all fall somewhere in between and serve different needs.
Comment: Playing in a big band, I'm aware that most of the nuances are in fact notated. As they are in most classical orchestral pieces, so don't particularly agree here.
Comment: In the big band, we use the usual 'proper' dots, with no reflection on the aforementioned tabs, so everything is pretty well tight.
Comment: Yes, and 'proper dots' are a darn sight more accurate than tab. Which is essentially what the question addresses.
Comment: The point I was trying to make is that for the kid who's trying to learn Highway To Hell, the timing notation is pointless because they can get the basic rhythm and feel from listening the recording, and to get the exact timing how it's played, they need to listen to the recording again. On the other hand, for big band player the note durations are essential because they need the exact instructions how to play their part.
Comment: @AndyBonner I agree, there are many ways of representing music and many levels of detail that can be included or omitted and I have pretty much used them all at one point or another. The interesting thing about this rather long discussion is that it got sidetracked from:(paraphrasing): "Is this a good way to express rhythms in tab?" to "Should rhythms be included in tabs?" Unfortunately only one person can be tagged in a comment or I'd include everyone on this.

Tab. timing inaccuracies


Calculate contrasts from lme model across specified timepoints

Question: I have an MMRM with the below structure:
#la_mm2 - continuous float
#arm - 2 level factor ("2mg", "SHAM")
#t_months - continuous float
#partI_bool - 2 level factor (1, 0)
#da_bool - 2 level factor (1, 0)

linr_2mg_mm2 <- lme(la_mm2 ~ arm*t_months + partI_bool*t_months + da_bool*t_months,
                      data = test,
                      method = "REML",
                      na.action = na.omit,
                      random = ~1|pt_id,
                      correlation = corSymm(form = ~1|pt_id),
                      weights = varIdent(form = ~1|t_months),
                      control=lmeControl(msMaxIter = 200, opt = "optim"))

I want to calculate the contrasts of the model estimates within arms over time.
I've arrived at the below to get the estimates at specified times, but I can't figure out how to difference in the contrasts.
tmp <- emmeans(linr_2mg_mm2,~arm|t_months, at=list(t_months = c(0,6,12)))

#
#Output
#

t_months =  0:
 arm  emmean    SE  df lower.CL upper.CL
 2mg    9.32 0.345 150     8.64     10.0
 SHAM   9.84 0.303 150     9.24     10.4

t_months =  6:
 arm  emmean    SE  df lower.CL upper.CL
 2mg   10.32 0.355 150     9.62     11.0
 SHAM  11.14 0.313 150    10.52     11.8

t_months = 12:
 arm  emmean    SE  df lower.CL upper.CL
 2mg   11.33 0.385 150    10.57     12.1
 SHAM  12.44 0.339 150    11.77     13.1

Results are averaged over the levels of: partI_bool, da_bool
Degrees-of-freedom method: containment
Confidence level used: 0.95

The closest I've come to obtaining contrasts as desired is the below, but this is only returning the mean estimate for the "2mg" group at each of the time points:
tmp.c <- contrast(emmeans(linr_2mg_mm2, ~arm|t_months, at=list(t_months = c(0,6,12))), list(my.con = c(1,0)))

#
# Output
#

t_months =  0:
 contrast estimate    SE  df t.ratio p.value
 my.con       9.32 0.345 150  27.038  <.0001

t_months =  6:
 contrast estimate    SE  df t.ratio p.value
 my.con      10.32 0.355 150  29.061  <.0001

t_months = 12:
 contrast estimate    SE  df t.ratio p.value
 my.con      11.33 0.385 150  29.401  <.0001

Results are averaged over the levels of: partI_bool, da_bool
Degrees-of-freedom method: containment

I've tried the "pairwise" approach as below but this reports contrasts across arm at a specified time.
> contrast(tmp, "pairwise")
t_months =  0:
 contrast   estimate    SE  df t.ratio p.value
 2mg - SHAM   -0.528 0.389 150  -1.358  0.1766

t_months =  6:
 contrast   estimate    SE  df t.ratio p.value
 2mg - SHAM   -0.820 0.401 150  -2.046  0.0425

t_months = 12:
 contrast   estimate    SE  df t.ratio p.value
 2mg - SHAM   -1.112 0.434 150  -2.559  0.0115

Results are averaged over the levels of: partI_bool, da_bool
Degrees-of-freedom method: containment

Overall I'm trying to calculate:
(2mg at 12 months - 2 mg at 0 months) - (SHAM at 12 months - SHAM at 0 months)
Answer: You can do
contrast(tmp, "pairwise")

or justpairs(tmp). I suggest looking at some of the vignettes vignettes that accompany the package, for example vignette("basics", "emmeans"). There are lots of examples.
Note: The my.con "contrasts" shown in the OP are just the first of the two means, because the linear function specified is 1 times the first plus 0 times the second.
Comment: ``` contrast(tmp, "pairwise")```

Produces the below output, which is contrasting one arm versus the other (e.g., 2mg-SHAM). What I am trying to do is  calculate:

(2mg at month 12 - 2mg at baseline) - (SHAM at month 12 - SHAM at baseline)

So I'm looking for a way to calculate contrasts within the same arm across time.
Comment: ```
t_months =  0:
 contrast   estimate    SE  df t.ratio p.value
 2mg - SHAM   -0.528 0.389 150  -1.358  0.1766

t_months =  6:
 contrast   estimate    SE  df t.ratio p.value
 2mg - SHAM   -0.820 0.401 150  -2.046  0.0425

t_months = 12:
 contrast   estimate    SE  df t.ratio p.value
 2mg - SHAM   -1.112 0.434 150  -2.559  0.0115

Results are averaged over the levels of: partI_bool, da_bool
Degrees-of-freedom method: containment
```
Comment: pairs(tmp, by = "arm")
Comment: Or switch sides of the `|` when creating `tmp`


How to reason that $n^5 - n$ is divisible by 2 as proof for a consequence of Fermat's little theorem.

Question: In my text book on Discrete Mathematics (I), we have a chapter that covers a bit of elementary Number Theory. In it we see the famous Theorem of Euler as well as the derived little theorem of Fermat. I understand these theorems and even the proofs that are given for them in my text book. There is however a specific step in the proof given for Fermat's little theorem that I do not understand. For the sake of completeness I'll write both the resulting theorem (derived from Fermat's little theorem) and its proof here as written in my text book.
$$
\forall n \in \mathbb N^* : n \text{ and } n^5 \text{ always end on the same digit.}
$$
The proof goes as follows.
Because Fermat's little theorem we know that
$$
\begin{equation}
\begin{aligned}
n^5 &\equiv n \ (\text{mod } 5) &\Leftrightarrow \\
n^5 - n &= 5q &\Leftrightarrow  \\
5\ &|\ (n^5 - n).
\end{aligned}
\end{equation}
$$
On the other hand
$$
n^5 - n = n(n-1)(n^3+n^2+n+1). \ \ \ \ \ \ \ \ \ \ \ \ \text{(a)}
$$
As both $2$ and $5$ are divisors of $(n^5 - n)$ we can conclude that
$$
n^5 \equiv n\ (\text{mod } 10). \ \ \ \ \ \text{QED}
$$
I understand the given result as well as the theorems it build upon. I also can easily see that $5$ is a divisor of $(n^5 - n)$. As I keep the target in mind I also can figure out that the only missing part of this proof would be to figure out a way to show that $2$ is also a divisor of $(n^5 - n)$.
At first equation $(a)$  did not make any sense to me. After checking the case where $n$ is odd as well as the case where $n$ is even, I did find out that the equation results in an even number in both cases.
My question, sorry for the very long introduction, goes as follows:
Should I wanted to have proven this myself. What approach would have lead me to trying to factor $(n^5 - n)$ to the given equation $(a)$? In fact while it is easy fo to factor from right to left in that equation, I do not easily see how one would go from left to right? Probably I am missing some fundamental mathematical knowledge here. Can anyone please help me figure out how would exactly figure that out? Is it trial and error? Is it just knowing some specific concepts? What knowledge am I missing here?
Comment: $n^5-n=n(n^4-1)=n(n^2+1)(n^2-1)=n(n^2+1)(n+1)(n-1)$
Comment: I think the book was assuming it was well known that $(x^k-1) = (x-1)(x^{k-1} + x^{k-2}+ ..... + x + 1)$. (It *is* well-known. Take a moment to play with it.  You will see it a *lot* in the future.  Obviously the first thing to try to factor out of $n^5 - n$ is the $n$ so $n^5 - n = n(n^4 -1)$.  Then we use the formula and get $n^4 - 1) = (n-1)(n^3 + n^2 + n + 1)$.  The book doesn't care about $n^3 + n^2 + n+1$ (which *can* be furthered factored).  It just cares about $n$ and $n-1$.  One of those must be even so the whole thing must be even.
Comment: "Factoring from right to left" would be called *distributing* (or some might say "FOILing"), not factoring. There are many techniques for factoring. In this case, we used a special case formula (which are factoring formulas that only work in special cases), which are generally difference of squares, sum/difference of cubes, and perfect square trinomials. (There is a homogenized geometric sum formula which generalizes the difference of powers formulas, generalized much further by cyclotomic polynomials, and the binomial theorem generalizes the perfect square formula.)
Comment: For quadratics, there is the "$ac$-method" if it factors with integers else the quadratic formula. There are methods for solving cubics and quadrics, which are still elementary and hand-doable but are cumbersome, but in some cases factoring-by-grouping works. Generally there is no way to solve fifth-degree or higher with radicals.
Answer: This is trivial:

If $n$ is odd, is $n^5-n$ odd or even?
If $n$ is even, is $n^5-n$ odd or even?
Comment: @glendc: if $n$ is odd, then $n^5$ is also odd, right? And the difference of two odd numbers is even. It's that simple.
Comment: $\mod 2$ is presumed to be near trivial.  Either $a\equiv 0$ or $a \equiv 1\pmod 2$.  It follows that $a^k\equiv a\pmod 2$.  Also $a + a\equiv 0 \pmod 2$ always.  (THat's not useful here but arithmetic on $\mathbb Z_2$ is supposed to be *very* easy.
Comment: Thank you for these follow up questions. You are absolutely correct with your hints, if I straight up calculate on paper both cases, using the substitutions $n = 2k$ (case 1) and $n = 2k + 1$ (case 2), I do indeed get that $n$ is even in both cases. I do have to say that while calculating case (1) was easy, computing case (2) was quite tedious and involved some combinatorics.

So while I am happy that asking myself these questions would have given me the answer as well. I do think that if time is of the essence it would be nice to know a quicker approach.
Answer: 1) Also by fermat  $n^2 \equiv n \pmod 2$. so $n^5\equiv n^4\equiv n^3\equiv n^2 \equiv n\pmod 2$ so $n^5-n\equiv 0 \pmod 2$.
2) In simpler explanation of 1)  $n$ is either equiv $1$ or $0\pmod 2$.  If $n\equiv 1\pmod 2$ then $n^5-n\equiv 1-1\equiv 0\pmod 2$ and if $n\equiv 0 \pmod 2$ then $n^5 -n\equiv 0 \pmod 2$.
3) But what the text is doing is factoring $n^5 -n = n(n^4 - 1)=n(n^2-1)(n^2+1) = n(n-1)(n+1)(n^2 + 1) = n(n-1)(n^3 + n^2 + n+1)$.
The $n^3 + n^2 + n+1$ will not be relevant.
But $n$ and $n-1$ are.  One of them must be even.  And if one of them is even the entire product is even.
Bear in mind "$n\equiv 0 \pmod 2$" and "$n$ is even" are the exact same statements.
=====
Arithmetic on $\mod 2$ is presumed to be very easy.
Keeping in mind $n\equiv 0 \pmod 2 \iff n$ is even and $n\equiv 1\pmod 2 \iff n$ is odd;
We actually learned everything there is to know about $\mod 2$ in elementary school when we learned:
$even\times even = even$
$odd\times even = even$
$odd \times odd = odd$
$even + odd = odd$
$even + even = even$
$odd + odd = odd$.
That is EVERYTHING you need to know.
.....
$n^k;k > 0$ is either $even^k=even$ or $odd^k=odd$.  Either way:  $n^k \equiv n\pmod 2$.
Answer: There is already one answer, however you can use fermat's little theorem in the following way:

Fermat's little theorem states that if $a$ and $p$ are coprime, then $a^{p-1}\equiv 1(\text{mod} p)$ (and as fleablood pointed out $a^{p}\equiv a(\text{mod} p)$, whenever p is prime)

As a result, $n^5\equiv n\cdot (n^2)^2\equiv n^2\equiv n(\text{mod} 2)$, so $n^5-n\equiv 0(\text{mod} 2)$ and so your desired result follows
Comment: This is true if the *aren't* coprime too.  If $\gcd(a,p)\ne 1$ then as $p$ is prime, $p|a$ and $a\equiv 0\pmod p$ and $a^p\equiv a\pmod p$ is trivially true.  But if $\gcd(a,p)=1$ then $a^{p-1}\equiv 1\pmod p$ and $a^p\equiv p \pmod p$.  So for primes $a^p \equiv a\pmod p$ will always be true no matter the $a$.
Comment: @fleablood You're right, I edited it. Thank you very much
Answer: If $n$ is even, then $n = 2k$ with $k\in Z$. Substituting, I obtain: $32k^5-2k$; in other words $2k(16k^4-1)$. This is always divisible by $2$.
If $n$ is odd, then $n=2k+1$ with $k\in Z$. Substituting, I obtain: $(2k+1)^5-2k-1$; in other words: $32k^5+16\cdot5k^4+10\cdot8k^3+10\cdot 4k^2+5\cdot 2k+1-2k-1=32k^5+80k^4+80k^3+40k^2+8k=2k(16k^4+40k^3+40k^2+20k+4)$  that is still divisible by 2.
Comment: this way is error-prone:  should be $\color{red}{...+40k^2+10k...}$
Comment: Seems very difficult as we don't care about *any* of the arithmetic calculations you labored through;  We only care if the results are even or odd.
Comment: @J.W.Tanner it's my error. Sorry.
Comment: @fleablood my calculations can be used to show that the result of that expression is always even.
Comment: Yes but it seems like a lot of work to get there.
Comment: @fleablood if you don't want to use $mod$ rules, this is an esay and very clear way.
Comment: Thank you for your time @matteo, as suggested by my comment on tonyk's answer, I indeed also took a perhaps naive approach such as this one, after he suggested those hints. It is a lot of work, but it does indeed work and did so fo me.
Answer: To factor $n^5-n$, first factor out $n$:  $n^5-n=n(n^4-1)$.
Now use difference of squares:  $n^4-1=(n^2+1)(n^2-1)$.
And again:  $n^2-1=(n+1)(n-1)$.
Putting it all together, $n^5-n=n(n^2+1)(n+1)(n-1)$.
If $n$ is even, then $n^5-n$ is even, since a product with an even factor is even.
If $n$ is odd, then $n\pm1$ is even, so $n^5-n$ is even.
Comment: Alternatively there is the $(x^k-1) = (x-1)(x^{k-1} + .... + 1)$ rule.  Which is what the book did.  I personally prefer to put off using if $k$ is composite as it is hard to see if $(x^{k-1}+.... +1)$ is factorable.
Comment: @fleablood:  That works too, but OP tagged and asked about factoring, so I did; my factorization could show, for example, that $3$ divides $n^5-n$, though that's not needed for this particular problem
Answer:
For the factorisation: it results from high-school well known formulæ:
$$n^5-n=n(n^4-1)=n(n^2-1)(n^2+1)=n(n-1)(n+1)(n^2+1)=n(n-1)(n^3+n+n^2+1).$$
For divisibility by $2$: let's use congruences modulo $2$.
Lil' Fermat says that, for every $n$, $n^2\equiv n\bmod 2$, so $n^4\equiv n^2\equiv$ and ultimately $\;^5=n\cdot n^4\equiv n\cdot n\equiv n$, so $$n^5-n\equiv n-n=0\mod 2.$$
Answer: $$2x+2x=2y;2x+1+2x+1=4x+2=2z;2x+2x+1=4x+1=2y+1$$
from theses you can prove multiplication rules like odd times odd is odd. and if that second number is the same as the first, that's exponentiation if repeated. A power has the same parity as it's base can then be proved. $n$ is our base in $n^5$.


Javascript confirm validation form

Question:
I need to ask the confirmation to leave two fields in the form blank with javascript.. here there is the example
Teory
Field1: Blank; Field2: Blank; Field3: Blank;
return false if the field1 in empy; ask confirmation for the other 2 such as "are you sure you want to leave the field #.. blank?" > if press ok, check the field3 otherwise return false
code
var field1 = document.form.field1.value;
var field2 = document.form.field2.value;
var field3 = document.form.field3.value;

if ((field1 == "") || (field1 == "undefined")) {
       alert("Cannot leave field1 blank");
       document.form.field1.focus();
       return false;
    }

     else if ((field2 == "") || (field2 == "undefined")) {
     var x = confirm("Are U sure to leave field2 blank?");
  if (x)
      return true;
  else
    return false;
    }

var y = confirm("Are U sure to leave field3 blank?");
  if (y)
      return true;
  else
    return false;
    }

        else {
       document.form.submit();
    }

Of course it doesn't work... any ideas?
Thanks
Comment: Ofcourse you've to tell us what exactly is going wrong, "it doesn't work" is not a problem description. Apart from that, how have you defined `document.form`, it's not a native DOM property. Are you after [`document.forms`](https://developer.mozilla.org/en-US/docs/Web/API/Document/forms) collection?
Comment: Can you include the HTML associated with this form?
Comment:
Comment: Your code has an odd number of braces.  The bottom section contains the extra close brace - what's going on here?
Comment: Doesn't work means that if both field2 and field3 are empty the form does NOT submit but I only have the confirmation message for the field2...
Comment: @raduation yeah because I cut some example from the entire form.. the brace is because of the function "Save"    function Save() {
Comment: Looks like you inadvertently left a closing curly brace, }, in the code just before your second confirmation, "Are U sure to leave field3 blank?"
Comment: Please post some complete, runnable code.
Answer: I have quickly rewritten your js. I hope it will help you out.

var form = document.getElementById("myform");
var field1 = form.field1;
var field2 = form.field2;
var field3 = form.field3;

if (form.attachEvent) {
    form.attachEvent("submit", formValidation);
} else {
    form.addEventListener("submit", formValidation);
}

function formValidation(e) {
    if (e.preventDefault) e.preventDefault();

    if ((field1.value == "") || (field1.value == "undefined")) {
        alert("Cannot leave field1 blank");
        field1.focus();
        return false;
    }

    else if ((field2.value == "") || (field2.value == "undefined")) {
        var x = confirm("Are U sure to leave field2 blank?");
        if (!x) {
            field2.focus();
            return false;
        }
    }

    else if ((field3.value == "") || (field3.value == "undefined")) {
        var y = confirm("Are U sure to leave field3 blank?");
        if (!y){
            field3.focus();
            return false;
        }
    }

    else {
        console.log("sending");
        form.submit();
    }
};
<form action="" id="myform" method="POST">
    <input type="text" id="field1" name="field1">
    <input type="text" id="field2" name="field2">
    <input type="text" id="field3" name="field3">
    <input type="submit" value="send">
</form>
Comment: Thanks but I have three different button on my form executing 3 different submit.. this is why I prefer using the button instead. I can post you the entire form later..
Answer: Finally I solved thanks to a suggestion from yesterday (I can't see the message anymore?!)..
If someone need, the solution that works for me is below:
$ret = false
if ((field2 == "") || (field2 == "undefined")) {
   var x = confirm("Are U sure to leave field2 blank?");
if (x) {
  $ret = true;
}
}

if ((field3== "") || (field3== "undefined")) {
if (confirm("Are U sure to leave field3 blank?")){
  $retu = true;
}
}

if ( ($ret == true) && ($retu == true) ) {
document.form.submit();
    }

Thanks to everyone who help finding the solution!

Javascript confirm validation form


How to make/build project against one version of a library but its dependencies against a different version of that library?

Question: I have workspace structure as shown below. It involves PROJ for project, TPL for third party library and DEP-PROJ for dependency project (and ws for workspace). I have also specified their dependencies inside brackets, next to them.
ws
├── opencv34
│   ├── opencv
│   └── opencv_contrib
├── opencv44
|   ├── opencv
|   └── opencv_contrib
├── DEP-PROJ (opencv 3.4)
└── PROJ (DEP-PROJ, opencv 4.4)
    └── TPL (opencv 4.4)

I have built both versions of opencv with cmake .. and make -j6 commands. But did not run make install.
Next, DEP-PROJ has following lines in its CMakeLists.txt (notice OPENCV3_DIR):
set(OpenCV_DIR $ENV{OPENCV3_DIR})
find_package(OpenCV 3.4 REQUIRED)

Before doing cmake in DEP-PROJ/build directory, I run export OPENCV3_DIR=/ws/opencv34/opencv/build, so that cmake succeeds.
Next, PROJ has following lines in its CMakeLists.txt (notice OPENCV4_DIR):
set(OpenCV_DIR $ENV{OPENCV4_DIR})
find_package(OpenCV 4.4 REQUIRED)

Next, before doing cmake in PROJ/build directory, I run export OPENCV4_DIR=/ws/opencv34/opencv/build, so that cmake succeeds.
Before doing cmake in PROJ/build directory, I run export OPENCV4_DIR=/ws/opencv44/opencv/build, so that cmake succeeds.
This cause cmake to succeed, but make fails with error:
fatal error: opencv/cv.h: No such file or directory

It seems that doing make inside PROJ rebuilds DEP-PROJ. However, CMakeLists.txt of PROJ sets OpenCV_DIR to opencv44 directory. This makes DEP-PROJ build fail giving above error.
To avoid this, I run make install inside /ws/opencv34/opencv/build. This lets DEP-PROJ find opencv 3.4 from /usr directory and PROJ references opencv 4.4 from /ws/opencv44/opencv/build directory leading to successfully building PROJ.
However, I feel its a bit hacky way to resolve this (doing make install in opencv 3.4 and not doing it in opencv 4.4). What is correct way to do this? How can I avoid rebuilding DEP-PROJ while building PROJ? or build it against /ws/opencv34/opencv/build (instead of opencv in /usr) along with building PROJ against /ws/opencv44/opencv/build?
PS: I am noob in cmake.
Comment: [...] It is also possible that `PROJ` and `DEP-PROJ` need to exchange data structures that differ based on the OpenCV version.  If you were lucky, this would manifest as a compile-time error, but if you were unlucky it could manifest as mysterious, weird runtime behavior.
Comment: without reading the entire question, let's say A depends on B and C2, but B also depends on C1. do you expect to run a single build that does everything, or do you build B ***separately***, so you can then ***use*** it in the build of A?
Comment: ***will hard coding path in DEP-PROJ's CMakeLists.txt help[...]?*** -- it might help get a successful build.  It would not at all address any of the overall issues with dual OpenCV dependencies.  ***Can CMake's `ExternalProject_Add` module help use independently built `DEP-PROJ` while building `PROJ`?*** -- probably not.  It might change the nature of the build dependency, but it does not get you an independent build.
Comment: this is not specific to opencv. this is a general problem of *dynamic linking*. with static linking, this would be a non-issue. however, legal issues prevent many libraries from being linked statically.
Comment: But there has to be some cmake config or something else, that is usually used to solve such things?
Comment: Anything works for me. I first built B separately. It worked. But then while building A, it fails with error: `opencv/cv.h: No such file or directory`. Turns out that function is there in C1, but not in C2. Ideally, it should NOT have tried to build B again against C2 as a part of building A, instead it should have used already built B while building A. But that does not seem to happen.
Comment: There are multiple possible link issues here, @ChristophRackwitz, but none of them cause the particular *compilation* error the OP reports.
Comment: @MsA, chances of making this work are poor, but what chances there are are tied up in the details of the software and build system.  It's unlikely that you can put those in a form suitable for an SO question.  Your best bet is to figure out how to use the same version of OpenCV for everything.  Your next best bet is probably to build the dependency independently, but there are multiple reasons why that might not suffice.  You should consider engaging an expert to work on this project, and I don't mean by asking questions here.
Comment: @JohnBollinger the error `opencv/cv.h: No such file or directory` seems related to linking since cv.h is there in OpenCV 3 and no more there in OpenCV4. So it seems `DEP-PORJ` indeed seem to get re-compiled against OpenCV4 while building `PROJ`. **Q1.** Does this detail help to imagine any solution? I indeed tried to build `DEP-PROJ` with OpenCV 4. But it did not. I tried to replace imports for cv.h with equivalent header in OpenCV 4, but then it resulted in cascaded code changes. So, making `DEP-PROJ` work with OpenCV 4 does not seem to be easy task. (continued ...)
Comment: (... continued) Regarding "build the dependency independently", I am indeed able to build `DEP-PROJ` independently with OpenCV 3, but during building `PROJ`, it seems to rebuild `DEP-PROJ` against OpenCV 4. **Q2.** Is this normal / default CMake behavior, or am missing somethin? How do I fix this? that is, make `PROJ` build use `DEP-PROJ` already built against OpenCV3 instead of rebuilding it against OpenCV4. Any hint / web link  discussing related CMake config? **Q3.** Regarding " there are multiple reasons why that might not suffice" - any detail / quick hint / web link discussing the same?
Comment: @MsA, headers such as `opencv/cv.h` are processed by the compiler, not the linker. They are not involved in linking.  This has nothing to do with whether one project is rebuilt during the build of the other.
Comment: @MsA, when I suggest building `DEP-PROJ` independently, I mean to imply that you also persuade the build of `PROJ` to *use* that independently-built result instead of rebuilding.  How you might do that depends on your tools, but it might involve installing `DEP-PROJ` to the system.
Comment: @MsA, there is no particular "normal CMake behavior" at the level of abstraction at which you are describing your problem.  CMake is a program that does what you tell it to do.
Comment: Reasons why using an independently built `DEP-PROJ` might not suffice all revolve around lack of build-time and / or run-time isolation of the two versions of OpenCV.  Whether the OpenCV libs are built as shared or static libraries, there are several patterns of details that could lead to one project trying to call the functions of the wrong OpenCV version at runtime.  It is also possible that `DEP-PROJ` `#include`s `opencv/cv.h` in its own public headers, which `PROJ` needs to use, thereby making that file required regardless. [...]
Comment: I never said or supposed that it would be easy to upgrade `DEP-PROJ` to OpenCV 4.  If it's *your* project then that might nevertheless be worthwhile.  If not, then perhaps someone else has already done so.  And if not that, then maybe you should look for an alternative.
Comment: Yes difference in OpenCV data structures will be deal breaking issue. Super thanks for all detailed inputs. Couple of last questions: **(1)** Though I dont like hard coding, will hard coding path in `DEP-PROJ`'s CMakeLists.txt help: `find_package(OpenCV 3.4 REQUIRED PATHS /ws/opencv34/opencv/build)`? **(2)** Can CMake's `ExternalProject_Add` module help use independently built `DEP-PROJ` while building `PROJ`? (cmake noob again)
Answer: TL;DR: mixing multiple versions of a single library in the same process on UNIX doesn't work, just give up!

You appear to be building for UNIX.
Unlike on Windows, a UNIX shared library is not self-contained -- it is subject to symbol interposition and symbol collisions.
Also, OpenCV versions 3.4 and 4.4 define the same symbols, and are not ABI-compatible.
Taken together the two statements above mean that IF you manage to link your project dynamically with versions 3.4 and 4.4 of OpenCV, you are almost guaranteed to have inexplicable crashes, memory corruption, and more.
(If you try to link your project with archive versions instead, you will most likely fail with multiple symbol definition instead.)


Attribute 'skipFirstLine' is not allowed to appear in element 'csv'

Question: I'm trying to use the skip first line and use maps in camel. I'm on version 2.17 or 2.17.0.redhat-630310 - it doesn't appear to work??? also, looking for how to use the use set maps option in xml dsl? thank you!
<route>
  <from uri="direct:start" />
  <unmarshal>
    <csv skipFirstLine="true" />
  </unmarshal>
</route>

gives
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'skipFirstLine' is not allowed to appear in element 'csv'.

Also, can the csv.setUseMaps feature be used in the XML DSL ? thanks again!
Answer: Option skipFirstLine was removed in Apache Camel 2.15. Use skipHeaderRecord in Apache Camel 2.15 and newer. Refer CSV DataFormat documentation for more details about available options.
But since you are going to use useMaps option, skipHeaderRecord have no effect and you don`t need it.
This should be enough:
<unmarshal>
 <csv useMaps="true" />
</unmarshal>

Comment: thank you again Bedla, I greatly appreciate your help, this is a great mentoring site also for us newbies. still trying to figure out how to accept answers?  not obvious unless i need new glasses. :)
Comment: @GLMills Still not accepted :-) Maybe this tutorial can help [How to update and accept answers](https://meta.stackoverflow.com/questions/251078/how-to-update-and-accept-answers)? Or this animation [What does "accepting an answer" mean? How do I do it?](https://meta.stackexchange.com/a/65088/389339)


Máscara em tabela Ajax

Question: Possuo um autoComplete que desenvolvi, onde ao digitar algum valor, o sistema retorna uma tabela com os dados desse autoComplete.
Essa tabela está sendo retornada via Ajax. Porém, gostaria de adicionar uma máscara em um campo.
Esta é minha função:
function CarregaCadastroImobiliario(elementoInput, elementoDiv, elementoModal) {
$(elementoInput).keyup(function () {
    var texto = $.trim($(this).val()),
        elemento = $(elementoDiv),
        tabela = "",
        linhas = "";

    elemento.html("");

    if (texto.length > 0) {
        tabela += '
'
        tabela += '
'
        tabela += '
'
        tabela += '            Inscrição	'
        tabela += '            Cadastro Imobiliário	'
        tabela += '            Logradouro	'
        tabela += '            Nº	'
        tabela += '            Complemento	'
        tabela += '            Bairro	'
        tabela += '            	'
        tabela += '
'
        tabela += '
'
        tabela += '

'
        tabela += '
'

        $(elemento).append(tabela);
        var tblCadastroImobiliario = $("table#tblCadastroImobiliario");

        $.ajax({
            type: "GET",
            cache: true,
            url: BASE_URL + "Endereco/BuscaCadastroImobiliario",
            data: { CadastroImobiliario: texto },
            dataType: "json",
            timeout: 5000,
            success: function (data) {
                $.each(data, function (i, item) {
                    linhas += "
";
                    linhas += "  " + item.cdChaveInscri + "	";
                    linhas += "  " + item.nmCadastroimobiliario + "	";
                    linhas += "  " + item.nmLogradouro + "	";
                    linhas += "  " + item.nrImovel + "	";
                    linhas += "  " + item.dsComplEndereco + "	";
                    linhas += "  " + item.nmBairro + "	";
                    linhas += "  ";
                    linhas += "    <button onclick='javascript:SelecionaCadastroImobiliario(\"" + item.nmCadastroimobiliario + "\", \"" + elementoModal + "\");' class='btn btn-primary btn-xs'></button>";
                    linhas += "  	";
                    linhas += "
";
                });
                tblCadastroImobiliario.children("tbody").append(linhas);
            },
            beforeSend: function () {
                tblCadastroImobiliario.hide();
            },
            complete: function () {
                if (linhas.length > 0) {
                    tblCadastroImobiliario.show();
                } else {
                    tblCadastroImobiliario.remove();
                }
            }
        });

    }
});
}

Tentei algo como:
linhas += "  " + item.cdChaveInscri.mask("99.99.999.9999.999") + "	";
// ou
linhas += "  " + item.cdChaveInscri.maskInput("99.99.999.9999.999") + "	";.

Porém, creio que não seja possível utilizar dessa forma, recebendo assim um erro no console.

Uncaught TypeError: item.cdChaveInscri.mask is not a function

Tentei utilizar o Jquery Mask Input. Porém, sem sucesso.
         linhas += "   " + item.cdChaveInscri + "	";
  complete: function () {
                    if (linhas.length > 0) {
                        tblCadastroImobiliario.show();
                            $("label.Inscricao").mask("99.999.999/9999-99", { reverse: true });
                        console.log(id);
                    } else {
                        tblCadastroImobiliario.remove();
                    }
                }

Comment: Esse `.maskInput()` é o quê? jQuery? teu? ou queres dizer que é assim que queres aplicar?
Comment: @Sergio eu não trabalho muito bem com ajax. Foi uma opção que apareceu na IDE, que testei para ver se funcionava.
Answer: Utilizei o Replace()  para isso. Onde eu passo o para minha variável a forma de apresentar os valores.
Ficou assim minha tabela:
  linhas += "  " + item.cdChaveInscri.replace(/^(\d{2})(\d{2})(\d{3})(\d{4})(\d{3}).*/, "$2.$2.$3.$4.$5") + "	";

Máscara em tabela Ajax


Prove that $\sum\limits_{cyc}\left(\frac{a+b}{a+b+c}\right)^2\geq\frac{16}{9}$

Question: Let $a$, $b$, $c$ and $d$ be positive numbers. Prove that:
$$\left(\frac{a+b}{a+b+c}\right)^2+\left(\frac{b+c}{b+c+d}\right)^2+\left(\frac{c+d}{c+d+a}\right)^2+\left(\frac{d+a}{d+a+b}\right)^2\geq\frac{16}{9}$$
I tried C-S and more, but without success.
I am looking for an human proof, which we can use during competition.
Comment: Did you try the following substitution: $x =a+b+c, y = b+c+d, z = c+d+a, t = a+b+d$, and solve for $a, b, c,d$ in terms of $x,y,z,t$ to "kill" the denominators ?
Comment: @Gribouillis equal to 1 is not needed
Comment: I understand that you are an aficionado of inequalities. May I ask you how/where do you find new ideas almost every week ?
Comment: With computer, BW kills it. Michael Rozenberg knew this.
Comment: haha. proof is surely written and analysed by a human. even a robot was programmed by a human first in order for it to solve the problem.
Comment: @DeepSea If so $a=\frac{x+z+t-2y}{3}$, which can be negative and we get four new conditions.
Comment: Actually @DeepSea idea is a very good one. It leads to great simplification
Comment: @Eugen Covaci Your are welcome to show us your proof.
Comment: 16/9 is reached when $a=b=c=d$
Answer: HINT
Using substitutions $x =a+b+c, y = b+c+d, z = c+d+a, t = a+b+d$ we get $$(\frac{a+b}{a+b+c})^2=\frac 1 9(2 + \frac t x - \frac y x -\frac z x)^2$$
Similar for the other terms. Eliminate the squares then use the fact that $r + \frac 1 r \ge 2, r \gt 0$.
Comment: Show please, how you use $r+\frac{1}{r}\geq2$. Thank you!


Mobile number validation for webforms

Question: I am looking for a way to easily implement an Integer field with webforms that can do mobile number validation (US numbers only). I am aware of http://drupal.org/project/webform_validation that can do numeric validation but looking for a more direct solution. If its a hook, that works as well.
Answer: You can do a hook_form_alter of your form, and add your own validation to it.
<code>function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'NAME_OF_FORM') {
    $form['#validate'][] = 'YOURMODULE_VALIDATE_FUNCTION';
  }
}

function YOURMODULE_VALIDATE_FUNCTION( $form, &$form_state ) {
  $mobile = $form_state['input']['field_MOBILE']['und'][0]['value'];
  $is_valid_mobile = YOUR_AWESOME_MOBILE_VALIDATOR($mobile);
  if( !$is_valid_mobile ) {
    $error_msg = 'Mobile is invalid. Please enter a valid mobile number e.g xxx-yyy.';
    form_set_error('field_MOBILE', t($error_msg));
    return false;
  }
}
</code>
Comment: I installed the webform_validation module. Would this code change in any way now since we have some additional validations we can do with that. Thanks.
Comment: When doing the hook_form_alter you are adding a validate function to the array: $form['#validate'][]
That means it will not overwrite any other validations, but also add one on top of it.
Comment: Never done a hook_form_alter hence asking. Does a hook_form_alter applies to webform as well?
Answer: Telephone numbers are not integers. For example they begin with a zero in Germany, which is meaningless for integers but significant when dialing. A string field would be more appropriate.
You will also have to think about what quality of validation you need:

The number looks like a telephone number
The number looks like a telephone number that belongs to a cellphone
The number is currently assigned to a cellphone.

In all cases, the way to go is a validation function as per Danno's suggestion. For 2, you need information from the ITU and its members. For 3, sending an SMS with a validation code is probably the most effective way (although some landline phones can receive SMS).
Comment: Hmm, will add that I am looking to validate only US numbers so that might reduce a bunch of cases for validating phone numbers. Also, my concern is more about getting numbers that look like phone numbers rather than some one adding 1234567890 which is not a phone number. Thanks for the input though.
Answer: Mobile number module (that I wrote) supports webforms and has a component for validating mobile numbers of any country. It is based on the libphonenumber composer library.

Mobile Number is a field type that provides mobile number validation and verification, and can be used for two factor authentication.
Comment: @pierre.vriens why are you editing all my answers?
Comment: I wanted to help ( ie ensure your answer would not get deleted because of not respecting some basic requirements on this site) ... you seem to not like that, so I performed a rollback. Feel free to reuse anything of my prior edit if you want (no credits due ...).
Comment: Module authors that provide the exact needed solution are not allowed talk about their module?
Comment: Also I would be happy to see the site's requirements as I can't find them.
Comment: @NirYariv If you are the module maintainer, we would like it if you mention it when you recommend your own module.  Also, it helps to provide a brief overview of how the module will provide a solution rather than just a link to the module.  Thanks.
Comment: See also [How to not be a spammer](https://drupal.stackexchange.com/help/promotion).

Mobile number validation for webforms


inserir valor em uma requisição de dados Json

Question: preciso escrever uma função que acesse um campo especifico dentro de um arquivo Json. Os campos do Json estão listados como id1, id2, id3... e o valor a ser acessado será passado pela própria função. A minha questão fica mais clara observando o código a seguir:
Javascript
function myFunction (x) {
    fetch ('dados.json')
    .then(function(response){
        return response.json();
    })
    .then(function(data){
        console.log("data.id" + x)
    })
}

Json
{
    "id1":{
            "nome": "João",
            "sobrenome": "Medeiros"
          },
    "id2":{
            "nome": "Mário",
            "sobrenome": "Freitas"
          },
    "id3":{
            "nome": "Joana",
            "sobrenome": "Cunha"
          },

No código acima o valor retornado no console é uma string, como eu faço para retornar o campo correspondente ao valor fornecido por X.
Desde já, agradeço.
Comment: Veja se é isso: `console.log(data["id"+x])`
Comment: Funcionou. Valeu!
Answer: id1 é o nome de uma propriedade do objeto expresso em dados.json. Assim sendo você pode acessar seu valor via bracket notation, ou notação em colchetes:
function myFunction (x) {
    fetch ('dados.json')
    .then(function(response){
        var data = response.json();
        var valor = data['id' + x];
        console.log(valor);
    })
}

Answer: Acesse como se fosse um índice:

var x = {
    "id1": {
            "nome": "João",
            "sobrenome": "Medeiros"
          },
    "id2":{
            "nome": "Mário",
            "sobrenome": "Freitas"
          },
    "id3":{
            "nome": "Joana",
            "sobrenome": "Cunha"
          }
        };

var num=1

console.log(x["id"+num].nome);