Not able to open url in webview

Question: When I load url it shows a window to select browser. For ex. - If I want to open "http://www.facebook.com/" then it show me window to choose chrome or default browser. I am not able to understand why this is happening.
Actually in below code if i successfully got url from server then I hide a sorry image and show webview. Otherwise I show webview and hide sorry image.
webView = (WebView) findViewById(R.id.webView);
            webView.setVisibility(View.VISIBLE);
            ImageView img = (ImageView) findViewById(R.id.image);
            img.setVisibility(View.GONE);
            webView.setInitialScale(1);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setLoadWithOverviewMode(true);
            webView.getSettings().setUseWideViewPort(true);
            webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            webView.setScrollbarFadingEnabled(false);
            webView.loadUrl("http://www.facebook.com/");

Answer: Try to add this line
webView.setWebViewClient(new WebViewClient());
Comment: this is an version issue. If you run your app above 3.0 you no need to write this line but when you run app in older version this line do a trick because if you not specify the webview client the browser will be treated as default webclient in older version.If you really like the solution you can upvote also for appreciate the answer.
Comment: Thanks it works. But why we add this line. Actually I want to know what happen if we add this line..
Comment: make this question as answered ;)
Answer: Add a WebViewClient like this
public class myWebClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }
}

You should override your shouldOverrideUrlLoading() method.
In your UI activity add this line
 web.setWebViewClient(new myWebClient());

It will solve your problem. Hope it helps!

Not able to open url in webview


Consider the multiplicative group $S = \{z:|z| = 1\}$, a subset of $C$. Let $G$ and $H$ be subgroups of $S$.Find order of intersection of $G$ and $H$.

Question: Consider the multiplicative group $S = \{z:|z| = 1\}$, a subset of $C$. Let $G$ and $H$ be subgroups of order $8$ and $10$ respectively. Find order of intersection of $G$ and $H$.
Since $1$ and $2$ both divide $8$ and $10$ so, order must be one of them.
What is the order$?$
Answer: It must be $2$ as $\{\pm 1\}\subseteq G\cap H$.
Notice that, $G$ has order $8$ implies each element of $G$ satisfies $x^8-1=0$. So $8$ distinct elements of $G$ satifies the polynomial $x^8-1\in \Bbb C[x]$ and this polynomial has exactly $8$ roots, namely $\big\{e^{\frac{2ik\pi}{8}}:k=1,...,8\big\}$.  Hence, $G=\big\langle e^{\frac{2i\pi}{8}}\big\rangle$ and similarly $H=\big\langle e^{\frac{2i\pi}{10}}\big\rangle$.
Now, $-1=\big(e^{\frac{2i\pi}{8}}\big)^4\in G$ and $-1=\big(e^{\frac{2i\pi}{10}}\big)^{5}\in H$.
Answer: Hint:
Consider the exact sequence
$$\{1\}\longrightarrow G\cap H\longrightarrow G\times H\longrightarrow GH\longrightarrow\{1\}, $$
where $G\times H  \longrightarrow GH$ maps $(g,h)$ onto $gh^{-1}$. The exactness of this sequence implies that $|G\times H|=|G\cap H|\cdot |GH|$, so you just have to determine the order of the subgroup $GH$. As $G$ and $H$ are cyclic, of orders $8$ and $10$ respectively, you can show that $GH$ is cyclic, of order $\operatorname{lcm}(8,10)$.
Comment: +1 from me, for alternative way of thinking.
Answer: The circle group $S$ has the property that for every $n\in\Bbb N_{>0}$ it has a unique subgroup of order$~n$, which is the cyclic group $C_n=\{\,z\in S \mid z^n=1\,\}$. Also one has $C_d\subseteq C_n\iff d\mid n$, which accounts for all subgroups of $C_n$ as such subgroups are also subgroups of $S$. It follows that whenever $d$ divides $n$ and $m$ one has $C_d\subseteq C_n\cap C_m$, and hence that $C_n\cap C_m=C_{\gcd(n,m)}$.


Envio de ArrayList e valor Geral para outra Activity

Question: Estou criando uma Activity, por exemplo A e nela tenho que adicionar dados de Lançamentos (Esta classe eu Serializei), como nome, tipo, etc... e vou adicionando também o valor geral atualizado na tela e tenho o botão de listar, onde vou listar todos lançamentos e ai que mora meu unico problema... Como enviar o array para esta activity? E quando eu voltar para tela principal vou precisar da lista novamente e o valor geral...
Comment: Aconselho você fazer um [Tuor](http://pt.stackoverflow.com/tour) aqui para aprender melhor com fazer boas perguntas e obter respostas melhores ainda.
Comment: Ficou bem confuso mesmo. Seria bom vc nos dar exemplo do código, de onde você pega essa lista, e etc
Comment: Oii, pessoal... Desculpa... é minha primeira vez aqui, mas pode deixar que estarei melhorando... obrigado!
Answer: Você pode fazer isto:
  Intent it = new Intent(this, proximaAcvitivity.class);
  it.putExtra("dadosC", vetorConta);
  startAcvitity(it);

O exemplo foi visto neste link: http://respostas.guj.com.br/29500-como-enviar-uma-arraylist-para-outra-activity-e-depois-receber-ela-atualizada
Para na volta não recarregar lista, terá que não chamar o metodo que recarrega. Sua tela continuara igual antes de ter trocado de activity.
Comment: Oii! Obrigado pela ajuda... mas o que eu precisava era trabalhar mesmo com startActivityForResult... consegui enviar meu Array para outra Activity e voltar.
Comment: Agora to pesquisando uma forma de clicar na minha lista View e ao clicar os dados do item voltará na activity de edição, onde posso editar o item ou excluir... Tem um exemplo para me indicar?
Comment: não da pra fazer o mesmo caminho de volta?
Comment: Credito que você precise trocar seu listview pelo recyclerview.
Com essa lista você consegue mudar seus "dados" atras do notifydatasetchanged


What's challenging?

Question: How does "challenging" work? On close line calls, sometimes there is a graphic showing whether the shuttle was in or out, but other times players just discuss with the umpire, and the match goes on. What's happening in these cases?
Answer: At high-level tournaments (sometimes only on TV courts), the HawkEye Instant Review System (IRS, informally challenging) allows players - or if neither line judge nor umpire could see the shuttle, the umpire - to challenge line judges' and umpires' decisions. It is regulated by section 4.1.8 of the laws.
As long as the challenges are successful in overturning the line judge's decision, players can challenge as often as they want. To prevent abuse, each side is limited to two unsuccessful challenges per game (until 2015 per match). Players must challenge immediately after the decision, and must not consult with coaches - so when you see an umpire denying a challenge, the player took to long to decide whether to challenge. Typically,  players will raise one finger to indicate that they are challenging.
The umpire will then raise their left arm to indicate to the referee that a challenge has been made.
The HawkEye system, aided by a technician, will then make a decision. Previously, an off-court umpire (on IRS duty) would review the footage and make the decision.
In any case, the decision gets relayed to the umpire, and a corresponding video shown to the audience.
In case of an unsuccessful challenge, the umpire will announce the (unchanged) score and how many challenges are remaining. In case of a successful challenge, the umpire will announce the corrected score.
If the line judge and umpire were not able to make a determination In or Out (e.g. because a player was between line judge and shuttle), the umpire can also call IRS themselves.
IRS is not available on every line; the service lines are not covered by current implementations due to cost reasons.
Only line calls can be challenged. Any fault or let calls are final. In the future, a similar system may be available for service fault calls, and may be fully automated so that a decision can be made immediately, whereupon the procedures laid out above are likely to change.

What's challenging?


replace 0's with 1's and vice versa for a diagonal matrix in R

Question: Can anyone tell me how to replace 0's with 1's and vice versa for a diagonal matrix in R.
Comment: I guess you're using the R programming language?  http://en.wikipedia.org/wiki/R_(programming_language)
Comment: @shookster yes i'm using R programming
Answer: If your matrix is mat and you want to flip all 1s as 0s...
mat <- 1-mat

Comment: +1 Ah. That makes sense... I probably could have thought of that.
Answer: I don't know anything about R but it seems like you can address a matrix like this:
http://cran.r-project.org/doc/manuals/R-intro.html#Array-indexing
I would suspect you could solve your problem using a for loop:
http://cran.r-project.org/doc/manuals/R-intro.html#Repetitive-execution
Answer: Since matrices are stored in mode of numeric, type of integer/double, and storage mode integer/double (assuming that matrix holds numerical values) you can use simple square bracket indexing to address specific values in them, e.g.
# create dummy data
> m <- matrix(rnorm(25), 5)
> mode(m)    # check mode
[1] "numeric"
> typeof(m)  # check type
[1] "double"
> storage.mode(m)
[1] "double"

Now, in order to create diagonal matrix, you can use lower.tri and upper.tri functions, which return logical values for matrix elements beneath and above the main diagonal, respectively.
You can use lower.tri and upper.tri functions to set off-diagonal elements to 0.
> m[lower.tri(m)] <- 0
> m[upper.tri(m)] <- 0
> m
          [,1]       [,2]       [,3]      [,4]      [,5]
[1,] 0.3356640  0.0000000  0.0000000  0.000000 0.0000000
[2,] 0.0000000 -0.2940369  0.0000000  0.000000 0.0000000
[3,] 0.0000000  0.0000000 -0.4490546  0.000000 0.0000000
[4,] 0.0000000  0.0000000  0.0000000 -1.093924 0.0000000
[5,] 0.0000000  0.0000000  0.0000000  0.000000 0.3199157

You can, of course, set any constant to lower/upper diagonal elements, be it numerical, character, logical, NA, etc...
Once you have set zeros as an off-diagonal elements, you can simply use square-bracket indexing. A little diversion: bare in mind that mathematically, vectors are special cases of matrices (and vice versa), but the same doesn't stand for R:
> is.vector(m)
[1] FALSE
> is.matrix(1:10)
[1] FALSE

But, finally, you can do:
> m[m == 0] <- 1

This will insert 1 in matrix wherever zeros occur. You can use diag function to access/change the diagonal elements, for example:
> m[m == 1] <- 0
> diag(m) <- rep(pi, 5)

will change your diagonal matrix to scalar one.
After this boring post of mine, let us all hope that it helped someone, somehow...
Cheers!
Comment: And to confuse you a bit more, try `m[lower.tri(m)] <- 1:10` and see what happens. =)


Como verificar se o usuário digitou algo quando solicitado uma entrada em C#

Question: A validação a seguir verifica se uma entrada é um número positivo.
<code>if (Q[i] < 0) {
    Console.WriteLine("Digite um número positivo!");
    goto Start;
}
</code>
Assim como esta verificação, caso nada fosse digitado, o programa apenas voltaria para o "Start" sem apresentar um erro.
Isto é, como faço para verificar se a entrada for vazia, pois o usuário não digitou nada?
Comment: Trate com alguma variável se a entrada de dados é NULL ou não.

string text;

