Limit of a Riemann sum: $\lim_{n\to\infty} {n^5 \sum^n_{r=0}\frac1{(n^2+r^2)^3}} $

Question: Required to find
$\lim_{n\to{\infty}} {n^5 \sum^n_{r=0}\frac{1}{(n^2+r^2)^3}} $
$\lim_{n\to{\infty}} \frac{1}{n} \sum^n_{r=0}(\frac{n^2}{n^2+r^2})^3$
$\lim_{n\to{\infty}} \frac{1}{n} \sum^n_{r=0}(\frac{1}{1+\frac{r^2}{n^2}})^3$
$\lim_{n\to{\infty}} \frac{1-0}{n} \sum^n_{r=0}f[0+r(\frac{1-0}{n})]$, where $f(x)=(\frac{1}{1+x^2})^3$.
Since $f(x)$ is continuous on $]0,1[$
$\frac{1}{n} \sum_{r=1}^n f(\frac{r}{n})$ is a Riemann sum.
$\lim_{n\to{\infty}}\frac{1}{n} \sum_{r=1}^n f(\frac{r}{n})=\int_0^1 \frac{1}{(1+x^2)^3}$ $dx$
I am getting problems to compute this integral.
I used a substitution of $x=\tan{u}$
My integral becomes $\int^\frac{\pi}{4}_0 (\cos{u}-\sin^2{u}\cos{u})du=\frac{5\sqrt{2}}{2}$
Hence $\lim_{n\to{\infty}}\frac{1}{n} \sum_{r=1}^n f(\frac{r}{n})=\int_0^1 \frac{1}{(1+x^2)^3}$ $dx=\frac{5\sqrt{2}}{2}$
But the limit is defined to be $\frac{3\pi}{32}+\frac{1}{4}$. I am getting it to be different.
Comment: I cant see where the "My integral becomes..." comes from: I get simply $\;\cos^4x\;$ ...
Comment: BTW  you probably mean $n\to\infty$ in several places where you write $x\to\infty$. (I have changed it to this in the title.)
Comment: @MartinSleziak,its understood, isn't it?.Typing error.
Answer: $$n^5\sum_{k=0}^n\frac1{(n^2+k^2)^3}=\frac1n\sum_{k=0}^n\frac1{\left(1+\left(\frac kn\right)^2\right)^3}\xrightarrow[n\to\infty]{}\int_0^1\frac{dx}{(1+x^2)^3}$$
Your substitution is fine...yet you must also change the limits accordingly:
$$x=\tan u\implies\begin{cases}x=0=\tan 0\implies u=0\\{}\\x=1=\tan u\implies u=\frac\pi4\end{cases}\;\;,\;\;\;dx=\frac{du}{\cos^2u}$$
and our integral becomes, using $\;1+\tan^2u=\frac1{\cos^2u}\;$ :
$$\int_0^{\pi/4}\frac{du}{\cos^2u}\cdot\frac1{(1+\tan^2u)^3}=\int_0^{\pi/4}\cos^4u\;du=\left.\frac1{32}\left(12u+8\sin2u+\sin4u\right)\right|_0^{\pi/4}=$$
$$=\frac1{32}\left(3\pi+8\right)=\frac{3\pi}{32}+\frac14$$
Comment: @SirusBlack That's only a typo, of course. Edited now.
Comment: I do not understand the computation of the integral. Your integrand in terms of u gets integrated to get a function in x.
Comment: But anyways, GOOD JOB. I got the concept.


Resizing input vectors of different lengths

Question: I have a set of data taken from a number of machines. A simplified version of the dataset is shown below:
   id  time1  time2  time3  time4  time5  time6  time7  failure
0   1  1.824  3.107  9.695  0.944  0.151  2.365    NaN        0
1   2  3.573  0.728  3.001  5.470  4.078  3.713  0.761        1
2   3  5.064  6.090  8.290    NaN    NaN    NaN    NaN        0
3   4  8.636  4.538  5.866  5.294  9.988    NaN    NaN        0
4   5  3.487  4.915  1.860  2.911    NaN    NaN    NaN        1

In this sample dataset, there are 5 machines, each with a unique id value. Each machine has a sensor that takes and records a measurement every few weeks. Each sensor reading is recorded in one of the timeN columns. Some machines are newer than others, meaning that newer machines have recorded fewer sensor measurements than older machines. The failure column shows a value of 1 if a machine failed/broke down, and a 0 if the machine is still operational.
I want to use the sensor measurement vectors as input data, and the failure state as my target value to train a predictive model. My problem is that the sensor measurement vectors are not all the same size. In the real dataset, the size of the input vectors can be anywhere between 200 and 800 measured values, and there are around 1000 machines.
My question is, what are some ways I can resize all my input vectors to be of equal lengths, while preserving any signals that might be in the data? Some things I am considering are

Some method of random sampling to downsample the larger vectors
Take incremental averages of sequential groups of sensor values (i.e. instead of [time1[value], time2[value], time3[value], time4[value], ...], use [mean(time1[value],time2[value],time3[value]), mean(time2[value],time3[value],time4[value]), ...]) to shorten longer vectors.

I'm intending to use something like XGBoost coded using Python. What other methods of resizing my input vectors would be recommended for the purposes described above?
Answer: If I understand your use case correctly, it is important to keep the time between the sensor measurements and the failure evaluation approximately comparable. So one approach could be to bin the time before the failure evaluation (FE) in equal intervals, e.g. monthly intervals before the failure evaluation (e.g. use the boundaries [n month before FE, n-1 month before FE, ..., two months before FE, FE]), and average the available measurements within each month. That way you get time series which might contain missing values. Here, you could apply one of the many imputation methods available. Which one is the most appropriate very much depends on your situation, but for your time series, a good choice could be Kalman filter smoothing.
This would leave you with a set of comparable time series without missing values that you can use as input to your binary classification algorithm.


Relacionar Categorias com Subcategorias da mesma tabela com outra tabela

Question: Relacionar Categorias com Subcategorias da mesma tabela com outra tabela
Tenho as seguintes tabelas:

Até aí acredito que a modelagem esteja ok, certo?
Aí no resultado eu gostaria de buscar os seguintes campos:
id_manual | titulo | arquivo | downloads | id_categoria | id_subcategoria | categoria | subcategoria -

Sendo que não gostaria de concatenar os campos categoria e subcategoria.

Até estou fazendo a junção das duas tabelas, porém os campos não estão ficando certos, o que eu gostaria é que no campo categoria, ficasse o nome da categoria e caso tenha subcategoria o nome da subcategoria ficasse no campo subcategoria, consequentemente isso para os campos id_categoria e id_subcategoria.
Como eu poderia fazer isso sem concatenar os campos (fazer com campos separador)? ou somente filtrando usando o PHP?
Gostaria de fazer somente uma Query com MySQL pra isso, se for possível.
Comment: Possível duplicata de [Ordenar por categoria](http://pt.stackoverflow.com/questions/129108/ordenar-por-categoria)
Comment: @GuilhermeSpinXO Como poderia ser feito sem concatenar o resultado conforme na imagem 2 que postei? valeu
Comment: como assim concatenar o resultado? Explique melhor pra que eu possa tentar lhe ajudar.
Comment: @GuilhermeSpinXO no post que você mencionou você utiliza um Sub-select o qual retorna uma coluna com vários registros utilizando o Group_Concat, o que eu gostaria é que retornasse os dois resultados em colunas separadas, exemplo: retornar o nome da categoria e subcategoria em campos separados. Não sei se isso seria possível. Tem alguma ideia?
Comment: Você fala de subcategoria mas eu não vi esse campo nem ID nas duas tabelas, só vi id_categoria e id_categoria_pai. Onde está subcategoria?
Comment: https://stackoverflow.com/questions/7631048/connect-by-prior-equivalent-for-mysql
Answer: O que você quer pode ser alcançado com o uso de joins. Exemplo:
select * from manuais_categorias as m
left join manuais_categorias as n on m.id = n.id_pai
LEFT JOIN manuais_tecnicos on manuais_tecnicos.id_categoria = m.id;

Exemplo no SQL Fiddle:
Comment: Tentei fazer este código, porém com vários registros os mesmos vem duplicados.
Comment: Pela comentários da resposta anterior acho que essa resposta não se adequa mais. Mas complementando, para resolver o problema da duplicidade basta trocar o segundo **LEFT JOIN** por **INNER JOIN**. Com essa abordagem nem todas as categorias serão mostrada, apenas as que tem um manual associado. Veja edição no link do [SQL Fiddle][1]:

  [1]: http://sqlfiddle.com/#!9/9c869/2/1
Comment: Infelizmente continua a repetir dados, eu coloquei aqui um SQL para exemplificar melhor, fiz o que você havia passado, da uma conferida: http://sqlfiddle.com/#!9/986fcf/6
Answer: SELECT * FROM nw_manuais_tecnicos AS mt
LEFT JOIN nw_manuais_tecnicos_categorias as mc USING (id_categoria)
GROUP BY mt.id_categoria

Comment: Na verdade ainda não está certo hehehe.. Olha só, na coluna nome, o registro "Prédio de múltiplas unidades consumidoras" é uma Categoria pai, certo? logo no registro posterior "Teste 2", ele é uma subcategoria da categoria pai "Prédio de múltiplas unidades consumidoras", então o correto seria ter as colunas Categoria com "Prédio de múltiplas unidades consumidoras" nos dois registros, e a coluna subcategoria com o registro "Teste 2" apenas na última linha. Não sei se consegui explicar direito.
Comment: Com esse código, o resultado acaba repetindo várias vezes.
Comment: Usou o GROUP BY? Se não deu certo com m.id_pai, tente manuais_tecnicos.id_categoria
Comment: Mesmo resultado, se quiser conferir: [link]http://s33.postimg.org/cokczojm7/Screen_Hunter_15_May_23_09_56.png[link]
Comment: você pode gerar o SQL dele?
Comment: select * from manuais_categorias as m
LEFT JOIN manuais_tecnicos on manuais_tecnicos.id_categoria = m.id;
GROUP BY m.id_categoria
Comment: Tenta assim....
Comment: Modifiquei minha resposta, tente dessa forma...
Comment: http://sqlfiddle.com/#!9/2dfe8f/1
Comment: Coloquei o código SQL aqui, da uma conferida, não consegui com seu código: http://sqlfiddle.com/#!9/986fcf/3
Comment: Acabei de copiar o codigo aqui e executar lá no seu sqlfiddle, deu certo aparentemente.. veja ai http://sqlfiddle.com/#!9/986fcf/4
Answer: Você precisar de um relacionamento com nw_manuais_tecnicos_categorias  e entre ela mesma para retorna a categoria PAI.
Veja o exemplo.
select m.id_manual , m.titulo , m.arquivo , m.downloads ,
Ca.id_categoria , CaPai.id_categoria as id_subcategoria , Ca.Nome as categoria ,  CaPai.Nome as subcategoria
from nw_manuais_tecnicos as m
join nw_manuais_tecnicos_categorias as Ca on Ca.id_categoria = m.id_categoria
left JOIN nw_manuais_tecnicos_categorias as CaPai on CaPai.id_categoria = Ca.id_categoria_pai;

Aqui uso o left Join como você mesmo falou pode ter categoria que não tem pai.


LibGdx - Slider not responding to touchUp

Question: I have a problem with LibGdx's Slider. Slider's value should be set to 128 every touchUp.
But it work only the first few times. After every time I slide and touch up, value is equal to place where I touch up.
<code>joY = new Slider(32, 224, 1, false, skin);
[...]
joY.addListener(new ClickListener(){
    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button){
        joY.setValue(128);
    }
});
</code>
Any help? Thanks a lot.
Answer: Look at ClickListener in documentation.
For touchUp method it says:

Called when a mouse button or a finger touch goes up anywhere, but only if touchDown previously returned true for the mouse button or touch.

Hope it helps.
Comment: I looked at it before. This isn't my problem.
I resolve my problem by placing Override function in main loop (before in contructor)
But thanks


O ggplot aparece vazio: os dados não aparecem

Question: Quero criar um `ggplot com as frequências em que aparecem as detecções de uma espécie de peixe. Mas, quando rodo, plota o gráfico sem os dados das frequencias das detecções, o quadro fica vazio. Como resolver?
Seguem alguns dados para reprodução:
ID          Freq
               0
Ana          390
Boca        2764
Joana          3
Cabelo      3276
Fabiane       10

table(myc_t$ID)->det_id
as.data.frame(det_id)->det_id
names(det_id)<-c("ID","Freq")
head(det_id)

library(ggplot2)

ggplot(det_id, aes(x = "ID", y = "Freq")) +
  geom_bar(stat = "identity") +
  scale_x_discrete(limits = c("Ana", "Boca", "Joana", "Cabelo", "Fabiane", "Manu")) +
  labs(x = "Nomes dos indivíduos marcados", y = "Frequencia de detecção") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

Gera o gráfico, mas sem valores e aparece a mensagem de erro:

Warning message:
  Removed 16 rows containing missing values (position_stack).

Dados
det_id <- read.table(text = "
ID          Freq
''             0
Ana          390
Boca        2764
Joana          3
Cabelo      3276
Fabiane       10
", header = TRUE)

Comment: Tente corrigir `aes(x="ID",y="Freq")` para `aes(x = ID,y = Freq)`. Isso já é um bom começo.
Comment: @RumenickPereira Com essa correção funcionou à primeira.
Comment: Sim, falei que é um bom começo, pois trata-se de uma nova contribuidora. Rsrs.
Comment: @RuiBarradas, pode sinalizar que é um comentário útil, por favor.
Comment: @RumenickPereira Não percebo, sinalizar o seu comentário? Já fiz.
Comment: @RuiBarradas, desculpa, não tinha visualizado ainda.
Comment: Só uma dica: pode usar `geom_col()`, que é um *alias* para `geom_bar(stat = "identity")`
Comment: Funcionou galera! Obrigada!
Comment: Só algo estranho no resultado. O número de detecções saiu diferente da tabela matriz. Os indivíduos "Fabiane" e "Manu" por exemplo tem muuitas detecções, mas quando peço para ler a quantidade de detecções head(det_id) o resultado é bem menor. (obs. A tabela matrix tem mais de 50 mil linhas).
Answer: Conforme falado no primeiro comentário, basta tirar as aspas de ID e Freq.
Assim teríamos:
ggplot(det_id, aes(x = ID, y = Freq)) +
    geom_bar(stat = "identity") +
    scale_x_discrete(limits = c("Ana", "Boca", "Joana", "Cabelo", "Fabiane", "Manu")) +
    labs(x = "Nomes dos indivíduos marcados", y = "Frequencia de detecção") +
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

Para tirarmos alguma lição disso, porque isso aconteceu?
Bem o ggplot usa o que chamamos de Non-Standard Evaluation (NSE) que é, dizendo de forma muito grosseira, a capacidade do R de ler o texto do código passado e não o seu conteúdo. Dentro de todo o tidyverse ele é usado porque permite digitar menos eliminar decessidade de i) usar aspas e ii) se referir repetidamente ao objeto inicial (ID no lugar de det_id$ID ou det_id[["ID"]] ou mesmo "ID").
Para usar a standard evaluation (caso precise em algum contexto) você pode usar a função aes_string()
ggplot(det_id, aes_string(x = "ID", y = "Freq")) +
        geom_bar(stat = "identity") +
        scale_x_discrete(limits = c("Ana", "Boca", "Joana", "Cabelo", "Fabiane", "Manu")) +
        labs(x = "Nomes dos indivíduos marcados", y = "Frequencia de detecção") +
        theme(axis.text.x = element_text(angle = 90, vjust = 0.5)

Mais informações sobre NSE podem ser encontradas aqui.
Answer: ggplot(det_id, aes(x = ID, y = Freq)) +
    geom_bar(stat = "identity") +
    scale_x_discrete(limits = c("Ana", "Boca", "Joana", "Cabelo", "Fabiane", "Manu")) +
    labs(x = "Nomes dos indivíduos marcados", y = "Frequencia de detecção") +
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5))


Chain rule for multi-variable

Question: If  $z = x + D(x + y)$ and I let $g(x,y) = x + y$
Would I be right in saying that :
$z = x + f(g(x))$
and
$\frac{dz}{dx} = 1 + \frac{df}{dg}\cdot\frac{dg}{dx}$?
Comment: D(x + y) is a function of one variable. g(x,y) is a substitution to apply chain rule
Answer: I think you meant $z=x+D(g(x,y))$. If $D$ is a function of one variable, then you can talk about the partial with respect to $x$; you would be correct in saying that
$$\frac{\partial z}{\partial x} = 1 + \frac{dD}{dg}\frac{\partial g}{\partial x}.$$
That is,
$$\frac{\partial z}{\partial x} = 1 + D'(x+y)$$
because $\frac{\partial g}{\partial x} = \frac{\partial}{\partial x}(x+y) = 1$.
Notice that for functions of one variable, we use $d$ and $dx$, but for functions of several variables you are talking about the partial derivative, $\partial$ and $\partial x$.
Comment: Thanks for quick and clear response
Answer: I assume $D(.)$ is a function not a constant.
Then yes: $$ \frac{\partial }{\partial x}z(x,y) = 1 + \frac{\partial }{\partial g}D(g(x,y)) \frac{\partial }{\partial x}g(x,y)$$

Chain rule for multi-variable


Comparar dois atributos datas na base dados com duas TextBox

Question: Como posso comparar um intervalo de duas datas?
data_Inicio date
data_Fim date

textbox_inicio
textbox_fim

Poderei fazer isso logo do lado do ASP.NET sendo que o objetivo é que a minha data de início nunca seja inferior a minha data de fim e a minha data de fim nunca seja inferior a minha data de início.
Comment: Coloque como está seu código até agora
Comment: Qual é a Base de Dados?
Answer: Considere usar um componente próprio para datas. Dito isto vou tentar dar uma solução ao que parece ser o que precisa:
DateTime dataInicio;
if (!DateTime.TryParse(textbox_inicio.Text, out dataInicio)) {
    lblErro.Text =  "Formato da data inicial é inválido";
    lblErro.Visible = true;
    return;
}
DateTime dataFim;
if (!DateTime.TryParse(textbox_fim.Text, out dataFim)) {
    lblErro.Text =  "Formato da data final é inválido";
    lblErro.Visible = true;
    return;
}

if (DateTime.Compare(dataInicio.Date > dataFinal.Date) {
    lblErro.Text = "Data inicial não pode ser superior à data final";
    lblErro.Visible = true;
} else {
    lblErro.Text = "";
    lblErro.Visible = false;
}

Coloquei no GitHub para referência futura.
Isto é só uma base, dá para fazer melhor que isto e provavelmente será precisa adaptar ao que você precisa já que você não postou seu código.


Protect site from flooding when user login is attacked by brute force

Question: I've been experiencing issues with bots trying to force their way into the website I manage. It seems to be a daily occurrence the the flood system is being triggered (I'm on D7).
I'm happy the the flood system is doing it's job and stopping the attacks, but the problem is the bots are using private IPs, so when the flood is triggered it just locks everyone out.
I would like to find out if there is a way to limit the amount of bots that are getting through to the actual login verification. I tried throwing hidden captcha on to the login form, which does an ok job of it, but even when it suspects a bot, it doesn't't stop the login verification, so the flood system still gets triggered. Does anyone know of anything I can put in front of that process to limit the amount of bots getting though? The less intrusive, obviously the better.
Comment: It will be hard to go around something that's meant as first line of defence. And if you want captcha, it will meant that form actually will be processed. So it will hurt your server **way more** than a built-in flood control. Maybe it's time to install mod_security ?
Comment: What anti-flood system you are using? Could you link to it? It's pretty hard to guess. [Flood control](https://drupal.org/project/flood_control)? And what exactly you want from us? If any of us knows how to make bot authors blacklist sites, I doubt he will admit it ;)
Comment: I'm using the built in flood system that D7 has in it (https://drupal.org/node/164983#comment-589458). I'm looking for a way to stop suspicious login attempts before they hit the validator. IE, if hidden captcha worked the way I had hoped it would, when it signaled it was a bot it would kill the login process right then and there instead of letting the validation process go thorough. That's what I'm looking for, a way to intercept potential bot logins before they hit the validator.
Comment: So the way hidden captcha works is it has a hidden field that it expects not to be filled in, if it is, it suspects a bot. At that point I would like it to simply kill all log in processes, but it dosn't do that. I'm looking for something that does.
Answer: The type malicious bots you describe can connect through open proxies all over the world (typically without permission), each having different IP addresses. They can also use trojans and viruses on hijacked client computers/servers to do their work.  In other words, Drupal's built-in flood control system, that uses IP-addresses for blocking, is no good for dealing with this type of attack.  If the flood system causes problems for you ("locks everyone out"), you need to reconfigure it or turn it off.
You can do this by adding one or both of the following pair of configuration settings to your site's settings.php file:
// Set per-IP failed login attempt limit to max and window to 5 seconds
$conf['user_failed_login_ip_limit'] = PHP_INT_MAX;
$conf['user_failed_login_ip_window'] = 5;

// Set per-user failed login attempt limit to max and window to 5 seconds
$conf['user_failed_login_user_limit'] = PHP_INT_MAX;
$conf['user_failed_login_user_window'] = 5;

In that way, no-one will be locked out.
Instead of using the built-in flood control in Drupal, try using Apache ModSecurity to limit bots access to your server, filtering on content (POST requests), instead of IP-address.
From its documentation on HTTP Traffic Logging:

Web servers are typically well-equipped to log traffic in a form
  useful for marketing analyses, but fall short logging traffic to web
  applications. In particular, most are not capable of logging the
  request bodies. Your adversaries know this, and that is why most
  attacks are now carried out via POST requests, rendering your systems
  blind. ModSecurity makes full HTTP transaction logging possible,
  allowing complete requests and responses to be logged. Its logging
  facilities also allow fine-grained decisions to be made about exactly
  what is logged and when, ensuring only the relevant data is recorded.

First discover the pattern in the POST requests the bots make, and use Apache to block them.
Answer: In case anyone else comes across a similar issue, I didn't realize that the two IP addresses were coming from my varnish servers. I was able to use secure login to redirect user login attempts to https (which I should have been doing anyway) and that ended up bypassing vanish, thus allowing me to capture the actual IPs. That allowed to flood table to function as it was intended.


MySQL 5.1 vs. MS SQL 2000 for small office

Question: We've got an MS SQL 2000 database server running internal applications (< 50 concurrent users, tables up to a few 100K rows, some web, some .NET clients).  We have no intention of shelling out $$ to upgrade the server, and are trying to decide whether to leave it on SQL 2000 or migrate to MySQL 5.1.  I've used MySQL for smaller installations, and have always liked it.  The pros of migration from my standpoint are that I like writing queries in MySQL more than MS SQL, and we can afford to run the most up-to-date version of MySQL.  The pros of remaining on MS are better integration with our active directory environment and better .NET interoperability.  I'd be interested in hearing others' advice on this, and further pros (and cons) about going either way.
No flames please, I like both MS SQL and MySQL and believe they both have their place.
Answer: Upgrade to SQL Server 2005 Express, or even SQL 2008 Express. These are both free and are much more powerful than MySQL (not that there's anything wrong with MySQL!). SQL 2005 will even restore backups from SQL 2000, so it's trivially easy to port the database (2k8 may do this too but I've never tred it).
Contrary to popular myths SQL 2005 and 2008 have no limit on the number of users, but there is a 4GB limit on database size and they will only use up to 1GB of memory.
You won't be able to manage SQL 2005/8 using the SQL 2000 Enterprise Manager, but both have a free management too (Management Studio Express) that is very good.
John Rennie
Comment: Can you back your "much more powerful" statement up with any facts? From what I've gathered, MySQL claim they are faster and Microsoft claim they are faster. I was unable to find any other benchmarks.
Answer: Where possible use free and open source software.
MySql cost nothing and works very well - Why waste the money on MsSql.
MySql has a large user base and is fast and reliable what more do you need?
Comment: MySQL is only free for GPL software or for use with php. Otherwise, it's not free.
Answer: As @renniej has mentioned, MSSQL has free Express versions now (with some limitations) so there's no need to waste money.  I'm also in the free / open source camp when it makes sense.  My say is that you use what you are most comfortable with and what works best for you, especially in a small office environment where you probably wear many hats.
A big pro of MSSQL (2005+) in my mind is the .NET interop, especially being able to create CLR objects within MSSQL.  This is hugely powerful (also at times fraught with peril :)
Another pro in my book of MSSQL is DTS (in 2000) and SSIS in 2005/2008 and the SQL Job Agent for automation tasks.
Answer: Have you considered other open source databases, such as PostGres or Firebird?
They are both more historically standards compliant than MySQL, and therefore more likely to be compatible with MS-SQL.
Comment: My experience is with MSSQL and MySQL, so I'm inclined to go one of those directions.  However, this isn't the first time I've heard that and other good things about PostGres so I'll probably check that out as an option as well.  Thanks.
Answer: MSSQL 2000 is a robust and very reliable product. If you already have the licenses on the company, there's no sense at all to use MySQL.
If you want to go the open source route, there are much better servers which rivals MSSQL (and in some aspects win) in terms of features and reliability.


connection error with Sqlite database

Question: I want to connect my application with sqlite database but it throw the exception.

An exception of type 'System.BadImageFormatException' occurred in
  Scrap_Book.Windows.exe but was not handled in user code
Additional information: An attempt was made to load a program with an
  incorrect format. (Exception from HRESULT: 0x8007000B)

        var dbpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "scrapbook.sqlite");
        using (var db = new SQLite.SQLiteConnection(dbpath))

Second line throw exception.
I am unable to resolve it. please help me i am new in programming.
Thanks in advance.
Comment: A package added .cs files? That's odd. Better check again, and add very precise info about which package you added. There are a lot of similar looking packages for sqlite/uwp .You should probably be using __sqlite-net-pcl__ .
Comment: Related http://stackoverflow.com/questions/8996653/troubleshooting-badimageformatexception
Comment: I install sqlite-net package
Comment: which added two class in my project  Sqlite.cs and SQLiteAsync.cs and exception occurs in SQlite.cs
Answer:
I install sqlite-net package.

@Henk was right, you installed a wrong package for UWP app, what you need is SQLite.Net-PCL package. And for connection, you can code for example like this:
using (var db = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), Path.Combine(ApplicationData.Current.LocalFolder.Path, "scrapbook.sqlite")))
{
    //TODO:
}

and don't forget, your project will also need to reference to SQLite for Universal App Platform.

connection error with Sqlite database


Simulation in statistics

Question: If 0.1178, 0.7843, 0.8713, 0.5472, 0.6977 are five simulated
values from a U [0, 1] distribution, simulate five values from a Bin(7, 0.3) distribution.
I'm going to be honest, I have tried to look up online what simulation exactly is, but I still don't understand it. If anyone can provide a good explanation as to what it actually is, and walk through the question above, I'd be grateful.
Thanks
Answer: Intuitively, simulation is generating random variables (or random numbers) with a particular distribution (for example, the binomial distribution).
The binomial distribution with the parameters $n=5$ and $p=0.3$ can take values from the set $\{0,1,2,\ldots,7\}$ with the positive probabilities given by the formula
$$
\binom 7 k  0.3^k(1-0.3)^{7-k}
$$
and equal to
$$
\begin{array}{|c|c|c|c|c|c|c|c|}\hline k & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\\hline P(X=k) &0.0824& 0.2471 &0.3177 &0.2269 &0.0972 &0.0250 &0.0036 &0.0002\\\hline
\end{array}.
$$
If you want to simulate the binomial distribution using the uniform distribution, one way to do this is to split the interval $[0,1]$ into subintervals such that the probability to obtain a number from the first interval is $P(X=0)$, the probability to obtain a value from the second interval is $P(X=1)$ and so on and so forth. For example, the intervals could be as follows:
\begin{align*}
[0,0.0824)\ [0.0824,0.3295)\ [0.3295,0.6472)\ [0.6472,0.8741)\\ [0.8741,0.9713)\ [0.9713,0.9963)\ [0.9963,0.9998)\ [0.9998,1].
\end{align*}
For example, if you obtain $0.1178$ from the uniform distribution, then that means that you obtain $1$ from the binomial distribution because $0.1178$ falls into the second interval.
I hope this is useful.

Simulation in statistics


How to get an image stored as an oracle blob into an Image object

Question: I am trying to retrieve an image stored in an oracle blob and place it in a new System.Drawing.Image instance. I know I can write the stream to a temp.bmp file on the disk and read it from there but thats just not l33t enough for me.  How do I convert the blob object directly to an image?
Answer: Assuming :

you are using the Microsoft client (System.Data.OracleClient).
you have a proper OracleConnection instance (connection).
you have an OracleCommand ready (command, based on SELECT my_blob FROM my_table WHERE id=xx).

This should go like this :
using (OracleDataReader odr=command.ExecuteReader())
{
    reader.Read();

    if (!dr.IsDBNull(0))
        using (Stream s=(Stream)dr.GetOracleValue(0))
            using (Image image=Image.FromStream(s))
                return Copy(image);
}

where Copy is
public static Image Copy(Image original)
{
    Image ret=new Bitmap(original.Width, original.Height);
    using (Graphics g=Graphics.FromImage(ret))
    {
        g.DrawImageUnscaled(original, 0, 0);
        g.Save();
    }

    return ret;
}

See my blog post and/or KB 814675 for why a Copy is necessary.
Answer: I know this uses sql but it should be similar for your needs
Dim cn As SqlConnection = Nothing
        Dim cmd As SqlCommand = Nothing
        Dim da As SqlDataAdapter = Nothing
        Dim ms As MemoryStream = Nothing
        Dim dsImage As Data.DataSet = Nothing
        Dim myBytes() As Byte = Nothing
        Dim imgJPG As System.Drawing.Image = Nothing
        Dim msOut As MemoryStream = Nothing

        Try
            cn = New SqlConnection(ConnectionStrings("conImageDB").ToString)
            cmd = New SqlCommand(AppSettings("sprocGetImage").ToString, cn)
            cmd.CommandType = Data.CommandType.StoredProcedure

            cmd.Parameters.AddWithValue("@dmhiRowno", irowno)

            da = New SqlDataAdapter(cmd)

            dsImage = New Data.DataSet
            da.Fill(dsImage, "image")

            If dsImage.Tables(0).Rows.Count = 0 Then
                Throw New Exception("No results returned for rowno")
            End If
            myBytes = dsImage.Tables(0).Rows(0)("Frontimage")

            ms = New MemoryStream
            ms.Write(myBytes, 0, myBytes.Length)

            imgJPG = System.Drawing.Image.FromStream(ms)

            'Export to JPG Stream
            msOut = New MemoryStream
            imgJPG.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg)
            imgJPG.Dispose()
            imgJPG = Nothing
            ms.Close()
            sFrontImage = Convert.ToBase64String(msOut.ToArray())

            dsImage = New Data.DataSet
            da.Fill(dsImage, "image")
            myBytes = dsImage.Tables(0).Rows(0)("Backimage")

            ms = New MemoryStream
            ms.Write(myBytes, 0, myBytes.Length)

            imgJPG = System.Drawing.Image.FromStream(ms)
            sBackImage = Convert.ToBase64String(ms.ToArray)

        Catch ex As System.IO.IOException ' : An I/O error occurs.
            Throw ex
        Catch ex As System.ArgumentNullException ': buffer is null.
            Throw ex
        Catch ex As System.NotSupportedException ': The stream does not support writing. For additional information see System.IO.Stream.CanWrite.-or- The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified.
            Throw ex
        Catch ex As System.ArgumentOutOfRangeException ': offset or count are negative.
            Throw ex
        Catch ex As System.ObjectDisposedException ' : The current stream instance is closed.
            Throw ex
        Catch ex As System.ArgumentException
            Throw ex
        Catch ex As System.Runtime.InteropServices.ExternalException ': The image was saved with the wrong image format
            Throw ex
        Catch ex As Exception
            Throw ex
        Finally
            If cn IsNot Nothing Then
                cn.Close()
                cn.Dispose()
                cn = Nothing
            End If

            If cmd IsNot Nothing Then
                cmd.Dispose()
                cmd = Nothing
            End If

            If da IsNot Nothing Then
                da.Dispose()
                da = Nothing
            End If

            If ms IsNot Nothing Then
                ms.Dispose()
                ms = Nothing
            End If

            If msOut IsNot Nothing Then
                msOut.Close()
                msOut.Dispose()
                msOut = Nothing
            End If

            If dsImage IsNot Nothing Then
                dsImage.Dispose()
                dsImage = Nothing
            End If

            If myBytes IsNot Nothing Then
                myBytes = Nothing
            End If

            If imgJPG IsNot Nothing Then
                imgJPG.Dispose()
                imgJPG = Nothing
            End If

        End Try

This code pulls back a tiff wrapped jpeg for the front image so the code is a bit different than for the back image.


remove specific char from string depending on the selected dropdown value

Question: I'm trying to remove a specific char from a string depending on the selected val of a dropdown.
What I'm trying to achieve is basically, only if #lang.val() == en, remove the first comma in the addr string.
Here is what I have so far.

$(document).ready(function() {
  $('#mainaddress').change(function() {
    var addr = $(this).find('option:selected').data('addr');
    if ($('#lang').val() == 'fr') {
      $('#theaddress').text(addr);
    } else if ($('#lang').val() == 'en') {
      addr.replace(new RegExp(","), '');
      $('#theaddress').text(addr);
    }
  })
});

  <select id="lang">
        <option disabled="1" selected="selected" class="succtext">language</option>
        <option value="en">english</option>
        <option value="fr">french</option>
      </select>

  <select id="mainaddress">
        <option disabled="1" selected="selected">City</option>
        <option value="" data-addr="11, abc, 90210">New York</option>
        <option value="" data-addr="22, qwe, 57937">Toronto</option>
        <option value="" data-addr="33, asd, 59384">Tokyo</option>
      </select>

  -----

What if the lang is selected after the addr? What's the easiest way to handle this?
Comment: try my solution
Answer: Try this. It will handle situation where he select language after addr selected.

$(document).ready(function() {
   $("#lang").change(function(){
     $('#mainaddress').trigger("change")
   })

   $('#mainaddress').change(function() {
     var addr = $(this).find('option:selected').data('addr');
     if(addr==undefined){
       // do nothing
     }
     else if ($('#lang').val() == 'fr') {
       $('#theaddress').text(addr);
       console.log('FRENCH!');
     } else if ($('#lang').val() == 'en') {
       new_text = addr.replace(/,/, '');
       $('#theaddress').text(new_text);
       console.log('ENGLISH!');
     }
   })
 });

  <select id="lang">
    <option disabled="1" selected="selected" class="succtext">language</option>
    <option value="en">english</option>
    <option value="fr">french</option>
    <option value="fr">spanish</option>
  </select>

  <select id="mainaddress">
    <option disabled="1" selected="selected">City</option>
    <option value="" data-addr="11, abc, 90210">New York</option>
    <option value="" data-addr="22, qwe, 57937">Toronto</option>
    <option value="" data-addr="33, asd, 59384">Tokyo</option>
  </select>

  xxxxxxxxxx

Answer: First, check if there is more than one comma in the string then replace the comma in the string with an empty character:
  if (addr.match(/,.*,/)) { // Check if there are 2 commas
    addr = addr.replace(',', ''); // Remove the first one
  }

If you want to replace all commas in the string use a regular expression with the g flag:
addr = addr.replace(/,/g , '');

Example

$(document).ready(function() {
  $('#mainaddress').change(function() {
    var addr = $(this).find('option:selected').data('addr');
    if ($('#lang').val() == 'fr') {
      $('#theaddress').text(addr);
    } else if ($('#lang').val() == 'en') {
      if (addr.match(/,.*,/)) { // Check if there are 2 commas
        addr = addr.replace(',', ''); // Remove the first one

        //To replace all commas
        //addr = addr.replace(/,/g , '');
      }
      $('#theaddress').text(addr);
    }
  })
});

 $(".subSelect").change(function(){
   $('#mainaddress').trigger("change")
 })

  <select id="lang" class="subSelect">
        <option disabled="1" selected="selected" class="succtext">language</option>
        <option value="en">english</option>
        <option value="fr">french</option>
      </select>

  <select id="mainaddress">
        <option disabled="1" selected="selected">City</option>
        <option value="" data-addr="11, abc, 90210">New York</option>
        <option value="" data-addr="22, qwe, 57937">Toronto</option>
        <option value="" data-addr="33, asd, 59384">Tokyo</option>
      </select>

  -----

To handle your issue with selecting address before language you can bind all future events to the .subSelect class selector. This means that if you add other select items they all trigger the change event for #mainaddress.
Comment: Then you can use a regular expression with the `g` flag to replace all of them: `addr.replace(/,/g , ''));`
Comment: ok, I'm trying to remove the first comma regardless of the amount of them on the string.


I want to swipe till an element that is present down in the view(iOS)

Question: Hi I want to swipe to an element that is present down in the screen and that is only accessible after scrolling.
I have tried the following code.
        JavascriptExecutor js = (JavascriptExecutor) driver;
        Map<String, Object> params = new HashMap<>();
        params.put("direction", "down");
        params.put("element", ((RemoteWebElement) driver.findElement(By.name("Hazard"))).getId());
        js.executeScript("mobile: swipe", params);

Previously I am able to scroll but not to a particular element. Rather then it just make a predefined scroll by eleminating
params.put("element", ((RemoteWebElement) driver.findElement(By.name("Hazard"))).getId());

.
But I want it scroll to a specific element.
I am using
appium version: 1.15.1
java-client: 7.2.0

Answer: Instead of swipe operation, you should use scroll operation.
You can use it like:
JavascriptExecutor js = (JavascriptExecutor) driver;
Map<String, Object> params = new HashMap<>();
params.put("direction", "down");
params.put("element", ((RemoteWebElement) driver.findElement(By.name("Hazard"))).getId());
js.executeScript("mobile: scroll", params);

Comment: Its not working sir. It is throwing NoSuchElementException.
Answer: Try this
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView(text(\"WebView\"));").click();

Comment: This is for android. I'm asking for iOS.
Comment: @SammarAhmad : Only Android


Relation between the types of convergences of sequences in $\mathbb{L}_p$ Spaces.

Question: As far as I know there are 4 types of convergence in $\mathbb{L}_p$ spaces.
1. Pointwise Convergent a.e
2. Uniformly Convergent almost a.e
3. Convergence in Measure
4. p-Convergence
My question is how they are related? Are there any more types of convergence in Function Spaces?
Comment: I found the following super helpful when studying these: https://www.johndcook.com/blog/modes_of_convergence/
Comment: Sir, Thank you so much. These diagrams are really nice.
Comment: Can you please explain me the dotted arrows in the diagram ? What do they mean ? One thing I know is given p-convergence, there exists a subsquence which converges to limit function a.e.
But what about the others?
Comment: The meaning of the lines is explained on the first paragraph under diagrams. For instance, a dashed line means that convergence in the mode at the tail of the arrow implies the existence of a subsequence that converges in the mode at the head of the arrow
Comment: Q. Are there any more types of convergence in Function Spaces?
A. Yes, look at my answer below. Besides the Cauchy versions, you did not have [almost uniform convergence](https://en.wikipedia.org/wiki/Uniform_convergence#Almost_uniform_convergence) in your list.
Answer: I looked online for a single diagram picturing all the modes of convergence and couldn't find one. The only available one was mentioned in the comments and comes as separate diagrams. Back in my college days, my measure theory professor, Guillermo Grabinsky, handed us a handwritten version of the following diagram. All the credit goes to him, I simply used TiKz to type it and post it here.

Definitions

$(X, \mu)$ is a measure space.
$p \in [1, \infty)$.
$L^p:=L^p(X, \mu)$ and $L^\infty:=L^\infty(X,\mu)$.
$a.e.$ := almost everywhere.
$u.$ := uniform.
$a.u$ := almost uniform.
$\mu$:= in measure.
$C.$ := Cauchy.

Arrows

$\longrightarrow$ Requires $\mu(X)< \infty$.
$\dashrightarrow$ Existence of a subsequence that converges in the mode at which the arrow points.
$\Longrightarrow$ Implication with no restrictions.


Solving using Chinese Remainder Theorem

Question: I now know my answer's incorrect but can someone explain why my approach is wrong? I tried to follow the logic from this YouTube tutorial https://www.youtube.com/watch?v=ru7mWZJlRQg:
<code>x=1(mod3)
x=2(mod5)
x=3(mod7)
</code>
I got 222 by doing the following:
<code>    mod 3      mod 5     mod 7
x= 5*7        +3*7      +3*5
x= 35         +21       +15
</code>
35(mod 3) = 2(mod3) and we want 1(mod3) so multiply 2(mod3)*2 = 4(mod3) = 1(mod3). So multiply 35*2 in the above chart.
Next, 21(mod5) = 1(mod5) and we want 2(mod5) so multiply 1(mod5)*7 = 7(mod5) = 2(mod5). So multiply 21*7 in the chart.
Last, 15(mod7) = 1(mod7), so multiply 3*1(mod7) = 3(mod7) and multiply 3*15 in the chart so get:
<code>    mod 3      mod 5     mod 7
x= 35*2       +21*7      +15*3   =   222
</code>
Comment: $222$ is congruent to $0$ mod $3$ so that isn't a solution
Answer: The congruence
$$x \equiv 1 \mod 3$$ tells us that $x = 1 + 3k$ for some $k$. Plug this into the second equation to get
$$1 + 3k \equiv 2 \mod 5$$
So $3k \equiv 1$ and $k\equiv 2 \mod 5$. This means $k = 2 + 5j$ for some $j$, which in turn means $x = 1 + 3(2 + 5j) = 7 + 15j$. Now plug this into the third equation
$$7+15j \equiv 3 \mod 7$$
So $15j \equiv -4 \equiv 3 \mod 7$, whence $j \equiv 3 \mod 7$. This means $j = 3 + 7m$ for some $m$. Therefore $x = 7+15j = 7 + 15(3 + 7m) = 52 + 105m$.
Therefore $x \equiv 52 \mod 105$. Specifically, $52$ is a solution.
Answer: You have an error in your final sum, it is not $\,222\,$ but rather $\,262\equiv \color{#c00}{52}\pmod{\!105}$
Simpler $\,3,5,7\mid 2x\!+\!1\,\Rightarrow {\rm lcm}(3,5,7)=105\mid 2x\!+\!1\,$ so $\,{\rm mod}\ 105\!:\ 2x\equiv -1\equiv 104\,\Rightarrow\, x\equiv \color{#c00}{52}$
Remark $\ $ It is usually easier to solve the congruences successively in pairs. See this answer for an example and further discussion

Solving using Chinese Remainder Theorem


Is "position" a reserved word in C++?

Question: Here's a simplified version of my code that compiles:
#include <iostream>

class pos
{
    public:
        char (&board)[64];
        pos(char (&arr)[64])
            : board(arr)
        {
            *board = *arr;
        }
        void print();
};

void pos::print()
{
    for (int y=0; y<8; y++)
    {
        for (int x=0; x<8; x++)
            std::cout << (int) board[x + y*8] << " ";
        std::cout << "\n";
    }
}

int main()
{
    char test[64] = {
        0, 1, 2, 3, 4, 5, 6, 7,
        1, 2, 3, 4, 5, 6, 7, 8,
        2, 3, 4, 5, 6, 7, 8, 9,
        3, 4, 5, 6, 7, 8, 9,10,
        4, 5, 6, 7, 8, 9,10,11,
        5, 6, 7, 8, 9,10,11,12,
        6, 7, 8, 9,10,11,12,13,
        7, 8, 9,10,11,12,13,14 };

    pos p(test);
    p.print();

    std::cin.get();
    return 0;
}

But if I change all instances of pos to position, I get the error: main.obj : error LNK2005: "public: void __thiscall position::print(void)" (?print@position@@QAEXXZ) already defined in position.obj
1>D:\Programming\Test\Debug\Test.exe : fatal error LNK1169: one or more multiply defined symbols found
Oddly, the class used to be named position and compiled fine until I made some changes to how it handles the board array. Can someone explain why I'm getting this error?
Update
Now it doesn't matter what the class is named, I get the same error. I created a new MSVC++ project, copied the source files, and did a new build. Same error. Here's the actual code, instead of the concise version.
main.cpp
#include <iostream>
#include "position.cpp"

int main()
{
    char test[64] = {               // Simple mate test position; TODO: move to test suite
        OO,BK,OO,OO,OO,OO,OO,OO,
        OO,OO,OO,OO,OO,OO,OO,WR,
        OO,WK,OO,OO,OO,OO,OO,OO,
        OO,OO,OO,OO,OO,OO,OO,OO,
        OO,OO,OO,OO,OO,OO,OO,OO,
        OO,OO,OO,OO,OO,OO,OO,OO,
        OO,OO,OO,OO,OO,OO,OO,OO,
        OO,OO,OO,OO,OO,OO,OO,OO };

    position pos(test);
    pos.print();

    std::cin.get();

    return 0;
}

position.cpp
#include <iostream>

// Board-centric representation; pass as 64-byte array

#define WK 0x0  // White King
#define WQ 0x1  // White Queen
#define WR 0x2  // White Rook
#define WB 0x3  // White Bishop
#define WN 0x4  // White Knight
#define WP 0x5  // White Pawn
#define BK 0x6  // Black King
#define BQ 0x7  // Black Queen
#define BR 0x8  // Black Rook
#define BB 0x9  // Black Bishop
#define BN 0xA  // Black Knight
#define BP 0xB  // Black Pawn
// 0xC: unused
// 0xD: unused
// 0xE: unused
#define OO 0xF  // Empty

class position
{
    public:
        char (&board)[64];
        position(char (&arr)[64])   // TODO: 'board' dies if the variable passed through 'arr' dies. Allocating memory might fix this. See 'new' and 'shared_ptr'.
            : board(arr)
        {
            *board = *arr;
        }
        void print();
};

void position::print()
{
    for (int y=0; y<8; y++)
    {
        for (int x=0; x<8; x++)
            std::cout << (int) board[x + y*8] << " ";
        std::cout << "\n";
    }
}

(I'm writing a program to figure out simple chess endgames.)
As you can see, position::print() is only defined in one place, contrary to the error message...unless I'm seriously overlooking something. It's pretty early.
Comment: Are you linking against an old obj file where the class used to be named position?  Where did position.obj come from?
Comment: No, `position` is not a keyword. Are you sure you're doing a completely clean build?
Comment: There are no errors with compiling your code with g++ after replacing all `pos` to `position`.
Comment: @Retired Ninja: The `pos` class above used to be called `position`.
Answer: You shouldn't #include "position.cpp" in your main file, but a header file for the position class instead.
Comment: dang, should have posted a shorter answer :D
Comment: I'm too lazy to do it, but I think the OP deserves a better explanation of how translation units work. It's your chance :)
Comment: after a big lunch like I just had I don't think that will happen right now :)
Answer: The problem is that you're compiling the code contained in position.cpp twice, and you're trying to linking the compiled code into one file.
The problem is caused by this line in main.cpp:
#include "position.cpp"

You're including the C++ source file, not the header. This means that all code in position.cpp is included in main.cpp and then the resulting file is compiled. You then compile position.cpp on it's own.
Try to include position.h instead - if there's no such header yet, define it. The alternative fix is to not add position.cpp to the list of sources to be compiled.
Comment: Thank you. I'm a novice, so I've yet to learn about header files. Now seems to be the right time. ;)
Answer: You are including postition.cpp in main.cpp, probably your build system also builds position.cpp separately and then the linker finds multiple definitions of your class.
You should make a separate header and add include guards, #pragma once for example on msvc
Comment: Strange that it worked fine until recently... The consensus is definitely to include a header file instead of the cpp file. Thank you for your explanation and advice.
Answer: The error message states that you have two definitions of void position::print(), one in main.cpp the other one in position.cpp.
Comment: But I don't. Is there another explanation?
Comment: My best guess is that you don't master your build system and you are linking in `position.cpp` even if you think you aren't.
Comment: Oh, I'm linking in `position.cpp` in my original code. But the class and its methods are only defined in one place. The code I gave above was rewritten for brevity.
Answer: It's not a reserved word, it's a name that you used in position.cpp. You're using the same name, but with a different meaning in main.cpp.
Answer: The compiler/linker deals in translation units, not files. You may have the definition of position::print in one file (position.cpp). But the definition is actually present in two translation units since you wrote #include "position.cpp". You violated the ODR (one definition rule).

Is "position" a reserved word in C++?


Drupal 8: javascript not loading in theme

Question: I would like to add a little javascript to my bootstrap child-theme, but is not loading.
These are the configuration files:
child.info.yml :
 core: 8.x
type: theme
base theme: bootstrap

name: 'child'
description: 'Uses the jsDelivr CDN for all CSS and JavaScript. No source files or compiling is necessary and is recommended for simple sites or beginners.'
package: 'Bootstrap'

regions:
  navigation: 'Navigation'
  navigation_collapsible: 'Navigation (Collapsible)'
  header: 'Top Bar'
  highlighted: 'Highlighted'
  help: 'Help'
  content: 'Content'
  sidebar_first: 'Primary'
  sidebar_second: 'Secondary'
  footer: 'Footer'
  page_top: 'Page top'
  page_bottom: 'Page bottom'

libraries:
  - 'child/global-styling'

child.libraries.yml:
global-styling:
  css:
    theme:
      css/style.css: {}
      css/masonry.css: {}
      css/basic-page.css: {}

  js:
  js/main.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

main.js
$(document).ready(function($) {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})(jQuery);

Comment: instead of using '$' sign use 'jQuery'
Comment: no, that didn't work
Comment: The JavaScript needs to be compatible with Drupal by wrapping it in an anonymous closure and passing in the $ variable. Consult the docs on writing JS and Drupal behaviors for an example
Comment: Also I'm betting your YAML isn't formatted correctly.
Comment: indeed, when i updated my YAML the javascript was loading.
Answer: Change
$(document).ready(function($) {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})(jQuery);

to
Drupal.behaviors.basic = {
   attach: function (context, settings) {
   (function($) {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
   })(jQuery);
  }

};
Comment: Get rid of document ready and use Drupal.behaviors.
Comment: @Kevin it's better solution,I update the answer
Comment: Making it a behavior is equivalent of "document ready"
Comment: @Kevin thanks, I know that. but sometimes in debugging it's better to bypass  layers to find the bug faster.
Comment: this worked for me
Comment: @jimi good, I'm happy it works for you and resolve your problem.
Answer: Two things.
One, YAML has to be properly formatted. In another question, I recommended using YAML Lint to ensure you have the right structure.
Should be:
global-styling:
  css:
    theme:
      css/basic-page.css: {}
      css/masonry.css: {}
      css/style.css: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
  js:
    js/main.js: {}

Also, it is best to split your style and Javascript into two definitions but I suppose thats up to you.
Two, your Javascript has to be compatible with Drupal per the docs.
Instead of:
$(document).ready(function() {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})();

What you want is:
(function($) {
    Drupal.behaviors.windowScroll = {
      attach: function (context, settings) {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
      });
    }
})(jQuery);

Note: Since Drupal uses jQuery.noConflict() and only loads JavaScript
  files when required, to use jQuery and the $ shortcode for jQuery you
  must include jQuery and Drupal as dependencies in the library
  definition in your MODULE.libraries.yml and add a wrapper around your
  function.

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
     $(context).find('input.myCustomBehavior').once('myCustomBehavior').each(function () {
      // Apply the myCustomBehaviour effect to the elements only once.
    });
    }
  };
})(jQuery, Drupal);

Answer: In your-theme.libraries.yml file:
base:

 version: 1.x

js:

 js/main.js: {}

In your-theme.info.yml file:
libraries:

 - 'your-theme/global-styling'

 - 'your-theme/base'

Try  above method worked on my previous drupal8 website, i think your js file is not loading.
Also place a js folder in your bootstrap subtheme along with your main.js file


Silent drum warm-up exercises

Question: In my brass band, we usually start rehearsals with a hymn tune to warm up. Hymn tunes make a good warm-up exercise, but not for the drummer: I usually have either tacet or long rests punctuated by pianissimo rolls which are a pig to play from cold.
What can I usefully be doing to warm up while the band is playing? It can't just be quiet: it must be completely silent to avoid interrupting the rest of the band. Even spinning my sticks around my fingers presents too much risk of noisily dropping one.
Comment: If you have the chance tighten up your ride cymbal/put a cloth over it then use drum mallets on them. At least you would get a chance to practice some singles/doubles but it's not completely silent. Do you have to be on stage while they are warming up? Geting a knee pad and staying somewhere you can warm-up is a better option.
Comment: Hymns such as Onward Christian Soldiers may still suit the horns, whilst providing you with the opportunity to play a decent drum line.
Comment: Ah yes, hymns. I don't know what our kit player does, setup I would imagine. Since it's summer now maybe its time to suggest that you run comfortable march instead of that second or third hymn, because you'll be needing them soon.
Answer: Ideally when warming up with a large ensemble, it shouldn't be your first warmup of the day - regardless of what instrument you play.
Take a half-hour or so a few hours before your rehearsal and do a nice, solid warmup.  When you meet the group for rehearsal, you'll just need a minute or so to get things moving again.  For that, you could pat rudiments on your knees while sitting (since you really just need the wrist motion.)  By the time the band gets to their goofy tune, you're good to go.
Having a separate warmup session from my rehearsal / practice sessions really helped improve my playing.
Hope that helps!

Silent drum warm-up exercises


How will I highlight active item in glossary view?

Question: I have created a glossary view which shows alphabetical navigation to filter the list.
But I can't find a way to highlight the active link - would like for "G" to be highlighted if I am clicking the "G".
I have this tutorial for this but it works only when ajax is disabled. But I am using ajax for this glossary view.
Below is the code which isn't working
$(".view-display-id-attachment_1 span a").each(function(){
     if($(this).attr("href") == location.pathname) {
       $(this).addClass('my-class');
     }
});

I want something like this

When C will be clicked it will be highlighted this way
How will I achieve this in view glossary when ajax is enabled?
Thanks in advance.
Please check the issue I am facing currently. Click Here
Comment: Is that code inside of an attach property as shown in the JavaScript API docs? https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview If it is not, it should be.
Comment: Does this answer your question? [Better understanding of Drupal behaviors](https://drupal.stackexchange.com/questions/11756/better-understanding-of-drupal-behaviors)
Comment: @cilefen that code is working if the glossary is not ajax enabled. But my glossary view is Ajax enabled. Though as per your suggestion I added this code `Drupal.behaviors.mymodule = {attach: function (context, settings) {$('#.view-display-id-attachment_1 span a', context).change(function () {alert('hi');});}};`. But its not working.
Comment: @cilefen I have edited my question and added a link to show the problem I am facing.
Answer: After so many research I understood that unfortunately glossary view doesn't add is-active class if AJAX enabled in the view.
So I had to use a contrib module for that. It provides a simple A-Z filter as radio button/checkbox.
https://www.drupal.org/project/custom_view_filters


Joint PDF of $Y=\min\{{X_1,X_2,X_3}\}$ and $Z=\max\{{X_1,X_2,X_3}\}$

Question:
Suppose $X_1, X_2,$ and $X_3$ are independent and uniformly distributed in $[0,1]$.
(a) Find the joint PDF of $Y=\min\{{X_1,X_2,X_3}\}$ and $Z=\max\{{X_1,X_2,X_3}\}$.
  (b) Determine $E(Z|Y)$.
  (c) Verify the law of total variance in this setting by explicitly computing all terms.

(a) Using the answer below the joint PDF is
$$f_X,_Y(x,y)=6(z-y)$$ I understand how the marginal pdfs are obtained below, but I am still struggling with finding the bounds of integration for the joint pdf.
(b) Using the solution from part (a) I was able to find $E(Z|Y)$.
$$E(Z|Y)=\int_{-\infty}^\infty z f_{Z|Y} (z,y)dz$$
The conditional can be expressed as the joint divided by the marginal of Y, both of which have been determined and so the integral becomes
$$=\frac{1}{3(1-y^2)}\int_y^1z(6(z-y))dz$$
$$E(Z|Y)=\frac{2}{3}+\frac{y}{3}$$
(c) I must verify the formula $$var(z)=E(var(Z|Y))+var(E(Z|Y))$$
using part (b) $var(E(Z|Y))=var(\frac{2}{3}+\frac{y}{3})=\frac{1}{9}var(Y
)$
here I am uncertain about $var(Y)$ I know that $Y=\min\{{X_1,X_2,X_3}\}$ but how do I find the var of this? For a single uniform random variable I know that the variance will be $\frac{1}{12}$ but since there are 3 $(X_1,X_2,X_3)$ should I multiple $\frac{1}{12}$ by 3?
now for $E(var(Z|Y))$, I am not sure about how to find the $var(Z|Y)$
If someone could please help clarify my questions, it would be very helpful to me.
Comment: Related: https://math.stackexchange.com/questions/54505/distribution-of-maxx-i-minx-i-x-i-are-iid-uniform-random-variables
Comment: The direct approach to this is to note that $$[y\leqslant Y,Z\leqslant z]=\bigcap_{i=1}^3[y\leqslant X_i\leqslant z]$$ hence, for every $y<z$, $$P(y\leqslant Y,Z\leqslant z)=P(y\leqslant X\leqslant z)^3=(F_X(z)-F_X(y))^3$$ from which, differentiating twice, the joint PDF follows as $$f_{Y,Z}(y,z)=-\frac{\partial^2}{\partial y\partial z}P(y\leqslant Y,Z\leqslant z)=6f_X(y)f_X(z)(F_X(z)-F_X(y))\mathbf 1_{y<z}$$
Comment: Is there more information given about $X_1, X_2, X_3$?
Comment: @ElizabethHan Yes, I just updated the question
Comment: Also, X and Y are not independent, and thus you might not be able to separate their probability density functions. And actually, what is X? We only have $X_1$, $X_2$, etc.
Comment: @YujieZha I just updated the question
Comment: @andreawong I'm saying you cannot split the joint density function into multiplication. In your case, Y,Z are not independent, and they are not independent with $X_1,X_2,X_3$
Comment: @YujieZha oh I see my mistake. Because $X_1, X_2, X_3$ are independent, but this does not imply that $Y,Z$ are.
Comment: @andreawong yea, you got it
Answer: The following may get you started, by finding the density functions of $Y$ and $Z.$
For $Z = \max(X_1, X_2, X_3),$ we have the CDF
$$F_Z(t) = P(Z \le t) = P(X_1 \le t)P(X_2 \le t)P(X_3 \le t) = t^3,$$
for $0 <t <1.$ [If the maximum is less than $t,$ then so must each of the three independent $X_i$'s be less than $t.$] So $f_Z(t) = 3t^2,$ which is the density function of the distribution
$\mathsf{Beta}(3,1).$
Similarly, for the minimum, $F_Y(t) = (1-t)^3,$ for $0 < t < 1,$ and
$Y \sim \mathsf{Beta}(1,3).$
For illustration, the plot below shows histograms of simulations of 100,000 realizations of $Y$ and of $Z,$ along with the appropriate Beta densities.
Comment: @Did. Hmmm. In view of the suggested link, I didn't intend to give the complete answer. If you think that's appropriate, go ahead.
Comment: Hmmm, finding the joint PDF definitely requires another idea -- which you do not touch upon.
Comment: Again: of course, incomplete answers (aka hints) are allright **provided they are  bearing on the question asked**, the trouble here is that you solve an entirely different question and that the tools used to solve the latter are not the ones necessary to solve the former.
Comment: This is a fairly standard problem. Perhaps [_this_](https://math.stackexchange.com/questions/1242784/the-maximum-and-minimum-of-five-independent-uniform-random-variables) is a more directly relevant link on our site. There it is shown that $f(z,y) = 6(z-y),$ for $0 < y < z < 1.$ Integrating to get the marginals, one finds the beta distributions shown in my Answer.
Comment: Yes, this is fairly standard, as at least 95% of the questions asked on the site. Re the method to solve the question, yes it is standard as well (and you might wish to read my comment from yesterday on main about this) but the trouble is that you do not explain it.
Comment: @BruceET Thank you for your explanation. I rewrote my question with the help that you provided, but am still stuck on certain parts which I specified in the edited version.
Comment: $Var(Y)$ is simple because you have the density. Look at Wikipedia on 'beta distribution' if you're unsure of the answer.
Answer: I'll provided a way, might not be the most straight-forward/easy one, but should be able to solve it. Plus it starts from direct definitions, and could apply generically to statistics other than max/min as well.
$$F_{Y,Z}(y,z)=\mathbb P((Y\le y)\cap(Z\le z))$$
$$=\mathbb P(((X_1 \le y)\cup (X_2 \le y) \cup (X_3 \le y)) \cap ( (X_1 \le z) \cap (X_2 \le z) \cap (X_3 \le z)))$$
Now for the set:
$$((X_1 \le y)\cup (X_2 \le y) \cup (X_3 \le y)) \cap ( (X_1 \le z) \cap (X_2 \le z) \cap (X_3 \le z))$$
$$=\bigcup_{i \ne j \ne k \in \{1,2,3\}}((X_i \le \min(y,z))\cap(X_j \le z) \cap (X_k \le z))$$
Then use the fact that $\mathbb P(A \cup B \cup C)= \mathbb P(A) + \mathbb P(B) + \mathbb P(C) - \mathbb P (A \cap B) - \mathbb P (C \cap B) - \mathbb P (A \cap C) + \mathbb P(A\cap B \cap C)$
to cut them into probability of intersections of events that's from the different $X_1,X_2,X_3$, and since the three r.v. are independent, the events from $\sigma(X_1), \sigma(X_2), \sigma(X_3)$ respectively are independent, then you could break up those intersection events into multiplication, and find the distribution.
Comment: To whoever down-voted, I think I am at least correct. Please tell me if you find this is wrong. Plus I said it is not the easiest one, but I start from the definition, and deduce by set operations
Comment: And I think the value of this solution is that you do not think about any high-level trick and business logics, but you deduce from the very fundamental ground and rudimentary definitions about probability. I do not see a reason for a down vote just because this is not a smart solution.
Comment: I did not down-vote, but I guess someone thinks this is unnecessarily complicated. Maybe OP will find it helpful, and up-vote.


How do you speed up Dialogflow CX speech recognition on single word responses?

Question: I have a Dialogflow CX agent working in polish [pl] language as an audio bot using AudioCodes.
I want it to respond to yes/no answers (pl: "tak"/"nie"), yet it takes usually 15 seconds or more to detect the end of utterance. Enabling advanced speech settings and setting "End of speech sensitivity" and "No speech timeout" does not help.
I'd love to set some Audiocodes parameters, like fast STT recognition, but I don't know where to set them.
Any ideas on how to speed up the detection time? Forcing users to respond with two or more words is not allowed in my case.
Answer: Well, "End of speech sensitivity" in Dialogflow CX is only available for agents using the en-US language tag, as seen here.


Why $\omega\left[\begin{pmatrix} 0 &Q\\ R &0 \end{pmatrix}\right]\leq\omega\left[\begin{pmatrix} P &Q\\ R &S \end{pmatrix}\right]$?

Question: Let $E$ be a complex Hilbert space, with inner product $\langle\cdot\;, \;\cdot\rangle$ and the norm $\|\cdot\|$ and let $\mathcal{L}(E)$ the algebra of all operators on $E$. The numerical radius of an operator $T\in\mathcal{L}(E)$ is given by
$$\omega(T)=\sup_{\|x\|=1}|\langle Tx, x\rangle|.$$

Let $P,Q,R,S\in\mathcal{L}(E)$. I want to prove that
$\omega\left[\begin{pmatrix}
0 &Q\\
R &0
\end{pmatrix}\right]\leq\omega\left[\begin{pmatrix}
P &Q\\
R &S
\end{pmatrix}\right].$
Here $\begin{pmatrix}
0 &Q\\
R &0
\end{pmatrix},\begin{pmatrix}
P &Q\\
R &S
\end{pmatrix}\in \mathcal{L}(E\oplus E)$.

My attempt: One can remark that
$$
 \begin{pmatrix}
0 &Q\\
R &0
\end{pmatrix} = \frac{1}{2} \begin{pmatrix}
P &Q\\
R &S
\end{pmatrix} + \frac{1}{2} \begin{pmatrix}
-P &Q\\
R &-S
\end{pmatrix},
$$
This implies that
$$
\omega\left[\begin{pmatrix}
0 &Q\\
R &0
\end{pmatrix}\right] \leq \frac{1}{2} \omega\left[\begin{pmatrix}
P &Q\\
R &S
\end{pmatrix}\right] + \frac{1}{2} \omega\left[\begin{pmatrix}
-P &Q\\
R &-S
\end{pmatrix}\right].
$$
But I'm facing difficulties to prove that
$$\omega\left[\begin{pmatrix}
P &Q\\
R &S
\end{pmatrix}\right]=\omega\left[\begin{pmatrix}
-P &Q\\
R &-S
\end{pmatrix}\right].$$
Let $T=\begin{pmatrix}
P &Q\\
R &S
\end{pmatrix}$. I want to find an unitary operator $U$ such that
$$U^*TU=\begin{pmatrix}
-P &Q\\
R &-S
\end{pmatrix}.$$
In this case we get the desired result since
$$\omega(U^*TU)=\omega(T).$$
Answer: Note that $\omega(T) = \omega(-T)$. Thus it suffices to find a unitary operator such that satisfies
$$U^*TU=\begin{pmatrix}
P & -Q\\
-R &S
\end{pmatrix}.$$
But for this we can take
$$U=\begin{pmatrix}
I & 0\\
0 & -I
\end{pmatrix}.$$
Answer: You might not be able to find the desired $U$.  E.g. if $P=S=I$, and $Q=R=0$, then
$$
  \pmatrix{P & Q \cr R & S}
  $$
is not conjugate to
$$
  \pmatrix{-P & Q \cr R & -S},
  $$
since they have different eigenvalues.  However, letting
$$
  V=\pmatrix{-I & 0 \cr 0 & I},
  $$
one has
$$
  V\pmatrix{P & Q \cr R & S}V^{-I} =   \pmatrix{P & -Q \cr -R & S} = -\pmatrix{-P & Q \cr R & -S}
  $$
so you get what you want because $\omega (-T)=\omega (T)$.


Haar Measure of a Topological Ring

Question:
A topological ring is a (not necessarily unital) ring $(R,+,\cdot)$ equipped with a topology $\mathcal{T}$ such that, with respect to $\mathcal{T}$, both $(R,+)$ is a topological group and $\cdot:R\times R\to R$ is a continuous map.  A left Haar measure on $R$ is a (nonnegative) measure $\lambda$ on $R$ with respect to the Borel $\sigma$-algebra of $R$ such that there is a multiplicative map $l:R\to[0,\infty]$ called a left multiplier for which

$l(x\cdot y)=l(x)\,l(y)$ for all $x,y\in R$,
$\lambda(x\cdot S)=l(x)\,\lambda(S)$ for all $x\in R$ and for any Borel measurable subset $S\subseteq R$ (with respect to $\mathcal{T}$), and
$\lambda$ is a Haar measure for the topological group $(R,+)$.

(We interpret $0\cdot \infty$ and $\infty\cdot 0$ as $0$.)

An example is the ring $\text{Mat}_{n\times n}(\mathbb{R})$ of $n$-by-$n$ matrices over $\mathbb{R}$ under the topology inherited from $\mathbb{R}^{n\times n}\cong\text{Mat}_{n\times n}(\mathbb{R})$ (here, $\cong$ means "is homeomorphic to").  If $\textbf{A}=\left[a_{i,j}\right]_{i,j=1,2,\ldots,n}$, then we take $\text{d}\lambda(\textbf{A})$ to be $\prod_{i=1}^n\,\prod_{j=1}^n\,\text{d}a_{i,j}$ (i.e., $\lambda$ is the Lebesgue measure of $\text{Mat}_{n\times n}(\mathbb{R})\cong \mathbb{R}^{n\times n}$).  Then, $\lambda$ is a left Haar measure of $\text{Mat}_{n\times n}(\mathbb{R})$ with respect to the left multiplier $l(\textbf{X}):=\big|\det(\textbf{X})\big|^n$ for all $\textbf{X}\in\text{Mat}_{n\times n}(\mathbb{R})$.
Another example is $(\mathbb{C},+,\cdot)$.  We take $\lambda$ to be such that $\text{d}\lambda(z):=\text{d}x\,\text{d}y$ for $z=x+\text{i}y$.  Then, a left multiplier is $l(w):=|w|^2$ for each $w\in\mathbb{C}$.  Similarly to the case of the ring of real $n$-by-$n$ matrices, $\text{Mat}_{n\times n}(\mathbb{C})$ has a left Haar measure $\lambda$ with respect to $l(\textbf{X}):=\big|\det(\textbf{X})\big|^{2n}$ for all $\textbf{X}\in\text{Mat}_{n\times n}(\mathbb{C})$, i.e., $\text{d}\lambda(\textbf{A}):=\prod_{i=1}^n\,\prod_{j=1}^n\,\left(\text{d}x_{i,j}\,\text{d}y_{i,j}\right)$ for $\textbf{A}=\left[x_{i,j}+\text{i}y_{i,j}\right]_{i,j=1,2,\ldots,n}$.
The third example here is $\mathbb{R}[T]/\left(T^n\,\mathbb{R}[T]\right)$ equipped with the topology inherited from $\mathbb{R}^n$.  For $f(T)=\left(a_0+a_1T+\ldots+a_{n-1}T^{n-1}\right)+\left(T^n\,\mathbb{R}[T]\right)$, we take $\text{d}\lambda(f):=\prod_{i=0}^{n-1}\,\text{d}a_i$.  Then, a left multiplier is $l(g):=\left|b_0\right|^n$, for $g(T)=\left(b_0+b_1T+\ldots+b_{n-1}T^{n-1}\right)+\left(T^n\,\mathbb{R}[T]\right)$.

Note that we can also similarly define the notion of right Haar measures for rings and their corresponding right multipliers (which are usually denoted by $r$ in this thread).  If a ring has both left and right Haar measures, then (due to commutativity of addition) the two Haar measures coincide (up to scalar multiple) and we can omit the adjectives left and right, and simply call them Haar measures (or two-sided Haar measures to be precise).  The adjectives "left" and "right" only indicate which kind of multipliers the ring has.  A ring with a Haar measure is unimodular if the left multiplier coincides with the right multiplier; otherwise, we call the ring non-unimodular.

Then, $\text{Mat}_{n\times n}(\mathbb{R})$, $\mathbb{C}$ (as well as $\text{Mat}_{n\times n}(\mathbb{C})$), $\mathbb{R}[T]/\left(T^n\,\mathbb{R}[T]\right)$ (as well as $\mathbb{C}[T]/\left(T^n\,\mathbb{C}[T]\right)$), the ring $\mathbb{Z}_{p}$ of $p$-adic integers (see Crostul's comment below), and the ring of formal power series $\mathbb{F}_p[\![ T]\!]$ (see Jyrki Lahtonen's comment below) are examples of unimodular rings.  Of course, many of these rings are commutative rings, and commutative rings with Haar measures are necessarily unimodular.
An example of non-unimodular rings is as follows.  Consider $\mathbb{R}\times\mathbb{R}$ (some people may denote it by the semidirect sum $\mathbb{R}\,{\supset\!\!\!\!\!\!+}\,\mathbb{R}$) with the usual entry-wise addition, but with the twisted multiplication $(u,v)\cdot(x,y):=(ux,uy+v)$.  Then, with the Haar measure $\text{d}\lambda(a,b):=\text{d}a\,\text{d}b$, we notice that a left multiplier of $\mathbb{R}^2$ is $l(u,v):=|u|^2$ for every $u,v\in\mathbb{R}$, whereas a right multiplier is $r(u,v):=|u|$ for every $u,v\in\mathbb{R}$.  The ring $\text{Mat}_{n\times n}(\mathbb{R})\times\mathbb{R}^n$ (also denoted by $\text{Mat}_{n\times n}(\mathbb{R})\,{\supset\!\!\!\!\!\!+}\,\mathbb{R}^n$) and the ring $\text{Mat}_{n\times n}(\mathbb{C})\times\mathbb{C}^n$ (also denoted by $\text{Mat}_{n\times n}(\mathbb{C})\,{\supset\!\!\!\!\!\!+}\,\mathbb{C}^n$), with the usual entry-wise addition and with the twisted multiplication $(\mathbf{A},\mathbf{u})\cdot(\mathbf{B},\mathbf{v}):=(\mathbf{AB},\mathbf{Av}+\mathbf{u})$, are also non-unimodular for the same reason.

Has there been any study on this sort of concepts?  I'm sure that I am not the first who thought about the notion of Haar measures for rings.  Are there any criteria for a ring to be unimodular?  Are there rings with Haar measures of a given characteristic $k>0$ which are non-unimodular, or simple, or at least non-commutative?  Are there rings with left Haar measures, but without right Haar measures?  (Unlike groups, I expect to find rings with only one kind of Haar measures.)  The cardinality of each example of rings with Haar measures I have so far is that of the continuum $\mathfrak{c}=2^{\aleph_0}$.  Do there exist rings with Haar measures of higher cardinalities?  Please let me know if you have or know of any references.
On the other hand, there may be some pathology with this concept of Haar measures for rings, and because of that, nobody introduces this concept.  If that is the case, would you please let me know why?

EDIT I: I removed a wrong example from the question.  It turns out that, with respect to the discrete topology, $(\mathbb{Z},+,\cdot)$ does not have a Haar measure.
EDIT II: I think I may need another compatibility condition, as stated in menag's reply below.  That is, I may need to enforce the following condition (which I shall name it left compatibility): for any Borel measurable subset $S\subseteq R$ and for every $x\in R$, $x\cdot S$ is also Borel measurable.  For right Haar measures, we may similarly define right compatibility.  Alternatively, I may need to modify Condition 2 to $\lambda(x\cdot S)=l(x)\,\lambda(S)$ for each Borel measurable subset $S\subseteq R$ and for any $x\in R$ such that $x\cdot S$ is Borel measurable (and likewise for right Haar measures).  I am in favor of the former modification (i.e., the left or right compatibility condition) and shall assume it in all instances.
EDIT III: I may be wrong about this claim: "An abelian group has at most one Haar measure (up to scalar multiple)."  (See the boldfaced portion of my question.)  Without the locally compact Hausdorff assumption, there may be an abelian group with two essentially different Haar measures.  If the underlying additive group of a ring is isomorphic to such an abelian group, then the ring may have a left Haar measure and a right Haar measure which are not proportional.  Maybe somebody who knows better about topological groups can give me some insight.
Comment: Anyway, I think that $p$-adic integers with the usual Haar measure are another example, whith $l (x) = 1/[\Bbb{Z}_p : x \Bbb{Z}_p]$. I have not checked all details, though.
Comment: Would the ring of formal power series over a finite field work as a characteristic $p$ example? Say $R=\Bbb{F}_p[[x]]$ with the $x$-adic topology. $\lambda (x^nR)=1/p^n$ for all integers $n\ge0$,  $\ell(\Bbb{F}_p^*)=\{1\}$, $\ell(x)=1/p$ et cetera?
Comment: Just as an offbeat remark. Local compactness is _very_ important for group Haar measure theory. An unfortunately very obscure result by Oxtoby indicates how bad things can get. If you have a metric abelian group that is not locally compact, it is possible to get an invariant measure that is not even locally finite. Metric abelian groups are extremely nice (it's about as nice as you can get without having a differential structure) so this highlights just how important it is to have local compactness.
Comment: No, $l\equiv1$ does not work.  It doesn't work even when we set $l(0)=0$.  See what happens to $0\cdot S=\{0\}$, where $S$ is a finite subset of $\mathbb{Z}$.  I have come to a conclusion that, for any nonzero ring with a Haar measure, any finite subset is of measure $0$.  Hence, finite nonzero rings do not possess Haar measures.
Comment: Maybe you know the theorem saying that for a locally compact topological group $G$, there exists exactly one Haar measure $\mu$. Now, if your ring is locally compact, then you have exactly the usual Haar measure. But this may fail to be a ring-Haar measure.
Comment: I know that theorem, but I'm not going to assume the locally compact Hausdorff (LCH) condition.  I just wonder what kind of rings possess Haar measures, and the LCH condition seems to be getting in the way.
Comment: This works for $\mathbb{Z}$, doesn't it? The discrete topology has the counting measure as the usual Haar measure. With the multiplier $l(x) = 1$ this should satisfy your conditions, since finite sets are mapped to finite sets by left-multiplications.
Comment: While I don't normally care about getting downvoted, this time I need to know why.  I am not familiar with what I'm doing here and need advice.  If this downvoting is not a trolling attempt, please clarify.
Answer: To not load the question with too much text, I decided to add my discoveries as an answer, though very lacking it may be.  However, these results are simple and have no references.  I would greatly appreciate if you find any mistake, if you can add anything to this, or if you make some comments.  My answer here is still loaded with many questions.

Proposition:  For a fixed integer $k>0$, there exists a commutative topological ring of characteristic $k>0$ with a Haar measure.

Let $R_1,R_2,\ldots,R_m$ be topological rings with Haar measures $\lambda_1,\lambda_2,\ldots,\lambda_m$ corresponding to left multipliers $l_1,l_2,\ldots,l_m$.  Define $R:=\bigoplus\limits_{i=1}^m\,R_i$, $\lambda:=\bigotimes\limits_{i=1}^m\,\lambda_i$, and $l:=\prod\limits_{i=1}^m\,\left(l_i\circ \pi_i\right)$, where $\pi_i:R\to R_i$ is the canonical projection.  Then, under the product topology, $R$ is a topological ring with Haar measure $\lambda$ with respect to the left multiplier $l$.  Hence, if $k_i:=\text{char}\left(R_i\right)$, then the characteristic of $R$ is $\text{lcm}\left(k_1,k_2,\ldots,k_m\right)$.  In particular, we know that there exists a ring of a given prime characteristic which possesses a Haar measure, so that there is a ring of a characteristic $k$ which has a Haar measure, where $k$ is a square-free positive integer.  It is therefore left to find a ring of characteristic $p^j$ with $p$ being prime and $j>1$ that possesses a Haar measure.
Now, let $R:=\Big(\mathbb{Z}\big/\left(p^j\,\mathbb{Z}\right)\Big)[\![T]\!]$.  Each $f(T)\in R$ can be written as $p\,f_0(T)+f_1(T)$, where $f_0(T),f_1(T)\in R$ and the nonzero coefficients of $T^i$ in $f_1(T)$ are not divisible by $p$.  Let $\lambda$ be the Haar measure of the group $(R,+)$, which is compact and so we can assume $\lambda(R)=1$.  Let $l(f):=l\left(f_1\right)$ for all $f(T)\in R$, $l(f):=1$ if $f(T)$ is an invertible element of $R$, $l(0):=0$, and $l(T):=\frac{1}{p^j}$.  Extend the definition of $l$ onto $R$ using the multiplicativity condition.  Then, $R$ as a ring has a Haar measure $\lambda$ with respect to the left multiplier $l$ (which is also a right multiplier).  Ergo, there exists a topological ring of characteristic $p^j$ with a Haar measure.
Now, how about simple rings with Haar measures?  We know that the characteristic of a simple ring is either $0$ or a prime integer.  Then, for a fixed prime $p\in\mathbb{N}$, does there exist a simple topological ring of characteristic $p$ with a left, right, or two-sided Haar measure?  (For the case of rings of characteristic $0$, $\text{Mat}_{n\times n}(\mathbb{R})$ and $\text{Mat}_{n\times n}(\mathbb{C})$ are simple topological rings with Haar measures.)

Proposition:  Any ring with a left, right, or two-sided Haar measure is uncountable.

If $R$ is a countable nonzero ring, then $\left\{0_R\right\}$ must be of zero measure, so that $R=\bigcup_{r\in R}\,\big(r+\left\{0_R\right\}\big)$ has zero measure, but this contradicts positivity of Haar measures of the group $(R,+)$.  Hence, the only countable ring with a Haar measure is the zero ring $\{0\}$, which is the unique ring of characteristic $1$, with the counting measure and the two-sided multiplier (or simply the multiplier) $m$ with $m(0):=1$.
Here is another trivial example.  A trivial ring (i.e., a ring with trivial multiplication) is a ring with Haar measure.  For an uncountable trivial ring $R$ and a Haar measure $\lambda$ of the group $(R,+)$, we can define the multiplier $m$ as $m(x):=0$ for all $x\in R$.

Proposition: For any finite group $G$, the group algebra $\mathbb{C}[G]$ equipped with the standard topology of $\mathbb{C}^{|G|}\cong \mathbb{C}[G]$ (again, $\cong$ means "is homeomorphic to") is a unimodular ring with a Haar measure.

This result is due to the Artin-Wedderburn Theorem.  That is, $\mathbb{C}[G]$ decomposes as the direct sum $\bigoplus\limits_{V\,\text{ irrep}}\,\left(V\underset{\mathbb{C}}{\otimes} V^*\right)$ of two-sided ideals $V\underset{\mathbb{C}}{\otimes} V^*$ where $V$ runs over all the (non-isomorphic) simple $\mathbb{C}[G]$-modules and $V^*$ is its algebraic dual.  Since $V\underset{\mathbb{C}}{\otimes} V^*$ is isomorphic (and homeomorphic) to the ring $\text{Mat}_{\dim_\mathbb{C}(V)\times \dim_\mathbb{C}(V)}(\mathbb{C})$ for any finite-dimensional $\mathbb{C}$-vector space $V$, the claim follows.
Similarly, $\mathbb{R}[G]$ is also a unimodular ring for any finite group $G$.  The Artin-Wedderburn Theorem can also be used here to show that $\mathbb{R}[G]$ decomposes as a direct sum of two-sided ideals of the form $\text{Mat}_{n\times n}(\mathbb{R})$ or $\text{Mat}_{n\times n}(\mathbb{C})$.
On the other hand, if $\mathbb{F}$ is a finite field and $G$ is a Lie group, then what can we say about $\mathbb{F}[G]$?  Is there a way to equip $\mathbb{F}[G]$ with a "nice" topology, "compatible" with that of $G$?  If so, under this topology, is $\mathbb{F}[G]$ a ring with a left, right, or two-sided Haar measure?

Under the usual topology of the quaternion skew-field $\mathbb{H}\cong\mathbb{R}^4$, $\mathbb{H}$ equipped with the Lebesgue measure is a unimodular ring with a Haar measure.  Its multiplier is given by $x\mapsto |x|^4$ for all $x\in\mathbb{H}$.  One can also verify that $\mathbb{H}[T]/\left(T^n\,\mathbb{H}[T]\right)$ is a unimodular ring.  Now, I speculate that $\text{Mat}_{n\times n}(\mathbb{H})$ too is a unimodular ring, whilst $\text{Mat}_{n\times n}(\mathbb{H})\times\mathbb{H}^n$ (better denoted by $\text{Mat}_{n\times n}(\mathbb{H})\,{\supset\!\!\!\!\!\!+}\,\mathbb{H}^n$) is non-unimodular.  (Maybe somebody with more experiences in handling $\mathbb{H}$ can help me with my claims.)  What can we say about $\mathbb{H}[G]$ for a finite group $G$?

Definition: A symmetric subset $S$ of a ring $R$ is a subset $S$ of $R$ such that $x\cdot S=S\cdot x$ for all $x\in R$.

If there exists a Borel measurable symmetric subset $S$ of a ring $R$ with a Haar measure $\lambda$ such that $0<\lambda(S)<\infty$, then $R$ is unimodular.  For $l(x)\,\lambda(S)=\lambda(x\cdot S)=\lambda(S\cdot x)=\lambda(S)\,r(x)$ for all $x\in R$ (where $l$ is the left multiplier and $r$ is the right multiplier).  Note that $\mathbb{H}$ is an example of a noncommutative ring $R$ with a Haar measure with such a subset $S$ (by taking $S$ to be the open unit $4$-disc $\big\{x\in\mathbb{H}\,\big|\,|x|<1\big\}$).  Ergo, we have a very weak sufficient condition for a ring to be unimodular.  Is there a noncommutative topological ring with a Haar measure which is not a division ring and which possesses a Borel measurable symmetric subset?

Some benefits of having the notion of Haar measures for rings are as follows.  Firstly, we have, depending on whether the ring $R$ has a left or a right Haar measure, the equalities $$l(t)\,\left(\int_S\,f(t\cdot x)\,\text{d}\lambda(x)\right)=\int_{t\cdot S}\,f(x)\,\text{d}\lambda(x)$$ and $$\left(\int_S\,f(x\cdot t)\,\text{d}\lambda(x)\right)\,r(t)=\int_{ S\cdot t}\,f(x)\,\text{d}\lambda(x)\,,$$ for $t\in R$, for a Borel measurable $S\subseteq R$, and for a measurable function $f:R\to\mathbb{C}$.
Secondly, we may have a way to define the derivative of some function $f:R\to\mathbb{C}$, provided that $R$ is a unital ring, using the formula $$\left(\text{D}_l\,f\right)(x):=\lim_{t\to 1_R}\,\frac{f(t\cdot x)-f(x)}{l(t)-1}$$
or
$$\left(\text{D}_r\,f\right)(x):=\lim_{t\to 1_R}\,\frac{f(x\cdot t)-f(x)}{r(t)-1}\,,$$
depending on whether the ring has a left multiplier or a right multiplier.  (Note that, in cases where the ring is non-unimodular, we may have two types of derivatives: left derivatives and right derivatives.)  These derivatives are not quite the derivatives in the usual sense.  For example, for the ring $\mathbb{R}$, $\left(\text{D}_l\,f\right)(x)=x\,f'(x)=\left(\text{D}_r\,f\right)(x)$.  (This derivative concept may be totally useless as, in most cases, I would expect that the limit does not exist, or otherwise, we would need some kind of manifold structures on $R$, but then there is already a concept of derivatives on manifolds.)

What can we say about the quotient $R/I$, where $R$ is a topological ring with a left, right, or two-sided Haar measure and $I$ is a two-sided ideal of $R$?  Do we have anything similar to https://mathoverflow.net/questions/21704/haar-measure-on-a-quotient?  What are good conditions on $I$ such that the Haar measure on $R$ will "carry over" onto $R/I$?  What are good conditions on $R$ such that a good $I$ exists?
What can we say about topological unital rings $R$ with Haar measures if we add this strong condition to the topology: $x\mapsto x^{-1}$ is a continuous map from $\text{Units}(R)$ into itself?  Here, $\text{Units}(R)$ is the multipliciative group of units in $R$, equipped with the subspace topology.  Topological division rings are examples of such rings with this stronger condition.  My examples as well as others' examples so far obey this condition.  Do we have a situation where a topological unital ring with this strong condition doesn't have a Haar measure, while it will have a Haar measure if this condition is dropped, and vice versa?  What are examples of non-unital rings with Haar measures which are non-trivial or non-commutative?

Now, regarding representations of a topological ring $R$ with a left, right, or two-sided Haar measure, is it possible to introduce a representation theory of $R$ in parallel to the representation theory of topological groups?    I can think of the case where $R$ is a unital $\mathbb{R}$-algebra, where we may use a unitary left $R$-module $V$ of finite $\mathbb{R}$-dimension and define an $R$-invariant inner product $\langle \bullet,\bullet\rangle$ on $V$ via $$\langle u,v\rangle:=\int\limits_R\,\langle\!\langle x\cdot u,x\cdot v\rangle\!\rangle\,\text{d}\lambda(x)$$ for $u,v\in V$ and for a fixed inner product $\langle\!\langle\bullet,\bullet\rangle\!\rangle$ on $V$.  I haven't tried to make anything out of this $R$-invariant inner product yet.  It might not even make sense at all because $\mathbb{R}$-algebras with Haar measures are unlikely to be compact, whence the integral may not be defined or have a finite value in most cases.  We can also look at the Banach space $\mathcal{L}^\kappa(R,\lambda)$ for $\kappa\in[1,\infty]$.
Comment: @PedroTamaroff How is this a blog post?  My post here serves two purposes: (1) to add more questions; (2) to add details so that it may be helpful to other people who are trying to help me find references.  When I could answer some of my own questions, I would return to edit the post.  Maybe it is you who is missing the point.
Comment: While I don't normally care about getting downvoted, this time I need to know why.  I am not familiar with what I'm doing here and need advice.  If this downvoting is not a trolling attempt, please clarify.
Comment: @PedroTamaroff It was a question originally.  Then, I worked out something on my own question.  How is that against the rule?  Am I not allowed to supply my own question with information I have gathered?
Comment: It is not usually encouraged to use MSE as a "personal blog" of some sorts. This post is closer to being a blog post than an actual question.
Comment: You're missing the point: asking questions is OK. Turning a post into a blogpost is not.
Answer: I want to give a little discussion:
Let $R$ be a topological ring and i assume the underlying group to be locally compact with Haar-measure $\lambda$. For $x \in R$ we set $\mu(A):=\lambda(xA)$ and observe
$$\mu(y + A) = \lambda(x(y + A)) = \lambda(xy + xA) = \lambda(xA) = \mu(A),$$
where we assumed that every occuring set is measurable (maybe someone knows a short proof or some sufficient conditions? I don't know if it's possible). So the map $\mu$ is translation invariant.
This is not enough for being a measure. Let $\bigcup_n A_n = A$ be a disjoint union. We obtain
$$\mu(A) = \mu(\bigcup_n A_n) = \lambda(x \bigcup_n A_n) = \lambda(\bigcup_n xA_n) \overset{?}{=} \sum_n \lambda(xA_n) = \sum_n \mu(A_n).$$
The problem: The last occuring union doesn't have to be disjoint (take i.e. $A_0 = {0},A_1 = {a},x$ with $xa = 0$). This is a problem which has to be fixed somehow, maybe with excluding elements which don't induce an injection via multiplication. But this is a stupid fix. There might be elements which don't induce an injection, for which the equality is still true, i.e. if the occuring intersections have measure zero.
Let's assume that this equality holds for all measureable sets. If one can show that $\mu$ is a regular borelmeasure, it would also be a Haar-measure and by uniqueness there exists $l(x) > 0$ such that $\mu(A) = l(x) \lambda(A)$. We see that $l(xy) = l(x)l(y)$.
Now we only have to discuss when $\mu$ is a regular borelmeasure.

Haar Measure of a Topological Ring


If we make a method synchronized then all the instance method will be locked or only the synchronized methods will be locked?

Question: If we make a method synchronized then all the instance method will be locked while executing that method or only the other synchronized methods will be locked?
Comment: don't use the title as content at least add some more information
Answer: Well, if the synchronized method is static then it will be synchronized for all instances, otherwise it will be synchronized for a specific object which called it.
if 1 object tried to access the synchronized method and the object has two calls to that method then the second call can't be proceed until the first operation is done


Onto Functions and Integers

Question: The function $f: ℝ → ℝ$ defined by $f(x) = x^{3}$ is onto because for any real number $r$, we have that $\sqrt[3]r$ is a real number and $f(\sqrt[3]r)=r$. Consider the same function defined on the integers $g: ℤ → ℤ$ by $g(n) = n^3.$ Explain why $g$ is not onto $ℤ$ and give one integer that $g$ cannot output.
I can't think of any integer that cannot be cubed, so this problem has me confused.
Answer: You don't have to think of an integer that cannot be cubed, but of an integer from which you cannot extract a cubic root (staying in $\mathbb{Z}$, of course, it will have a cubic root in $\mathbb{R}$).
For instance, $g(x)=2$ doesn't have any solution if you ask that $x\in \mathbb{Z}$.
Answer: You've got your definitions wrong. "Not onto" means that there exists an integer that is not a cube.
Answer: The problem is not that we can't cube some integer, its that not every integer has an integer cube root. Consider $5\in\mathbb{Z}.$ To say that $5$ is in the image of $g$ is to say that $5^{1/3}\in \mathbb{Z}.$ As we know, $5^{1/3}\approx1.71\not\in \mathbb{Z}$.

Onto Functions and Integers


Partial Image display from Sybase Image data type over ODBC

Question: I have been struggling with this all day yesterday but can't get to the bottom of it.
I have an existing database that I am trying to retrieve an image from (I know image storing is bulky but it's what I'm stuck with).  I am able to query the appropriate database field and get the data out but when I display it, it seems like only part of the data is being displayed.
I am using this code to display the image:
require_once('../odbc_config.php');
if((isset($_GET['ur'])) AND ($_GET['ur'] != "")) {
    $aria_query1_ur = $_GET['ur'];
    $aria_query1 = "SELECT * FROM Patient WHERE PatientId='$aria_query1_ur' ";
    $patient_result = odbc_exec($aria,$aria_query1) or die("Error getting Patient Data");
    $patient_data = odbc_fetch_array($patient_result);
    }
$ID=$patient_data['PatientSer'];
$query = odbc_exec($aria, "SELECT * FROM Photo WHERE PatientSer=".$ID);
$row = odbc_fetch_array($query);
$content = $row['Picture'];
header('Content-type: image/jpeg');
echo $content;

I am calling this code like this:
echo '';

Unfortunately I only seem to be able to display the image partially.  The dimensions of the image are correctly read and I can see the first 50 x 480 or so pixels from the top but after that all I see is a gray background of 640 x 480 pixels.
Like this:
http://i1218.photobucket.com/albums/dd411/Barbs_ldsr/stuff/th_partial_image.jpg
Is it possible the Sybase ODBC driver is only allowing a certain amount of data through?  How would I check or fix this? Or is there a problem with the PHP?
Any help appreciated.
Thanks
Answer: I commented the solution to our problem has to do with the limited text editing the php.ini solves it. Finds the next row.
 odbc.defaultlrl = 4096
 Only enlarges the value for example
 odbc.defaultlrl = 40960000
 and now with this whole picture leaves you. I hope will be of your help and cuerdate we put the answer in the forums where nannies asked for when someone else runs into this will solve
Comment: Thanks a lot... Its saved me :)


Como descobrir se a sessão expirou?

Question: Preciso descobrir quando a sessão expira, em ASP.Net MVC, pra eu mostrar um modal e redirecionar.
Como eu posso fazer isso?
Tem algo no httpcontext que eu posso usar?
Comment: O que você quer fazer? mostrar uma modal para o usuário dizer que quer permanecer logado ou exibir uma modal falando que ele foi deslogado por desuso?
Comment: Desculpe, acho que não me expressei direito rs
Eu quero mostrar uma modal pro usuário avisando que ele foi deslogado por desuso, em seguida redirecionar ele pra página de login.
Answer: Para verificar se a sessão ainda é válida basta verificar a propriedade:  HttpContext.Current.User.Identity.IsAuthenticated.
E faça o código que pretende de acordo com o resultado. (modal, redirecionamento)
Recomendo que veja a documentação oficial para mais detalhes e exemplos.
Comment: Colega, me corrija se estiver errado, mas a propriedade `IsAuthenticated` somente verifica se o usuário esta autenticado, e não que a sessão seja valida, ou seja diferente de null
Comment: Sim, @ThomasErichPimentel, `isAuthenticated` verifica se está autenticado justamente verificando se a sessão daquele usuário ainda é válida. O tempo da sessão deve ser definido de outra forma como `Session.Timeout = 60;` recomendo que veja a [documentação a respeito](https://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout%28v=vs.110%29.aspx).
Answer: Como o servidor não tem uma conexão persistente com o cliente você pode criar um timer em javascript com o mesmo tempo de duração da session no seu servidor.
Ao atingir esse tempo você exibe a modal e ao fechar a modal você pode redirecioná-lo para a tela de login. Não importa se passou alguns segundos a mais ou não, desde que a sessão no servidor não exista mais, ele será redirecionado, se você fez as validações corretas...
Nesse caso não tem com o que se preocupar, mas se ainda quiser desloga-lo, ao atingir o tempo você pode usar uma chamada em ajax (preferência post) em uma simples action que deleta a session.

Como descobrir se a sessão expirou?