if (text == NULL){
   Console.WriteLine("Não foi digitado nada");
}
else{
   Console.WriteLine("Foi digitado : ", text);
}
Answer: <code> Console.Write("Informe um valor: ");
 string value = Console.ReadLine();
 if (String.IsNullOrEmpty(value))
 {
     Console.WriteLine("O usuário não informou valor");
     goto Start;
 }
 else
 {
    Console.WriteLine("O valor é: {0}", s);
 }
</code>
Observe que usei o método booleano String.IsNullOrWhiteSpace, pois ela indica se uma cadeia de caracteres especificada é null, vazia ou consiste apenas em caracteres de espaço em branco. Logo se a variável não tiver nenhum caractere, consequentemente entrará no primeiro if, informando que o usuário não digitou nenhum valor.
Espero ter ajudado.


How to "sync"/revision-control an entire mysql database with all git commits and checkouts?

Question: I want to "synchronize" a mysql database (and not just the schema) with all git commits and checkouts (probably via hooks) in Linux/BSD/Unix enviornment.
[Useful when controlling the entire presentation + content of a mysql-based web site/application, and other mysql applications, as the code for said sites/applications are under development, and/or to "rev control" the entire website. Presumably useful for pushing "copies" (exclusively via git) of small, relatively-static websites to various test/production servers that each have separate, independent mysql servers.]
Potential design/workflow: a git commit dumps a mysql database and adds said database (in a .sql file) to the commit (probably via a pre-commit hook).  A subsequent git checkout imports said .sql file (from the current git branch) to the database (probably via a post-commit hook), hence "synchronized" with the git commit/branch.  This basically rev-controls the entire database, synchronizing each database rev to a git commit.
How to implement this?
Comment: (I plan to provide my own answer after the "8hrs self-answer" rule constraint lapses.  Will be a variant of my [mysql-schema-only save upon git commits answer](http://stackoverflow.com/a/8483269/605356).)
Comment: I don't get how your MySQL database is tied at all to Git. Could you please explain this part more clearly?
Comment: @Ryan Bigg. I've updated the question, hopefully that addresses/answers yours.
Comment: This doesn't seem efficient. Assume that database A deleted table D1, whereas database B inserted rows in D1. How would you sync in this scenario? Why don't you use replication?
Comment: Prob best to wait for me to post answer before discussing further.  Waiting for 8hr time limit to pass... feel free to remind me in the morning.
Comment: @JohnnyUtahh Could you provide your answer as promised? I have exactly the same question! :)
Comment: @Connum Was wondering why there weren't more people doing this.  Could you maybe uptick my question?
Answer: My WordPress-database-control example follows.

WordPress-specific parts. ./dbase-baseurl-set.sh $baseurl needed to tell WordPress which host it's on--WP unfortunately not that modular.  ./dbase-baseurl-set.sh runs from the top level of the working tree.
git hooks env vars. Far-and-away best doc I've found to answer "what's the working directory" and "which environment variables are set" in git hooks: Mark's Blog: "Missing git hooks documentation."
Bybass pre-commit.  Employ git commit -n [...] to avoid executing the pre-commit hook.  (Potentially useful when first-time adding/committing dabase-dump.sql.gz.)
Optional. git-control the hooks.

Example Ubuntu session:
root@host /var/www/.git/hooks# ls -lF
total 12
-rwxr-xr-x 1 root webmasters  218 2012-02-23 22:06 post-checkout*
lrwxrwxrwx 1 root webmasters   13 2011-12-13 21:45 post-merge -> post-checkout*
-rwxr-xr-x 1 root webmasters  357 2012-02-23 22:06 pre-commit*
drwxr-sr-x 2 root webmasters 4096 2011-12-13 10:19 samples/
root@host /var/www/.git/hooks#
root@host /var/www/.git/hooks# cat pre-commit
#!/bin/bash
set -e
# run with '--no-data=true' to capture only schema
# mysqldump -umysqluser -pmysqlpasswd wordpressdbase --no-data=true | gzip > wordpressdbase-schema.sql.gz
echo -n 'dumping and compressing wordpress database... '
mysqldump -umysqluser -pmysqlpasswd wordpressdbase | gzip > wordpressdbase.sql.gz
git add wordpressdbase.sql.gz
echo 'done'
root@host /var/www/.git/hooks#
root@host /var/www/.git/hooks# cat post-checkout
#!/bin/bash
set -e
baseurl="http://host.domain.com"
echo -n 'loading wordpress database... '
gunzip -c wordpressdbase.sql.gz | mysql -umysqluser -pmysqlpasswd wordpressdbase
echo 'done'
./dbase-baseurl-set.sh $baseurl
root@host /var/www/.git/hooks#
root@host /var/www/.git/hooks# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 10.04.3 LTS
Release:    10.04
Codename:   lucid
root@host /var/www/.git/hooks#
root@host /var/www/.git/hooks# git --version
git version 188.8.131.52
root@host /var/www/.git/hooks#

Contents of dbase-baseurl-set.sh (note said file was edited from its original for best presentation, unlikely it introduced bugs, but still possible):
#!/bin/bash
# Reset the WordPress "base" URL.  Useful in a git hook
set -e
echo -n "setting WordPress baseurl to '$1'... "printf -v sqlstr 'SELECT * FROM wp_options WHERE option_name = "home" OR option_name = "siteurl"; UPDATE wp_options SET option_v
alue = "%s" WHERE option_name = "home" OR option_name = "siteurl"' "$1"
echo "$sqlstr" | mysql -umysqluser -pmysqlpasswd wordpressdbase > /dev/null
echo "done"

Comment: Could you post your code for dbase-baseurl-set.sh?  I'm looking for an efficient way to do the same...
Comment: @ColinSmillie Code for said file added. Pls ping me again if there's more questions. Enjoy.


Solving the integral $\int\frac{1}{\sqrt{x^2+1}}\,dx$

Question: I need to solve
$$\int\frac{1}{\sqrt{x^2+1}}$$
but I'm nowhere near the solution. I tried substituting
$u = x^2 + 1$
such that $dx = \frac{1}{2x}$
yielding
$$\int u^{-1/2} du = \frac{1}{2x}\frac{u^{1/2}}{1/2}=\frac{\sqrt{u}}{x} =\frac{\sqrt{x^2+1}}{x}$$
but this is nothing near the solution of
$$\int\frac{1}{\sqrt{x^2+1}} = ln|\sqrt{x^2+1}+x|+C$$
Comment: See e.g. [How to integrate $\frac{1}{\sqrt{1+x^2}}$ using substitution?](https://math.stackexchange.com/questions/179129/how-to-integrate-frac1-sqrt1x2-using-substitution)
Comment: Try $\;x=\sinh u\;$ ....
Answer: Hint: Substituting $$x=\tan(t)$$ then we get $$x^2+1=\tan^2(t)+1=\frac{\sin^2(t)+\cos^2(t)}{\cos^2(t)}=\frac{1}{\cos^2(t)}$$
and $$dx=(\tan^2(t)+1)dt$$
Answer: Use the trigonometric substitution $x(\theta)=\tan{\theta}$:
$$\int\frac{1}{\sqrt{x^2+1}}\,dx=
\int\frac{1}{\sqrt{[x(\theta)]^2+1}}x'(\theta)\,d\theta=\\
\int\frac{1}{\sqrt{\tan^2{\theta}+1}}\sec^2{\theta}\,d\theta=
\int\frac{\sec^2{\theta}}{\sqrt{\sec^2{\theta}}}\,d\theta=\\
\int\frac{\sec^2{\theta}}{|\sec{\theta}|}\,d\theta.
$$
Here, $-\frac{\pi}{2}<\theta<\frac{\pi}{2}$ because on that interval $\tan\theta$ gives you the entire real line and $\sec{\theta}\ge 1$ there. Therefore, $|\sec\theta|=\sec\theta$:
$$
\int\frac{\sec^2{\theta}}{|\sec{\theta}|}\,d\theta=
\int\frac{\sec^2{\theta}}{\sec{\theta}}\,d\theta=
\int\sec{\theta}\,d\theta.
$$
Now just use the following fact:
$$\int\sec{x}\,dx=\ln{|\tan{x}+\sec{x}|}+C.$$
Comment: For anyone curious, the fact that $\int \sec x\, dx = \ln \left| \tan x + \sec x\right|+C$ is proved here: [How do I integrate $\sec(x)$?](https://math.stackexchange.com/questions/506780/how-do-i-integrate-secx)


Forms - Save Draft and unique user access code to Resume (on any computer)

Question: Is it possible for the site users to get a unique access code, so that they can resume the form from any computer?
I am currently using the Webform module for its "Save Draft" feature and am wondering if it is also able to provide an access code ...
Answer: You could always have users register accounts, use their passwords as the access code, and then use one of the revision management modules (Workbench, Revisioning/Workflow, etc.) to handle draft/publishing.
Comment: Thanks. Is there a quicker way to get the access code? The client doesn't want to deter users by having to register...
Comment: You could add on to the webform module yourself with custom code, but that would probably be pretty complicated in this case.
Comment: Cheers for that


How many $3$-character strings can be formed using the letters of word MISSISSIPPI?

Question: Only the letters that repeat in the original word can be repeated. I've tried $\frac{11!}{4!4!2!}$ and the for n = then result of the previous permutation I did $\binom{n}{3}$. Just feels like there are way more values than necessary.
Comment: Does the order of the characters in the 3 character  strings matter ?
Comment: @trueblueanil yes.
Comment: Have you studied exponential generating functions ?
Comment: @trueblueanil nope.
Answer: Hint
Since you don't know exponential g.f's, an easy  mechanical alternative is outlined below:
There are $4 S's, 4 I's, 2 P's \;and\; 1 M$
Form $4$ digit numbers from largest to smallest,  (from the characters available),  each row summing to $3$, eg
$3000\;2100\;2010\;2001\;1200\;1110 ...\;$ and add their permutations, viz
$3!(\frac 1{3!} +\frac1{2!1!} +\frac 1{2!1!} + \frac1{2!1!}+\frac1{1!2!}+\frac1{1!1!1!}...)$
Answer: Rather than coming up with a single expression, it is easier to enumerate different possibilities. We can start with M: either there is one, or there isn't.

 If there is no M, the three characters can be any combination of I, S and P, with just one exception: it can't be PPP. So there are $3^3 - 1 = 26$ possibilities.

 If there is a M, then there are three possibilities for its position. The other two characters can be any combination of I, S and P. So there are $3 \times 3^2 = 27$ possibilities.

 Conclusion: in total there are $26 + 27 = 53$ possibilities.
Comment: The spoilers don't add anything to your answer, whatsoever.
Answer: Answer:
We see that there is 1 M, 4 I's, 4 S's, and 2P's in MISSISSIPPI.
As we want 3 letters, we, technically, have 1 M, 3 I's, 3 S's and 2P's now.
We have MIS, MIP, MSP, MSI, MPI, MPS, MII, MSS, MPP - 9 for M

 IMS,ISM,IMP,IPM,ISP,IPS,ISS,IPP,IIM,IIS,IIP,III,IMI,IPI,ISI - 15 for I, and 15 again for S.

 PMI,PIM,PMS,PMP,PIP,PSP,PSM,PIS,PSI,PII,PSS,PPM,PPI,PPS - 14.

 Therefore, our answer will be $9+15+15+14=53$.
Comment: You missed some combinations: IMI, IPI, ISI, PMP, PIP, PSP.
Comment: And how do you know that you aren't missing any others, in addition to what Aetol pointed out?
Answer: The first letter can be any of 4 possibilities (I, M, P, or S).
The second letter can also be any of those four except that MM is not a valid combination (as MISSISSIPPI has only one M).  So there are $4 \times 4-1=15$ valid permutations for the first two letters.
Having the same 4 options for the third letter brings us up to $15 \times 4 = 60$ permutations, but we must exclude PPP (since we're limited to two P's), and six permutations that already have an M in the first two letters (IMM, MIM, MPM, MSM, PMM, and SMM).
This leaves us with 53 valid permutations: III, IIM, IIP, IIS, IMI, IMP, IMS, IPI, IPM, IPP, IPS, ISI, ISM, ISP, ISS, MII, MIP, MIS, MPI, MPP, MPS, MSI, MSP, MSS, PII, PIM, PIP, PIS, PMI, PMP, PMS, PPI, PPM, PPS, PSI, PSM, PSP, PSS, SII, SIM, SIP, SIS, SMI, SMP, SMS, SPI, SPM, SPP, SPS, SSI, SSM, SSP, and SSS.


For a branch-defined function, analyze the uniform convergence of it and of its series

Question:
Let $(f_n)$ be a sequence of functions on $\mathbb{R}$ such that $$f_n(x) = \left\{ \begin{array}{ll} 0, x \leq 0, \\ \frac{x}{n^2}, x \in (0,n^2), \\ 1, x \geq n^2.  \end{array}\right. $$
a) Show that $(f_n)$ converges point-wise on $\mathbb{R}$.
b) Determine whether $(f_n)$ converges uniformly on $\mathbb{R}$.
c) Show that $\displaystyle \sum_{n=1}^\infty f_n$ converges point-wise on $\mathbb{R}$.
d) Show that $\displaystyle \sum_{n=1}^\infty f_n$ is uniformly convergent on every interval $[0,a], a > 0$, but it is not uniformly convergent on $\mathbb{R}$.
e) Show that $s:\mathbb{R} \to \mathbb{R}$ given by $$ s(x) = \sum_{n=1}^\infty f_n(x)$$ is continuous.

For a), I think that we can easily see that $f_n$ tends to the function $f \equiv 0$ for all $ x \in \mathbb{R}$ as $n \to \infty$.
For b), I am not sure how to determine whether $(f_n)$ is uniformly convergent. Do we just try and find out if $\displaystyle \sup_{x \in \mathbb{R}} \{f_n(x) - 0 \} \to 0$ as $n \to \infty$? Because if that's how it should be solved, then the function does not converge uniformly, since the supremum is $1$.
I think that for c) we have that for all $x \in \mathbb{R}$, the series $\displaystyle \sum_{n =1}^\infty f_n(x)$ contains a finite number of 1's and the other terms are $\frac{x}{n^2},$ so I think it's safe to assume that the series converges point-wise?
I do not know how to start d) (maybe for the interval $[0,a]$, we can apply the Weierstrass M-test). My intuition says that there is something bad happening when $x \to \infty$. The same goes for e).
Comment: Hint for $b.)$ what is $f_n(n^2)-f(n^2)$?
Comment: That's exactly what I thought, I also edited the question right about now.
Comment: Uniform convergence doesn't mean for $\sum_{n=1}^\infty f_n(x)$. Possibly you mean $\sum_{k=1}^n f_k(x)$ right?
Answer: I think e) is false. In fact, $s(1+\frac 1 k) \to \sum_{n=2}^{\infty} \frac 1 {n^{2}}+1$ whereas  $s(1) = \sum_{n=2}^{\infty} \frac 1 {n^{2}}$.
Your argument for a) is correct. For c) use the fact that $f_n(x) \leq \frac x {n^{2}}$ for all $x \geq 0$. This also proves uniform convergence on $[0,a]$ by M-test. Second part of d) follows from b).
Answer: (b) $f_n$ is not uniformly convergent. We show that this is not the case even when $x\in (0,n^2)$. Recall the definition of uniform convergence:$$\forall \epsilon>0\quad,\quad \exists N\quad,\quad\forall n>N\quad,\quad |{x\over n^2}|<\epsilon$$therefore $$n>{\sqrt{x\over \epsilon}}$$this means that we must choose $N=\lfloor {\sqrt{x\over \epsilon}}\rfloor +1$ which is surely dependent to $x$ not only to $\epsilon$, therefore $f_n(x)$ is not uniformly convergent.  (c) the statement is false since $s(x)$ is no function of $n$, but for $s_n(x)$ with the following definition$$s_n(x)=\sum_{k=1}^{n} f_k(x)$$we have $$s_n(x)\to s(x)$$where $$s(x)=\sum_{k=1}^{\infty} f_k(x)=\begin{cases}0&,\quad x<0\\\sum_{n=1\\ n>\sqrt x}^{\infty}{x\over n^2}+\sum_{n=1\\n\le \sqrt x}1&,\quad x\ge 0\end{cases}$$here is a sketch of $s(x)$

 As you see, the function is continuous (which can be proved easily only in points $x$ with $x=k^2$ for some $k\in \Bbb Z$) and piecewise linear whose slope on each piece (from $k^2$ to $(k+1)^2$ increases unboundedly) therefore the function is uniformly continuous on each $(0,a)$ for $a\in \Bbb R^+$but not on $\Bbb R$. The proofs are easy and straight forward. Finally we have
d,e) $s(x)$ is continuous though not uniformly and $s_n(x)$ tends to $s(x)$ pointwise


For which values of $k$ can $( x +y +z)^2 + k(x^2 +y^2 +z^2)$ be resolved into linear rational factors?

Question: My first attempt : Tried to solve by polynomial formulas but can't proceed after few steps.
Second attempt : Tried by vectors  but found nothing useful.
Answer: If $ax^2+by^2+cz^2+2ryz+2sxz+2txy$ is a homogeneous quadratic
in three variables, then it can only
split into linear factors if the determinant
$$\begin{vmatrix}a&r&s\\r&b&t\\s&t&c\end{vmatrix}=0.$$
Here, that determinant is
$$\begin{vmatrix}k+1&1&1\\1&k+1&1\\1&1&k+1\end{vmatrix}.$$


Interface-EJB not injected in no-interface-EJB

Question: Awaiting answers.
I've a JAX-RS controller (Jersey 2.21 on WildFly 9.0).
@Named
@Path("v1/populateList/")
public class PopulateDataController {

    @EJB
    ListItemService listItemService;

    @GET
    @Path("auto")
    @Produces(MediaType.TEXT_PLAIN)
    public String populateList(){
        listItemService.populateList();
        return "done";
    }
}

The below ListItemService no-interface EJB is successfully injected in above JAX-RS controller.
@Stateless
public class ListItemService {

    @EJB
    ListItemDao listItemDao;

    public void populateList(){
        listItemDao.persist();
    }
}

However, the below ListItemDaoImpl interface-EJB is not in turn injected in above no-interface EJB.
@Stateless
public class ListItemDaoImpl implements ListItemDao{

    @PersistenceContext(unitName = "pu")
    private EntityManager em;

    public void persist(){
        ListItem listItem = new ListItem();
        listItem.setLevel(1);
        listItem.setName("item1");
        em.persist(listItem);
    }
}

The listItemDao remains null in populateList() method of ListItemService, causing NullPointerException.
How is this caused and how can I solve it?
--- Edit and update ---
I tried to make a Singleton bean to run on startup (to check my app logic).
It works fine without JAX RS. So its clear that the problem is not with EJB but JAX RS. (Do correct me if wrong)
    @Singleton
    @Startup
    public class TestController {
        @EJB
        ListItemService listItemService;

        @PostConstruct
        void test(){
        System.out.println("starting..........");
        listItemService.populateList();
        System.out.println("ending..........");
        }

    }

Comment: Did you annotate your 'ListItemDao' interface with @Local ?
Comment: @BalusC Thanks for fixing my question
Comment: @Szarpul yes. `@Local
public interface ListItemDao{
    void persist();
}`
Comment: @BalusC oh, I am not an expert. Just thought that the error trace might have some other information (like class names etc) or otherthings that I might not be aware of the importance and those might be useful for others.
Comment: Not in this case. A specific EJB not being injected is sufficient clue. Keep your question as focused as possible. You're not interested in why a `NullPointerException` is thrown. You're interested in why the EJB not is injected.
Comment: oh ok. I will remove the error
Comment: On GlassFish 4, your code works fine. I suspect this is an issue with WildFly
Comment: @perissf Did you tried it on wildfly? and you dont have other envirnment like web.xml etc. Can you paste the full project that worked for you in glassfish?
Comment: I have not tried on wildfly. On GlassFish I have used web.xml for registering the RESTful web service as explained in any "Hello World" jax-rs tutorial. Note that I have omitted the injection of the PersistenceContext because it's not relevant to the problem.
Comment: @perissf would definitly need it to work on wildfly and with environment xml or other relevant things. It also seems a known problem if you google
Comment: Tested on WildFly 10.0.0.CR2. Works fine without issues. I suspect there are other issues in your code that you haven't mentioned. Maybe you have used some imports from wrong packages? Is this a true MCVE? See [how to ask](http://stackoverflow.com/help/how-to-ask).
Comment: @perissf in that case, here is the full package I have http://126.96.36.199/goo.zip
Answer: Creating the following class helped.
    @javax.ws.rs.ApplicationPath("api")
    public class InjectionApplication extends javax.ws.rs.core.Application {
        private Set<Object> singletons = new HashSet<Object>();
        private Set<Class<?>> classes = new HashSet<Class<?>>();

        public InjectionApplication() {
        // no instance is created, just class is listed
        classes.add(ListItemController.class); //replace with yours
        classes.add(ParseFeedController.class); //replace with yours
        //add more or use some auto class finding technique

        }

        @Override
        public Set<Class<?>> getClasses() {
        return classes;
        }

        @Override
        public Set<Object> getSingletons() {
        return singletons;
        }
    }


Categorical vs Quantitative Variables

Question: I have a project I am working on, and while this seems like a simple question, I thought I'd post this as there has been some different opinions I have heard on this. I have a list of the following variables (shown below) from a data set. One part of the project is to "identify each variable as quantitative or categorical (with levels specified for each categorical variable)". Can anyone give me a rule of thumb for this? Our goal is to build a model for selling price of a house. Obviously this help knowing which is which so you can add the categorical variables last for the predictors, but we haven't talked much about this aspect. I know this is probably way easier than I am making it out to be, but I wanted to get some opinions. I have some ideas, for instance, if I make the basement square footage an indicator (Y/N), that could be categorical. Any suggestions? Thanks!

Thanks so much for any suggestions!
Comment: What do you mean by adding the categorical variables last?
Comment: In our class we are talking about OLS/WS/GLM, we were advised that while, at times, categorical values are good to have in our models, we should add them last (the last ones as predictors) as typically they are just 0 and 1 values.
Comment: Bat what does that mean? The OLS equation $\hat{beta} = (X^TX)^{-1}X^Ty$ does not care about variable order.
Comment: azdatasci - two points. The ORDER that you put variables in a regression model doesn't matter at all. Secondly, if you are talking about whether it's OK to put "categorical" variables in a regression model, it depends on on the type (see my answer below). Binary categorical  variables are perfectly fine. Ordinal categorical variables are controversial and it depends on the context. Nominal categorical variables will get you garbage unless you transform them into a set of binary "dummy" variables.
Comment: @GrahamWright I think what she is getting at with this case study is the "dummy variables" since that was the last section of lectures we went over.
Answer: I think whoever wrote the question is causing you additional confusion by conflating two concepts. The term "quantitative variable" (which is not a term I've ever really heard before) is especially confusing/ambiguous, since it's not clear whether it's referring to the kind of data stored in the variable  or what that represents.
Firstly, in a given dataset a variable can store "numeric" data meaning that is only contains numbers, or it can store "string" data, meaning that it can contain words or symbols or whatever.
String variables are, in general, useless for ANY statistical analysis - if you want to do anything with them you usually need to transform them into numeric variables that only contain numbers. Unless otherwise specified we always assume variables are numeric.
Now, we can classify (numeric) variables by what the numbers they store actually represent.
In a "continuous" variable the numbers actually represents "numbers of things." So in the variable "age" a value of "35" means "35 years old," and in a variable "income" a value of "30,213" mean "30,213 dollars (per year)." This is important to know because it tells us that a "one unit" increase in these variables actually means something - it means "one more dollar" or "one more year of age." There is also an additional sub-type of continuous variable called an "interval level" variable, in which the zero value is actually meaningful (so age and income are both technically "interval level continuous variables" whereas "degrees Fahrenheit" is continuous but NOT interval level).
In a "categorical" variable by contrast, the numbers don't actually represent numbers, but are simply "codes" to represent different categories (a good statistical program will usually allow you to see the codes when looking at the variables, even though the values are still stored as numbers). So you might have a variable "gender" where a value of 0 represents "male" and 1 represents "female." In particular, this gender variable is a binary categorical variable because there are only two options (but you could also have a gender variable with more than two options). Some categorical variables are "ordinal" where higher numbers represent "more" of something (like a "how happy are you"  question with values of 1=not very happy 2=kind of happy 3=very happy, but note that we have no idea whether the "distance" between 1 and 2 is the same as between 3 and 4), while others are "nominal," where the order of the categories is arbitrary (e.g. a "race" variable where 1="white" 2="Black" and 3="other").
Categorical variables require special treatment in statistical analyses because the numbers they store aren't "really" numbers. For binary categorical variables you can often get away with treating them like continuous variables because a "one unit increase" (say from 0 to 1) is still a meaningful concept. But treating ordinal variables like this is dangerous and treating nominal variables like this will get you garbage.
Comment: +1 I agree that it is important to decouple the statistics concept of variable type and the software concept of data type. Both matter but not in the same way.
Comment: Overall good answer, but I don't really agree with the notion that string variables are useless and should always be converted to numbers. Lots of string variables like house color are categorical, so converting to numbers doesn't achieve much except opening the door to erroneously treating them as numeric/ordinal variables. Keeping them as strings (or in R, as *factors* which can take a limited number of fixed values) seems preferable.
Comment: Again I'm not really sure what your professor means by "quantitative" (and I teach stats myself) but in general a categorical variable is any variable where the values don't represent actual numbers. So for for the variable "year:"  if one house was built in 1992 and another was built in 1982 we can figure out how many years apart they were built by doing subtraction. But we can't do that for "condition," even though it is represented by a scale of numbers, because  a value of 3 doesn't mean the house has "3" of anything.
Comment: You write "gender is a binary categorical variable because there are only two options". There are many other possible examples you could use to make your point more simply and without a real risk of upsetting some people who would contest this on non-statistical grounds (and I tend to agree).
Comment: While this is super great information and very detailed, I think it's getting a bit off the main topic of my original question. I'll ask the professor about this. As far as this data set goes, would I be correct in stating that ID and waterfront are categorical? Grade and condition are continuous scales, so even though in my head they sound like categories, should I consider them to be quantitative? Other than the model stuff, we have also been asked to identify if each variable is quantitative or categorical and to list the levels for the categorical ones.
Comment: I've often seen  _quantitative_ used as a term for kinds of variables, usually to mean interval and ratio variables. People should just standardize on the terminology I happen to like....
Answer: A quantitative variable is one whose values can be measured on some numeric scale. Some examples in your dataset are price, bedrooms and bathrooms. Note that all these share numeric relationships to one another e.g. $10 > 6 > 4$ and $10 = 6 + 4$.
A categorical variable is one who just indicates categories. It's values don't have any numeric relationships to one another. For example, id is a categorical value. If you add the IDs $2+1$, you won't get ID $3$, because they are just an arbitrary enumeration.

Note: the distinction does not have to do with the data type of the variable, rather what that variable represents! It is possible to have a quantitative variable with string values, as well as a categorical one with numeric ones.
Some other examples:

Zip code: this is a categorical variable with numeric values. The relationship z1 < z2 has no meaning in zip codes.
House color (e.g. 'red', 'blue'): this is a categorical variable with string values. The relationship 'red' < 'blue' has no meaning.
Age: this is a quantitative variable with numeric values. It is pretty obvious that you can say 20 < 30, in this context.
Rating (e.g. 'bad', 'good', 'excellent'): this is a quantitative variable with string values. You can absolutely say 'bad' < 'good' < 'excellent'
Comment: That last one would be an ordinal variable, which is kind of a hybrid of numerical and categorical.
Comment: @Dave aren't ordinal variables considered quantitative?
Comment: Ordinal variables are hybrids, and they can be tricky. For instance, I would say that a "star" rating for a movie is an ordinal variable.
Comment: Well I'm not sure if binary variables are considered categorical or not... condition and grade are ordinal which is kind of ambiguous (I'd put these more close to quantitative than categorical). Depending on their format dates can be considered quantitative, yes.
Comment: @Djib2011 So for the context of the list above, I get that ID is categorical. Waterfront is just a 0 or 1 variable noting if it has a water front or not. Would this be categorical? What about condition and grade? Those are just values given to assess that condition and grade, so to me it puts the homes into a category on those respective variables. Finally, I see an association with the dates sold and the date renovated, so using the dates, would these be considered quantitative? I would assume so since its just a time period. Thanks!

Categorical vs Quantitative Variables


Multi-site: how to handle some module differences?

Question: I have a Drupal 7 multi-site installation with some shared modules. Some of these modules declares some forms. And here comes the problem: How to make these forms look different in two different sites? For example: In one site the whole form needs to be on a single page but in another site it needs to be divided in two steps, how can I solve this without change the module code?
I tought in some solutions:

Create a custom module for the site that needs the form to be in two steps.
Break in two steps using javascript and handle the navigation on the client site.
Create a configuration on the shared module (the problem here is that I'd have to create a specific configuration for every possible customization on the form).
Create a template for the form and handle this steps in specific site theme.
Change the module to, instead of creating a form using FAPI, creates a webform node that could be changed for the specific site when the module is installed.

What would be perfect for me is that is someway I could implement a form alter hook in the theme but it isn't possible, right?
What do you think? How you solve this problem?
Answer: Create three modules named site1.module, site2.module and site1site2.module respectively. Store changes (hook_form_alters) for site1's forms (including those of your custom module) in site1.module, sites2's forms in site2.module, and forms of both sites in site1site2.module.
The module names will of course need to be swapped for more meaningful alternatives.
Answer: You can always call hook_form_FORM_ID_form_alter (not sure about the exact hook name) in a custom module you create and change the form according to a URL that is probably different depending on the site that you are accessing:
<code>function mymodule_form_myform_form_alter($form, &$form_state){
     switch(urldecode(request_uri())):
         case 'www.mywebsite1.com': $form['new_field'] = array('#type','textfield');
               break;
         case 'www.mywebsite2.com': $form['new_field'] = array('#type','textarea');
}
</code>
Comment: I didn't like your solution. My url changes depending on the environment (dev, test and production). I don't think it's a good idea to hardcode this kind of things on my module.
Comment: It doesn't matter how you recognize your current site, I thought url might be good, you can set a cookie or check a database field or do as you wish. The answer is still valid, depending on your site you can do form changes with what I wrote. Of course the switch has to be modified accordingly.
Comment: Despite the hard-coded urls (which might be centralized somewhere and made available through vars), what do you expect? There must be some way to distinguish which site of the multisite environment is requesting the form and my first thought would also be the url.


How to search through database of businesses/how to build the content template?

Question: sorry in advance for the more than likely simple/beginner/waste of time question(s). Anyway, I'm working on building a business ratings site of sorts (Yes, I know, way overdone. Don't worry about it! :D). However, since I know very little programming and am completely new to Drupal (7), I don't quite know the best way to go about building the basic nodes, how to add an itemized search function to the site, or how to get the listings to show up in said search. I've done as many searches as I can think of, but I think the problem is that I don't know what I don't know, and therefore am searching the wrong things.
I guess for me those are all different ways of asking a similar question. How do I build the template node for the business page so that it can be searched for and sorted based on its characteristics. For instance, when creating the basic content type template, how would I build it so that the listing can be searched, for instance, by state?
I need to display the address of the business on its page simply because of the nature of the site. So, is there a way for a search to pick up on that, and display it in a search sorted by the state that it's in? Do I need to somehow link that field to a taxonomy term of some sort? Also, what module would be the best to use for adding that type of search to the site?
I'm not sure whether this is helpful, but the modules that I have installed so far in my journey toward building this site/solving this problem are: Views, CTools, Display Suite, and Custom Search. I'm guessing that I will be able to use custom search for the actual search function, but I haven't delved into using it yet since I haven't figured out how to build what it searches.
Sorry for what I'm sure is a silly post, and thank you in advance for any help anybody may have to offer.
Answer: The two major approaches to adding locations in Drupal 7 are location/gmap and addressfield/geocoder.  Comparing these two sets of modules in detail is the subject of a book, Mapping with Drupal, and is outside the scope of this post.  Unfortunately, both approaches are still under heavy development and in all honesty you will likely encounter a fair number of bugs either way.  At the moment, I would choose the Location approach because it has working proximity search (show me all businesses within 100 km of me).
If I were approaching this project, rather than using the built-in Drupal search, I would use the Views modules and filters (exposed filters) to allow users to search.  Once you are proficient with the Views module (Node One has an excellent series of screencasts on learning Views), you will probably find it easier to work with and customize than the basic Drupal search.
A few tips on location-
If you do install the location module it provides a "location directory" view by default, though it is disabled.  You can enable this view and play with it; it creates an index of all your nodes that have locations attached to them.  This should give you some idea about how to build location-based search in Views.
If you do use location, choose Location CCK (which will eventually be named to fields for D7), not the Node Location submodule.  They are mutually exclusive and Location CCK is the direction that the next major release of the Location module will take.
Comment: Thanks for the tips. I'll definitely take a look at Location (CCK). I had another question that I think is related to this with regards to searching. If I want to allow search/sorting by other parameters such as prices, overall rating, and things of that nature, would I use Views for that as well?
Comment: Yes.  You can add any field on a content type as an exposed filter in Views and allow users to search based on that.  Price, rating, etc. will all be fields on your content type, so this should be no problem.  Example: I have a site that allows users to be filtered based on age, gender, etc. using Views exposed filters).
Comment: Awesome. I think I installed view and subsequently forgotten that I had already found the answer to all of my questions. I don't think I could figure out how to access it before because I was so stuck on clicking content types under structure. Of course, obviously there's a link right to it. Must have been late. Thanks a bundle!


Passing arguments down in Tkinter to a method

Question: I'm struggling to get my method working correctly. I've thought about using a lambda function which I did for another problem and that worked, however here it does not seem to work. I'm trying to change the functions to methods and for some reason, my method is not working correctly since it has no reference to the tree. I've tried using a lambda function although that does not work.
My error:
NameError: name 'tree' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
    return self.func(*args)
  File "/home/bitvivaz/Documents/Software Development/Python/PasswordManager/mainFrame.py", line 54, in select
    print([tree.item(x) for x in tree.selection()])
NameError: name 'tree' is not defined

Here is my code:
import tkinter as tk
import tkinter.ttk as ttk
from encryption import encrypted_password, decrypt_password
import backend as db

def get_credentials(tree):
    '''Retrieves all credentials from the database and inserts it into the tree widget'''
    for row in db.show_credentials():
        tree.insert("", 'end', text=row['name'], values=(
            row['username'], decrypt_password(row['password'])))

class MainframeApp:
    def __init__(self, master=None):
        # build ui
        frame_main = ttk.Frame(master)
        frame_main.config(height='600', width='600')
        frame_main.grid()

        # Creates tree widget
        tree = ttk.Treeview(frame_main)

        tree["columns"] = ("one", "two")

        tree.column("#0")
        tree.column("one")
        tree.column("two")

        tree.heading("#0", text="Website")
        tree.heading("one", text="Username")
        tree.heading("two", text="Password")

        tree.grid(padx='5', pady='5', rowspan='20')

        get_credentials(tree)

        tree.bind("<<TreeviewSelect>>", self.select, "+")

        button_add = ttk.Button(frame_main)
        button_add.config(text='Add')
        button_add.grid(column='1', padx='5', row='0')
        button_delete = ttk.Button(frame_main)
        button_delete.config(text='Delete')
        button_delete.grid(column='1', padx='5', row='1')
        button_logout = ttk.Button(frame_main)
        button_logout.config(text='Logout')
        button_logout.grid(column='1', padx='5', row='2')

        # Main widget
        self.mainwindow = frame_main

    def select(self, e):
        print([tree.item(x) for x in tree.selection()])

    def run(self):
        self.mainwindow.mainloop()

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Password Manager")
    app = MainframeApp(root)
    app.run()

Answer: When you make use of a class structure, certain variables are available across methods (class or instance variables), others are not (local variables).
In your case, you need to define variables you need across methods as instance variables, that is, rather than:
tree = ttk.Treeview(frame_main)

You declare:
self.tree = ttk.Treeview(frame_main)

Then you can reference the variable across methods as self.tree.


Get first letter from C string

Question: I have a program in C which is basically a contact book, and I've already done all the functionalities (add contact, delete etc) but I also have to implement a way to search for contacts by the initial letter (the user type any letter, and if they exist contacts that start with that letter they should be displayed) but I'm not getting the first letter of the vector of names to do this... My attempt to do this is in the SearchContactsByFirstLetter function...
<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <time.h>

#define MAX_LENGTH 50

typedef struct
{
    char name[MAX_LENGTH];
    char number[MAX_LENGTH];
    int bd;
    int bdm;
} ContactBook;

void ListContacts(ContactBook **c, int quant)
{
    int i;

    printf("\n List of contacts: \n");
    printf("\t---------------------\n");
    for (i = 0; i < quant; i++)
    {
        printf("\t%d = birthday: %2d month %2d\t name: %s \t number: %s\n", i + 1, c[i]->bd, c[i]->bdm, c[i]->name, c[i]->number);
    }
}

int addContacts(ContactBook **c, int quant, int size)
{
    if (quant < size)
    {
        ContactBook *new = malloc(sizeof(ContactBook));
        printf("\nenter contact name: ");
        scanf("%49[^\n]", new->name);
        printf("\nenter number: ");
        scanf("%s", new->number);
        printf("\nenter the birthday ");
        scanf("%d", &new->bd);
        printf("\n enter the month birthday: ");
        scanf("%d", &new->bdm);
        c[quant] = new;
        return 1;
    }
    else
    {
        printf("\n full list.\n");
        return 0;
    }
}

int deleteContact(ContactBook **c, int quant)
{
    int id;

    ListContacts(c, quant);

    printf("\n\t Enter the id you want to delete: \n");
    scanf("%d", &id);
    id--;
    if (id >= 0 && id < quant)
    {
        free(c[id]);
        if (id < quant - 1)
        {
            c[id] = c[quant - 1];
        }
        return -1;
    }
    else
    {
        printf("\n\t wrong code;\n");
        return 0;
    }
}

void birthdays(ContactBook **c, int quant)
{
    int i;

    time_t t = time(NULL);
    struct tm tm = *localtime(&t);

    printf(" os aniversariantes do mês são: \n");

    for (i = 0; i < quant; i++)
    {
        if (tm.tm_mon + 1 == c[i]->bdm)

        {

            printf("\t%d = birthday: %2d month %2d\t name: %s \t number: %s\n", i + 1, c[i]->bd, c[i]->bdm, c[i]->name, c[i]->number);
        }
    }
}

void SearchContactByFirstLetter(ContactBook **c, int quant)
{
    int i;
    char searchedName[2];

    printf("\n Search a letter: \n");
    scanf("%s", searchedName);
    getchar();

    for (i = 0; i < quant; i++)
    {
        if (strcmp(searchedName, c[i]->name[0]) == 0)
        {
            printf("\t\nname: %s, \nnumber: %s, \nbirthday: %d \nmonth birthday %d \t\n", c[i]->name, c[i]->number, c[i]->bd, c[i]->bdm);
        }
    }
}

void SearchContact(ContactBook **c, int quant)
{
    int i;
    char searchedName[30];

    printf("\n Search name: \n");
    scanf("%s", searchedName);
    getchar();

    for (i = 0; i < quant; i++)
    {
        if (strcmp(searchedName, c[i]->name) == 0)
        {
            printf("\t\nname: %s, \nnumber: %s, \nbirthday: %d \nmonth birthday %d \t\n", c[i]->name, c[i]->number, c[i]->bd, c[i]->bdm);
        }
    }
}

void saveBinary(char arquivo[], ContactBook **c, int quant)
{
    FILE *file = fopen(arquivo, "wb");
    int i;

    if (file)
    {
        for (i = 0; i < quant; i++)
            fwrite(c[i], sizeof(ContactBook), 1, file);
        fclose(file);
    }
    else
        printf("erro");
}

int readBinaryArq(char arquivo[], ContactBook **c)
{
    int quant = 0;
    ContactBook *new = malloc(sizeof(ContactBook));
    FILE *file = fopen(arquivo, "rb");

    if (file)
    {
        while (fread(new, sizeof(ContactBook), 1, file))
        {
            c[quant] = new;
            quant++;
            new = malloc(sizeof(ContactBook));
        }
        fclose(file);
    }
    else
        printf("\nerro");
    return quant;
}

int main()
{

    ContactBook *contacts[50];
    int option, size = 50, quant = 0;
    char arq2[] = ("agenda.dat");
    quant = readBinaryArq(arq2, contacts);

    do
    {
        printf(" \n\t0 - exit\n\t1 - register contact\n\t2 - Remove contact\n\t3- List contacts\n\t4- Search contact\n\t5 - ver aniversariantes do mês\n\t6-Pesquisar por inicial\n ");
        scanf("%d", &option);
        getchar();

        switch (option)
        {
        case 1:
            quant += addContacts(contacts, quant, size);
            break;
        case 2:
            quant += deleteContact(contacts, quant);
            break;
        case 3:
            ListContacts(contacts, quant);
            break;

        case 4:
            SearchContact(contacts, quant);
            break;
        case 5:
            birthdays(contacts, quant);
            break;
        }
        saveBinary(arq2, contacts, quant);

    } while (option != 0);

    return 0;
}
</code>
Comment: If you only want to check a single letter, don't use strcmp. Just do `if(searchedName[0] == c[i]->name[0])`
Comment: I don't really see a question in there. And you've given us a lot of code that seems to have nothing to do with getting the first letter from a C string.
Comment: Also, always pay attention to and fix all compiler warnings. It should have warned you to the fact that the second parameter given to `strcmp` is not the expected type.
Answer: <code>    if (strcmp(searchedName, c[i]->name[0]) == 0)
</code>
That should be:
<code>    if (searchedName[0] == c[i]->name[0])
</code>
But you probably shouldn't read in a string in the first place if you only want to read a single character.

Get first letter from C string


Access to the C:\ and D:\ restricted for local admin

Question: One of our servers, TTSA, has no group policies applied to it when logging in as a local admin (other than the local policy), yet access to the C:\ and D:\ are still restricted.
I've checked the local policy, and sure enough there is no restriction on these drives set (Administrative Templates -> Windows Components -> Windows Explorer -> Hides these specified drives in My Computer / Prevent access to drives from My Computer).
Does anybody know what else could be restricting access to these drives for local admin, or if there is perhaps more settings in GP that could be causing this that I am unaware of? Thanks.
Comment: Have you tried running RSOP? That should rule out Group Policy. Is it a terminal server by any chance? Also you say as **a** local admin - have you tried creating a brand new local admin account and seeing if that has the issue.
Comment: Ah, if that worked then it's probably NOT the issue in my answer. You can either use regedit to edit the other users NTUSER.DAT file, or just delete the account and start again (Probably easier)
Comment: @Dan - It is indeed a terminal server. Just run RSoP (neet tool, much easier then scouring through the output from the cmd GPresult), and neither of the keys mentioned in my post are in there. Will try creating a new admin account now and see if that does the trick. Thanks.
Comment: I have hunch - I can't remember the reg path, but I suspect that the regkeys are in the Terminal Services installation folder thing (You know the whole "change user /install" thing). Let me Google!
Comment: Ha, created a new admin account (in the exact same groups as the built-in local admin), and it allowed me access. Just having a look at your answer now. Thanks.
Comment: Agreed that it is easier, and I think I'll just probably do that and then rename the new one I set up. Just out of interest though, when logged in as the user that has the problem, do you know what key I am looking for to allow access? I assume it is not the one in your answer?
Comment: It'll be in users hive, under "Software\Policies". It *should* be safe to delete everything in there, but the usual warnings apply!
Comment: Found it - `HKEY_LOCAL_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer`. I set the NoViewOnDrive key to '0', logged off and back on and it is sorted. Detailed description here - [link](http://www.pctools.com/guides/registry/detail/1157). Thanks for you help with this.
Comment: You should post what you've done and accept it as the answer. This is encouraged on SF :)
Comment: Was already on it, although I'm not allowed to accept it for 2 days!
Answer: What I suspect has happened is that a user with GPO's applied has installed software by using the
change user /install

command. Browse to the following registry location
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\

And see if you have a key anywhere under there called "Policies". (Possibly \Software\Policies) If so, then this key is probably being applied, at logon, to all users (Including administrators). I'm afraid this is off the top of my head and I don't have a Terminal Server to view right now, but hopefully this will point you the right way.
You'll need to delete it (Take a backup first!) in order to resolve this issue.
Comment: Did have a quick look, and as you suspected above, this was not the answer. Have sorted though, thanks for you help along the way.
Answer: It appears that the issue is because, once applied at any time through Group Policy, the 'Prevent access to drives from My Computer' policy setting is not reset in registry when a policy that sets it is no longer called.
To fix, change the 'NoViewOnDrive' key in the location below to '0' (to allow access to all drives) -
HKEY_LOCAL_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
Here is a detailed description of the key, and how to restrict access to specified drives if required - http://www.pctools.com/guides/registry/detail/1157


inserting UITableViewCell not working

Question: Could somebody explain what I'm doing wrong in attempting to insert a new UITableViewCell? I'm trying to insert a custom UITableViewCell, but it throws the following error: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0)
    return 1;
else if (section == 1)
    return numberOfRows;
return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EditableCell";

EditableCell *editableCell = (EditableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (editableCell == nil) {

    editableCell = [[EditableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

_myTextField = [editableCell textFieldCell];

if (indexPath.section == 0){
    [_myTextField setPlaceholder:@"Menu Name"];
    [_myTextField setReturnKeyType:UIReturnKeyNext];
}
else if (indexPath.section == 1){
    [_myTextField setPlaceholder:@"Category"];
    [_myTextField setReturnKeyType:UIReturnKeyNext];
}
else {
    [_myTextField setPlaceholder:@"Category"];
    [_myTextField setReturnKeyType:UIReturnKeyDone];
}

_myTextField.keyboardType = UIKeyboardTypeDefault;
_myTextField.delegate = self;

return editableCell;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

if (textField.returnKeyType == UIReturnKeyNext) {

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    NSArray *array = [[NSArray alloc] initWithObjects:indexPath, nil];

    [self.tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationTop];

    numberOfRows = numberOfRows + 1;

    [self.tableView reloadData];
    }
}

Answer: You need to make sure that the number of rows returned in the method below now returns the correct number of rows.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
I am sure what is happening is that you are returning the same value here after your insert, whereas the runtime is expecting it to be one more than it was before you made the call to insert a row.
In a bit more detail, what is happening in MVC terms (Model/View/Controller) is this:

Your call to insertRowsAtIndexPaths is requesting that the Controller update the View with an additional row.
The Controller then does a sanity check to see if you have your sums right, so it calls:
   tableView:numberOfRowsInSection
Now the controller knows what value this method returned last time (in your case, 1), and it also knows that you have requested to insert a row. There have been no delete calls, so it expects the next time it calls this method, the value should be (last time's value + rows inserted - rows deleted) = 2
If the Controller deems that you have things in order, it will then call cellForRowAtIndexPath (along with other methods) to get the actual cells for each of the rows in each section.

So for your problem, you need to keep track of the rows in your model - maybe in an array or an ivar with the count of rows available. Update your model by updaing this value as you add/delete rows before you make the call to insertRowsAtIndexPath, and then return this value when tableView:numberOfRowsInSection is called.
Additional tip:
If you wish to have your cell inserts/deletes to be animated, change your code to the below. Notice there is no call to reloadData anymore, instead the insert/reload is wrapped in begin/end update calls - The animated updates will occur after endUpdates due to the reloadSections call.
NSMutableIndexSet *sectionsToReload = [[NSMutableIndexSet alloc] init];
[sectionsToReload addIndex:1]; // Add sections as necessary

[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationTop];
[self.tableView reloadSections:sectionsToReload withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

Check out the WWDC 2010 video from Apple, "Mastering Table Views" - explains everything really nicely, regarding using insertRowsAtIndexPaths and associated methods.
HTH,
Stretch
Comment: I tried your suggestion using an int variable, but to no avail. I updated my code above, so would you mind taking one more look? Thanks a lot
Comment: ok will take a look. Do you get exactly the same error message, before I start?
Comment: ok - try updating your `numberOfRows` before you make the call to `insertRowsAtIndexPaths`. You need to update your model before this call, not before the `reloadData` call.
Comment: ah great - glad it fixed your problem! The controller does those checks when you make the insert/delete/reload calls, so yeah, you need to update your model before those calls are made.
Comment: Hey Derek, I updated my answer to be a bit more clearer, plus added an extra tip which you might find useful instead of using `reloadData`
Comment: you went above and beyond on this answer, even after it was accepted. thanks again.
Answer: After you attempt to insert a new cell, your datasource must contain the number of original cells (1) plus the "extra" cell you are inserting (1) for a total of 2.  So your tableView:numberOfRowsInSection: must return 2.
The error message indicated that tableView:numberOfRowsInSection: returned 1.
Update your datasource so that it returns this "extra" cell.
Comment: How do I do that? I'm already calling [self.tableview reloadata]; Does that not do it? Thanks
Comment: I"ve just updated my answer - take a look, hopefully it explains which methods are called, and what you need to do.

inserting UITableViewCell not working


Send Nested JSON With POST Request iOS Swift 3

Question: I want to send JSON to Server with POST request but i did not understand how i do this. I select friends from table view and show these friends in my Collection view. And the selected peoples shows in collection views and their email are sent in JSON to Create group. Here is my code written in Swift.
@IBAction func createGroupButton(_ sender: Any) {

    let groupName = groupNameTextField.text

    let adminEmail = UserDefaults.standard.value(forKey: "userEmail")

    if groupName == "" {

    alertMessage(msg: "Enter Group name")

    }

    else if base64String == nil {

        alertMessage(msg: "Select Group Image")

    }

    else if emailArray.isEmpty {

        alertMessage(msg: "Select atleast one person")

    }

    else {

    if isNetAvailable {

        var emailData: String?

        print("email data \(emailArray)")

        for i in emailArray {

         emailData = "\"email\":\"\(i)\""

        }

    let postData = "\"name\":\"\(groupName!)\",\"adminemail\":\"\(adminEmail!)\",\"image\":\"\(base64String!)\",\"emailArray\":\"\(emailData!)\""

    let postDat = "jsondata={\(postData)}"

    print("Post Data \(postDat)")

    let urlString = create_group

    let url = URL(string: urlString)

    var request = URLRequest(url: url!)

    request.httpMethod = "POST"

    request.httpBody = postDat.data(using: String.Encoding.utf8)

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let session = URLSession.shared

    let task = session.dataTask(with: request) { (data, response, error) in

        if error != nil {

        print("Something wrong with creating Group")

        }

        if data == nil {

            print("Nil Data")

        }

        if response == nil {
            print("Nil Response")

        }

        if response != nil {
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

            print("Response String is \(responseString)")
        }
    }
    task.resume()

    }

    else {
        alertMessage(msg: "Internet Not Available")
     }

    }
}

Here is my API
<?php

if($_SERVER["REQUEST_METHOD"] !="POST"){ exit; }
require_once 'dbcon.php';
if (!empty($_POST['jsondata']))
{
$configjson = $_POST['jsondata'];

$config = json_decode($configjson, true);

$groupname = $config['name'];
$adminemail = $config['adminemail'];
$image = $config['image'];

$queryemailcheck = "SELECT * FROM groups_name WHERE admin =   '$adminemail' AND groupname = '$groupname'";
$selectquery = mysqli_query($connect, $queryemailcheck);
$totalemails= mysqli_num_rows($selectquery);
if($totalemails>0)
{
echo "Already exist";
}
else {
$queryinsert= "INSERT INTO groups_name(admin , groupname , pic ) VALUES('$adminemail' ,'$groupname' , '$image')";

if(mysqli_query($connect, $queryinsert)){
    echo "Successfully Saved";
}else{
    echo "Error: " ;
}
$members = $config['emailArray'];
foreach($members as $row ){
$email = $row['email'];

$queryinsert2= "INSERT INTO group_members(groupname , member , status    ) VALUES('$groupname' ,'$email' , '0')";

if(mysqli_query($connect, $queryinsert2)){
    echo "Successfully Saved";
}else{
    echo "Error: " ;
}
}

}

}

else echo "post data is empty";
?>

Comment: check your json format, that seems not correct, if you are passing json object, you would use  NSJSONSerialization class to get data then set it in http body
Comment: Please check my answer below
Answer: You can use Alamofire library for handling your webservices. like
Alamofire.request(logoutUrl, method: .post, parameters: dict, encoding: JSONEncoding.default, headers:["Authorization":"Bearer \(accessToken)", "Accept":"application/json", "Content-Type":"application/json; charset=UTF-8"]).responseJSON { (response) in

            let json:JSON = JSON(response.result.value)

            let status =  json["status"].stringValue
            let statusCode = response.response?.statusCode

Comment: I did not use Alamofire. I am using URL Session and i want to do this task this way i doing.
Answer: Create network handler class where you can hit webservices from all of your app.
func makeHttpPostRequest(uri:String, postBody:Dictionary<String, Any>  ,Completion:@escaping (_ response: AnyObject, _ success: Bool) -> Void) {
    let networkCheck = self.getNetworkStatus()
    if networkCheck == false {
        Completion("NO internet connection." as AnyObject,false)
        return
    }//end network check block
    var urlRequest = self.makeHttpRequestWithUrl(url: uri)
    urlRequest.httpMethod = "POST"
    urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
    //check and set authorization header
    if (UserDefaults.standard.object(forKey: AppConstant.KAppAuthenticationToken) != nil) {
        let authToken = UserDefaults.standard.object(forKey: AppConstant.KAppAuthenticationToken) as! String
        urlRequest.setValue("Token token="+authToken, forHTTPHeaderField: "Authorization")
    }
    //let postData = [self.addDefultParameters(detailDict: postBody)]
    let jsonData = try? JSONSerialization.data(withJSONObject: postBody)
    urlRequest.httpBody = jsonData

    //create connection
    self.httpConnectionWithRequest(request: urlRequest, Completion: Completion)
}

func makeHttpRequestWithUrl(url: String) -> URLRequest {
    let urlString = AppConstant.baseUrl+url
    let networkUrlRequest = URLRequest.init(url: URL.init(string: urlString)!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 50)
    return networkUrlRequest
}

func httpConnectionWithRequest(request: URLRequest, Completion:@escaping (_ response: AnyObject, _ success: Bool) -> Void) {
    let session = URLSession.shared
    // make the request
    let task = session.dataTask(with: request) {
        (data, response, error) in
        // check for any errors
        guard error == nil else {
            print("error is: " + String.init(format: "%@", error?.localizedDescription as! CVarArg))
            Completion(error!.localizedDescription as String as AnyObject, false)
            return
        }
        // make sure we got data
        guard let responseData = data else {
            print("Error: did not receive data")
            Completion("didn't get response data" as String as AnyObject, false)
            return
        }

        let responseString =  String.init(data: responseData, encoding: .utf8)
        // parse the result as JSON, since that's what the API provides

        if let resp = response as? HTTPURLResponse{

            if (UserDefaults.standard.object(forKey: AppConstant.KAppAuthenticationToken) != nil) {
                if resp.statusCode == 401{
                    //auth token expired

                    self.makeRequestWithNewToken(request: request, Completion: Completion)
                }
            }
            //check if response is Array or dictionary
            var jsonArray:[Any]?
            var jsonDict:[String:Any]?

            // response is in array
            do{
                jsonArray = try JSONSerialization.jsonObject(with: responseData, options: [])as? [Any]
            }catch{
                print("response doesn't contain array")
            }
            //response is in dictionary
            do{
                jsonDict  = try JSONSerialization.jsonObject(with: responseData, options: [])as? [String:Any]
            }catch{
                print("response doesn't contain dict")
            }
            //=====
          //  if resp.statusCode == 200{

                if jsonArray != nil{
                    Completion(jsonArray! as AnyObject, true)
                    return
                }

                if jsonDict != nil{
                    Completion(jsonDict! as AnyObject, true)
                    return
                }

                Completion("didn't get response data" as String as AnyObject, false)
                return
        }

    }
    task.resume()
        }

And through the completion handler you will get the fetched data.


Microsoft SQL Server 2005 shrinking log file Consequences?

Question: At the moment SQL Server 2005 is running a database that is 8,9GB in size.
the log file is 20.1GB in size and the HDD is filling up fast.
Now i know i can shrink the log file. but i can't find any answers as to what the Consequences are to doing that. this is a database witch feeds a production environment application so if any thing is broken, we have a problem.
We run a daily backup of the database.
So basicly what happens when i shink the log file, i don't lose any production data. but still i have the feeling that i am breaking some thing when i run the query:
<code>DBCC SHRINKFILE('<Logfile_name>', 1)
BACKUP LOG <Database_name> WITH TRUNCATE_ONLY
DBCC SHRINKFILE('<Logfile_name>', 1)
GO
</code>
Answer: The log is growing because is not being backed up. The full database backups you do do not count, they do not backup the log. You must take periodic backups of the log in addition to the full database backup, or it will keep growing. Add a job to backup the log every 30 minutes to your maintenance plan.
Alternatively, change the recovery model of the database to SIMPLE.
Until you backup the log or change recovery mode not only that it will keep growing, but it will be marked as in use won't shrink.
Answer: From what I understand, the transaction log is everything that has happened since the last backup. So before you are allowed to shrink it you need to perform a backup. Since it sounds like you don't have a real DBA, I suggest using a full backup.
My DBA runs log shrinkage once a week as a scheduled job.
Answer: When you shrink the log file, you are effectively removing transactions that have taken place.  So, if your database goes down and you need to restore from your transaction log, you'll have to restore your backed up log file and then start your data retrival using that.
Comment: When would i need to restore from transaction log. sins the data that is in the database is the correct data.
Comment: After you restore a database from a backup, you can play back the transaction log to cover everything that happened since the backup was made.
Comment: @LordSauron: If you had a hard drive crash and lost the database, you would need to restore from the most recent backup. The log files can then be used to replay transactions to get you back up-to-date.
Comment: so if i do a full backup before i run the shrink command i shoudent have any problems?


Async Await / Promise / API Google Tradutor Node JS

Question: Comecei a utilizar a API do Google Tradutor (Google Cloud Translate API) hoje e não estou conseguindo aplicar o async/await na função translate. Segue o código:
const api = require("../keys/google-translate.json").API_KEY
const googleTranslate = require("google-translate")(api);

googleTranslate.translate(text, "pt-BR", function (err, translation) {
    console.log(translation.translatedText)
});

Teria alguma maneira de fazer esta função retornar uma Promise para que eu consiga utilizar o async/await?
Answer: Você precisa criar uma Promise explicitamente. Você já pesquisou sobre o funcionamento básico de uma promessa?
Basicamente, toda Promise funciona assim:
const myPromise = new Promise((resolve, reject) => {
  // Quando o trabalho assíncrono estiver feito,
  // basta chamar o `resolve`, passando um valor qualquer.
  resolve(__QUALQUER_VALOR__);

  // Em um eventual erro, rejeitamos a promessa:
  reject(new Error('Whoops!'));
});

Para saber mais, leia este excelente artigo do Jake Archibald e a documentação na MDN.
Então, no seu caso, basta usar o que vimos acima:
const api = require("../keys/google-translate.json").API_KEY
const googleTranslate = require("google-translate")(api);

function translateText(text) {
  // Note que a função retorna uma `Promise`. Poderemos, então, usar `async`/`await`.
  return new Promise((resolve, reject) => {
    googleTranslate.translate(text, 'pt-BR', function (err, translation) {
      if (err) {
        // No caso de erro, a promessa será rejeitada.
        reject(err);
      } else {
        // No sucesso, a promessa será resolvida.
        resolve(translation);
      }
    });
  });
}

Answer: Em node tem o util.promisify que faz a conversão de uma função callback para promise. Ele faz automaticamente o processo descrito pelo Luiz Felipe, mas atenção promisify converte apenas callbacks como ultimo parâmetro, e callbacks que tenham de erro como primeiro parâmetro.
const api = require("../keys/google-translate.json").API_KEY
const googleTranslate = require("google-translate")(api);
const util = require('util')

util.promisify(googleTranslate.translate)(text, "pt-BR");

Comment: Ótima ideia. Nem tinha pensado em usar o `promisify`... Mas realmente, é válido!! O único problema é se os _callbacks_ da função forem fora do padrão... +1 :)


ThemeKey rule; how to target IMCE pages

Question: On my Drupal 7 site, I noticed that the IMCE popup loses its action buttons and all functionality when I'm using Adminimal as the admin theme:

In the Known Issues section of the IMCE project page, it mentions using the ThemeKey module if there is a conflict with your custom theme. Here are the ThemeKey rules it says to write:
drupal:path = %token
drupal:path:wildcard token * imce

When I do this, the IMCE buttons are, in fact, back in place (yay!)... BUT the entire site, both public pages and administration pages, are also displayed in Garland (boo!).
How can I force just the IMCE popup window to render in Garland?
Answer: As is my nature, I was totally overthinking this. Here's what I had to do in ThemeKey:
First, for the File field:
drupal:path = imce-filefield/%

Basically, this is matching the first section of the URL path with imce-filefield and then whatever else comes after it is matched with /%.
This solves the problem for file/image uploads. The IMCE file browser used in the WYSIWYG editor (in my case, CKEditor) has a different URL path, so its interface is still broken. That one is simply:
drupal:path = imce

So far so good...

ThemeKey rule; how to target IMCE pages


Parar eventos multiplos Jquery

Question: Tenho a seguinte situação:
<code>$('input[name=buscar]').on( "keydown keypress keyup", function( event ) {
    console.log('foi');
});
</code>
Todas as vezes que digito, os 3 eventos são acionados. Como faço para que apenas 1 seja acionado, ao invés dos três? ou seja, cliquei no botão, disparou o primeiro evento, vez oque deveria fazer e pronto...
Comment: Se for identificar o evento adicionado  pode ser da forma citada abaixo, se for para executar apenas um evento especifico remova os demais.
Comment: @GabrielRodrigues A maneira que você citou da certo. Mas teve uma vez, acredito que utilizei alguma função, onde ela parava os demais eventos, então eu não precisa verificar evento por evento, ele disparava uma vez, e não realizava os demais. Mas não recordo a maneira que fiz isso. ATT
Comment: Se não tiver um caso especifico fica difícil ajudar, estes três eventos trabalham "quase" no mesmo tempo, talvez você deva analisar qual evento é ideal e utiliza-lo
Comment: Qual a razão de teres os 3 eventos associados a esse input?
Comment: @Sergio Anos atrás tive problemas utilizando apenas 1 evento, daí para frente sempre utilizo os três... Pois de nenhuma forma irá deixar de pegar um evento...
Comment: @abcd ok, mas adicionar os 3 pesa na performance do browser, e gera problemas como este que estás a ter. Deves sempre adicionar só o necessário à funcionalidade que precisas. Nalguns casos pode ser que precises mais do que um. Qual é a funcionalidade que procuras?
Comment: @Sergio Em relação a hoje, Gera alguns problemas de visualização, minimos que não irão interferir. Mas no passado0 já tive problemas quando utilizei ajax, pois solicita 3 vezes... O que o usuário GabrieRodrigues respondeu resolve. Mas, anos atrás, eu tenho em mente que resolvi este mesmo problema de uma forma mais "elegante", onde se houvesse disparado algum dos 3 eventos, ele não repetia os demais... Mas por ter dúvida, eu não recordo o que fiz naquela época. ATT
Answer: Acredito que esteja executando por ser três eventos diferentes mas que seriam executados ao "mesmo tempo". Vou explicar:
keyup(): o evento ocorre quando a tecla volta a posição original no teclado (exemplo: quando você solta a tecla).
keydown(): o evento ocorre quando a tecla é pressionada.
keypress(): o evento ocorre quando a tecla é pressionada.
A diferença entre keydown() e keypress() é que o segundo não é capturado quando as teclas ctrl, alt ou shift são pressionadas.
Logo, se você aperta uma tecla, passará pelos 3 "estados" apresentados acima, para disparar apenas um, você poderia utilizar apenas uma das funções e remover as outras.
Answer: Você pode pegar o tipo de evento e colocar em uma condição para separar onde cada evento:
<code>$('input[name=buscar]').on("keydown keypress keyup", function(event) {
  if (event.type === 'keydown') {
    console.log('1');
  } else if (event.type === 'keypress') {
    console.log('2');
  } else if (event.type === 'keyup') {
    console.log('3');
  }
});
</code>
Ou encadear vários eventos.
<code>$('input[name=buscar]').on("keydown", function() {
  console.log('1');
}).on('keypress', function() {
  console.log('2');
}).on('keyup', function() {
  console.log('3');
});
</code>
Answer: Como você está utilizando esses eventos em um input, creio que o código abaixo seja a maneira mais simples de solucionar o seu problema:
<code>$('input[name=buscar]').change( function() {
  console.log('foi');
});
</code>
Comment: Sua opção pode dar certo... Mas em minha situação em especifica, com todo o código, houve algumas modificações indesejadas nos eventos. ATT

Parar eventos multiplos Jquery


Vue Composition API - Can't add a property to an object

Question: I'm using Vue's Composition API. When I write some code that adds a property to a ref object, the template renderer does not seem to detect the change. Here is my code:
<template>

    <button @click="updateObj">Click</button>

{{ obj[1] }}

</template>

Clicking on the button calls updateObj which then sets the property "1" on obj to "hello". If obj[1] is set, you should see "hello" in the browser, but nothing is displayed. Here's a codepen to the demo.
I've been using the Composition API for months now and feel like I've gotten the hang of it, but  I have no idea what's going on here. I've also tried reactive instead of ref but still no luck.
Answer: You should use ref when you work with primitive values, if you want to use an object you have to use reactive, in the official docs they say :

If using ref, we are largely translating style (1) to a more verbose equivalent using refs (in order to make the primitive values reactive).

Using reactive is nearly identical to style (2). We only need to create the object with reactive and that's it.
Using reactive is nearly identical to style (2). We only need to create the object with reactive and that's it.

...
Use ref and reactive just like how you'd declare primitive type variables and object variables in normal JavaScript. It is recommended to use a type system with IDE support when using this style.

To make it reactive assign the object directly to the ref's value :
 obj.value = { 1: "hello" };

LIVE DEMO
Comment: The docs also say: "If an object is assigned as a ref's value, the object is made deeply reactive by the reactive method."  So ref still works for it.
Comment: Yes they mean something like `obj.value = { 1: "hello" };` not `obj.value[1] = "hello";` here a [demo](https://codesandbox.io/s/property-addition-forked-4cnf7?file=/src/App.vue:331-358) compare it to the demo provided by in the OP
Comment: @BoussadjraBrahim Your comment makes sense. It seems like directly assigning the `obj.value` is the way to go.
Comment: As i did in the demo
Answer: I'm adding my answer here so when I google this again in six months I'll find it.
If you are using composition api with Vue 2, you need to use set to add a new tracked property to an object.
From https://github.com/vuejs/composition-api

⚠ set and del workaround for adding and deleting reactive properties
⚠ Warning: set and del do NOT exist in Vue 3. We provide them as a workaround here, due to the limitation of Vue 2.x reactivity system.
In Vue 2, you will need to call set to track new keys on an
object(similar to Vue.set but for reactive objects created by the
Composition API). In Vue 3, you can just assign them like normal
objects.
Similarly, in Vue 2 you will need to call del to ensure a key deletion
triggers view updates in reactive objects (similar to Vue.delete but
for reactive objects created by the Composition API). In Vue 3 you can
just delete them by calling delete foo.bar.

<template>

    <button @click="updateObj">Click</button>

{{ obj[1] }}

</template>

LIVE DEMO


Check performance of drupal websites using some modules or tools

Question: My website starts well and after few days of access it goes terribly slow. Is there any module or any external tool to check the performance of the drupal website. So that we can point out where we are facing issues in drupal so that we can solve them. My pages are built out of average 5-6 views, does this effect the performance of the website ?
Answer: You could try new relic, it will give you insight into how expensive database queries are or where you have a bottle neck which is slowing down your site. It has some integration with Drupal and could also show you if you have a problematic module...
Also if your pages use a lot of views, have you tried caching the views? It is part of default views module, go into your view edit under "advanced" on the right. Click caching and turn this to time based. This means that rather than running each view query / view rendering on every page load - It will run it on the first load and retrieve a cache until it expires. The caveat here is that you will have a lag on the results for how ever long you choose to cache.
Comment: How do i do caching of views? Is there any good module for that ?
Comment: Problem is that the module does not exists for drupal 7
Comment: It is part of default views module, I have updated my answer
Answer: If you have ssh access to your server you can install XHProf and than add the Drupal module.

XHProf is capable of reporting function-level call counts and inclusive and exclusive wall time, CPU time and memory usage. Additionally, it supports ability to compare two runs (hierarchical DIFF reports), or aggregate results from multiple runs. Originally developed at Facebook, XHProf was open sourced in Mar, 2009 (source)

I'm using it frequently and it really helped me find some bad bottlenecks.
Answer: You may use the Boost module. Here is more info on it: http://www.onyxbits.de/content/quick-drupal-performance-test-boost-module-makes-huge-difference.

Boost provides static page caching for Drupal enabling a very significant performance and scalability boost for sites that receive mostly anonymous traffic. Boost is very easy to install and has been throughly tested on Shared, VPS and Dedicated hosting. Apache is fully supported, with Nginx, Lighttpd and IIS 7 semi-supported.


Non linear regression in R Exponential curve fitting

Question: I am trying to fit an exponential model to some data. The data is:
Wavelength  aCDOM
350.01  0.80605
350.22  0.78302
350.43  0.78302
350.64  0.78302
350.85  0.78302
351.06  0.78302
351.27  0.78302
351.48  0.78302
351.68  0.75999
351.89  0.75999
352.1   0.75999
352.31  0.75999
352.52  0.75999
352.73  0.73696
352.94  0.73696
353.15  0.73696
353.36  0.73696
353.57  0.73696
353.78  0.73696
353.99  0.73696
354.2   0.73696
354.41  0.73696
354.62  0.73696
354.83  0.73696
355.04  0.73696
355.25  0.71393
355.46  0.71393
355.67  0.71393

I know that the best model fit this type of data is an exponential function in the for y ~ a * exp(-b * c) where a is the absorbance estimate at the reference wavelength, b is the spectral slope which is the value I am looking for, and c is the wavelength minus the reference wavelength (440nm). I have tried using the nls function by estimating the starting parameters following the method outlined in Fox (2002) but I keep getting the following error in nlsModel(formula, mf, start, wts):
singular gradient matrix at initial parameter estimates

The formula I am using is model1 <- nls(St0104 ~ a * exp(-b * (Wavelength-440)), start = list(a=0.1, b=0.0012), trace=T), I'm not even if I have calculated the starting parameters correctly.
I have tried instead to plot the log of Y and do linear as well as polynomial regression, but I know this is not correct for this data and the residuals are horrible. I'm pretty new to R but I have tried everything I can but this is driving me nuts can anybody help please?
Comment: **This is an irreproducible result:** when I run your code with your data and starting values, `nls` completes successfully with a reasonable set of estimates.
Comment: (1) The residuals will be awful because the $(x,y)$ data trace out a step function (having only five levels). (2) The narrow range of y-values (varying less than $\pm 6\%$ from their middle) indicates there is little difference between fitting $(x,y)$ or fitting $(x,\log(y))$. (3) One would guess the $y$ values are either counts or rounded decimals that have been converted (via some kind of calibration information) to absorbance values. A maximum likelihood estimate suitable for *the raw data* ought to converge and do a good job of estimating $b$.
Comment: 1. The two variables you gave in your data (Wavelength, aCDOM) do not match the two variables in your model (St0104, Wavelength). $\,$ 2. the $Y$ variable in the data that you have supplied is discrete. Indeed, it appears to be integers between 31 and 35, all scaled by a constant. What is it?
Comment: hi sorry I should have mentioned the name of the y variable is St0104 the values are actually the absorbance of CDOM at 440nm over the wavelength range of a sample called St0104.I only gave a small set of the full data as it was quite long. X values are wavelength Y are the a440 (absorbance at 440nm).
Comment: How is absorbance measured? Why are the values all multiples of a constant?
Comment: The Y values were calculated by choosing a wavelength of interest (in this case 440nm) and using the formula a440 = 2.303(A440) where 2.303 is a constant and A440 is the (corrected) absorbance at that wavelength. I used a spec fluorometer to measure absorbance of the sample. I am trying to calculate the spectral slope (SCDOM) which is estimated from the slope of an exponential curve of a440 as a function of wavelength. Again I am new to R and stats so I find R a bit confusing. I tried this regression in Matlab and it works fine if I use  exp function with 2 terms but I cant figure it out in R.
Answer: For the formula, include an I() to indicate that the asterisks are to be used as arithmetic multipliers rather than crossing variables as is the standard for formula writing in R, i.e. I(a * exp(-b * (Wavelength-440))). See http://stat.ethz.ch/R-manual/R-devel/library/stats/html/formula.html.
Comment: An identical example in the manual page for `nls` does not require the use of `I`, nor do any of the other examples there.  The code as given in the question works.
Comment: `nls`  doesn't use quite the same interface for formulas that `lm` uses, so this shouldn't be an issue.


Making midis off of real songs - syncing tempo

Question: Occasionally throughout a song, the tempo will change by 2-3 BPM, completely throwing off the song. As a result, I have to put the tempo change in the midi itself to sync, but even then it's slightly off. This makes it difficult to gauge whether something is out of sync or if my midi is wrong. Is there a way painless way of making a midi sync with the music it's based on?
Answer: There is a way to tempo shift in several DAW's.  They allow you to either tap tempo, or move bar and beat lines to match up to the audio track.  Digital Performer, Reason, and Logic have this capability.  Cubase probably has it too, although I haven't personally tested it.  Once you've matched the tempo you can export a MIDI tempo map.


Is it needed to add reCaptcha to built in Django's login form?

Question: Hello I'm new to Django and I'm using Django's built in forms to login my users, also I have a contact form where I'm using Google reCaptcha to avoid attacks.
I was wondering if it is needed to add reCaptcha to my login form. I have heard Django takes care most of security and I don't want to repeat code if default login form is already prepared for brute force attacks.
In case its better to add reCaptcha to default login form how can I process the validation? In my contact form I call Google's API to verify user click within my views, but I don't feel comfortable adding that code inside the auth_views.LoginView class.
Thanks!
Comment: It is a matter of choice. Personally, I won't do that especially if the passwords are stored in hashed format. To be honest if I hear that a website has been hacked and passwords are stolen, it does not bother me if I know that the passwords are hashed
Answer: Django does not take care of any rate-limiting with its forms, including login.
I think that it is a good idea to include some sort of rate-limiting security measure to your login form. re-Captcha might be overkill as a default, unless there are several incorrect attempts within a timeframe.
Take a look at the Django rate-limit project for an easy to implement alternative to captcha.
In order to add reCaptcha to the login view, rather than modifying the auth_views.LoginView class, just create a new view that extends that class. You can add your recaptcha form validation just like in your contact form.
Then you can update your url to point to your custom view and template:
url(r'^login/$', custom_auth_views.recaptcha_login, {'template_name': 'core/recaptcha_login.html'}, name='login'),

See this post on how to extend the login views / templates.